LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
dependency_parser.h
Go to the documentation of this file.
1// Copyright 2021 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6#ifndef DEEPLIMA_DEPENDENCY_PARSER
7#define DEEPLIMA_DEPENDENCY_PARSER
8
9#include <vector>
10#include <string>
11#include <memory>
12#include <chrono>
13#include <thread>
14#include <algorithm>
15
16#include "token_type.h"
17#include "utils/str_index.h"
19#include "deeplima/graph_dp.h"
20#include "deeplima/token_type.h"
21// #include "graph_dp/impl/graph_dp_impl.h"
24
25#include "graph_dp.h"
26
27namespace deeplima
28{
29
31{
32public:
33
35 {
36 uint32_t m_lemm_idx = 0;
37 std::vector<uint8_t> m_classes;
38 uint16_t m_head_idx = 0; // => max sentence length == 2^16
39 uint16_t m_rel_type = 0;
40
41 token_with_analysis_t(size_t num_classes)
42 : impl::token_t(), m_classes(num_classes, 0)
43 {
44 }
45
48 virtual ~token_with_analysis_t() = default;
49 };
50
51 struct tokens_with_analysis_t : public token_buffer_t<token_with_analysis_t>
52 {
55
56 tokens_with_analysis_t(size_t size, size_t num_classes)
57 : Parent(size, token_with_analysis_t(num_classes))
58 {
59 }
60 };
61
63 {
64 friend class DependencyParser;
65
66 protected:
69
70 inline void set_token(const typename tokens_with_analysis_t::token_t* p)
71 {
72 m_ptoken = p;
73 }
74 public:
75
77 : m_stridx(stridx),
78 m_ptoken(nullptr)
79 { }
80
81 inline token_flags_t flags() const
82 {
83 assert(nullptr != m_ptoken);
84 return m_ptoken->m_flags;
85 }
86
87 inline bool eos() const
88 {
89 assert(nullptr != m_ptoken);
91 }
92
93 inline uint32_t cls(size_t idx) const
94 {
95 assert(nullptr != m_ptoken);
96 return m_ptoken->m_classes[idx];
97 }
98
99 inline const std::string& form() const
100 {
101 assert(nullptr != m_ptoken);
102 const std::string& f = m_stridx.get_str(m_ptoken->m_form_idx);
103 return f;
104 }
105 };
106
108 {
109 const tokens_with_analysis_t& m_data;
110 mutable enriched_token_t m_token; // WARNING: only one iterator is supported
111
112 public:
114
116 : m_data(data), m_token(stridx) { }
117
118 inline typename tokens_with_analysis_t::size_type size() const
119 {
120 return m_data.size();
121 }
122
123 inline const enriched_token_t& operator[](size_t idx) const
124 {
125 m_token.set_token(m_data.data() + idx);
126 return m_token;
127 }
128 };
129
131 {
132 const StringIndex& m_stridx;
133 const std::vector<token_with_analysis_t>& m_buffer;
134 std::shared_ptr< StdMatrix<uint32_t> > m_heads;
135 size_t m_current;
136 size_t m_offset;
137 size_t m_end;
138 const std::vector<std::string>* m_rel_names; // deprel id -> string (may be null)
139
140 public:
142 const std::vector<token_with_analysis_t>& buffer,
143 std::shared_ptr< StdMatrix<uint32_t> > heads,
144 size_t offset,
145 size_t end,
146 const std::vector<std::string>* rel_names = nullptr)
147 : m_stridx(stridx), m_buffer(buffer), m_heads(heads),
148 m_current(0), m_offset(offset), m_end(end - offset), m_rel_names(rel_names)
149 {
150 assert(end > offset + 1);
151 }
152
153 inline bool end() const
154 {
155 return m_current >= m_end;
156 }
157
158 inline token_flags_t flags() const
159 {
160 assert(! end());
161 return m_buffer[m_current].m_flags;
162 }
163
164 inline uint16_t token_offset() const
165 {
166 return m_buffer[m_current].m_offset;
167 }
168
169 inline uint16_t token_len() const
170 {
171 return m_buffer[m_current].m_len;
172 }
173
174 inline uint32_t form_idx() const
175 {
176 return m_buffer[m_current].m_form_idx;
177 }
178
179 inline uint32_t lemma_idx() const
180 {
181 throw std::runtime_error("TokenIterator::lemma_idx");
182 return 0;
183 }
184
185 inline uint32_t head() const
186 {
187 return m_heads->get(m_offset + m_current, 0);
188 }
189
190 // Predicted deprel (relation label) id, or 0 if the model has no label decoder.
191 inline uint32_t rel() const
192 {
193 return (m_heads->size() >= 2) ? m_heads->get(m_offset + m_current, 1) : 0;
194 }
195
196 // Predicted deprel as a string ("dep" if no vocabulary is available).
197 inline const char* deprel() const
198 {
199 if (nullptr != m_rel_names && rel() < m_rel_names->size())
200 {
201 return (*m_rel_names)[rel()].c_str();
202 }
203 return "dep";
204 }
205
206 inline const char* form() const
207 {
208 assert(! end());
209 const std::string& f = m_stridx.get_str(m_buffer[m_current].m_form_idx);
210 return f.c_str();
211 }
212
213 inline const char* lemma() const
214 {
215 assert(! end());
216 const std::string& f = m_stridx.get_str(m_buffer[m_current].m_lemm_idx);
217 return f.c_str();
218 }
219
220 // MWT: number of sub-words if this token starts an expanded multiword token
221 // (0 otherwise), and the surface form for the "N-M surface" range line.
222 inline uint8_t mwt_len() const
223 {
224 return m_buffer[m_current].m_mwt_len;
225 }
226
227 inline const char* mwt_surface() const
228 {
229 return m_stridx.get_str(m_buffer[m_current].m_mwt_surface_idx).c_str();
230 }
231
232 inline void next()
233 {
234 m_current++;
235 }
236
237 inline void reset(size_t position = 0)
238 {
239 m_current = position;
240 }
241
242 inline size_t position() const
243 {
244 return m_current;
245 }
246
247 inline uint8_t token_class(size_t cls_idx) const
248 {
249 assert(m_offset == 0);
250 uint8_t val = m_buffer[m_current].m_classes[cls_idx];
251 return val;
252 }
253 };
254
255 typedef std::function < void (const StringIndex& stridx,
256 const std::vector<token_with_analysis_t>& tokens,
257 std::shared_ptr< StdMatrix<uint32_t> > heads,
258 size_t begin,
259 size_t end) > output_callback_t;
260
261 DependencyParser(const std::string& model_fn,
262 const PathResolver& path_resolver,
263 std::shared_ptr< StringIndex > stridx,
264 const std::vector<std::string>& input_class_names,
265 size_t buffer_size,
266 size_t num_buffers,
267 size_t threads = 1)
268 : m_buffer_size(buffer_size),
271 m_stridx_ptr(stridx),
272 // m_stridx(*stridx),
273 m_impl()
274 {
275 assert(m_buffer_size > 0);
276 assert(num_buffers > 0);
277 m_buffers.reserve(num_buffers);
278
279 m_impl.load(model_fn, path_resolver);
280 // Sentence-level parallelism: run several inference workers, each parsing a
281 // different slot single-threaded (Eigen intra-op parallelism is disabled at
282 // startup, see Eigen::setNbThreads(1)). Workers must not exceed the number
283 // of slots (num_buffers), otherwise the thread pool would starve/deadlock.
284 size_t eff_threads = std::max<size_t>(1, std::min(threads, num_buffers));
285 m_impl.init(eff_threads, num_buffers, buffer_size, *m_stridx_ptr, input_class_names);
286
287 for (size_t i = 0; i < num_buffers; ++i)
288 {
289 m_buffers.emplace_back(m_buffer_size, input_class_names.size());
290 }
291
292 m_impl.register_handler([this](
293 std::shared_ptr< StdMatrix<uint32_t> > heads,
294 size_t begin, size_t end, size_t slot_idx) {
295 // std::cerr << "handler called (dp): " << slot_idx << std::endl;
296
298 m_buffers[slot_idx],
299 heads,
300 begin,
301 end);
302
303 m_buffers[slot_idx].unlock();
304 });
305
306 }
307
309 {
310 // std::cerr << "~DependencyParser" << std::endl;
311 }
312
315 }
316
317 // deprel id -> string mapping from the model; empty if the model has no
318 // label decoder (in that case TokenIterator::deprel() falls back to "dep").
319 const std::vector<std::string>& get_rel_class_names() const {
320 return m_impl.get_rel_class_names();
321 }
322
323 void setStringIndex(std::shared_ptr<deeplima::StringIndex> stringIndexPtr) {
324 m_stridx_ptr = stringIndexPtr;
325 // m_stridx = StringIndex(*m_stridx_ptr;
326 }
327
328 void set_classes(size_t idx, const std::string& class_name, const std::vector<std::string>& data)
329 {
330 m_class_names.push_back(class_name);
331
332 if (idx + 1 > m_classes.size())
333 {
334 m_classes.resize(idx + 1);
335 }
336 assert(0 == m_classes[idx].size());
337 m_classes[idx] = data;
338
339 if (m_classes.size() > 1)
340 {
341 //m_has_feats = true;
342 for (size_t i = 0; i < m_class_names.size(); ++i)
343 {
344 const std::string& feat_name = m_class_names[i];
345 if (feat_name == "upos" || feat_name == "xpos" || feat_name == "eos")
346 {
347 continue;
348 }
349 //m_first_feature_to_print = i;
350 break;
351 }
352 }
353 }
354
355 // Apply the model to the sequence of tokens given by iter from the tagger
357 {
358 // std::cerr << "DependencyParser::operator(TokenSequenceAnalyzer<>::TokenIterator& iter)" << std::endl;
360 {
362 }
363
364 size_t first_timepoint_idx = 0;
365 // count_max_tokens_until_eos() APPENDS, so m_lengths must start empty. This
366 // handler is called once per tagger batch; without clearing here, a batch's
367 // per-sentence lengths were appended to the previous batch's leftover lengths,
368 // so predict() iterated far more (sum_lengths) than the buffer held (count) and
369 // every sentence in such a buffer was parsed at the wrong offset.
370 m_lengths.clear();
371 m_lengths.reserve(256);
372 // A non-empty buffer at this point holds the beginning of a sentence left
373 // open by the previous tagger batch (see carry_open_sentence()): continue it,
374 // without a new root, and count its tokens in the first sentence's length.
375 const size_t pending = m_current_timepoint;
376 size_t tokens_to_process = count_max_tokens_until_eos(iter, m_lengths);
377 if (pending > 0 && !m_lengths.empty())
378 {
379 m_lengths.front() += pending;
380 }
381 // std::cerr << "DependencyParser::operator() tokens_to_process: " << tokens_to_process << std::endl;
382 bool insert_root = (0 == pending);
383 bool sentence_closed = true;
384 while (!iter.end())
385 {
387 assert(m_current_buffer < m_buffers.size());
388
390 // std::cerr << "DependencyParser::operator() processing token: " << iter.form() << std::endl;
391
392 if (insert_root)
393 {
394 token.m_offset = 0;
395 token.m_len = 0;
396 token.m_form_idx = m_stridx_ptr->get_idx("<ROOT>");
397 // std::cerr << "<ROOT>" << std::endl;
399 token.m_lemm_idx = token.m_form_idx;
400 // The synthetic <ROOT> is never a multiword token; clear stale metadata
401 // since the buffer slot is reused across calls.
402 token.m_mwt_len = 0;
403 token.m_mwt_surface_idx = 0;
404 // Its tag inputs too: they kept those of the token that last used the
405 // slot, so a sentence's parse depended on its neighbours. In training,
406 // the root's UPOS (ROOT, unknown) and features ("-", the first in the
407 // sorted dictionaries) are all class 0.
408 std::fill(token.m_classes.begin(), token.m_classes.end(), 0);
409 insert_root = false;
410 tokens_to_process--;
412 continue;
413 }
414 else
415 {
416 token.m_offset = iter.token_offset();
417 token.m_len = iter.token_len();
418 token.m_form_idx = iter.form_idx();
419 // std::cerr << iter.form() << std::endl;
420 // std::cerr << m_stridx_ptr->get_str(token.m_form_idx) << std::endl;
421 token.m_flags = iter.flags();
422 token.m_lemm_idx = iter.lemma_idx();
423 // Carry MWT metadata (surface idx is valid: DP shares the analyzer's
424 // StringIndex) so the dumper can emit the "N-M surface" range line.
425 token.m_mwt_len = iter.mwt_len();
426 token.m_mwt_surface_idx = iter.mwt_surface_idx();
427 // token.m_head_idx = iter.head();
428 // token.m_rel_type = 0; // TODO where is stored the rel type ???
429 // TODO lines below were commented out to avoid crash. Does it really work?
430 token.m_head_idx = iter.position();
431 token.m_rel_type = 0; // TODO where is stored the rel type ???
432 for (size_t i = 0; i < m_classes.size(); ++i)
433 {
434 token.m_classes[i] = iter.token_class(i);
435 }
436
437 sentence_closed = (iter.flags() & token_flags_t::sentence_brk ||
439 if (sentence_closed)
440 {
441 insert_root = true;
442 }
443 }
444
446 tokens_to_process--;
447 iter.next();
448
449 if (iter.end() && !sentence_closed && m_current_timepoint < m_buffer_size)
450 {
451 // The tagger batch ends inside a sentence. Parsing now would cut it in
452 // two, each part with its own root. Keep it for the next batch.
453 carry_open_sentence(first_timepoint_idx);
454 break;
455 }
456
457 if (m_current_timepoint >= m_buffer_size || 0 == tokens_to_process)
458 {
459 // std::cerr << "DependencyParser::operator() call start_analysis " << m_current_buffer << ", "
460 // << first_timepoint_idx << "," << m_current_timepoint << std::endl;
462 m_started = true;
463
464 // if we can't wait until next call
466
467 if (!iter.end())
468 {
469 m_lengths.clear();
470 tokens_to_process = count_max_tokens_until_eos(iter, m_lengths);
471 insert_root = true;
472 first_timepoint_idx = m_current_timepoint;
473 }
474 }
475 }
476
477 m_started = true;
478 }
479
480 void finalize()
481 {
482 // std::cerr << "DependencyParser::finalize" << std::endl;
483 while (!m_started)
484 {
485 // std::cerr << "DependencyParser::finalize sleeping" << std::endl;
486 std::this_thread::sleep_for(std::chrono::milliseconds(500));
487 }
488
489 if (m_current_timepoint > 0)
490 {
492 {
493 // std::cerr << "DependencyParser::finalize call start_analysis" << std::endl;
494 // Analyse exactly the tokens accumulated in this (final, partial) buffer,
495 // not the whole buffer_size: passing -1 made handle_token_buffer fall back
496 // to buffer.size(), processing a stale tail of uninitialised timepoints.
498 // The parser may analyse another text (LIMA, several input files): it
499 // must not take this sentence for the beginning of its first one
501 m_lengths.clear();
502 }
503 else
504 {
505 //m_cls.no_more_data(m_current_buffer);
506 }
507 }
508
509 // std::cerr << "DependencyParser::finalize call send_all_results" << std::endl;
510 m_impl.send_all_results();
511 }
512
513protected:
515 {
516 // std::cerr << "DependencyParser::acquire_buffer" << std::endl;
517 size_t next_buffer_idx = (m_current_buffer + 1 < m_buffers.size()) ? (m_current_buffer + 1) : 0;
518 const token_buffer_t<token_with_analysis_t>& next_buffer = m_buffers[next_buffer_idx];
519
520 // wait for buffer
521 while (next_buffer.locked())
522 {
523 // std::cerr << "DependencyParser::acquire_buffer locked" << std::endl;
524 m_impl.send_next_results();
525 }
526 assert(!next_buffer.locked());
527
528 m_current_buffer = next_buffer_idx;
530 // std::cerr << "DependencyParser::acquire_buffer DONE:" << m_current_buffer << std::endl;
531 }
532
533 // The current buffer ends with an open sentence (its last m_lengths entry).
534 // Analyse the complete sentences before it, then move it to the beginning of
535 // the next buffer, where the next call to operator() completes it. If it is
536 // the only sentence of the buffer, it just stays there. finalize() parses a
537 // sentence still open at the end of the input.
538 void carry_open_sentence(size_t first_timepoint_idx)
539 {
540 assert(!m_lengths.empty());
541 const size_t open_len = m_lengths.back();
542 assert(open_len <= m_current_timepoint);
543 const size_t open_begin = m_current_timepoint - open_len;
544 if (open_begin > 0)
545 {
546 m_lengths.pop_back();
547 start_analysis(m_current_buffer, first_timepoint_idx, m_lengths, open_begin);
548 m_started = true;
549 // The parse of the buffer only reads its tokens: they can be read here
550 const size_t from = m_current_buffer;
552 for (size_t i = 0; i < open_len; ++i)
553 {
554 m_buffers[m_current_buffer][i] = m_buffers[from][open_begin + i];
555 }
556 m_current_timepoint = open_len;
557 }
559 }
560
561 void start_analysis(size_t buffer_idx,
562 size_t first_timepoint_idx,
563 const std::vector<size_t>& lengths,
564 int count = -1)
565 {
566 // std::cerr << "DependencyParser::start_analysis buffer_idx=" << buffer_idx << ", first_timepoint_idx=" << first_timepoint_idx
567 // << ", lengths=" << lengths << ", count=" << count << std::endl;
568 assert(!m_buffers[buffer_idx].locked());
569 m_buffers[buffer_idx].lock();
570
571 const tokens_with_analysis_t& current_buffer = m_buffers[buffer_idx];
572 m_impl.handle_token_buffer(buffer_idx,
573 first_timepoint_idx,
574 enriched_token_buffer_t(current_buffer, *m_stridx_ptr),
575 lengths,
576 count);
577 }
578
579 size_t count_max_tokens_until_eos(TokenSequenceAnalyzer<>::TokenIterator& iter, std::vector<size_t>& lengths)
580 {
581 size_t current_iter_pos = iter.position();
582 size_t tokens_counter = 0;
583 size_t this_sentence_tokens = m_current_timepoint > 0 ? 0 : 1;
584
585 // std::cerr << "DependencyParser::count_max_tokens_until_eos m_current_timepoint=" << m_current_timepoint
586 // << "; tokens_counter=" << tokens_counter << "; this_sentence_tokens=" << this_sentence_tokens
587 // << "; m_buffer_size=" << m_buffer_size << std::endl;
588 if (m_current_timepoint + tokens_counter + this_sentence_tokens >= m_buffer_size)
589 {
590 throw std::runtime_error("No place for new tokens in this buffer");
591 }
592
593 while (!iter.end())
594 {
595 this_sentence_tokens++;
596 // std::cerr << "DependencyParser::count_max_tokens_until_eos m_current_timepoint=" << m_current_timepoint
597 // << "; tokens_counter=" << tokens_counter << "; this_sentence_tokens=" << this_sentence_tokens
598 // << "; m_buffer_size=" << m_buffer_size
599 // << "; token=" << iter.form() << std::endl;
600
601 if (iter.flags() & token_flags_t::sentence_brk ||
603 {
604 // End of a sentence. Record its length (including its synthetic root) and
605 // keep accumulating the following sentences into the SAME buffer, each
606 // with its own root. They are then analysed together in one pass and
607 // written to distinct output regions (predict() advances by length),
608 // instead of one slot per sentence all writing at output offset 0 (which
609 // made a shorter following sentence overwrite the previous one).
610 lengths.push_back(this_sentence_tokens);
611 tokens_counter += this_sentence_tokens;
612 iter.next();
613 if (iter.end())
614 {
615 this_sentence_tokens = 0;
616 break;
617 }
618 // Need room for at least the next sentence's root + one token.
619 if (m_current_timepoint + tokens_counter + 2 > m_buffer_size)
620 {
621 this_sentence_tokens = 0;
622 break;
623 }
624 this_sentence_tokens = 1; // synthetic root of the next sentence
625 continue;
626 }
627
628 if (m_current_timepoint + tokens_counter + this_sentence_tokens >= m_buffer_size)
629 {
630 // The buffer just filled in the MIDDLE of a sentence. Splitting it across
631 // two buffers parses each half separately (each with its own synthetic
632 // root), corrupting both — and, because predict() advances by length, every
633 // following sentence's heads end up shifted. If at least one whole sentence
634 // is already in this buffer, leave the current (incomplete) sentence for the
635 // next buffer, where it starts fresh and fits. Only a single sentence that
636 // on its own exceeds buffer_size has to be cut (kept here, rare).
637 if (tokens_counter > 0)
638 {
639 this_sentence_tokens = 0;
640 }
641 break;
642 }
643
644 iter.next();
645
646 }
647 if (this_sentence_tokens > 0)
648 {
649 lengths.push_back(this_sentence_tokens);
650 tokens_counter += this_sentence_tokens;
651 }
652
653 iter.reset(current_iter_pos);
654 // std::cerr << "DependencyParser::count_max_tokens_until_eos lengths=" << lengths
655 // << "; tokens_counter=" << tokens_counter << std::endl;
656 return tokens_counter;
657 }
658
659 std::vector<std::string> m_class_names;
660 std::vector<std::vector<std::string>> m_classes;
661
665 bool m_started = false;
666
667 std::shared_ptr</*const*/ StringIndex> m_stridx_ptr;
668 // /*const*/ StringIndex& m_stridx;
670 std::vector<tokens_with_analysis_t> m_buffers;
671 std::vector<size_t> m_lengths;
672
673#ifdef DP_VECTORIZER_WITH_PRECOMPUTING
674 using Vectorizer = FeaturesVectorizerWithPrecomputing<
678#elif DP_VECTORIZER_WITH_CACHE
679 using Vectorizer = FeaturesVectorizerWithCache<
682#else
686#endif
689{
690public:
691
693 m_fastText(std::make_shared<FastTextVectorizer<eigen_wrp::EigenMatrixXf::matrix_t, Eigen::Index>>()),
698 {}
699
700 // GraphDpImpl(
701 // size_t threads,
702 // size_t buffer_size_per_thread
703 // )
704 // : deeplima::graph_dp::impl::GraphDependencyParser(
705 // 0 /* TODO: FIX ME */, 4, threads * 2, buffer_size_per_thread, threads),
706 // m_fastText(std::make_shared<FastTextVectorizer<eigen_wrp::EigenMatrixXf::matrix_t, Eigen::Index>>()),
707 // m_current_timepoint(deeplima::graph_dp::impl::GraphDependencyParser::get_start_timepoint())
708 // {
709 // }
710
711 std::shared_ptr<EmbdUInt64Float> convert(const EmbdStrFloat& src)
712 {
713 auto d = src.get_int_dict<EmbdUInt64Float::value_t>();
714 auto t = src.get_tensor().transpose();
715 auto p = std::make_shared<EmbdUInt64Float>();
716 p->init(d, t);
717
718 return p;
719 }
720
721 virtual void load(const std::string& fn, const PathResolver& path_resolver)
722 {
724
725 m_featVectorizers.resize(this->get_input_str_dicts().size());
726 for (size_t i = 0; i < this->get_input_str_dicts().size(); ++i)
727 {
728 //auto d = (this->get_input_str_dicts()[i]);
729 m_featVectorizers[i] = convert(this->get_input_str_dicts()[i]);
730 }
731
732 m_fastText->load(path_resolver.resolve("embd", deeplima::graph_dp::impl::GraphDependencyParser::get_embd_fn(0), {"bin", "ftz"}));
733 }
734
735 void init(size_t threads,
736 size_t num_buffers,
737 size_t buffer_size_per_thread,
738 StringIndex& stridx,
739 const std::vector<std::string>& class_names)
740 {
741 m_fastText->get_words([&stridx](const std::string& word){ stridx.get_idx(word); });
742
743 std::vector<typename Vectorizer::feature_descr_t> feats;
744 feats.reserve(1/* + m_featVectorizers.size()*/);
745 feats.emplace_back(Vectorizer::str_feature, "form", m_fastText);
746
747 // Match the parser's required input features to the tagger's output columns
748 // by NAME rather than by position. The parser's input dimension is fixed by
749 // the model, so we iterate the features it expects (index 0 is "raw"/form,
750 // handled above). For each, we look up the tagger column producing it. Morph
751 // classes the tagger does not produce are fed UNK; tagger classes the parser
752 // does not need (e.g. xpos) are simply ignored. This tolerates tagger/parser
753 // feature-set and ordering drift between independently trained models.
754 const auto& dp_input_names =
755 deeplima::graph_dp::impl::GraphDependencyParser::get_input_str_dicts_names();
756 for (size_t j = 0; j + 1 < dp_input_names.size(); ++j)
757 {
758 const std::string& feat_name = dp_input_names[j + 1];
759
760 size_t tagger_col = Vectorizer::uint_feat_extractor_t::NO_COLUMN;
761 for (size_t i = 0; i < class_names.size(); ++i)
762 {
763 if (class_names[i] == feat_name)
764 {
765 tagger_col = i;
766 break;
767 }
768 }
769
770 if (Vectorizer::uint_feat_extractor_t::NO_COLUMN == tagger_col)
771 {
772 std::cerr << "Warning: tagger does not produce feature '" << feat_name
773 << "' expected by the dependency parser; using UNK." << std::endl;
774 }
775
776 feats.emplace_back(Vectorizer::int_feature, feat_name, m_featVectorizers[j]);
777 m_vectorizer.get_uint_feat_extractor().add_feature(feat_name, tagger_col);
778 }
779 // for (const auto& class_name: class_names)
780 // {
781 // int i = 0;
782 // for (const auto& input_str_dicts_names: deeplima::graph_dp::impl::GraphDependencyParser::get_input_str_dicts_names())
783 // {
784 // if (class_name == input_str_dicts_names)
785 // {
786 // feats.emplace_back(Vectorizer::int_feature,
787 // class_name,
788 // m_featVectorizers[i]);
789 //
790 // m_vectorizer.get_uint_feat_extractor().add_feature(class_name, i);
791 // break;
792 // }
793 // i++;
794 // }
795 // }
796 m_vectorizer.init_features(feats);
797
798 m_vectorizer.set_model(this);
799
801 0, num_buffers, buffer_size_per_thread, threads,
802 m_vectorizer.is_precomputing());
803
805 }
806
807 void precompute_inputs(const typename Vectorizer::dataset_t& buffer)
808 {
809 m_vectorizer.precompute(buffer);
810 }
811
812 typedef std::function < void (std::shared_ptr< StdMatrix<uint32_t> > classes,
813 size_t begin, size_t end, size_t slot_idx) > tagging_callback_t;
814
816 {
817 m_callback = fn;
818 }
819
820 virtual ~GraphDpImpl()
821 {
822 // std::cerr << "~GraphDpImpl" << std::endl;
823 }
824
825protected:
826
833
834 inline void send_results(int32_t slot_idx)
835 {
836 // uint8_t lock_count = deeplima::graph_dp::impl::GraphDependencyParser::get_lock_count(slot_idx);
837 // std::cerr << "GraphDpImpl::send_results " << slot_idx+1
838 // << " (lock_count=" << int(lock_count) << ")\n";
841 // std::cerr << "GraphDpImpl::send_results " << slot_idx+1 << ", from=" << from << ", to=" << to << std::endl;
842
844
846 m_last_completed_slot = slot_idx;
847 }
848
849public:
850 inline void send_next_results()
851 {
852 auto slot_idx = m_last_completed_slot;
853 // std::cerr << "GraphDpImpl::send_next_results " << slot_idx+1 << std::endl;
854 if (-1 == slot_idx)
855 {
856 slot_idx = 0;
857 }
858 else
859 {
861 }
862 // int a=0;
864 // std::cerr << "GraphDpImpl::send_next_results " << slot_idx+1
865 // << " (lock_count=" << int(lock_count) << ")" << std::endl;
866
867 while (lock_count > 1)
868 {
869 // Worker still uses this slot. Waiting...
870 // std::cerr << "GraphDpImpl::send_next_results: waiting for slot " << slot_idx+1
871 // << " (lock_count==" << int(lock_count) << ")\n";
872 // deeplima::graph_dp::impl::GraphDependencyParser::pretty_print();
875 }
876 if (1 == lock_count)
877 {
878 // Data is ready. We can return it to caller
879 send_results(slot_idx);
880 }
881 }
882
883 inline void send_all_results()
884 {
885 auto slot_idx = m_last_completed_slot;
886 // std::cerr << "GraphDpImpl::send_all_results" << slot_idx << std::endl;
887 while (true)
888 {
889 if (-1 == slot_idx)
890 {
891 slot_idx = 0;
892 }
893 else
894 {
896 }
897
899 if (0 == lock_count)
900 {
901 // std::cerr << "GraphDpImpl::send_all_results DONE" << std::endl;
902 return;
903 }
904
905 while (lock_count > 1)
906 {
907 // Worker still uses this slot. Waiting...
908 // std::cerr << "GraphDpImpl::send_all_results: waiting for slot " << slot_idx+1
909 // << " (lock_count==" << int(lock_count) << ")\n";
910 // deeplima::graph_dp::impl::GraphDependencyParser::pretty_print();
913 }
914 if (1 == lock_count)
915 {
916 send_results(slot_idx);
917 }
918 }
919 }
920
921protected:
923 {
924 auto slot_idx = m_last_completed_slot;
925 if (-1 == slot_idx)
926 {
927 slot_idx = 0;
928 }
929 else
930 {
932 }
933
935
936 if (1 == lock_count)
937 {
938 // Data is ready. We can return it to caller
939 send_results(slot_idx);
940 }
941 }
942
943 inline void acquire_slot(size_t slot_no)
944 {
945 // m_current_slot_no = deeplima::graph_dp::impl::GraphDependencyParser::get_slot_idx(m_current_timepoint);
947 // std::cerr << "GraphDpImpl::acquiring_slot: " << (slot_no+1) << "; current lock count: " << int(lock_count) << std::endl;
948 // deeplima::graph_dp::impl::GraphDependencyParser::pretty_print();
949
950 while (lock_count > 1)
951 {
952 // Worker still uses this slot. Waiting...
953 // std::cerr << "GraphDpImpl::acquiring_slot, waiting for slot " << (slot_no+1)
954 // << " lock_count=" << int(lock_count) << std::endl;
955 // deeplima::graph_dp::impl::GraphDependencyParser::pretty_print();
958 }
959 if (1 == lock_count)
960 {
961 // Data is ready. We can return it to caller
962 send_results(slot_no);
963 }
964
966 // std::cerr << "GraphDpImpl::acquiring_slot: " << (slot_no+1) << "; before increment_lock_count: " << int(lock_count) << std::endl;
967 // deeplima::graph_dp::impl::GraphDependencyParser::pretty_print();
970 // std::cerr << "GraphDpImpl::acquiring_slot: " << (slot_no+1) << "; after increment_lock_count: " << int(lock_count) << std::endl;
971 // deeplima::graph_dp::impl::GraphDependencyParser::pretty_print();
972 }
973
974public:
975 virtual void handle_token_buffer(size_t slot_no,
976 size_t first_timepoint_idx,
977 const typename Vectorizer::dataset_t& buffer,
978 const std::vector<size_t>& lengths,
979 int timepoints_to_analyze = -1)
980 {
981 // int lock_count = deeplima::graph_dp::impl::GraphDependencyParser::get_lock_count(slot_no);
982 // std::cerr << "GraphDpImpl::handle_token_buffer " << (slot_no+1) << ", "
983 // << first_timepoint_idx
984 // << ", lengths=" << lengths
985 // << ", " << timepoints_to_analyze
986 // << "; lock_count=" << lock_count << std::endl;
988 acquire_slot(slot_no);
989 size_t count = (timepoints_to_analyze > 0) ? timepoints_to_analyze : buffer.size();
990 // Each slot has its own columns of the shared input and output tensors, so
991 // that the workers parse several buffers at once: token i of the buffer is
992 // vectorised at column base + i, its head and label are written there, and
993 // TokenIterator reads them back at base + i (its offset). Heads are local to
994 // the sentence. Writing and reading at different places shifted the heads
995 // (head ≈ gold − first_timepoint_idx, before #197).
996 (void) first_timepoint_idx;
998 for (size_t i = 0; i < count; i++)
999 {
1000 m_vectorizer.vectorize_timepoint(eigen_wrp::EigenMatrixXf::get_tensor(), base + i, buffer[i]);
1001 }
1002
1006
1007 // auto& slot = deeplima::graph_dp::impl::GraphDependencyParser::m_slots[slot_no];
1008
1009 // lock_count = deeplima::graph_dp::impl::GraphDependencyParser::get_lock_count(slot_no);
1010 // std::cerr << "GraphDpImpl::handle_token_buffer slot " << (slot_no+1) << " retrieved: input="
1011 // << slot.m_input_begin << ", " << slot.m_input_end << "; output="
1012 // << slot.m_output_begin << ", " << slot.m_output_end << ", lock_count=" << lock_count
1013 // << std::endl;
1014
1015 deeplima::graph_dp::impl::GraphDependencyParser::start_job(slot_no, timepoints_to_analyze > 0);
1016 // std::cerr << "Slot " << slot_no << " sent to inference engine (graph_dp)" << std::endl;
1017
1018 // No wait here: the workers parse the following buffers meanwhile. Results
1019 // are emitted in order (send_next_results, send_all_results) and a slot's
1020 // region is only rewritten when its buffer comes back, which acquire_buffer()
1021 // and acquire_slot() delay until its results were sent. (#197 waited here,
1022 // when every slot used columns 0 to count: one buffer at a time.)
1023 }
1024
1036
1037protected:
1039 std::shared_ptr<FastTextVectorizer<eigen_wrp::EigenMatrixXf::matrix_t, Eigen::Index>> m_fastText;
1040 std::vector<std::shared_ptr<FeatureVectorizerBase<Eigen::Index>>> m_featVectorizers;
1041
1043
1046
1049
1051};
1052
1054
1056};
1057
1058
1059
1060} // deeplima
1061
1062#endif // DEEPLIMA_DEPENDENCY_PARSER
virtual void load(const std::string &fn, const PathResolver &path_resolver)
virtual void handle_token_buffer(size_t slot_no, size_t first_timepoint_idx, const typename Vectorizer::dataset_t &buffer, const std::vector< size_t > &lengths, int timepoints_to_analyze=-1)
void precompute_inputs(const typename Vectorizer::dataset_t &buffer)
virtual void register_handler(const tagging_callback_t fn)
std::shared_ptr< EmbdUInt64Float > convert(const EmbdStrFloat &src)
std::shared_ptr< FastTextVectorizer< eigen_wrp::EigenMatrixXf::matrix_t, Eigen::Index > > m_fastText
void increment_timepoint(uint64_t &timepoint)
std::function< void(std::shared_ptr< StdMatrix< uint32_t > > classes, size_t begin, size_t end, size_t slot_idx) > tagging_callback_t
void init(size_t threads, size_t num_buffers, size_t buffer_size_per_thread, StringIndex &stridx, const std::vector< std::string > &class_names)
std::vector< std::shared_ptr< FeatureVectorizerBase< Eigen::Index > > > m_featVectorizers
uint8_t token_class(size_t cls_idx) const
TokenIterator(const StringIndex &stridx, const std::vector< token_with_analysis_t > &buffer, std::shared_ptr< StdMatrix< uint32_t > > heads, size_t offset, size_t end, const std::vector< std::string > *rel_names=nullptr)
const enriched_token_t & operator[](size_t idx) const
tokens_with_analysis_t::size_type size() const
enriched_token_buffer_t(const tokens_with_analysis_t &data, const StringIndex &stridx)
const tokens_with_analysis_t::token_t * m_ptoken
void set_token(const typename tokens_with_analysis_t::token_t *p)
std::shared_ptr< StringIndex > m_stridx_ptr
const std::vector< std::string > & get_rel_class_names() const
std::vector< std::string > m_class_names
void setStringIndex(std::shared_ptr< deeplima::StringIndex > stringIndexPtr)
void register_handler(const output_callback_t fn)
void set_classes(size_t idx, const std::string &class_name, const std::vector< std::string > &data)
std::vector< std::vector< std::string > > m_classes
void start_analysis(size_t buffer_idx, size_t first_timepoint_idx, const std::vector< size_t > &lengths, int count=-1)
output_callback_t m_output_callback
void operator()(TokenSequenceAnalyzer<>::TokenIterator &iter)
size_t count_max_tokens_until_eos(TokenSequenceAnalyzer<>::TokenIterator &iter, std::vector< size_t > &lengths)
eigen_wrp::EigenMatrixXf Matrix
DependencyParser(const std::string &model_fn, const PathResolver &path_resolver, std::shared_ptr< StringIndex > stridx, const std::vector< std::string > &input_class_names, size_t buffer_size, size_t num_buffers, size_t threads=1)
std::vector< tokens_with_analysis_t > m_buffers
std::vector< size_t > m_lengths
std::function< void(const StringIndex &stridx, const std::vector< token_with_analysis_t > &tokens, std::shared_ptr< StdMatrix< uint32_t > > heads, size_t begin, size_t end) > output_callback_t
void carry_open_sentence(size_t first_timepoint_idx)
deeplima::graph_dp::eigen_impl::FeaturesVectorizer< enriched_token_buffer_t, typename enriched_token_buffer_t::token_t > Vectorizer
const M & get_tensor() const
Definition embd_dict.h:91
std::string resolve(const std::string &prefix, const std::string &path, const std::vector< std::string > &accepted_ext={}) const
virtual void init(uint32_t max_feat, uint32_t overlap, uint32_t num_slots, uint32_t slot_len, uint32_t num_threads, bool precomputed_input=false)
std::shared_ptr< StdMatrix< uint32_t > > get_output()
void set_slot_begin(uint32_t idx, uint64_t slot_begin)
void start_job(uint32_t idx, bool no_more_data=false)
void set_slot_lengths(uint32_t idx, const std::vector< size_t > &lengths)
idx_t get_idx(const char *p, size_t len)
Definition str_index.h:24
A kind of RnnSequenceClassifier, used for named entities tagging (?), but also the parent of TaggingI...
Definition ner.h:129
EigenMatrix< Eigen::MatrixXf > EigenMatrixXf
RnnSequenceClassifier< Model, BaseMatrix, uint32_t > GraphDependencyParser
Definition graph_dp.h:78
Edit rules for lemmatizing words absent from the lemma dictionary.
TStringIndex< std::string, std::u32string, uint32_t > StringIndex
Definition str_index.h:119
@ paragraph_brk
Definition token_type.h:22
@ sentence_brk
Definition token_type.h:21
EmbdDict< std::string, Eigen::MatrixXf, Eigen::Index > EmbdStrFloat
Definition embd_dict.h:209
STL namespace.
token_with_analysis_t(const token_with_analysis_t &t)=default
token_with_analysis_t & operator=(const token_with_analysis_t &t)=default
token_buffer_t< token_with_analysis_t > Parent
tokens_with_analysis_t(size_t size, size_t num_classes)
token_flags_t m_flags
Definition token_type.h:44
token_t(uint16_t offset=0, uint16_t len=0, uint32_t idx=0, token_flags_t flags=token_flags_t::none)
Definition token_type.h:37