将模型切换为评估模式
现在,您将把语言模型切换到评估模式。如果在推理时模型未处于评估模式,诸如批归一化和 dropout 等层会改变模型行为,导致翻译质量不一致。请构建评估模型的循环!
以下数据已预加载:model、eval_dataloader、accelerator 和 metric。
本练习是课程的一部分
使用 PyTorch 高效训练 AI 模型
练习说明
- 在遍历数据集中的批次之前,将模型切换为评估模式。
- 使用 Accelerator 的
.gather_for_metrics()方法在多设备间聚合predictions和labels,以计算评估指标。 - 在末尾计算评估指标。
交互式实操练习
通过完成这段示例代码来试试这个练习。
metric = evaluate.load("glue", "mrpc")
# Set the model in evaluation mode
____.____()
for step, batch in enumerate(eval_dataloader):
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
# Aggregate values across devices
predictions, references = ____.____((predictions, batch["labels"]))
metric.add_batch(predictions=predictions, references=references)
# Compute the evaluation metric
eval_metric = metric.____()
print(eval_metric)