LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
RnnDependencyParser.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
2//
3// SPDX-License-Identifier: MIT
4
5#include <QtCore/QTemporaryFile>
6#include <QtCore/QRegularExpression>
7#include <QDir>
8
9
14
24
25#include <queue>
26
27#include "RnnDependencyParser.h"
30#include "deeplima/token_type.h"
35
36#include <thread>
37#include <algorithm>
38#include <eigen3/Eigen/Core>
39
40
41#define DEBUG_THIS_FILE true
42
44using namespace Lima::Common::PropertyCode;
45using namespace Lima::Common::MediaticData;
46using namespace Lima::Common::Misc;
48using namespace Lima::Common::AnnotationGraphs;
49using namespace deeplima;
50
51
53
54// Tokens per buffer of the deeplima parser, its synthetic <ROOT>s included. A
55// longer sentence is parsed in parts, each with its own <ROOT> (see process())
56static constexpr size_t DP_BUFFER_SIZE = 128;
57
58#if defined(DEBUG_LP) && defined(DEBUG_THIS_FILE)
59#define LOG_MESSAGE(stream, msg) stream << msg;
60#define LOG_MESSAGE_WITH_PROLOG(stream, msg) SALOGINIT; LOG_MESSAGE(stream, msg);
61#else
62 #define LOG_MESSAGE(stream, msg) ;
63 #define LOG_MESSAGE_WITH_PROLOG(stream, msg) ;
64#endif
65
67
69
71{
72public:
75 void init(GroupConfigurationStructure& unitConfiguration);
76 void analyzer(std::shared_ptr<TokenSequenceAnalyzer<>::TokenIterator> ti);
78 MediaId m_language;
79 QString m_data;
80 std::shared_ptr<DependencyParser> m_dependencyParser = nullptr;
81 // std::shared_ptr<TokenSequenceAnalyzer<>> m_sequenceAnalyser = nullptr;
82 std::function<void()> m_load_fn;
83 std::shared_ptr< StringIndex > m_stridx;
85 std::vector< std::map<std::string, std::string> > m_tags;
86 std::vector<QString> m_lemmas;
87 // std::vector<typename DependencyParser::token_with_analysis_t> m_tokens;
88 std::vector<std::string> m_class_names;
89 std::vector< std::vector<std::string> > m_classes;
90 std::vector<uint32_t> m_heads;
91 std::vector<std::string> m_deprels; // predicted deprel per token, parallel to m_heads
92 std::vector<bool> m_isRoot; // true for synthetic <ROOT> tokens (no real vertex)
93 std::vector<std::string> m_relClassNames; // deprel id -> string, from the model
95 bool m_enabled; // false when no parser model is available: process() is a no-op
96 size_t m_threads; // inference workers of the parser
97};
98
100 THIS_FILE_LOGGING_CATEGORY()),
101 m_stridx(new StringIndex()),
102 m_loaded(false),
103 m_enabled(true),
104 m_threads(1)
105{
106}
107
111
116
118{
119 LOG_MESSAGE_WITH_PROLOG(LDEBUG, "RnnDependencyParser::init");
120
121 m_d->m_language = manager->getInitializationParameters().media;
122
123 m_d->init(unitConfiguration);
124
125}
126
128{
130 TimeUtilsController RnnDependencyParserProcessTime("RnnDependencyParser");
131 SALOGINIT;
132 LOG_MESSAGE(LDEBUG, "RnnDependencyParser::process");
133 if (!m_d->m_enabled)
134 {
135 LOG_MESSAGE(LDEBUG, "RnnDependencyParser disabled (no model); skipping.");
136 return SUCCESS_ID;
137 }
138 // Ensure the model is loaded (no-op if already loaded or not lazy-initialized).
139 if (m_d->m_load_fn)
140 {
141 m_d->m_load_fn();
142 }
143 auto tiData = std::dynamic_pointer_cast<TokenIteratorData>(analysis.getData("TokenIterator"));
144 if (tiData == nullptr)
145 {
146 SALOGINIT;
147 LERROR << "Can't Process RnnDependencyParser : missing data 'TokenIterator'";
148 return MISSING_DATA;
149 }
150 if (tiData->empty())
151 {
152 return SUCCESS_ID; // no token
153 }
154 auto stridxPtr = tiData->getStringIndex();
155 m_d->m_dependencyParser->setStringIndex(stridxPtr);
156 auto tokenIterator = tiData->getTokenIterator();
157
158 auto anagraph = std::dynamic_pointer_cast<AnalysisGraph>(analysis.getData("PosGraph"));
159 if (anagraph == nullptr)
160 {
161 LERROR << "no PosGraph ! abort";
162 return MISSING_DATA;
163 }
164
165 auto syntacticData = std::dynamic_pointer_cast<SyntacticAnalysis::SyntacticData>(analysis.getData("SyntacticData"));
166 if (syntacticData == nullptr)
167 {
168 syntacticData = std::make_shared<SyntacticAnalysis::SyntacticData>(anagraph.get(), nullptr);
169 analysis.setData("SyntacticData",syntacticData);
170 }
171 syntacticData->setupDependencyGraph();
172
173 m_d->analyzer(tokenIterator);
174
175 const auto& languageData = static_cast<const Common::MediaticData::LanguageData&>(
177
178 auto sd = std::dynamic_pointer_cast<SegmentationData>(
179 analysis.getData(m_d->m_data.toStdString()));
180 if (sd == nullptr)
181 {
182 LERROR << "RnnDependencyParser: missing segmentation data '" << m_d->m_data << "'";
183 return MISSING_DATA;
184 }
185 LinguisticGraph* posGraph = anagraph->getGraph();
186 const LinguisticGraphVertex lastVertex = anagraph->lastVertex();
187
188 // The parser emits one sentence at a time: a synthetic <ROOT> followed by the
189 // sentence's real tokens, whose heads are sentence-LOCAL (0 == that sentence's
190 // root, 1..k == its tokens in order). Build, per sentence/segment, the ordered
191 // list of real token vertices by walking the PoS graph the same way the CoNLL
192 // dumper does (ordered[0] is the boundary, rendered as HEAD 0 / DEPREL root).
193 std::vector<LinguisticGraphVertex> segmentBegin;
194 std::vector<std::vector<LinguisticGraphVertex>> segmentTokens;
195 for (auto segIt = sd->getSegments().begin(); segIt != sd->getSegments().end();
196 ++segIt)
197 {
198 const LinguisticGraphVertex sentBegin = segIt->getFirstVertex();
199 const LinguisticGraphVertex sentEnd = segIt->getLastVertex();
200 segmentBegin.push_back(sentBegin);
201 segmentTokens.emplace_back();
202 std::vector<LinguisticGraphVertex>& tokens = segmentTokens.back();
203
204 std::queue<LinguisticGraphVertex> toVisit;
205 std::set<LinguisticGraphVertex> visited;
206 toVisit.push(sentBegin);
207 while (!toVisit.empty())
208 {
209 const LinguisticGraphVertex v = toVisit.front();
210 toVisit.pop();
211 if (visited.count(v) > 0)
212 {
213 continue;
214 }
215 visited.insert(v);
216 // Real tokens (skip the sentence boundary and any non-token vertex).
217 if (v != sentBegin && get(vertex_token, *posGraph, v) != nullptr)
218 {
219 tokens.push_back(v);
220 }
221 if (v == sentEnd)
222 {
223 break;
224 }
225 LinguisticGraphOutEdgeIt outIt, outItEnd;
226 for (boost::tie(outIt, outItEnd) = boost::out_edges(v, *posGraph);
227 outIt != outItEnd; ++outIt)
228 {
229 const LinguisticGraphVertex tgt = boost::target(*outIt, *posGraph);
230 if (visited.count(tgt) == 0 && tgt != lastVertex)
231 {
232 toVisit.push(tgt);
233 }
234 }
235 }
236 }
237
238 // Walk the parser output. Each <ROOT> starts a new sentence (matched to the
239 // next segment in order); the following tokens map to that sentence's vertices.
240 // A sentence longer than the parser's buffer comes in parts, each after its
241 // own <ROOT> and with heads local to the part: such a <ROOT> continues the
242 // sentence. Taking it for a new one shifted every following sentence onto
243 // the previous one's vertices (UD_Spanish-AnCora test, a 128-word sentence:
244 // LAS 85.9 -> 13.7 for the rest of the text).
245 int segIdx = -1;
246 size_t localPos = 0; // 1-based position of the current token within its sentence
247 size_t partOffset = 0; // tokens of the sentence in its previous parts
248 for (size_t i = 0; i < m_d->m_heads.size(); ++i)
249 {
250 if (i < m_d->m_isRoot.size() && m_d->m_isRoot[i])
251 {
252 const bool cut = segIdx >= 0 && segIdx < static_cast<int>(segmentTokens.size())
253 && localPos < segmentTokens[segIdx].size()
254 && localPos - partOffset + 1 >= DP_BUFFER_SIZE;
255 if (cut)
256 {
257 partOffset = localPos;
258 }
259 else
260 {
261 ++segIdx;
262 localPos = 0;
263 partOffset = 0;
264 }
265 continue;
266 }
267 ++localPos;
268 if (segIdx < 0 || segIdx >= static_cast<int>(segmentTokens.size()))
269 {
270 continue;
271 }
272 const std::vector<LinguisticGraphVertex>& tokens = segmentTokens[segIdx];
273 if (localPos > tokens.size())
274 {
275 continue; // parser/graph token counts disagree for this sentence
276 }
277 // Sentence-local: the parser's heads are local to the part (0 stays the
278 // root: a cut sentence has one root per part)
279 const size_t head = m_d->m_heads[i] == 0 ? 0 : m_d->m_heads[i] + partOffset;
280 const std::string& deprel = (i < m_d->m_deprels.size())
281 ? m_d->m_deprels[i]
282 : std::string("dep");
284 languageData.getSyntacticRelationId(deprel);
285 const LinguisticGraphVertex src = tokens[localPos - 1];
286 // head == 0 -> this sentence's root boundary (HEAD 0 / DEPREL root);
287 // otherwise the head-th token of the same sentence.
288 const LinguisticGraphVertex dest =
289 (head == 0 || head > tokens.size()) ? segmentBegin[segIdx]
290 : tokens[head - 1];
291 syntacticData->addRelationNoChain(relType, src, dest);
292 }
293 TimeUtils::logElapsedTime("RnnDependencyParser");
294 return SUCCESS_ID;
295}
296
298{
299
300 m_data = QString(getStringParameter(unitConfiguration, "data", 0, "SentenceBoundaries").c_str());
301 // Optional "threads": the parser's inference workers, by default the cores
302 // (it uses at most one per buffer, 8). Each buffer has its own columns of
303 // the parser's tensors and the results come in order, so the output does
304 // not depend on it
305 const int threads = getIntParameter(unitConfiguration, "threads", 0, 0);
306 m_threads = threads > 0 ? static_cast<size_t>(threads)
307 : std::max<size_t>(1, std::thread::hardware_concurrency());
308 QString dependency_parser_model_prefix = getStringParameter(unitConfiguration, "dependency_parser_model_prefix", ConfigurationHelper::REQUIRED | ConfigurationHelper::NOT_EMPTY).c_str();
309 QString tagger_model_prefix = getStringParameter(unitConfiguration, "tagger_model_prefix", ConfigurationHelper::REQUIRED | ConfigurationHelper::NOT_EMPTY).c_str();
310 LOG_MESSAGE_WITH_PROLOG(LDEBUG, "RnnDependencyParserPrivate::init dependency parser model: " << dependency_parser_model_prefix);
311
312 QString lang_str = MediaticData::single().media(m_language).c_str();
313 QString resources_path = MediaticData::single().getResourcesPath().c_str();
314 QString dependency_parser_name = dependency_parser_model_prefix;
315 QString tagger_model_name = tagger_model_prefix;
316
317 std::string udlang;
318 MediaticData::single().getOptionValue("udlang", udlang);
319
320 if (!fix_lang_codes(lang_str, udlang))
321 {
323 "RnnDependencyParserPrivate::init: Can't parse language id " << udlang.c_str(),
325 }
326
327 dependency_parser_name.replace(QString("$udlang"), QString(udlang.c_str()));
328 tagger_model_name.replace(QString("$udlang"), QString(udlang.c_str()));
329
330 auto dependency_parser_file_name = findFileInPaths(resources_path,
331 QString::fromUtf8("/RnnDependencyParser/%1/%2.pt")
332 .arg(lang_str, dependency_parser_name));
333
334 auto tagger_model_file_name = findFileInPaths(resources_path,
335 QString::fromUtf8("/RnnTagger/%1/%2.pt")
336 .arg(lang_str, tagger_model_name));
337 if (dependency_parser_file_name.isEmpty())
338 {
339 // No dependency parser model for this language yet: disable the unit
340 // rather than aborting the whole pipeline. process() becomes a no-op, so
341 // the rest of the pipeline (tagging, lemmatization, dumping) still runs.
342 SALOGINIT;
343 LWARN << "RnnDependencyParserPrivate::init: no dependency parser model found for "
344 << lang_str << " (" << dependency_parser_name
345 << "); dependency parsing disabled.";
346 m_enabled = false;
347 return;
348 }
349
350 if (tagger_model_file_name.isEmpty())
351 {
352 throw InvalidConfiguration("RnnTokensAnalyzerPrivate::init: tagger model file not found.");
353 }
354
355 LOG_MESSAGE(LDEBUG, "RnnDependencyParserPrivate::init call TokenSequenceAnalyzer<>().get_classes_from_fn");
356 TokenSequenceAnalyzer<>().get_classes_from_fn(tagger_model_file_name.toStdString(), m_class_names, m_classes);
357 auto temp_classes_names = m_class_names;
358 auto temp_classes = m_classes;
359 temp_classes_names.erase(temp_classes_names.begin()+1);
360 temp_classes.erase(temp_classes.begin()+1);
361 m_load_fn = [this, dependency_parser_file_name, tagger_model_file_name, temp_classes_names, temp_classes]()
362 {
363 if (m_loaded)
364 {
365 return;
366 }
367
368 // Disable Eigen intra-op (OpenMP) parallelism process-wide. The neural
369 // units already parallelize at the sentence/slot level, so letting Eigen
370 // also fork a parallel region for every small matmul only oversubscribes
371 // the cores. For the parser this is catastrophic: it does dozens of tiny
372 // biaffine products per sentence, and the OpenMP fork/join overhead dwarfs
373 // the arithmetic (measured ~20x slowdown). This is a global Eigen setting,
374 // so it also benefits the tagger/segmenter units in the same process.
375 Eigen::setNbThreads(1);
376
377 // Several inference workers parse buffers in parallel (see "threads")
378 m_dependencyParser = std::make_shared<DependencyParser>(dependency_parser_file_name.toStdString(),
380 for (size_t i = 0; i < temp_classes.size(); i++)
381 {
382 m_dependencyParser->set_classes(i, temp_classes_names[i], temp_classes[i]);
383 }
384 // The model's relations missing from the language's relationList
385 // would get the id 0: their arcs were dropped (dep "_", e.g. GUM's
386 // obl:unmarked with the English MERGE model)
387 auto& languageData = static_cast<Common::MediaticData::LanguageData&>(
389 for (const auto& relation : m_dependencyParser->get_rel_class_names())
390 {
391 if (!relation.empty())
392 {
393 languageData.addSyntacticRelation(relation);
394 }
395 }
396 m_loaded = true;
397 };
398
399 if (!isInitLazy())
400 {
401 m_load_fn();
402 }
403
404
405}
406
408{
409 m_heads.clear();
410 m_deprels.clear();
411 m_isRoot.clear();
412 // deprel id -> string vocabulary from the model; empty if the model has no
413 // label decoder (then deprel() falls back to "dep").
414 m_relClassNames = m_dependencyParser->get_rel_class_names();
415 m_dependencyParser->register_handler([this](const StringIndex& stridx,
416 const std::vector<typename DependencyParser::token_with_analysis_t>& tokens,
417 std::shared_ptr< StdMatrix<uint32_t> > classes,
418 size_t begin,
419 size_t end)
420 {
421 typename DependencyParser::TokenIterator dti(stridx,
422 tokens,
423 classes,
424 begin,
425 end,
426 m_relClassNames.empty() ? nullptr : &m_relClassNames);
428 });
429 (*m_dependencyParser)(*ti);
430 m_dependencyParser->finalize();
431}
432
434{
435 // The iterator prefixes the stream with a synthetic <ROOT> token; real tokens
436 // carry global head indices (0 == root). Mark the <ROOT>(s) so process() skips
437 // them when assigning relations to actual graph vertices.
438 while (!ti.end())
439 {
440 m_heads.push_back(ti.head());
441 m_deprels.push_back(ti.deprel());
442 m_isRoot.push_back(std::string(ti.form()) == "<ROOT>");
443 ti.next();
444 }
445}
446
447}
This file is the main header file for the data related to annotation graphs.
#define CONFIGURATIONHELPER_LOGGING_INIT(X)
#define LOG_MESSAGE_WITH_PROLOG(stream, msg)
#define LOG_MESSAGE(stream, msg)
#define LWARN
Definition LimaCommon.h:160
#define LIMA_EXCEPTION_SELECT_LOGINIT(X, Y, Z)
This macro writes the message Y to the error stream configured by its first parameter X,...
Definition LimaCommon.h:332
#define LDEBUG
Definition LimaCommon.h:157
#define LERROR
Definition LimaCommon.h:161
A graph structure for linguistic analysis.
@ vertex_token
LinguisticGraph::vertex_descriptor LinguisticGraphVertex
LinguisticGraph::out_edge_iterator LinguisticGraphOutEdgeIt
boost::adjacency_list< boost::vecS, boost::vecS, boost::bidirectionalS, LinguisticVertexProperties > LinguisticGraph
Property to identify the chains in the graph.
#define SALOGINIT
#define RNNDEPENDENCYPARSER_CLASSID
Defines a Factory to create Object of type Base.
Data used for the syntactic analyzis of texts.
Holds all data that pass through the ProcessUnits Analysis data are shared pointers,...
std::shared_ptr< AnalysisData > getData(const QString &id)
return AnalysisData by id
void setData(const QString &id, std::shared_ptr< AnalysisData > data)
set an analysisData with the given id.
Holds linguistic data for one language.
const MediaData & mediaData(MediaId media) const
InitializableObjectManager< MediaProcessUnit, MediaProcessUnitInitializationParameters > Manager
Use this exception to signal an error in one of the configuration files.
Definition LimaCommon.h:345
void getIntParameter(Common::XMLConfigurationFiles::GroupConfigurationStructure &unitConfiguration, const std::string &name, int &value, int flags=Flags::REQUIRED, int default_value=0)
void getStringParameter(Common::XMLConfigurationFiles::GroupConfigurationStructure &unitConfiguration, const std::string &name, std::string &value, int flags=Flags::REQUIRED, std::string default_value="")
ConfigurationHelper(const std::string &processUnitName, const std::string &loggingCategory)
void analyzer(std::shared_ptr< TokenSequenceAnalyzer<>::TokenIterator > ti)
LimaStatusCode process(AnalysisContent &analysis) const override
Process on data in analysisContent.
void init(Lima::Common::XMLConfigurationFiles::GroupConfigurationStructure &unitConfiguration, Manager *manager) override
static const MediaticData & single()
Definition Singleton.h:51
static MediaticData & changeable()
Definition Singleton.h:71
This file contains a class to control log of informations about time, such as logging cumulated time ...
static void logElapsedTime(const std::string &mess, const std::string &taskCategory=std::string(""))
log the number of microseconds since last UpdateCurrentTime
static void updateCurrentTime(const std::string &taskCategory=std::string(""))
store current time for new elapsed time computation
void get_classes_from_fn(const std::string &fn, std::vector< std::string > &classes_names, std::vector< std::vector< std::string > > &classes)
QString findFileInPaths(const QString &paths, const QString &fileName, const QChar &separator)
Find the given file in the given paths.
static SimpleFactory< MediaProcessUnit, RnnDependencyParser > RnnDependencyParserFactory(RNNDEPENDENCYPARSER_CLASSID)
bool fix_lang_codes(QString &lang_str, std::string &udlang)
LimaStatusCode
Definition LimaCommon.h:236
@ SUCCESS_ID
Definition LimaCommon.h:237
@ MISSING_DATA
Definition LimaCommon.h:243
Edit rules for lemmatizing words absent from the lemma dictionary.
TStringIndex< std::string, std::u32string, uint32_t > StringIndex
Definition str_index.h:119