LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
lemmatization_impl.cpp
Go to the documentation of this file.
1// Copyright 2002-2023 CEA LIST
2// SPDX-FileCopyrightText: 2023 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
7
8#include <cstdlib>
9
11
12
14 : m_beam_size(5),
15 m_upos_idx(std::numeric_limits<size_t>::max())
16{}
17
19 size_t /*threads*/,
20 size_t /*buffer_size_per_thread*/
21 )
22 : m_beam_size(5),
23 m_upos_idx(std::numeric_limits<size_t>::max())
24{
25}
26
27
28void LemmatizationImpl::load(const std::string& fn, const PathResolver& /*path_resolver*/)
29{
30 try
31 {
33 }
34 catch (const std::runtime_error& e)
35 {
36 std::cerr << "LemmatizationImpl failed to load " << fn << ": " << e.what();
37 throw;
38 }
39}
40
41void LemmatizationImpl::init(size_t max_input_word_len,
42 const std::vector<std::string>& class_names,
43 const std::vector<std::vector<std::string>>& class_values)
44 {
45 m_upos_idx = std::numeric_limits<size_t>::max();
46 m_upos_feat_idx = std::numeric_limits<size_t>::max();
47 m_feat_value_map.clear();
48 m_max_input_word_len = max_input_word_len;
49 auto uint_dicts = RnnSeq2Seq::get_input_uint_dicts();
50 decltype(uint_dicts) enc_uint_dict;
51 enc_uint_dict.push_back(uint_dicts[0]);
52 m_vectorizer.init(enc_uint_dict, max_input_word_len, 1);
53
54 const auto& str_dicts = RnnSeq2Seq::get_input_str_dicts();
55 const auto& lang_morph_model = RnnSeq2Seq::get_morph_model();
56 m_fixed_upos = std::vector<bool>(32, false); // TODO: find the number of possible UPOS values
57 for (auto& idx : RnnSeq2Seq::get_fixed_upos())
58 {
59 m_fixed_upos[idx] = true;
60 }
61
62 assert(class_names.size() == class_values.size());
63 EmbdUInt64FloatHolder enc_feats_dict;
64 for (size_t feat_idx = 0; feat_idx < lang_morph_model.get_feats_count(); ++feat_idx)
65 {
66 std::vector<uint64_t> v;
67 auto cls_idx = std::numeric_limits<size_t>::max();
68
69 const auto& feat_name = lang_morph_model.get_feat_name(feat_idx);
70 auto it = std::find(class_names.begin(), class_names.end(), feat_name);
71
72 if (class_names.end() != it)
73 {
74 const auto& feat_vec = lang_morph_model.get_feat_vec_ref(feat_idx);
75 auto it_diff = it - class_names.begin();
76 if (it_diff != std::numeric_limits<ptrdiff_t>::max())
77 cls_idx = it_diff;
78 assert(cls_idx != std::numeric_limits<uint64_t>::max());
79 assert(cls_idx != std::numeric_limits<size_t>::max());
80
81 v.resize(class_values[cls_idx].size(), 0);
82 // assert(class_values[cls_idx].size() == feat_vec.size());
83 for (size_t j = 0; j < feat_vec.size(); ++j)
84 {
85 // TODO: rewrite this
86 for (size_t k = 0; k < class_values[cls_idx].size(); ++k)
87 {
88 if (feat_vec[j] == class_values[cls_idx][k]
89 || ("_" == feat_vec[j] && "-" == class_values[cls_idx][k]))
90 {
91 v[k] = j;
92 break;
93 }
94 }
95 }
96 }
97 else if (std::getenv("DEEPLIMA_VERBOSE") != nullptr)
98 {
99 // The lemmatizer was trained with a feature the tagger does not predict
100 // (e.g. Foreign, Typo): its value is unknown. Not actionable by a user,
101 // and printed at each model load: only on request
102 std::cerr << "Warning: classifier doesn't provide required feature: \""
103 << feat_name << "\"" << std::endl;
104 }
105
106 m_feat_value_map.push_back(v);
107 auto dd = std::make_shared<Dict<uint64_t>>(v);
109
110 d.init(dd, str_dicts[feat_idx].get_tensor().transpose());
111 enc_feats_dict.push_back(d);
112 m_feat2cls.push_back(cls_idx);
113 if (cls_idx != std::numeric_limits<size_t>::max() && cls_idx < class_names.size() && class_names[cls_idx] == "upos")
114 {
115 m_upos_idx = cls_idx;
116 m_upos_feat_idx = feat_idx;
117 }
118 }
119 m_feat_vectorizer.init(enc_feats_dict, 1, enc_feats_dict.size());
120
121 if (m_upos_idx == std::numeric_limits<size_t>::max())
122 {
123 throw std::logic_error("Underlying classifier doesn't provide UPOS.");
124 }
125
126 RnnSeq2Seq::init_new_worker(max_input_word_len);
127}
128
129bool LemmatizationImpl::is_fixed(std::shared_ptr< StdMatrix<uint8_t> > classes, size_t idx)
130{
131 assert(m_upos_idx != std::numeric_limits<size_t>::max());
132 // In the lemmatization model's UPOS values (get_fixed_upos)
133 const auto& upos_map = m_feat_value_map[m_upos_feat_idx];
134 const uint64_t tagger_upos = classes->get(idx, m_upos_idx);
135 const uint64_t upos = tagger_upos < upos_map.size() ? upos_map[tagger_upos] : 0;
136 return upos < m_fixed_upos.size() && m_fixed_upos[upos];
137}
138
140{
141 const auto& lang_morph_model = RnnSeq2Seq::get_morph_model();
142 std::vector<size_t> feats(lang_morph_model.get_feats_count());
143
144 const auto& feat2cls = m_feat2cls;
145 // The tagger's values in the lemmatization model's: its lemma dictionary and
146 // rules are keyed on them. Taking the tagger's indices as they were was only
147 // right for a tagger trained on the same corpus (a treebank's own tagger with
148 // a merged corpus' lemmatizer: fr-GSD test Lemmas 97.6 -> 87.1)
149 const auto& value_map = m_feat_value_map;
150 const morph_model::morph_feats_t v = lang_morph_model.convert([idx, &feat2cls, &value_map, &classes](size_t feat_idx) {
151 if (feat_idx == std::numeric_limits<size_t>::max())
152 {
153 throw std::runtime_error(std::string("get_morph_feats wrong feat_idx: max size_t"));
154 }
155 else if (feat_idx >= feat2cls.size())
156 {
157 throw std::runtime_error(std::string("get_morph_feats wrong feat_idx: larger than feat2cls size"));
158 }
159 assert(feat_idx < feat2cls.size() && feat_idx != std::numeric_limits<size_t>::max());
160 auto class_idx = feat2cls[feat_idx];
161 if (class_idx == std::numeric_limits<size_t>::max())
162 return std::numeric_limits<uint64_t>::max();
163 assert(class_idx != std::numeric_limits<uint64_t>::max());
164 const uint64_t tagger_value = classes->get(idx, class_idx);
165 const auto& map = value_map[feat_idx];
166 return tagger_value < map.size() ? map[tagger_value] : uint64_t(0);
167 });
168
169 return v;
170}
171
172void LemmatizationImpl::predict(const std::u32string& form,
173 std::shared_ptr< StdMatrix<uint8_t> > classes, size_t idx,
174 std::u32string& target)
175{
176 // An empty form has nothing to lemmatize. It must never reach the seq2seq
177 // encoder: the BiLSTM cannot run on a zero-length sequence (with input_len == 0
178 // it indexes column -1 of its workbench → SIGSEGV). Return an empty lemma.
179 if (form.empty())
180 {
181 target.clear();
182 return;
183 }
184
185 // The vectorizer and the encoder workbench were sized for at most
186 // m_max_input_word_len characters (see init). A longer form would overrun both
187 // the vectorizer storage and the encoder output matrix, so clamp it.
188 const size_t form_len = (m_max_input_word_len > 0 && form.size() > m_max_input_word_len)
190 : form.size();
191
192 // 1. vectorize
193 for (size_t i = 0; i < form_len; ++i)
194 {
195 m_vectorizer.set(i, 0, form[i]);
196 }
197
198 for (size_t i = 0; i < m_feat2cls.size(); ++i)
199 {
200 if (m_feat2cls[i] != std::numeric_limits<size_t>::max())
201 {
202 m_feat_vectorizer.set(0, i, classes->get(idx, m_feat2cls[i]));
203 }
204 else
205 {
206 m_feat_vectorizer.set(0, i, 0);
207 }
208 }
209
210 // 2. run prediction
211 std::vector<uint32_t> output(0, form_len * 2);
213 static_cast<const EmbdVectorizer>(m_vectorizer).get_tensor(),
214 static_cast<const EmbdVectorizer>(m_feat_vectorizer).get_tensor(),
215 form_len,
216 form_len * 2,
218 output,
219 { "output" });
220
221 // 3. generate output
222 target.clear();
223 output.push_back(0);
224 target = std::u32string((char32_t*)(output.data()));
225}
226
227
228
229} // namespace impl
230 // namespace lemmatization
231 // namespace deeplima
232
void load(const std::string &fn)
virtual void predict(size_t worker_id, const Eigen::MatrixXf &inputs, int64_t input_begin, int64_t input_end, int64_t output_begin, int64_t output_end, std::shared_ptr< StdMatrix< uint8_t > > &output, const std::vector< std::string > &outputs_names)=0
const uint_dicts_holder_t & get_input_uint_dicts() const
virtual size_t init_new_worker(size_t input_len, bool precomputed_input=false)
const str_dicts_holder_t & get_input_str_dicts() const
bool is_fixed(std::shared_ptr< StdMatrix< uint8_t > > classes, size_t idx)
size_t m_upos_idx
index in the features matrix of the upos line
std::vector< bool > m_fixed_upos
index i is true if upos whose index is i is considered as fixed
std::vector< std::vector< uint64_t > > m_feat_value_map
per feature of the lemmatization model, its value index for each value index of the tagger (matched b...
size_t m_max_input_word_len
max word length the encoder workbench / vectorizer were sized for (see init)
void init(size_t max_input_word_len, const std::vector< std::string > &class_names, const std::vector< std::vector< std::string > > &class_values)
size_t m_upos_feat_idx
the upos feature in m_feat_value_map
void predict(const std::u32string &form, std::shared_ptr< StdMatrix< uint8_t > > classes, size_t idx, std::u32string &target)
morph_model::morph_feats_t get_morph_feats(std::shared_ptr< StdMatrix< uint8_t > > classes, size_t idx) const
virtual void load(const std::string &fn, const PathResolver &)
Encoding on one 64 bits integer of the set of morphological features for one token.
Definition morph_model.h:36
DictEmbdVectorizer< EmbdUInt64FloatHolder, EmbdUInt64Float, eigen_wrp::EigenMatrixXf > EmbdVectorizer
DictsHolderImpl< EmbdUInt64Float > EmbdUInt64FloatHolder
Definition embd_dict.h:210
EmbdDict< uint64_t, Eigen::MatrixXf, Eigen::Index > EmbdUInt64Float
Definition embd_dict.h:208
STL namespace.