31 const torch::Tensor& input,
32 const torch::Device& device)
34 map<string, torch::Tensor> current_inputs;
37 auto output_map =
forward(current_inputs, output_names.begin(), output_names.end());
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)
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);
53 const torch::Tensor& inputs,
59 const std::vector<std::string>& outputs_names,
60 const torch::Device& device)
62 assert(output->size() == outputs_names.size());
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);
69 const torch::Tensor inputs_slice = inputs.index({ Slice(input_begin, input_end), Slice() });
71 map<string, torch::Tensor> current_inputs;
74 auto output_map =
forward(current_inputs, outputs_names.begin(), outputs_names.end());
75 for (
size_t i = 0; i < outputs_names.size(); i++)
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++)
83 (*output)[i][input_begin + p] = accessor[p];
89 map<string, torch::Tensor>& dst,
90 const torch::Device& device)
97 throw std::runtime_error(
"Duplicates in embd list.");
99 if (src.sizes().size() == 2)
104 = src.index({Slice(), Slice(c, c+1) }).reshape({ (int64_t)src.size(0), 1 }).
to(device);
113 else if (src.sizes().size() == 3)
119 = src.index({Slice(), Slice(), Slice(c, c+1) }).reshape({ (int64_t)src.size(0), -1 }).
to(device);
147 const map<string, torch::Tensor>& input,
148 const vector<string>& output_names)
151 const int64_t n = input.begin()->second.size(0);
154 return forward(input, output_names.begin(), output_names.end());
156 map<string, vector<torch::Tensor>> parts;
157 for (int64_t begin = 0; begin < n; begin +=
kEvalWindow)
159 const int64_t end = std::min(n, begin +
kEvalWindow);
160 const int64_t from = std::max<int64_t>(0, begin -
kEvalContext);
162 map<string, torch::Tensor> window;
163 for (
const auto& kv : input)
165 window[kv.first] = kv.second.index({ Slice(from,
to) });
167 auto output_map =
forward(window, output_names.begin(), output_names.end());
168 for (
const string& task_name : output_names)
170 parts[task_name].push_back(output_map[task_name].index({ Slice(begin - from, end - from) }));
173 map<string, torch::Tensor> output_map;
174 for (
const string& task_name : output_names)
176 output_map[task_name] = torch::cat(parts[task_name], 0);
182 const map<string, torch::Tensor>& input,
183 const torch::Tensor& target,
185 const torch::Device& )
190 torch::NoGradGuard no_grad;
193 for (
size_t i = 0; i < output_names.size(); ++i)
195 const string& task_name = output_names[i];
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 });
204 static constexpr int64_t kIgnoreIndex = -100;
205 torch::Tensor loss_tensor = torch::nn::functional::nll_loss(
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>();
216 auto gold_eos = torch::zeros_like(valid);
217 auto pred_eos = torch::zeros_like(valid);
220 gold_eos = gold_eos.logical_or(this_task_target.eq(k));
221 pred_eos = pred_eos.logical_or(prediction.eq(k));
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;
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>();
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);
248 else if (o.size(-1) > 2)
256 const int64_t num_classes = o.size(-1);
258 double sum_p = 0, sum_r = 0, sum_f1 = 0;
259 for (int64_t c = 0; c < num_classes; ++c)
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);
270 sum_f1 += (2 * prec * rec) / (prec + rec + 0.00001);
273 task_stat.
m_recall = sum_r / num_classes;
274 task_stat.
m_f1 = sum_f1 / num_classes;
282 const vector<string>& output_names,
287 torch::optim::Optimizer& opt,
288 const std::string& model_name,
289 const torch::Device& device)
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;
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() });
298 = aligned_input.reshape({ num_batches, seq_len_i64, num_features }).transpose(0, 1);
300 = aligned_gold.reshape({ num_batches, seq_len_i64 }).transpose(0, 1);
302 double best_eval_accuracy = 0;
303 double best_eval_loss = std::numeric_limits<double>::max();
304 size_t count_below_best = 0;
310 for (
auto& group : opt.param_groups())
312 if (group.has_options())
314 lr_copy =
static_cast<torch::optim::AdamOptions&
>(group.options()).lr();
317 for (
size_t e = 0; e < epochs; e++)
322 train_epoch(batch_size, seq_len, output_names, input_batches, gold_batches, opt, train_stat, device);
324 evaluate(output_names, eval_input, eval_gold, eval_stat, device);
326 for (
const string& task_name : output_names)
330 std::cout <<
"EPOCH " << e <<
" | " << task_name <<
" | LR=" << lr_copy;
331 std::cout <<
" | TRAIN LOSS=" <<
train.m_loss <<
" ACC=" <<
train.m_accuracy
336 std::cout <<
" EOS_F1=" << eval.
m_eos_f1;
338 std::cout << std::endl << std::flush;
341 task_stat_t& main_task_eval = eval_stat[output_names[0]];
343 best_eval_loss = min(best_eval_loss, main_task_eval.
m_loss);
348 if (score > best_eval_accuracy)
350 best_eval_accuracy = score;
351 if (model_name.size() > 0)
353 torch::save(*
this, model_name +
".pt");
355 count_below_best = 0;
362 else if (score < best_eval_accuracy)
364 for (
auto &group : opt.param_groups())
366 if (group.has_options())
368 auto &options =
static_cast<torch::optim::AdamOptions &
>(group.options());
370 lr_copy = options.lr();
373 if (lr_copy < 0.0000001)
378 if (main_task_eval.
m_loss > best_eval_loss && count_below_best >
m_patience)
382 if (count_below_best > 50)
392 const vector<string>& output_names,
393 const torch::Tensor& input_batches,
394 const torch::Tensor& gold_batches,
395 torch::optim::Optimizer& opt,
397 const torch::Device& device)
399 for (int64_t b = 0; b < input_batches.size(1); b += batch_size)
401 auto current_batch_size
402 = ((b + (int64_t)batch_size) > input_batches.size(1)) ? input_batches.size(1) - b : batch_size;
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) }),
413 const vector<string>& output_names,
414 const torch::Tensor& input,
415 const torch::Tensor& gold,
416 torch::optim::Optimizer& opt,
418 const torch::Device& device)
420 map<string, torch::Tensor> current_batch_inputs;
423 auto target = gold.reshape({-1, 1}).
to(device);
425 train_batch(batch_size, seq_len, output_names, current_batch_inputs, target, opt, stat, device);
430 const vector<string>& output_names,
431 const map<string, torch::Tensor>& input,
432 const torch::Tensor& target,
433 torch::optim::Optimizer& opt,
435 const torch::Device& )
439 auto output_map =
forward(input, output_names.begin(), output_names.end());
445 for (
size_t i = 0; i < output_names.size(); ++i)
447 const string& task_name = output_names[i];
450 auto output = output_map[task_name];
452 auto o = output.reshape({ -1, output.size(2) });
453 auto this_task_target = target.index({ Slice(), Slice(i, i+1) }).reshape({ -1 });
459 static constexpr int64_t kIgnoreIndex = -100;
460 auto nll_options = torch::nn::functional::NLLLossFuncOptions().ignore_index(kIgnoreIndex);
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;
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>();
475 loss_tensor.backward({},
true);
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))