在 GLUE 任务上微调 BERT 时,如何监控训练和评估损失?

How can I monitor both training and eval loss when finetuning BERT on a GLUE task?

我正在 运行宁 https://github.com/huggingface/transformers/blob/master/examples/run_glue.py 对二元分类任务 (CoLA) 执行微调。 我想监控训练和评估损失以防止过度拟合。

目前库是 2.8.0,我是从源代码安装的。

当我运行的例子用

python run_glue.py --model_name_or_path bert-base-uncased 
                   --task_name CoLA 
                   --do_train 
                   --do_eval
                   --data_dir my_dir 
                   --max_seq_length 128
                   --per_gpu_train_batch_size 8
                   --per_gpu_eval_batch_size 8 
                   --learning_rate 2e-5
                   --num_train_epochs 3.0
                   --output_dir ./outputs
                   --logging_steps 5

在 stdout 日志中,我看到只有一个损失值的行,例如

{"learning_rate": 3.3333333333333333e-06, "loss": 0.47537623047828675, "step": 25}

通过查看 https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py,我看到那里计算了训练和评估损失(在我看来,代码最近被重构了)。

因此我将 https://github.com/huggingface/transformers/blob/abb1fa3f374811ea09d0bc3440d820c50735008d/src/transformers/trainer.py#L314 替换为

 cr_loss = self._training_step(model, inputs, optimizer)
 tr_loss += cr_loss

并在行后添加 https://github.com/huggingface/transformers/blob/abb1fa3f374811ea09d0bc3440d820c50735008d/src/transformers/trainer.py#L345

logs["training loss"] = cr_loss

有了这个我得到:

0502 14:12:18.644119 23632 summary.py:47] Summary name training loss is illegal; using training_loss instead.  
                          | 4/10  [00:02<00:04,  1.49it/s]  
{"learning_rate":  3.3333333333333333e-06, "loss": 0.47537623047828675, "training loss": 0.5451719760894775, "step": 25}

这样可以吗,还是我做错了什么?

在 stdout both 中监控微调期间给定记录间隔的平均训练和评估损失的最佳方法是什么?

如果安装更新的版本(我通过 pip 尝试了 2.9.0),代码中可能不需要更改:只需使用附加标志 --evaluate_during_training 启动微调,输出就可以了

0506 12:11:30.021593 34540 trainer.py:551] ***** Running Evaluation ***** 
I0506 12:11:30.022596 34540 trainer.py:552]   Num examples = 140  
I0506 12:11:30.023634 34540 trainer.py:553]   Batch size = 8 Evaluation:  
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 18/18 [00:19<00:00,  1.10s/it]  
{"eval_mcc": 0.0, "eval_loss": 0.6600487811697854, "learning_rate": 3.3333333333333333e-06, "loss": 0.50044886469841, "step": 25}

请注意,示例脚本经常更改,因此完成此操作的标志可能会更改名称...另请参阅此处 https://discuss.huggingface.co/t/how-to-monitor-both-train-and-validation-metrics-at-the-same-step/1301