Skip to content

← ML Foundations step 9 of 10

Easy Primitives

Implement Gradient Descent Step

Gradient descent updates parameters in the direction opposite the loss gradient. The gradient tells you how the loss changes locally as each parameter changes. The learning rate controls how far to move.

For weights [5, -3], gradients [2, -1], and learning rate 0.1, the updated weights are [4.8, -2.9]. A positive gradient decreases that parameter; a negative gradient increases it.

The rule is new_weights = weights - lr * gradients. Here gradients means the derivative of the loss with respect to the weights, not the derivative of the weights themselves. A finite step need not reduce the loss if the learning rate is too large.

Your task

Implement gradient_descent_step(weights, gradients, lr) for matching floating-point tensors of any shape and a nonnegative Python float lr. Return the updated weights with the same shape, applying the rule to each element. Do not reduce or normalize the gradient.

The gradients are supplied. You do not compute a loss, call backward, zero a gradient buffer, or run an optimizer object. Return the result without changing either input tensor. With lr=0, the weight values stay the same; a zero gradient leaves its corresponding weight unchanged.