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
None
{'initial_weight': [0.7645, -0.8049, 0.2343], 'final_weight': [1.0577, 0.3795, 2.5983], 'has_velocity': True, 'weight_changed': True}- We initialize the
MomentumSGDoptimizer with a learning rate of 0.1 and momentum of 0.9, and create ann.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 theinitial_weightoutput. - We run 5 training steps with MomentumSGD, updating the model parameters using the momentum update rule: , then , which changes the weights to
[1.0577, 0.3795, 2.5983]. - The optimizer state is checked for velocity buffers, and since
MomentumSGDstores velocity inself.state[p],has_velocityis True, and since the weights have changed,weight_changedis also True.
Constraints
- Store velocity in self.state[p]
- Update: v = momentum * v + grad, param -= lr * v
- Use @torch.no_grad() on step