Problem
Implement train_one_step(model, optimizer, criterion, x, y) to execute one canonical PyTorch gradient descent update: (1) optimizer.zero_grad(), (2) forward pass preds = model(x), (3) loss = criterion(preds, y), (4) loss.backward(), (5) optimizer.step(), and return float(loss.item()).
Why It Matters: The 5-line PyTorch training step is the single most tested practical deep learning interview snippet—forgetting zero_grad() causes silent gradient accumulation bugs.
Function Signature
import torch
import torch.nn as nn
def train_one_step(model: nn.Module, optimizer, criterion, x: torch.Tensor, y: torch.Tensor) -> float:
"""Execute one PyTorch training step and return float(loss.item())."""
Sample Input & Output
Example 1: Single Regression Update
Input:
model = nn.Linear(2, 1); opt = torch.optim.SGD(model.parameters(), lr=0.1); crit = nn.MSELoss()
loss_val = train_one_step(model, opt, crit, x, y)
Expected Output:
loss_val: float (e.g., 1.4285) # and model weights strictly updated by 1 SGD step
Explanation: Clears prior gradients, computes MSE loss, populates .grad via .backward(), updates weights, and returns the scalar float loss.
Example 2: Two Consecutive Steps Decrease Loss
Input:
loss_1 = train_one_step(model, opt, crit, x, y)
loss_2 = train_one_step(model, opt, crit, x, y)
Expected Output:
loss_2 < loss_1 # on a well-conditioned batch with small lr
Explanation: Because zero_grad() resets gradients before step 2, each update moves cleanly downhill.
Constraints & Edge Cases
- Return
float(loss.item()). - Call
optimizer.zero_grad()beforeloss.backward()so stale gradients never leak into the step. - Return
float(loss.item())(not a tensor) to avoid retaining the computation graph in memory.
Constraints & Evaluation Criteria
- Return `float(loss.item())`.
Hints
Linear(4,1) + SGD(lr=0.1)
loss2 < loss1 and weights changed