用 Accelerator 评估模型

使用 PyTorch 高效训练 AI 模型

Dennis Lee

Data Engineer, Amazon

为何切换到评估模式?

  • 训练模式
    • Dropout:将部分神经元置零
    • 批归一化

Dropout 和批归一化 一个包含输入、隐藏、输出层的神经网络示意图。对隐藏层应用 Dropout 以防过拟合,并在激活前对每层输出进行批归一化。

使用 PyTorch 高效训练 AI 模型

为何切换到评估模式?

  • 训练模式
    • Dropout:将神经元置零
    • 批归一化
  • 评估模式会禁用这些层
  • model.eval() 激活评估模式

Dropout 和批归一化 一个包含输入、隐藏、输出层的神经网络示意图。对隐藏层应用 Dropout 以防过拟合,并在激活前对每层输出进行批归一化。

使用 PyTorch 高效训练 AI 模型

用 torch.no_grad() 关闭梯度

  • 训练需要计算梯度
  • torch.no_grad() 关闭梯度
  • 同时调用 model.evaltorch.no_grad
model.eval()
with torch.no_grad():
    outputs = model(**inputs)

反向传播中的梯度计算 一个神经网络的反向传播示意图,显示在各层计算梯度并用于更新权重,误差从输出层向隐藏层反向传播,通过梯度下降更新权重。

使用 PyTorch 高效训练 AI 模型

准备验证数据集

  • 加载 MRPC 数据集的验证集
validation_dataset = load_dataset("glue", "mrpc", split="validation")
  • 对验证集进行分词
def encode(examples):
    return tokenizer(examples["sentence1"], 
                      examples["sentence2"],
                      truncation=True,
                      padding="max_length")

validation_dataset = validation_dataset.map(encode, batched=True)
使用 PyTorch 高效训练 AI 模型

一个 epoch 的流程:训练与评估循环

  • 每个 epoch 依次遍历训练集和验证集
  • 先以训练模式运行模型
  • 再以评估模式运行并记录指标
for epoch in range(num_epochs):

model.train() for step, batch in enumerate(train_dataloader): # Perform training step
model.eval() for step, batch in enumerate(eval_dataloader): # Perform evaluation step
# Log evaluation metrics
使用 PyTorch 高效训练 AI 模型

评估循环内部

metric = evaluate.load("glue", "mrpc")
model.eval()
for step, batch in enumerate(eval_dataloader):

with torch.no_grad(): outputs = model(**batch) predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(predictions=predictions, references=references)
eval_metric = metric.compute() print(f"Eval metrics: \n{eval_metric}")
评估指标:
{'accuracy': 0.81, 'f1': 0.77}
使用 PyTorch 高效训练 AI 模型

在评估后记录指标

  • 跟踪工具:记录指标的可视化工具,如 TensorBoard、MLflow
  • log_with:使用所有实验跟踪工具
  • .init_trackers():初始化跟踪工具
  • .log():记录 accuracyf1epoch
  • .end_training():结束跟踪
accelerator = Accelerator(project_dir=".",
                          log_with="all")

accelerator.init_trackers("my_project")
for epoch in range(num_epochs): # Training loop is here # Evaluation loop is here accelerator.log({
"accuracy": eval_metric["accuracy"], "f1": eval_metric["f1"],
}, step=epoch)
accelerator.end_training()
使用 PyTorch 高效训练 AI 模型

Passons à la pratique !

使用 PyTorch 高效训练 AI 模型

Preparing Video For Download...