读取并清零 .grad
了解梯度为何会累积,以及为何必须重置
读取并清零 .grad 是 CoddyKit 上的免费 Deep Learning Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Deep Learning Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Deep Learning Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The .grad Attribute
After backward, every trained tensor stores its gradient in .grad. Reading it tells you how the loss responds to changes in that tensor.
print(weight.grad)Gradients Start as None
Before any backward call, .grad is None, not zero. PyTorch only allocates it once the first set of gradients actually arrives.
Gradients Accumulate
Here is the surprise: backward adds to .grad rather than replacing it. Call backward twice without clearing and the numbers pile up.
Why Accumulation Exists
This adding behavior is on purpose. It lets you sum gradients from several mini-batches before one update, handy for simulating a larger batch.
The Hidden Bug
Forget to clear and old gradients poison your next step, so the model trains on the wrong numbers. This silent bug trips up almost everyone once.
Zero Them Each Step
The fix is to reset gradients before each backward. With an optimizer you simply call zero_grad() at the top of every training step.
optimizer.zero_grad()The Right Order
The loop rhythm is fixed: zero_grad, forward, loss, backward, step. Zeroing first guarantees each step uses only this batch's gradients.
optimizer.zero_grad()
loss.backward()
optimizer.step()Clearing Without an Optimizer
No optimizer yet? You can null the gradients yourself by setting each tensor's .grad back to None before the next backward call.
w.grad = Noneset_to_none Is Cheaper
Newer code prefers zero_grad(set_to_none=True). Setting grads to None instead of filling zeros saves a little memory and time.
Reading Grads to Debug
Peeking at .grad is great for debugging. All zeros may mean a dead neuron, and huge values warn of exploding gradients before training blows up.
A Habit Worth Forming
Make zeroing automatic in your head. Every reliable training loop clears gradients first, so the model only ever learns from the current batch.
Quick Check
Recap
Gradients live in .grad and accumulate across backward calls, so you must clear them each step with zero_grad. Forgetting that quietly breaks training. 🧹
常见问题解答
「读取并清零 .grad」课时是免费的吗?
是的 — 「读取并清零 .grad」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Deep Learning Academy 课程的其余内容,请升级到 CoddyKit PRO。 Deep Learning Academy 课程共包含 4 节课。
「读取并清零 .grad」这节课中我会学到什么?
了解梯度为何会累积,以及为何必须重置 你通过在浏览器中直接运行的动手代码来练习 Deep Learning Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Deep Learning Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Deep Learning Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「读取并清零 .grad」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Deep Learning Academy 课中编写并运行代码吗?
能。每节 Deep Learning Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。