Skip to content

← Optimizers & Training step 2 of 8

Medium Primitives

Implement Momentum Update

Momentum keeps a running buffer of past gradients. Each step retains a fraction of the old buffer and adds the current gradient. That updated buffer determines the weight change.

This exercise uses the following convention:

new_velocity = momentum * velocity + gradients

new_weights = weights - lr * new_velocity

For weights [1, 2], gradients [0.5, -0.5], old velocity [1, 0], lr=0.1, and momentum=0.9, the new velocity is [1.4, -0.5] and the new weights are [0.86, 2.05]. The weights use the new velocity, not the buffer from the previous step.

Your task

Implement momentum_step(weights, gradients, velocity, lr, momentum). The three floating-point tensors have the same shape. lr is a nonnegative float and momentum is a float in [0, 1).

Return a Python dictionary with exactly these fields:

  • "new_weights": the updated weight tensor.
  • "new_velocity": the updated momentum-buffer tensor.

Both tensors keep the input shape. Do not return a tuple, and do not modify the input tensors. This is one update using supplied gradients; you do not calculate gradients or maintain hidden optimizer state.

The buffer stores a weighted sum of gradients, not a learning-rate-scaled parameter change. Do not multiply the current gradient by 1 - momentum, and do not add weight decay or a Nesterov correction.

With momentum=0, the new velocity equals the current gradient. With a zero current gradient, a nonzero old velocity can still move the weights. With lr=0, the weight values stay unchanged but the velocity still updates.