Code Room
Code reviewMediumcr-g628
Subject Model training pytorchLevel Mid–Senior~18 minCommon in Code quality & review interviewsIndustries Software development

Question

Review this PyTorch training loop.

Training is unstable and the loss behaves erratically. What's missing?

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix — specific and kind.

Talk through your review
Code to reviewpython
import torchimport torch.nn as nn def train(model, loader, epochs=10, lr=1e-3):    opt = torch.optim.Adam(model.parameters(), lr=lr)    loss_fn = nn.CrossEntropyLoss()    for epoch in range(epochs):        for xb, yb in loader:            logits = model(xb)            loss = loss_fn(logits, yb)            loss.backward()            opt.step()        print(f"epoch {epoch} loss {loss.item():.4f}")
Run or narrate your approach, then ask the coach.