LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
train_segmentation.cpp
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
9
12
14
15#include "char_dict_builder.h"
16#include "char_seq_vectorizer.h"
17#include "train_segmentation.h"
18
19#include <c10/util/Exception.h>
20
21#include <fstream>
22#include <iostream>
23#include <memory>
24#include <memory>
25#include <vector>
26
27using namespace std;
28
29using namespace deeplima::segmentation;
30using namespace deeplima::segmentation::train;
31using namespace deeplima::segmentation::impl;
32using namespace deeplima::nets;
33using namespace deeplima;
34
35template <class M>
36std::shared_ptr<M> vectorize_gold(const CoNLLU::Annotation& annot, int64_t len, bool eos, bool mwt)
37{
38 auto out = std::make_shared<M>(len, 1);
39
40 const auto& tokens = annot.get_tokens();
41 size_t p = 0;
42 for (size_t i = 0; i < tokens.size(); i++)
43 {
44 const auto& t = tokens[i];
45 while (p < t.m_pos)
46 {
47 out->set(p, 0, segm_tag_t::X);
48 p++;
49 }
50
51 if (t.m_len == 0)
52 {
53 throw std::runtime_error("vectorize_gold length should be 0");
54 }
55
56 // A surface token that is a multiword token (e.g. "du") gets the MWT
57 // variant of its end tag so the model learns to predict, in context, which
58 // tokens should be expanded into sub-words.
59 const bool is_mwt = mwt && t.is_multiword();
60
61 if (t.m_len == 1)
62 {
63 if (eos && t.eos())
64 {
65 out->set(p, 0, is_mwt ? segm_tag_t::S_EOS_MWT : segm_tag_t::S_EOS);
66 }
67 else
68 {
69 out->set(p, 0, is_mwt ? segm_tag_t::S_MWT : segm_tag_t::S);
70 }
71 p++;
72 continue;
73 }
74
75 out->set(p, 0, segm_tag_t::B);
76 p++;
77 while (p < t.m_pos + t.m_len - 1)
78 {
79 out->set(p, 0, segm_tag_t::I);
80 p++;
81 }
82 if (eos && t.eos())
83 {
84 out->set(p, 0, is_mwt ? segm_tag_t::E_EOS_MWT : segm_tag_t::E_EOS);
85 }
86 else
87 {
88 out->set(p, 0, is_mwt ? segm_tag_t::E_MWT : segm_tag_t::E);
89 }
90
91 p++;
92 }
93
94 return out;
95}
96
100
103 int gpuid)
104{
105 std::vector<ngram_descr_t> ngram_descr = {
108 { -1, 3, ngram_descr_t::char_ngram },
111 { -1, 3, ngram_descr_t::type_ngram },
112 { 0, 1, ngram_descr_t::script_ngram } };
113
114 const size_t c = params.m_char_embd_dim;
115 std::vector<embd_descr_t> embd_descr = { { "char1gram", c ? c : 2 }, { "char2gram", c ? c : 3 },
116 { "char3gram", c ? c : 4 },
117 { "class1gram", 2 }, { "class2gram", 2 }, { "class3gram", 2 },
118 { "scriptchange", 1 } };
119
120 // The lexicon feature: words of an external list ending at each character
121 std::shared_ptr<SegmLexicon> lexicon;
122 if (!params.m_lexicon_fn.empty())
123 {
124 lexicon = std::make_shared<SegmLexicon>(params.m_lexicon_fn);
125 std::cerr << "Lexicon feature: " << lexicon->size() << " words from " << params.m_lexicon_fn
126 << std::endl;
127 ngram_descr.emplace_back(0, 1, ngram_descr_t::lexicon_ngram);
128 embd_descr.emplace_back("lexicon", 4);
129 // Beside the model, where SegmentationImpl::load finds it
130 std::ifstream src(params.m_lexicon_fn, std::ios::binary);
131 std::ofstream dst(params.m_output_model_name + ".pt.lex", std::ios::binary);
132 dst << src.rdbuf();
133 if (!dst)
134 {
135 throw std::runtime_error("Can't write " + params.m_output_model_name + ".pt.lex");
136 }
137 }
138
139 const CoNLLU::Document& train_doc = tb.get_doc("train");
140 uint64_t train_char_counter = 0;
141
142 DictionaryBuilder dict_builder(ngram_descr);
143 dict_builder.set_lexicon(lexicon.get());
144 auto dicts = dict_builder.process(train_doc.get_original_text(), params.m_min_ipm,
145 train_char_counter);
146
147 if (train_char_counter >= std::numeric_limits<int64_t>::max())
148 {
149 throw std::overflow_error("Too much characters in training set.");
150 }
151
152 Utf8CharSeqToTorchMatrix vectorizer(ngram_descr);
153 vectorizer.set_lexicon(lexicon.get());
154 vectorizer.set_dicts(dicts);
155 auto train_input = vectorizer.process(train_doc.get_original_text(),
156 (int64_t)train_char_counter);
157
158 const auto& dev_doc = tb.get_doc("dev");
159 auto dev_input = vectorizer.process(dev_doc.get_original_text(), dev_doc.get_text().size() + 1);
160
161 auto train_gold = vectorize_gold<TorchMatrix<int64_t>>(tb.get_annot("train"), (int64_t)train_char_counter,
162 params.train_ss, params.train_mwt);
163
164 auto dev_gold = vectorize_gold<TorchMatrix<int64_t>>(tb.get_annot("dev"), dev_doc.get_text().size() + 1,
165 params.train_ss, params.train_mwt);
166
167 std::vector<rnn_descr_t> rnn_descr = { rnn_descr_t( params.m_rnn_hidden_dim ) };
168
169
170 // Class count: 5 (tokenization only), 7 (+ sentence segmentation), or 11
171 // (+ the four multiword-token end-tag variants). MWT implies sentence seg.
172 const uint32_t num_classes = params.train_mwt ? 11 : (params.train_ss ? 7 : 5);
173
174 BiRnnClassifierForSegmentation model(std::move(dicts),
175 ngram_descr,
176 embd_descr,
177 rnn_descr,
178 "tokens",
179 num_classes,
180 params.m_input_dropout_prob);
181
182 // Sentence ends: their loss weight, their F1 at evaluation, the epoch choice
183 if (params.train_ss)
184 {
185 std::vector<int64_t> eos = { segm_tag_t::E_EOS, segm_tag_t::S_EOS };
186 if (params.train_mwt)
187 {
188 eos.push_back(segm_tag_t::E_EOS_MWT);
189 eos.push_back(segm_tag_t::S_EOS_MWT);
190 }
191 model->set_eos_classes(eos, params.m_select_eos);
192 if (params.m_eos_weight != 1.0f)
193 {
194 std::vector<float> weights(num_classes, 1.0f);
195 for (int64_t k : eos)
196 {
197 weights[k] = params.m_eos_weight;
198 }
199 model->set_class_weights(weights);
200 }
201 }
202 model->set_schedule(params.m_lr_decay, params.m_max_epochs_without_improvement);
203
204 torch::optim::Adam optimizer(model->parameters(),
205 torch::optim::AdamOptions(params.m_learning_rate)
206 .weight_decay(params.m_weight_decay)
207 .betas({params.m_beta_one, params.m_beta_two}));
208
209 std::string dev = "cpu";
210 if (gpuid >= 0)
211 {
212 std::ostringstream oss;
213 oss << "cuda:" << gpuid;
214 dev = oss.str();
215 }
216 torch::Device device(dev);
217
218 train_input->to(device);
219 train_gold->to(device);
220
221 dev_input->to(device);
222 dev_gold->to(device);
223
224 model->to(device);
225
226 try
227 {
228 model->train(params.m_max_epochs, params.m_batch_size, params.m_sequence_length, { "tokens" },
229 *(train_input.get()), *(train_gold.get()),
230 *(dev_input.get()), *(dev_gold.get()),
231 optimizer, params.m_output_model_name, device);
232 }
233 catch (const c10::Error& e)
234 {
235 std::cerr << "Exception in model training: " << e.what() << std::endl;
236 return 1;
237 }
238
239 return 0;
240}
241
const std::vector< token_t > & get_tokens() const
Definition treebank.h:147
const std::string & get_original_text() const
Definition treebank.h:72
const Document & get_doc(const std::string &name) const
Definition treebank.h:479
const Annotation & get_annot(const std::string &name) const
Definition treebank.h:489
void set_dicts(DictsHolder &dicts)
void set_lexicon(const impl::SegmLexicon *lexicon)
std::shared_ptr< Matrix > process(const std::string &text, int64_t len=-1)
DictsHolder process(const std::string &text, uint32_t min_ipm, uint64_t &char_counter)
void set_lexicon(const impl::SegmLexicon *lexicon)
Edit rules for lemmatizing words absent from the lemma dictionary.
STL namespace.
DictionaryBuilderImpl< CharNgramEncoder< Utf8Reader<> > > DictionaryBuilder
int train_segmentation_model(const CoNLLU::Treebank &tb, deeplima::segmentation::train::train_params_segmentation_t &params, int gpuid)
std::shared_ptr< M > vectorize_gold(const CoNLLU::Annotation &annot, int64_t len, bool eos, bool mwt)
CharSeqVectorizerImpl< CharNgramEncoder< Utf8Reader<> >, TorchMatrix< int64_t >, DictHolderAdapter< UInt64Dict, TorchMatrix< int64_t > > > Utf8CharSeqToTorchMatrix