Một training step, theo đúng thứ tự

Một training step, theo đúng thứ tự A sequence diagram generated by Archify. batch: input_ids, attention_mask, labels ghi lại từng operation của forward logits [batch, num_classes] loss: một số vô hướng loss.backward() gradient cho mọi trainable parameter learning rate của step này gradient đang lưu trong .grad optimizer.step() rồi zero_grad() Forward Backward Update DataLoader · collate + padding · Sequence participant DataLoader collate + padding Model · encoder + head · Sequence participant Model encoder + head Cross-entropy · logits vs labels · Sequence participant Cross-entropy logits vs labels Autograd · computation graph · Sequence participant Autograd computation graph AdamW · giữ m_t và v_t · Sequence participant AdamW giữ m_t và v_t Scheduler · learning rate theo step · Sequence participant Scheduler learning rate theo step Legend request return security async trace default message

Thứ tự quan trọng hơn cú pháp

  • • backward() phải chạy sau khi loss đã có
  • • optimizer.step() phải chạy sau khi gradient đã tính xong
  • • zero_grad() phải chạy trước batch tiếp theo

Vì sao phải zero_grad()

  • • PyTorch mặc định cộng dồn gradient vào .grad
  • • Quên xoá thì gradient batch này cộng vào batch trước
  • • Cộng dồn có chủ đích chính là gradient accumulation