12Backward Pass + Optimizer Step

Gradient flows backward through the exact same stack, right to left
loss.backward() # training-only optimizer.step() # training-only optimizer.zero_grad(set_to_none=True)
every parameter gets a same-shape gradient buffer

This is the actual dividing line between training and inference — not the shape of any tensor, but whether these three lines run. model.train() additionally enables Dropout; forward()'s math is byte-for-byte identical either way.

Correction: this is really THREE independent switches, easy to collapse into one. It's tempting to treat "train vs. inference" as a single toggle — it's actually three, freely combinable:
Switch 1: does loss get computed?  — ONLY depends on whether targets is passed (step 11's `if targets is None`)
Switch 2: is Dropout on?           — ONLY depends on model.train() / model.eval(), unrelated to targets
Switch 3: do weights get updated?  — ONLY depends on calling loss.backward() + optimizer.step()
The combination that matters most in practice — computing validation loss — uses all three independently:
model.eval()                              # switch 2: dropout OFF
with torch.no_grad():
    logits, loss = model(xb_val, yb_val)  # switch 1: targets passed → loss IS computed
    # backward()/step() never called here — switch 3: weights stay frozen
"Can a loss be computed" and "train vs. eval mode" are genuinely independent questions — eval mode can still compute a real loss (used to monitor overfitting), it just won't update anything from it.
Correction: loss.backward() and optimizer.step() are two separate steps, not one. backward() only computes gradients and stores them in each parameter's .grad — at the instant it returns, every weight's actual value is still completely unchanged. optimizer.step() is the line that actually reads .grad and modifies the weight values. This is exactly why the training loop always writes both lines, never one alone: without backward(), step() has no gradient to act on; without step(), the computed gradient is wasted — weights never move.
Why training needs so much more GPU memory (unrelated to KV Cache): backprop must retain every layer's intermediate activations until gradients are computed; every parameter needs a same-size gradient buffer; the optimizer (Adam) needs ~2 more momentum buffers per parameter. Altogether this is typically 3-4× the model's own parameter memory — training never even uses KV Cache, so caching is not the explanation here.
Reality check for this notebook: the loop above trains m — the small, separately-defined pure bigram model (nn.Embedding(vocab_size, vocab_size), no attention at all). It's a different variable from the model used in steps 3-10 (the one with n_embd/Blocks) — that one is only ever forward-passed once, never trained, in this notebook. Same loop structure would train the full model too, just swapping m for model.
full source — training loop (gpt-dev.ipynb)10,000 steps
optimizer = torch.optim.AdamW(m.parameters(), lr=1e-3)

for steps in range(10000): # increase number of steps for good results...
    xb, yb = get_batch('train')          # step 2, every iteration
    logits, loss = m(xb, yb)             # forward pass, step 11 computes loss
    optimizer.zero_grad(set_to_none=True)
    loss.backward()
    optimizer.step()

print(loss.item())
PyTorch internals: optimizer.zero_grad(set_to_none=True) sets each parameter's .grad to None rather than zeroing it in place — slightly faster, and lets PyTorch skip a memory write. loss.backward() walks the autograd graph built during the forward pass and accumulates gradients into .grad. optimizer.step() (AdamW) then updates every parameter using its gradient plus two running-average buffers (momentum + variance) per parameter — this is exactly the "~2 extra buffers" referenced above.

📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied

cell b3da3e50
# create a PyTorch optimizer
optimizer = torch.optim.AdamW(m.parameters(), lr=1e-3)
cell 683c4764
batch_size = 32
for steps in range(10000): # increase number of steps for good results...

    # sample a batch of data
    xb, yb = get_batch('train')

    # evaluate the loss
    logits, loss = m(xb, yb)
    optimizer.zero_grad(set_to_none=True)
    loss.backward()
    optimizer.step()

print(loss.item())

📝 笔记 Chinese notes — live from gpt-dev.ipynb, not hand-copied

note 1598ec96

校正:loss 之后的三个独立开关,不要混成一个

容易把"训练 vs 推理"当成一个单一开关,但实际上有 三个互相独立、可以自由组合 的开关:

开关1:算不算 loss           —— 只取决于有没有传 targets(forward() 里 if targets is None)
开关2:Dropout 开不开         —— 只取决于 model.train() / model.eval(),和 targets 无关
开关3:要不要更新权重          —— 只取决于有没有调用 loss.backward() + optimizer.step()

三者可以任意组合,最典型的组合是算验证集 loss:

model.eval()                     # 开关2:关掉 dropout
with torch.no_grad():
    logits, loss = model(xb_val, yb_val)   # 开关1:传了 targets,照样算出 loss
    # 到此为止,不调用 backward()/step()   —— 开关3:不更新权重

这说明"能不能算出 loss"和"train/eval 模式"是两件独立的事——eval 模式下一样可以传 targets 拿到 loss(用来监控有没有过拟合),只是不会再去调整权重。


校正:loss.backward() 和 optimizer.step() 是两个分开的步骤,不是一步完成

loss.backward()      # 只计算梯度,存进每个参数的 .grad 里 —— 此刻权重数值完全没变
optimizer.step()     # 读取 .grad,按优化器的更新规则,真正修改权重的数值

backward() 执行完的瞬间,模型所有权重的实际数值仍然和调用前一模一样;真正"调整"权重这个动作,是紧随其后的 optimizer.step()。这也是为什么训练循环里这两行永远分开写、缺一不可——没有 backward(),step() 没有梯度可用;没有 step(),算出来的梯度只是白算,权重永远不会变化。