PIXELBANKv9.1.0
Menu

Implement SGD with Momentum

Problem Statement

Extend SGD with momentum, tracking velocity buffers in the optimizer state.

Background

Momentum SGD maintains a velocity: v = momentum * v + grad, then param -= lr * v. This smooths updates and helps escape local minima. The velocity buffer must persist across optimizer steps.

Your Task

The starter code defines a MomentumSGD class with init already implemented. Implement the step method that maintains a velocity buffer for each parameter and applies the momentum update rule.

The training loop and verification are pre-filled.

Output Format

Returns a dictionary with "initial_weight", "final_weight", "has_velocity", and "weight_changed".

Example:

Input:
None
Output:
{'initial_weight': [0.7645, -0.8049, 0.2343], 'final_weight': [1.0577, 0.3795, 2.5983], 'has_velocity': True, 'weight_changed': True}
Reasoning:
  • We initialize the MomentumSGD optimizer with a learning rate of 0.1 and momentum of 0.9, and create a nn.Linear(3, 1) model.
  • The initial weights of the model are recorded as [0.7645, -0.8049, 0.2343], which will be used to calculate the initial_weight output.
  • We run 5 training steps with MomentumSGD, updating the model parameters using the momentum update rule: v=0.9â‹…v+gradv = 0.9 \cdot v + \text{grad}, then param−=0.1â‹…vparam -= 0.1 \cdot v, which changes the weights to [1.0577, 0.3795, 2.5983].
  • The optimizer state is checked for velocity buffers, and since MomentumSGD stores velocity in self.state[p], has_velocity is True, and since the weights have changed, weight_changed is also True.

Constraints:

  • Store velocity in self.state[p]
  • Update: v = momentum * v + grad, param -= lr * v
  • Use @torch.no_grad() on step
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Implement SGD with Momentum - Hard | PixelBank