LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
birnn_seq_classifier.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#include <algorithm>
7#include <iostream>
8#include <limits>
9#include <map>
10#include <string>
11
13
14using namespace std;
15using torch::indexing::Slice;
16
17namespace deeplima
18{
19namespace nets
20{
21
22torch::Tensor BiRnnClassifierImpl::predict(const string& output_name,
23 const torch::Tensor& input,
24 const torch::Device& device)
25{
26 vector<string> output_names = { output_name };
27 return predict(output_names, input, device);
28}
29
30torch::Tensor BiRnnClassifierImpl::predict(const vector<string>& output_names,
31 const torch::Tensor& input,
32 const torch::Device& device)
33{
34 map<string, torch::Tensor> current_inputs;
35 split_input(input, current_inputs, device);
36
37 auto output_map = forward(current_inputs, output_names.begin(), output_names.end());
38
39 torch::Tensor prediction = torch::zeros({ input.size(0), long(output_names.size()) },
40 torch::TensorOptions().dtype(torch::kInt64));
41 for (size_t i = 0; i < output_names.size(); ++i)
42 {
43 const string& task_name = output_names[i];
44 torch::Tensor& output = output_map[task_name];
45 torch::Tensor o = output.reshape({-1, output.size(2)});
46 prediction.index({ Slice(), Slice(i, i+1) }) = o.argmax(1);
47 }
48
49 return prediction;
50}
51
52void BiRnnClassifierImpl::predict(size_t /*worker_id*/,
53 const torch::Tensor& inputs,
54 int64_t input_begin,
55 int64_t input_end,
56 int64_t output_begin,
57 int64_t output_end,
58 std::shared_ptr< StdMatrix<uint8_t> >& output,
59 const std::vector<std::string>& outputs_names,
60 const torch::Device& device)
61{
62 assert(output->size() == outputs_names.size());
63
64 int64_t start_shift = output_begin - input_begin;
65 assert(start_shift >= 0);
66 int64_t end_shift = input_end - output_end;
67 assert(end_shift >= 0);
68
69 const torch::Tensor inputs_slice = inputs.index({ Slice(input_begin, input_end), Slice() });
70
71 map<string, torch::Tensor> current_inputs;
72 split_input(inputs_slice, current_inputs, device);
73
74 auto output_map = forward(current_inputs, outputs_names.begin(), outputs_names.end());
75 for (size_t i = 0; i < outputs_names.size(); i++)
76 {
77 torch::Tensor& one_task_output = output_map[outputs_names[i]];
78 torch::Tensor o = one_task_output.reshape({-1, one_task_output.size(2)});
79 const torch::Tensor output_tensor = o.argmax(1);
80 torch::TensorAccessor<int64_t, 1> accessor = output_tensor.accessor<int64_t, 1>();
81 for (int64_t p = start_shift; p < output_tensor.size(0) - end_shift; p++)
82 {
83 (*output)[i][input_begin + p] = accessor[p];
84 }
85 }
86}
87
88void BiRnnClassifierImpl::split_input(const torch::Tensor& src,
89 map<string, torch::Tensor>& dst,
90 const torch::Device& device)
91{
92 int64_t c = 0;
93 for (size_t i = 0; i < m_embd_descr.size(); i++)
94 {
95 if (dst.end() != dst.find(m_embd_descr[i].m_name))
96 {
97 throw std::runtime_error("Duplicates in embd list.");
98 }
99 if (src.sizes().size() == 2)
100 {
101 if (m_embd_descr[i].m_type == 1)
102 {
103 dst[m_embd_descr[i].m_name]
104 = src.index({Slice(), Slice(c, c+1) }).reshape({ (int64_t)src.size(0), 1 }).to(device);
105 c++;
106 }
107 else if (m_embd_descr[i].m_type == 0)
108 {
109 //dst[m_embd_descr[i].m_name]
110 // = src.index({Slice(), Slice(i, i+m_embd_descr[i].m_dim) }).reshape({ (int64_t)src.size(0), m_embd_descr[i].m_dim });
111 }
112 }
113 else if (src.sizes().size() == 3)
114 {
115 //std::cout << "src.sizes() == " << src.sizes() << std::endl;
116 if (m_embd_descr[i].m_type == 1)
117 {
118 dst[m_embd_descr[i].m_name]
119 = src.index({Slice(), Slice(), Slice(c, c+1) }).reshape({ (int64_t)src.size(0), -1 }).to(device);
120 c++;
121 }
122 else if (m_embd_descr[i].m_type == 0)
123 {
124 //dst[m_embd_descr[i].m_name]
125 // = src.index({Slice(), Slice(), Slice(i, i+m_embd_descr[i].m_dim) }).reshape({ (int64_t)src.size(0), m_embd_descr[i].m_dim });
126 }
127 }
128 //std::cout << "dst[" << m_embd_descr[i].m_name << "]=" << dst[m_embd_descr[i].m_name].sizes() << std::endl;
129 }
130}
131
132void BiRnnClassifierImpl::evaluate(const vector<string>& output_names,
133 const TorchMatrix<int64_t>& input,
134 const TorchMatrix<int64_t>& gold,
135 epoch_stat_t& stat,
136 const torch::Device& device)
137{
138 map<string, torch::Tensor> current_inputs;
139 split_input(input.get_tensor(), current_inputs, device);
140
141 auto target = gold.get_tensor().reshape({ -1, long(output_names.size()) }).to(device);
142
143 evaluate(output_names, current_inputs, target, stat, device);
144}
145
147 const map<string, torch::Tensor>& input,
148 const vector<string>& output_names)
149{
150 // Every input is time-major (dimension 0), the batch being the whole set
151 const int64_t n = input.begin()->second.size(0);
152 if (n <= kEvalWindow)
153 {
154 return forward(input, output_names.begin(), output_names.end());
155 }
156 map<string, vector<torch::Tensor>> parts;
157 for (int64_t begin = 0; begin < n; begin += kEvalWindow)
158 {
159 const int64_t end = std::min(n, begin + kEvalWindow);
160 const int64_t from = std::max<int64_t>(0, begin - kEvalContext);
161 const int64_t to = std::min(n, end + kEvalContext);
162 map<string, torch::Tensor> window;
163 for (const auto& kv : input)
164 {
165 window[kv.first] = kv.second.index({ Slice(from, to) });
166 }
167 auto output_map = forward(window, output_names.begin(), output_names.end());
168 for (const string& task_name : output_names)
169 {
170 parts[task_name].push_back(output_map[task_name].index({ Slice(begin - from, end - from) }));
171 }
172 }
173 map<string, torch::Tensor> output_map;
174 for (const string& task_name : output_names)
175 {
176 output_map[task_name] = torch::cat(parts[task_name], 0);
177 }
178 return output_map;
179}
180
181void BiRnnClassifierImpl::evaluate(const vector<string>& output_names,
182 const map<string, torch::Tensor>& input,
183 const torch::Tensor& target,
184 epoch_stat_t& stat,
185 const torch::Device& /*device*/)
186{
187 eval();
188 // Evaluation never backpropagates: without this guard, autograd kept the
189 // activations of the whole evaluation set alive
190 torch::NoGradGuard no_grad;
191 auto output_map = forward_in_windows(input, output_names);
192
193 for (size_t i = 0; i < output_names.size(); ++i)
194 {
195 const string& task_name = output_names[i];
196 task_stat_t& task_stat = stat[task_name];
197
198 torch::Tensor& output = output_map[task_name];
199 torch::Tensor o = output.reshape({-1, output.size(2)});
200 auto this_task_target = target.index({ Slice(), Slice(i, i+1) }).reshape({ -1 });
201 //cerr << o.sizes() << endl;
202 //cerr << this_task_target.sizes() << endl;
203
204 static constexpr int64_t kIgnoreIndex = -100;
205 torch::Tensor loss_tensor = torch::nn::functional::nll_loss(
206 o, this_task_target,
207 torch::nn::functional::NLLLossFuncOptions().ignore_index(kIgnoreIndex));
208 task_stat.m_loss = loss_tensor.sum().item<double>();
209 auto valid = this_task_target.ne(kIgnoreIndex);
210 auto prediction = o.argmax(1);
211 task_stat.m_correct = prediction.eq(this_task_target).logical_and(valid).sum().item<int64_t>();
212 task_stat.m_items = valid.sum().item<int64_t>();
213 task_stat.m_accuracy = double(task_stat.m_correct) / task_stat.m_items;
214 if (0 == i && !m_eos_classes.empty())
215 {
216 auto gold_eos = torch::zeros_like(valid);
217 auto pred_eos = torch::zeros_like(valid);
218 for (int64_t k : m_eos_classes)
219 {
220 gold_eos = gold_eos.logical_or(this_task_target.eq(k));
221 pred_eos = pred_eos.logical_or(prediction.eq(k));
222 }
223 pred_eos = pred_eos.logical_and(valid);
224 const double tp = gold_eos.logical_and(pred_eos).sum().item<int64_t>();
225 const double np = pred_eos.sum().item<int64_t>(), ng = gold_eos.sum().item<int64_t>();
226 const double p = np > 0 ? tp / np : 0, r = ng > 0 ? tp / ng : 0;
227 task_stat.m_eos_f1 = (p + r) > 0 ? 2 * p * r / (p + r) : 0;
228 }
229
230 if (o.size(-1) == 2)
231 {
232 //cerr << this_task_target.sizes() << endl;
233 //cerr << prediction.sizes() << endl;
234 //cerr << this_task_target << endl;
235 //cerr << prediction << endl;
236 task_stat.m_num_classes = o.size(-1);
237 auto gold_positive = prediction.eq(1);
238 auto gold_negative = prediction.eq(0);
239 auto pred_positive = this_task_target.eq(1);
240 auto pred_negative = this_task_target.eq(0);
241 auto tp = torch::logical_and(gold_positive, pred_positive).count_nonzero().item<int64_t>();
242 // auto fp = torch::logical_and(gold_negative, pred_positive).count_nonzero().item<int64_t>();
243 // auto fn = torch::logical_and(gold_positive, pred_negative).count_nonzero().item<int64_t>();
244 task_stat.m_precision = tp / (prediction.eq(1).sum().item<int64_t>() + 0.00001);
245 task_stat.m_recall = tp / (this_task_target.eq(1).sum().item<int64_t>() + 0.00001);
246 task_stat.m_f1 = (2 * task_stat.m_precision * task_stat.m_recall) / (task_stat.m_precision + task_stat.m_recall + 0.00001);
247 }
248 else if (o.size(-1) > 2)
249 {
250 // Multi-class task (e.g. the 7-class segmentation "tokens" task): the
251 // binary positive-class P/R/F1 above doesn't apply, so report a
252 // macro-averaged P/R/F1 over all classes instead of leaving them at the
253 // default 0. ACC alone is a poor signal here because one class (e.g.
254 // "inside") dominates, pushing accuracy ~0.999 even for a mediocre
255 // boundary detector.
256 const int64_t num_classes = o.size(-1);
257 task_stat.m_num_classes = num_classes;
258 double sum_p = 0, sum_r = 0, sum_f1 = 0;
259 for (int64_t c = 0; c < num_classes; ++c)
260 {
261 // Ignored (-100) positions: excluded from gold_c (target never equals c)
262 // and masked out of pred_c so they can't inflate the predicted count.
263 auto pred_c = prediction.eq(c).logical_and(valid);
264 auto gold_c = this_task_target.eq(c);
265 auto tp_c = torch::logical_and(pred_c, gold_c).count_nonzero().item<int64_t>();
266 double prec = tp_c / (pred_c.sum().item<int64_t>() + 0.00001);
267 double rec = tp_c / (gold_c.sum().item<int64_t>() + 0.00001);
268 sum_p += prec;
269 sum_r += rec;
270 sum_f1 += (2 * prec * rec) / (prec + rec + 0.00001);
271 }
272 task_stat.m_precision = sum_p / num_classes;
273 task_stat.m_recall = sum_r / num_classes;
274 task_stat.m_f1 = sum_f1 / num_classes;
275 }
276 }
277}
278
279void BiRnnClassifierImpl::train(size_t epochs,
280 size_t batch_size,
281 size_t seq_len,
282 const vector<string>& output_names,
283 const TorchMatrix<int64_t>& train_input,
284 const TorchMatrix<int64_t>& train_gold,
285 const TorchMatrix<int64_t>& eval_input,
286 const TorchMatrix<int64_t>& eval_gold,
287 torch::optim::Optimizer& opt,
288 const std::string& model_name,
289 const torch::Device& device)
290{
291 int64_t num_batches = train_input.size() / seq_len;
292 int64_t num_features = (int64_t)train_input.get_max_feat();
293 int64_t seq_len_i64 = (int64_t)seq_len;
294
295 auto aligned_input = train_input.get_tensor().index({ Slice(0, num_batches * seq_len_i64), Slice() });
296 auto aligned_gold = train_gold.get_tensor().index({ Slice(0, num_batches * seq_len_i64), Slice() });
297 auto input_batches
298 = aligned_input.reshape({ num_batches, seq_len_i64, num_features }).transpose(0, 1);
299 auto gold_batches
300 = aligned_gold.reshape({ num_batches, seq_len_i64 }).transpose(0, 1);
301
302 double best_eval_accuracy = 0;
303 double best_eval_loss = std::numeric_limits<double>::max();
304 size_t count_below_best = 0;
305 // Seed lr_copy with the optimizer's actual learning rate so the EPOCH log
306 // prints the real LR from epoch 0. It was previously left at 0 and only set
307 // inside the accuracy-decay branch, so every epoch before the first decay
308 // (and every improving epoch) reported a bogus LR=0.
309 double lr_copy = 0;
310 for (auto& group : opt.param_groups())
311 {
312 if (group.has_options())
313 {
314 lr_copy = static_cast<torch::optim::AdamOptions&>(group.options()).lr();
315 }
316 }
317 for (size_t e = 0; e < epochs; e++)
318 {
319 epoch_stat_t train_stat, eval_stat;
320
321 Module::train(true);
322 train_epoch(batch_size, seq_len, output_names, input_batches, gold_batches, opt, train_stat, device);
323
324 evaluate(output_names, eval_input, eval_gold, eval_stat, device);
325
326 for (const string& task_name : output_names)
327 {
328 const task_stat_t& train = train_stat[task_name];
329 const task_stat_t& eval = eval_stat[task_name];
330 std::cout << "EPOCH " << e << " | " << task_name << " | LR=" << lr_copy;
331 std::cout << " | TRAIN LOSS=" << train.m_loss << " ACC=" << train.m_accuracy
332 << " | EVAL LOSS=" << eval.m_loss << " ACC=" << eval.m_accuracy
333 << " P=" << eval.m_precision << " R=" << eval.m_recall<< " F1=" << eval.m_f1;
334 if (eval.m_eos_f1 >= 0)
335 {
336 std::cout << " EOS_F1=" << eval.m_eos_f1;
337 }
338 std::cout << std::endl << std::flush;
339 }
340
341 task_stat_t& main_task_eval = eval_stat[output_names[0]];
342
343 best_eval_loss = min(best_eval_loss, main_task_eval.m_loss);
344 // The score the kept epoch is chosen on (named accuracy for history)
345 const double score = (m_select_on_eos && main_task_eval.m_eos_f1 >= 0)
346 ? (main_task_eval.m_accuracy + main_task_eval.m_eos_f1) / 2
347 : main_task_eval.m_accuracy;
348 if (score > best_eval_accuracy)
349 {
350 best_eval_accuracy = score;
351 if (model_name.size() > 0)
352 {
353 torch::save(*this, model_name + ".pt");
354 }
355 count_below_best = 0;
356
357 if (1 == score)
358 {
359 return;
360 }
361 }
362 else if (score < best_eval_accuracy)
363 {
364 for (auto &group : opt.param_groups())
365 {
366 if (group.has_options())
367 {
368 auto &options = static_cast<torch::optim::AdamOptions &>(group.options());
369 options.lr(options.lr() * m_lr_decay);
370 lr_copy = options.lr();
371 }
372 }
373 if (lr_copy < 0.0000001)
374 {
375 return;
376 }
377 count_below_best++;
378 if (main_task_eval.m_loss > best_eval_loss && count_below_best > m_patience)
379 {
380 return;
381 }
382 if (count_below_best > 50)
383 {
384 return;
385 }
386 }
387 }
388}
389
390void BiRnnClassifierImpl::train_epoch(size_t batch_size,
391 size_t seq_len,
392 const vector<string>& output_names,
393 const torch::Tensor& input_batches,
394 const torch::Tensor& gold_batches,
395 torch::optim::Optimizer& opt,
396 epoch_stat_t& stat,
397 const torch::Device& device)
398{
399 for (int64_t b = 0; b < input_batches.size(1); b += batch_size)
400 {
401 auto current_batch_size
402 = ((b + (int64_t)batch_size) > input_batches.size(1)) ? input_batches.size(1) - b : batch_size;
403
404 train_batch(current_batch_size, seq_len, output_names,
405 input_batches.index({Slice(), Slice(b, b + current_batch_size), Slice()}),
406 gold_batches.index({Slice(), Slice(b, b + current_batch_size) }),
407 opt, stat, device);
408 }
409}
410
411void BiRnnClassifierImpl::train_batch(size_t batch_size,
412 size_t seq_len,
413 const vector<string>& output_names,
414 const torch::Tensor& input,
415 const torch::Tensor& gold,
416 torch::optim::Optimizer& opt,
417 epoch_stat_t& stat,
418 const torch::Device& device)
419{
420 map<string, torch::Tensor> current_batch_inputs;
421 split_input(input, current_batch_inputs, device);
422
423 auto target = gold.reshape({-1, 1}).to(device);
424
425 train_batch(batch_size, seq_len, output_names, current_batch_inputs, target, opt, stat, device);
426}
427
428void BiRnnClassifierImpl::train_batch(size_t /*batch_size*/,
429 size_t /*seq_len*/,
430 const vector<string>& output_names,
431 const map<string, torch::Tensor>& input,
432 const torch::Tensor& target,
433 torch::optim::Optimizer& opt,
434 epoch_stat_t& stat,
435 const torch::Device& /*device*/)
436{
437 opt.zero_grad();
438
439 auto output_map = forward(input, output_names.begin(), output_names.end());
440
441 //torch::Tensor loss_tensor = torch::zeros({ batch_size * seq_len },
442 // torch::TensorOptions().dtype(torch::kFloat64));
443 //cerr << loss_tensor.sizes() << endl;
444
445 for (size_t i = 0; i < output_names.size(); ++i)
446 {
447 const string& task_name = output_names[i];
448 task_stat_t& task_stat = stat[task_name];
449
450 auto output = output_map[task_name];
451
452 auto o = output.reshape({ -1, output.size(2) });
453 auto this_task_target = target.index({ Slice(), Slice(i, i+1) }).reshape({ -1 });
454 //cerr << o.sizes() << endl;
455 //cerr << this_task_target.sizes() << endl;
456 // Positions whose target == kIgnoreIndex (e.g. the synthetic <ROOT> token)
457 // are excluded from the loss and the accuracy. Harmless for tasks whose
458 // targets are always valid class ids (the mask is then all-true).
459 static constexpr int64_t kIgnoreIndex = -100;
460 auto nll_options = torch::nn::functional::NLLLossFuncOptions().ignore_index(kIgnoreIndex);
461 if (0 == i && !m_class_weights.empty() && int64_t(m_class_weights.size()) == o.size(1))
462 {
463 nll_options = nll_options.weight(torch::tensor(m_class_weights).to(o.device()));
464 }
465 torch::Tensor loss_tensor = torch::nn::functional::nll_loss(o, this_task_target, nll_options);
466 double loss_value = loss_tensor.sum().item<double>();
467 task_stat.m_loss += loss_value;
468 //std::cerr << "o.sizes() == " << o.sizes() << std::endl;
469 auto valid = this_task_target.ne(kIgnoreIndex);
470 auto prediction = o.argmax(1);
471 int64_t correct_predictions = prediction.eq(this_task_target).logical_and(valid).sum().item<int64_t>();
472 task_stat.m_correct += correct_predictions;
473 task_stat.m_items += valid.sum().item<int64_t>();
474
475 loss_tensor.backward({}, true);
476 }
477 opt.step();
478}
479
480void BiRnnClassifierImpl::load(torch::serialize::InputArchive& archive)
481{
482 StaticGraphImpl::load(archive);
483
484 assert(m_embd_descr.size() == 0);
485
486 c10::IValue v;
487 if (archive.try_read("embd_descr", v))
488 {
489 if (!v.isList())
490 {
491 throw std::runtime_error("embd_descr must be a list.");
492 }
493
494 const c10::List<c10::IValue>& l = v.toList();
495 m_embd_descr.reserve(l.size());
496 for (size_t i = 0; i < l.size(); i++)
497 {
498 if (!l.get(i).isString())
499 {
500 throw std::runtime_error("embd_descr must be a list of strings.");
501 }
502 const string& str = l.get(i).toStringRef();
503 m_embd_descr.emplace_back(embd_descr_t(str));
504 }
505 }
506 else
507 {
508 throw std::runtime_error("Can't load embd_descr.");
509 }
510}
511
512void BiRnnClassifierImpl::save(torch::serialize::OutputArchive& archive) const
513{
514 StaticGraphImpl::save(archive);
515
516 // Save embd descriptions
517 c10::List<std::string> embd_descr_list;
518 for (size_t i = 0; i < m_embd_descr.size(); i++)
519 {
520 string embd_str = m_embd_descr[i].to_string();
521 assert(embd_descr_t(embd_str) == m_embd_descr[i]);
522 embd_descr_list.push_back(embd_str);
523 }
524
525 archive.write("embd_descr", embd_descr_list);
526}
527
528} // namespace nets
529} // namespace deeplima
530
uint64_t get_max_feat() const
const torch::Tensor & get_tensor() const
uint64_t size() const
void split_input(const torch::Tensor &src, std::map< std::string, torch::Tensor > &dst, const torch::Device &device)
std::vector< embd_descr_t > m_embd_descr
void evaluate(const std::vector< std::string > &output_name, const TorchMatrix< int64_t > &input, const TorchMatrix< int64_t > &gold, epoch_stat_t &stat, const torch::Device &device=torch::Device(torch::kCPU))
std::map< std::string, torch::Tensor > forward_in_windows(const std::map< std::string, torch::Tensor > &input, const std::vector< std::string > &output_names)
torch::Tensor predict(const std::string &output_name, const torch::Tensor &input, const torch::Device &device=torch::Device(torch::kCPU))
virtual void load(torch::serialize::InputArchive &archive)
virtual void save(torch::serialize::OutputArchive &archive) const
void train_epoch(size_t batch_size, size_t seq_len, const std::vector< std::string > &output_names, const torch::Tensor &input_batches, const torch::Tensor &gold_batches, torch::optim::Optimizer &opt, epoch_stat_t &stat, const torch::Device &device)
void train_batch(size_t batch_size, size_t seq_len, const std::vector< std::string > &output_names, const torch::Tensor &input, const torch::Tensor &gold, torch::optim::Optimizer &opt, epoch_stat_t &stat, const torch::Device &device)
void train(size_t epochs, size_t batch_size, size_t seq_len, const std::vector< std::string > &output_names, const TorchMatrix< int64_t > &train_input, const TorchMatrix< int64_t > &train_gold, const TorchMatrix< int64_t > &eval_input, const TorchMatrix< int64_t > &eval_gold, torch::optim::Optimizer &opt, const std::string &model_name="", const torch::Device &device=torch::Device(torch::kCPU))
virtual void to(torch::Device device, bool non_blocking=false) override
virtual void load(torch::serialize::InputArchive &archive) override
std::map< std::string, torch::Tensor > forward(const std::map< std::string, torch::Tensor > &inputs, const std::string &output_name)
virtual void save(torch::serialize::OutputArchive &archive) const override
std::map< std::string, task_stat_t > epoch_stat_t
Edit rules for lemmatizing words absent from the lemma dictionary.
STL namespace.