We use these steps to teach a computer how to learn from data by guessing, checking mistakes, and improving.
Forward pass, loss, backward, step in PyTorch
output = model(input)
loss = loss_function(output, target)
loss.backward()
optimizer.step()
optimizer.zero_grad()output = model(input) runs the data through the model to get predictions.
loss.backward() calculates how to change the model to reduce mistakes.
x and target y.output = model(x) loss = criterion(output, y) loss.backward() optimizer.step() optimizer.zero_grad()
predictions = model(images) loss = loss_fn(predictions, labels) loss.backward() optimizer.step() optimizer.zero_grad()
This code creates a simple model that learns to predict targets from inputs. It shows the loss before and after one training step.
import torch import torch.nn as nn import torch.optim as optim # Simple model: one linear layer class SimpleModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(2, 1) def forward(self, x): return self.linear(x) # Data: inputs and targets inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) targets = torch.tensor([[3.0], [7.0], [11.0]]) # Model, loss, optimizer model = SimpleModel() criterion = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=0.01) # Training step output = model(inputs) loss = criterion(output, targets) print(f"Loss before backward: {loss.item():.4f}") loss.backward() optimizer.step() optimizer.zero_grad() # Check loss after one step output2 = model(inputs) loss2 = criterion(output2, targets) print(f"Loss after one step: {loss2.item():.4f}")
Always call optimizer.zero_grad() before loss.backward() to clear old gradients.
The loss.backward() step calculates gradients automatically for all model parameters.
The optimizer.step() updates the model weights using the gradients.
The forward pass runs data through the model to get predictions.
The loss measures how far predictions are from targets.
Backward computes gradients to know how to improve the model.
Step updates the model weights to reduce future mistakes.
Practice
forward pass in a PyTorch model?Solution
Step 1: Understand the forward pass role
The forward pass takes input data and processes it through the model layers to produce predictions.Step 2: Differentiate from other steps
Updating weights is done by the optimizer step, loss calculation measures error, and backward computes gradients.Final Answer:
To run input data through the model and get predictions -> Option CQuick Check:
Forward pass = predictions [OK]
- Confusing forward pass with weight update
- Mixing loss calculation with forward pass
- Thinking backward computes predictions
loss?Solution
Step 1: Identify the backward method
In PyTorch, callingloss.backward()computes gradients for all tensors withrequires_grad=True.Step 2: Check other options
step()is for optimizers,forward()is for models, andupdate()is not a PyTorch method.Final Answer:
loss.backward() -> Option BQuick Check:
Backward pass uses loss.backward() [OK]
- Using step() on loss instead of optimizer
- Calling forward() on loss tensor
- Trying to update loss directly
import torch import torch.nn as nn model = nn.Linear(2, 1) optimizer = torch.optim.SGD(model.parameters(), lr=0.1) inputs = torch.tensor([[1.0, 2.0]]) targets = torch.tensor([[1.0]]) outputs = model(inputs) loss_fn = nn.MSELoss() loss = loss_fn(outputs, targets) loss.backward() optimizer.step() print(loss.item())
Solution
Step 1: Understand loss calculation and printing
The loss is computed before backward and step, soloss.item()returns the scalar loss value as a float.Step 2: Confirm optimizer.step() effect
Callingoptimizer.step()updates weights but does not change the already computed loss tensor value.Final Answer:
A positive float value representing the loss before weight update -> Option AQuick Check:
loss.item() shows loss before update [OK]
- Thinking loss becomes zero after optimizer.step()
- Expecting loss to be a tensor when printed
- Calling backward() after step() causes error
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) outputs = model(inputs) loss = loss_fn(outputs, targets) optimizer.step() loss.backward()
Solution
Step 1: Check order of backward and step
Gradients must be computed byloss.backward()before callingoptimizer.step()to update weights.Step 2: Analyze given code order
The code callsoptimizer.step()beforeloss.backward(), so weights update happens without gradients.Final Answer:
Calling optimizer.step() before loss.backward() -> Option DQuick Check:
Backward before step is required [OK]
- Swapping backward and step order
- Forgetting to zero gradients
- Assuming step() computes gradients
x and target y. Which sequence of commands correctly performs forward pass, loss calculation, backward pass, and weight update?Solution
Step 1: Understand correct training step order
The correct order is: clear gradients, forward pass, compute loss, backward pass, then update weights.Step 2: Check each option's sequence
optimizer.zero_grad(); outputs = model(x); loss = loss_fn(outputs, y); loss.backward(); optimizer.step() follows the correct order. Others call optimizer.step() too early or compute loss before forward pass.Final Answer:
optimizer.zero_grad(); outputs = model(x); loss = loss_fn(outputs, y); loss.backward(); optimizer.step() -> Option AQuick Check:
Zero grad -> forward -> loss -> backward -> step [OK]
- Calling optimizer.step() before backward
- Not zeroing gradients before backward
- Computing loss before forward pass
Ready to prove it?
Pass the test and this pattern moves unknown
