Bird
Raised Fist0
PyTorchml~20 mins

Forward pass, loss, backward, step in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Forward pass, loss, backward, step
Problem:Train a simple neural network to classify handwritten digits from the MNIST dataset.
Current Metrics:Training loss: 0.05, Training accuracy: 98%, Validation loss: 0.10, Validation accuracy: 95%
Issue:The model trains but the learner does not understand how the forward pass, loss calculation, backward pass, and optimizer step work together.
Your Task
Explain and implement the forward pass, loss calculation, backward pass, and optimizer step in PyTorch to train the model correctly.
Use PyTorch framework.
Use a simple feedforward neural network.
Use CrossEntropyLoss for classification.
Use SGD optimizer.
Hint 1
Hint 2
Hint 3
Hint 4
Hint 5
Solution
PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

# Define simple feedforward network
class SimpleNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear = nn.Linear(28*28, 10)

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear(x)
        return logits

# Prepare data
transform = transforms.ToTensor()
train_dataset = datasets.MNIST(root='.', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)

# Initialize model, loss, optimizer
model = SimpleNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)

# Training loop for 1 epoch
model.train()
for images, labels in train_loader:
    # Forward pass: compute predictions
    outputs = model(images)
    # Compute loss
    loss = criterion(outputs, labels)
    # Zero gradients before backward pass
    optimizer.zero_grad()
    # Backward pass: compute gradients
    loss.backward()
    # Update parameters
    optimizer.step()

    # Print loss for first batch only
    print(f'Loss: {loss.item():.4f}')
    break
Implemented forward pass by calling model(images) to get predictions.
Calculated loss using CrossEntropyLoss comparing predictions and true labels.
Called optimizer.zero_grad() to clear old gradients.
Called loss.backward() to compute gradients.
Called optimizer.step() to update model parameters.
Results Interpretation

Before: Learner did not understand the sequence of forward pass, loss, backward, and step.

After: Learner implemented and ran code that performs these steps correctly, seeing loss value printed.

The forward pass computes predictions, loss measures error, backward pass calculates gradients, and optimizer step updates model weights. This cycle trains the model.
Bonus Experiment
Try adding a hidden layer with ReLU activation to the network and observe how loss changes.
💡 Hint
Add nn.Linear and nn.ReLU layers between input and output layers, then rerun training.

Practice

(1/5)
1. What is the main purpose of the forward pass in a PyTorch model?
easy
A. To compute gradients for backpropagation
B. To update the model weights after training
C. To run input data through the model and get predictions
D. To calculate the loss between predictions and targets

Solution

  1. Step 1: Understand the forward pass role

    The forward pass takes input data and processes it through the model layers to produce predictions.
  2. Step 2: Differentiate from other steps

    Updating weights is done by the optimizer step, loss calculation measures error, and backward computes gradients.
  3. Final Answer:

    To run input data through the model and get predictions -> Option C
  4. Quick Check:

    Forward pass = predictions [OK]
Hint: Forward pass means getting predictions from inputs [OK]
Common Mistakes:
  • Confusing forward pass with weight update
  • Mixing loss calculation with forward pass
  • Thinking backward computes predictions
2. Which of the following is the correct PyTorch code to perform a backward pass on a loss tensor named loss?
easy
A. loss.step()
B. loss.backward()
C. loss.forward()
D. loss.update()

Solution

  1. Step 1: Identify the backward method

    In PyTorch, calling loss.backward() computes gradients for all tensors with requires_grad=True.
  2. Step 2: Check other options

    step() is for optimizers, forward() is for models, and update() is not a PyTorch method.
  3. Final Answer:

    loss.backward() -> Option B
  4. Quick Check:

    Backward pass uses loss.backward() [OK]
Hint: Use loss.backward() to compute gradients [OK]
Common Mistakes:
  • Using step() on loss instead of optimizer
  • Calling forward() on loss tensor
  • Trying to update loss directly
3. Given the following PyTorch code snippet, what will be printed?
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())
medium
A. A positive float value representing the loss before weight update
B. Zero, because optimizer.step() resets the loss
C. A tensor object, not a float
D. An error because backward() must be called after step()

Solution

  1. Step 1: Understand loss calculation and printing

    The loss is computed before backward and step, so loss.item() returns the scalar loss value as a float.
  2. Step 2: Confirm optimizer.step() effect

    Calling optimizer.step() updates weights but does not change the already computed loss tensor value.
  3. Final Answer:

    A positive float value representing the loss before weight update -> Option A
  4. Quick Check:

    loss.item() shows loss before update [OK]
Hint: Loss printed is before optimizer updates weights [OK]
Common Mistakes:
  • Thinking loss becomes zero after optimizer.step()
  • Expecting loss to be a tensor when printed
  • Calling backward() after step() causes error
4. Identify the error in this PyTorch training snippet:
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
outputs = model(inputs)
loss = loss_fn(outputs, targets)
optimizer.step()
loss.backward()
medium
A. Missing optimizer.zero_grad() before backward
B. Model parameters not passed to optimizer
C. Using wrong loss function
D. Calling optimizer.step() before loss.backward()

Solution

  1. Step 1: Check order of backward and step

    Gradients must be computed by loss.backward() before calling optimizer.step() to update weights.
  2. Step 2: Analyze given code order

    The code calls optimizer.step() before loss.backward(), so weights update happens without gradients.
  3. Final Answer:

    Calling optimizer.step() before loss.backward() -> Option D
  4. Quick Check:

    Backward before step is required [OK]
Hint: Always call loss.backward() before optimizer.step() [OK]
Common Mistakes:
  • Swapping backward and step order
  • Forgetting to zero gradients
  • Assuming step() computes gradients
5. You want to train a PyTorch model for one step with input x and target y. Which sequence of commands correctly performs forward pass, loss calculation, backward pass, and weight update?
hard
A. optimizer.zero_grad(); outputs = model(x); loss = loss_fn(outputs, y); loss.backward(); optimizer.step()
B. outputs = model(x); loss = loss_fn(outputs, y); optimizer.step(); loss.backward(); optimizer.zero_grad()
C. loss = loss_fn(x, y); outputs = model(x); optimizer.zero_grad(); loss.backward(); optimizer.step()
D. optimizer.step(); optimizer.zero_grad(); outputs = model(x); loss = loss_fn(outputs, y); loss.backward()

Solution

  1. Step 1: Understand correct training step order

    The correct order is: clear gradients, forward pass, compute loss, backward pass, then update weights.
  2. 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.
  3. Final Answer:

    optimizer.zero_grad(); outputs = model(x); loss = loss_fn(outputs, y); loss.backward(); optimizer.step() -> Option A
  4. Quick Check:

    Zero grad -> forward -> loss -> backward -> step [OK]
Hint: Clear grads, forward, loss, backward, then step [OK]
Common Mistakes:
  • Calling optimizer.step() before backward
  • Not zeroing gradients before backward
  • Computing loss before forward pass
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard