PIXELBANKv9.1.0
Menu

Implement Custom SGD Optimizer

Problem Statement

Implement a basic SGD optimizer from scratch by subclassing torch.optim.Optimizer.

Background

Building a custom optimizer teaches the fundamentals: iterate parameter groups, access .grad, and update .data in-place.

Your Task

The starter code defines a SimpleSGD class with init already implemented. Implement the step method that applies the basic SGD update rule to each parameter that has a gradient.

The training loop and verification are pre-filled.

Output Format

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

Example:

Input:
None
Output:
{'initial_weight': [0.7645, -0.8049, 0.2343], 'final_weight': [0.8373, -0.3944, 0.9289], 'weight_changed': True, 'is_optimizer': True}
Reasoning:
  • We start by defining the SimpleSGD class, which inherits from torch.optim.Optimizer, and create an instance of it with a learning rate of 0.1.
  • We then create a nn.Linear(3, 1) model, record its initial weights, and run 5 training steps using the SimpleSGD optimizer with mean squared error (MSE) loss: L=1n∑i=1n(yi−yi^)2L = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y_i})^2, where yiy_i is the target and yi^\hat{y_i} is the predicted output.
  • In each training step, the weights are updated according to the SGD update rule: param.data−=lrâ‹…param.gradparam.data -= lr \cdot param.grad, where lrlr is the learning rate and param.gradparam.grad is the gradient of the loss with respect to the parameter.
  • After the training steps, we record the final weights and compare them to the initial weights to determine if the weights have changed, and check if SimpleSGD is an instance of torch.optim.Optimizer to determine the value of "is_optimizer".

Constraints:

  • Subclass torch.optim.Optimizer
  • Implement step() with basic SGD update rule
  • Use @torch.no_grad() for step method
🔒

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.