LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
mwt_seq2seq.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 CEA LIST <gael.de-chalendar@cea.fr>
2//
3// SPDX-License-Identifier: MIT
4
5#ifndef DEEPLIMA_MWT_SEQ2SEQ_H
6#define DEEPLIMA_MWT_SEQ2SEQ_H
7
8#include <cmath>
9#include <cstdint>
10#include <cstring>
11#include <fstream>
12#include <memory>
13#include <mutex>
14#include <stdexcept>
15#include <string>
16#include <unordered_map>
17#include <vector>
18
19#include <eigen3/Eigen/Dense>
20
21namespace deeplima
22{
23
53{
54public:
55 typedef Eigen::MatrixXf Matrix;
56 typedef Eigen::VectorXf Vector;
57
58 MwtSeq2Seq() = default;
59
60 bool loaded() const { return m_loaded; }
61 // Should the lexicon try this model before its affix rules?
62 bool before_rules() const { return m_before_rules; }
63
64 void load(const std::string& fn)
65 {
66 std::ifstream f(fn, std::ios::binary);
67 if (!f.is_open())
68 {
69 throw std::runtime_error("Can't open MWT seq2seq model " + fn);
70 }
71 char magic[8];
72 f.read(magic, 8);
73 if (!f || std::memcmp(magic, "MWTS2S01", 8) != 0)
74 {
75 throw std::runtime_error("Not an MWT seq2seq model: " + fn);
76 }
77 const uint32_t decomposed = read_u32(f), before = read_u32(f);
78 const uint32_t V = read_u32(f), E = read_u32(f), H = read_u32(f);
79 if (V < 5 || E == 0 || H == 0 || V > 1000000 || E > 4096 || H > 4096)
80 {
81 throw std::runtime_error("Bad MWT seq2seq model dimensions in " + fn);
82 }
83 m_decomposed = decomposed != 0;
84 m_before_rules = before != 0;
85 m_chars.assign(V, 0);
86 m_ids.clear();
87 for (uint32_t i = 4; i < V; ++i)
88 {
89 m_chars[i] = read_u32(f);
90 m_ids[m_chars[i]] = i;
91 }
92 m_emb = read_matrix(f, V, E);
93 m_enc_f_wih = read_matrix(f, 4 * H, E);
94 m_enc_f_whh = read_matrix(f, 4 * H, H);
95 m_enc_f_b = read_matrix(f, 4 * H, 1);
96 m_enc_b_wih = read_matrix(f, 4 * H, E);
97 m_enc_b_whh = read_matrix(f, 4 * H, H);
98 m_enc_b_b = read_matrix(f, 4 * H, 1);
99 m_dec_wih = read_matrix(f, 8 * H, E + 2 * H);
100 m_dec_whh = read_matrix(f, 8 * H, 2 * H);
101 m_dec_b = read_matrix(f, 8 * H, 1);
102 m_att = read_matrix(f, 2 * H, 2 * H);
103 m_out = read_matrix(f, V, 4 * H);
104 m_out_b = read_matrix(f, V, 1);
105 m_gate = read_matrix(f, 1, 4 * H + E);
106 m_gate_b = read_matrix(f, 1, 1);
107 m_H = H;
108 m_loaded = true;
109 m_cache = std::make_shared<Cache>();
110 }
111
112 void clear()
113 {
114 m_loaded = false;
115 m_cache = std::make_shared<Cache>();
116 }
117
118 // The words of surface (UTF-8), or an empty vector when the model writes
119 // fewer than two (the surface stays as it is).
120 std::vector<std::string> expand(const std::string& surface) const
121 {
122 std::vector<std::string> words;
123 if (!m_loaded || surface.empty())
124 {
125 return words;
126 }
127 {
128 std::lock_guard<std::mutex> lock(m_cache->mutex);
129 const auto it = m_cache->words.find(surface);
130 if (m_cache->words.end() != it)
131 {
132 return it->second;
133 }
134 }
135 std::u32string src = utf8_to_u32(surface);
136 if (m_decomposed)
137 {
138 src = decompose(src);
139 }
140 const std::u32string out = decode(src);
141 std::u32string word;
142 for (char32_t c : out)
143 {
144 if (c == U' ')
145 {
146 if (!word.empty()) words.push_back(finish(word));
147 word.clear();
148 }
149 else
150 {
151 word.push_back(c);
152 }
153 }
154 if (!word.empty()) words.push_back(finish(word));
155 if (words.size() < 2)
156 {
157 words.clear();
158 }
159 std::lock_guard<std::mutex> lock(m_cache->mutex);
160 if (m_cache->words.size() >= CACHE_SIZE)
161 {
162 m_cache->words.clear();
163 }
164 m_cache->words.emplace(surface, words);
165 return words;
166 }
167
168 // --------------------------------------------------- abugida syllables
169 // Tamil consonant + vowel sign -> consonant + pulli + independent vowel
170 // (a bare consonant carries the inherent "a"); Ethiopic syllable -> its
171 // sixth-order (vowelless) form + the vowel letter of the glottal row.
172 static std::u32string decompose(const std::u32string& s)
173 {
174 std::u32string out;
175 for (size_t i = 0; i < s.size(); ++i)
176 {
177 const char32_t c = s[i];
178 const char32_t n = i + 1 < s.size() ? s[i + 1] : 0;
179 if (ta_consonant(c))
180 {
181 out.push_back(c);
182 out.push_back(TA_PULLI);
183 if (const char32_t v = ta_vowel_of_sign(n))
184 {
185 out.push_back(v);
186 ++i;
187 }
188 else if (n == TA_PULLI)
189 {
190 ++i;
191 }
192 else
193 {
194 out.push_back(TA_A);
195 }
196 continue;
197 }
198 if (et_syllable(c))
199 {
200 const int order = int(c - 0x1200) % 8;
201 if (const char32_t v = et_vowel(order))
202 {
203 out.push_back(c - order + 5);
204 out.push_back(v);
205 continue;
206 }
207 }
208 out.push_back(c);
209 }
210 return out;
211 }
212
213 static std::u32string recompose(const std::u32string& s)
214 {
215 std::u32string out;
216 for (size_t i = 0; i < s.size(); ++i)
217 {
218 const char32_t c = s[i];
219 if (ta_consonant(c) && i + 2 < s.size() && s[i + 1] == TA_PULLI)
220 {
221 const char32_t v = s[i + 2];
222 if (v == TA_A)
223 {
224 out.push_back(c);
225 i += 2;
226 continue;
227 }
228 if (const char32_t sign = ta_sign_of_vowel(v))
229 {
230 out.push_back(c);
231 out.push_back(sign);
232 i += 2;
233 continue;
234 }
235 }
236 if (et_syllable(c) && int(c - 0x1200) % 8 == 5 && i + 1 < s.size())
237 {
238 const int order = et_order_of_vowel(s[i + 1]);
239 if (order >= 0)
240 {
241 out.push_back(c - 5 + order);
242 ++i;
243 continue;
244 }
245 }
246 out.push_back(c);
247 }
248 return out;
249 }
250
251 static std::u32string utf8_to_u32(const std::string& s)
252 {
253 std::u32string out;
254 for (size_t i = 0; i < s.size();)
255 {
256 const unsigned char c = s[i];
257 char32_t cp;
258 size_t n;
259 if (c < 0x80) { cp = c; n = 1; }
260 else if ((c >> 5) == 0x6) { cp = c & 0x1f; n = 2; }
261 else if ((c >> 4) == 0xe) { cp = c & 0x0f; n = 3; }
262 else if ((c >> 3) == 0x1e) { cp = c & 0x07; n = 4; }
263 else { cp = 0xfffd; n = 1; }
264 if (i + n > s.size())
265 {
266 out.push_back(0xfffd);
267 break;
268 }
269 for (size_t k = 1; k < n; ++k)
270 {
271 cp = (cp << 6) | (static_cast<unsigned char>(s[i + k]) & 0x3f);
272 }
273 out.push_back(cp);
274 i += n;
275 }
276 return out;
277 }
278
279 static std::string u32_to_utf8(const std::u32string& s)
280 {
281 std::string out;
282 for (char32_t cp : s)
283 {
284 if (cp < 0x80)
285 {
286 out.push_back(char(cp));
287 }
288 else if (cp < 0x800)
289 {
290 out.push_back(char(0xc0 | (cp >> 6)));
291 out.push_back(char(0x80 | (cp & 0x3f)));
292 }
293 else if (cp < 0x10000)
294 {
295 out.push_back(char(0xe0 | (cp >> 12)));
296 out.push_back(char(0x80 | ((cp >> 6) & 0x3f)));
297 out.push_back(char(0x80 | (cp & 0x3f)));
298 }
299 else
300 {
301 out.push_back(char(0xf0 | (cp >> 18)));
302 out.push_back(char(0x80 | ((cp >> 12) & 0x3f)));
303 out.push_back(char(0x80 | ((cp >> 6) & 0x3f)));
304 out.push_back(char(0x80 | (cp & 0x3f)));
305 }
306 }
307 return out;
308 }
309
310private:
311 static constexpr uint32_t PAD = 0, BOS = 1, EOS = 2, UNK = 3;
312 static constexpr size_t CACHE_SIZE = 100000;
313 static constexpr char32_t TA_PULLI = 0x0bcd, TA_A = 0x0b85;
314
315 static bool ta_consonant(char32_t c) { return c >= 0x0b95 && c <= 0x0bb9; }
316
317 static char32_t ta_vowel_of_sign(char32_t s)
318 {
319 switch (s)
320 {
321 case 0x0bbe: return 0x0b86;
322 case 0x0bbf: return 0x0b87;
323 case 0x0bc0: return 0x0b88;
324 case 0x0bc1: return 0x0b89;
325 case 0x0bc2: return 0x0b8a;
326 case 0x0bc6: return 0x0b8e;
327 case 0x0bc7: return 0x0b8f;
328 case 0x0bc8: return 0x0b90;
329 case 0x0bca: return 0x0b92;
330 case 0x0bcb: return 0x0b93;
331 case 0x0bcc: return 0x0b94;
332 default: return 0;
333 }
334 }
335
336 static char32_t ta_sign_of_vowel(char32_t v)
337 {
338 for (char32_t s = 0x0bbe; s <= 0x0bcc; ++s)
339 {
340 if (ta_vowel_of_sign(s) == v && v != 0) return s;
341 }
342 return 0;
343 }
344
345 // The Ethiopic syllables, but the glottal row, whose letters are the vowels
346 static bool et_syllable(char32_t c)
347 {
348 return c >= 0x1200 && c <= 0x1357 && !(c >= 0x12a0 && c <= 0x12a7);
349 }
350
351 static char32_t et_vowel(int order)
352 {
353 switch (order)
354 {
355 case 0: return 0x12a7;
356 case 1: return 0x12a1;
357 case 2: return 0x12a2;
358 case 3: return 0x12a3;
359 case 4: return 0x12a4;
360 case 6: return 0x12a6;
361 default: return 0;
362 }
363 }
364
365 static int et_order_of_vowel(char32_t v)
366 {
367 for (int order = 0; order < 8; ++order)
368 {
369 if (et_vowel(order) == v && v != 0) return order;
370 }
371 return -1;
372 }
373
374 std::string finish(const std::u32string& word) const
375 {
376 return u32_to_utf8(m_decomposed ? recompose(word) : word);
377 }
378
379 static uint32_t read_u32(std::istream& f)
380 {
381 unsigned char b[4];
382 f.read(reinterpret_cast<char*>(b), 4);
383 if (!f)
384 {
385 throw std::runtime_error("Truncated MWT seq2seq model");
386 }
387 return uint32_t(b[0]) | (uint32_t(b[1]) << 8) | (uint32_t(b[2]) << 16) | (uint32_t(b[3]) << 24);
388 }
389
390 static Matrix read_matrix(std::istream& f, uint32_t rows, uint32_t cols)
391 {
392 const uint32_t r = read_u32(f), c = read_u32(f);
393 if (r != rows || c != cols)
394 {
395 throw std::runtime_error("Unexpected matrix shape in MWT seq2seq model");
396 }
397 std::vector<float> data(size_t(r) * c);
398 f.read(reinterpret_cast<char*>(data.data()), std::streamsize(data.size() * sizeof(float)));
399 if (!f)
400 {
401 throw std::runtime_error("Truncated MWT seq2seq model");
402 }
403 Matrix m(r, c);
404 for (uint32_t i = 0; i < r; ++i)
405 for (uint32_t j = 0; j < c; ++j)
406 m(i, j) = data[size_t(i) * c + j];
407 return m;
408 }
409
410 static Vector sigmoid(const Vector& x)
411 {
412 return (1.0f + (-x.array()).exp()).inverse().matrix();
413 }
414
415 // One LSTM step, PyTorch's gate order (input, forget, cell, output)
416 static void lstm_step(const Matrix& wih, const Matrix& whh, const Matrix& b,
417 const Vector& x, Vector& h, Vector& c)
418 {
419 const Eigen::Index n = h.size();
420 const Vector g = wih * x + whh * h + b.col(0);
421 const Vector i = sigmoid(g.segment(0, n));
422 const Vector f = sigmoid(g.segment(n, n));
423 const Vector cell = g.segment(2 * n, n).array().tanh().matrix();
424 const Vector o = sigmoid(g.segment(3 * n, n));
425 c = (f.array() * c.array() + i.array() * cell.array()).matrix();
426 h = (o.array() * c.array().tanh()).matrix();
427 }
428
429 std::u32string decode(const std::u32string& src) const
430 {
431 const Eigen::Index T = Eigen::Index(src.size()), H = m_H, E = m_emb.cols();
432 const Eigen::Index V = m_emb.rows();
433 std::vector<uint32_t> x(src.size());
434 for (size_t t = 0; t < src.size(); ++t)
435 {
436 const auto it = m_ids.find(src[t]);
437 x[t] = (m_ids.end() == it) ? UNK : it->second;
438 }
439
440 // Encoder: enc.col(t) = [forward h_t; backward h_t]
441 Matrix enc(2 * H, T);
442 Vector h = Vector::Zero(H), c = Vector::Zero(H);
443 for (Eigen::Index t = 0; t < T; ++t)
444 {
445 lstm_step(m_enc_f_wih, m_enc_f_whh, m_enc_f_b, m_emb.row(x[t]).transpose(), h, c);
446 enc.col(t).head(H) = h;
447 }
448 h.setZero();
449 c.setZero();
450 for (Eigen::Index t = T - 1; t >= 0; --t)
451 {
452 lstm_step(m_enc_b_wih, m_enc_b_whh, m_enc_b_b, m_emb.row(x[t]).transpose(), h, c);
453 enc.col(t).tail(H) = h;
454 }
455
456 // Decoder
457 Vector dh = Vector::Zero(2 * H), dc = Vector::Zero(2 * H), ctx = Vector::Zero(2 * H);
458 Vector input(E + 2 * H), feat(4 * H), gate_in(4 * H + E);
459 uint32_t y = BOS;
460 std::u32string out;
461 const size_t max_len = 2 * src.size() + 10;
462 for (size_t step = 0; step < max_len; ++step)
463 {
464 const Vector ye = m_emb.row(y).transpose();
465 input << ye, ctx;
466 lstm_step(m_dec_wih, m_dec_whh, m_dec_b, input, dh, dc);
467 const Vector scores = enc.transpose() * (m_att * dh);
468 const Vector a = softmax(scores);
469 ctx = enc * a;
470 feat << dh, ctx;
471 const Vector logits = m_out * feat + m_out_b.col(0);
472 Vector p = softmax(logits);
473 gate_in << feat, ye;
474 const float g = 1.0f / (1.0f + std::exp(-((m_gate.row(0) * gate_in)(0) + m_gate_b(0, 0))));
475 p *= g;
476 for (Eigen::Index t = 0; t < T; ++t)
477 {
478 p(x[t]) += (1.0f - g) * a(t);
479 }
480 Eigen::Index k = 0;
481 p.maxCoeff(&k);
482 if (k == EOS)
483 {
484 break;
485 }
486 if (k >= 4 && k < V)
487 {
488 out.push_back(m_chars[k]);
489 }
490 else
491 {
492 // An unknown character: copy the most attended source character
493 Eigen::Index j = 0;
494 a.maxCoeff(&j);
495 out.push_back(src[j]);
496 }
497 y = uint32_t(k);
498 }
499 return out;
500 }
501
502 static Vector softmax(const Vector& v)
503 {
504 const Vector e = (v.array() - v.maxCoeff()).exp().matrix();
505 return e / e.sum();
506 }
507
508 bool m_loaded = false;
509 bool m_decomposed = false;
510 bool m_before_rules = false;
511 Eigen::Index m_H = 0;
512 std::vector<char32_t> m_chars;
513 std::unordered_map<char32_t, uint32_t> m_ids;
514 Matrix m_emb, m_enc_f_wih, m_enc_f_whh, m_enc_f_b, m_enc_b_wih, m_enc_b_whh, m_enc_b_b;
515 Matrix m_dec_wih, m_dec_whh, m_dec_b, m_att, m_out, m_out_b, m_gate, m_gate_b;
516 // Shared by the copies of a model: they expand the same way
517 struct Cache
518 {
519 std::mutex mutex;
520 std::unordered_map<std::string, std::vector<std::string>> words;
521 };
522 std::shared_ptr<Cache> m_cache = std::make_shared<Cache>();
523};
524
525} // namespace deeplima
526
527#endif
Eigen::MatrixXf Matrix
Definition mwt_seq2seq.h:55
void load(const std::string &fn)
Definition mwt_seq2seq.h:64
static std::u32string recompose(const std::u32string &s)
static std::u32string decompose(const std::u32string &s)
Eigen::VectorXf Vector
Definition mwt_seq2seq.h:56
std::vector< std::string > expand(const std::string &surface) const
static std::string u32_to_utf8(const std::u32string &s)
bool loaded() const
Definition mwt_seq2seq.h:60
bool before_rules() const
Definition mwt_seq2seq.h:62
static std::u32string utf8_to_u32(const std::string &s)
Edit rules for lemmatizing words absent from the lemma dictionary.