v9.1.1
Menu

Custom Gradient Scaling Function

mediumPROCustom Autograd FunctionsPyTorch Advanced

Problem Statement

Implement a gradient scaling function that acts as identity in the forward pass but scales the gradient by a factor in the backward pass.

Background

Gradient scaling is used in techniques like gradient reversal layers (for domain adaptation) or gradient scaling for multi-task learning. The forward pass is identity, but backward multiplies gradients by a scalar.

Your Task

The starter code defines a GradientScale class and test harness. Implement a function that passes input through unchanged in the forward pass but multiplies the gradient by a given scale factor in the backward pass. Note that the scale is a plain number, not a tensor.

The test applies scale=0.5 and scale=-1.0 (gradient reversal) to verify both cases.

Output Format

The function returns a dictionary with "grad_half" and "grad_reverse".

Example

Input
None
Output
{'grad_half': [0.5, 0.5, 0.5, 0.5], 'grad_reverse': [-1.0, -1.0, -1.0, -1.0]}
Reasoning
  • Input: the harness builds x=[1.0,2.0,3.0,4.0]x = [1.0, 2.0, 3.0, 4.0]. Each run passes xx and a plain number ss (first s=0.5s = 0.5, then s=−1.0s = -1.0) through GradientScale, then sums the result into the loss L=∑iyiL = \sum_i y_i.
  • Forward: the map is the identity, y=xy = x, so y=[1,2,3,4]y = [1, 2, 3, 4] and L=10L = 10. The value of ss changes nothing here.
  • Plain chain rule: ∂L∂yi=1\frac{\partial L}{\partial y_i} = 1 and ∂yi∂xi=1\frac{\partial y_i}{\partial x_i} = 1, so a plain identity gives ∂L∂x=[1,1,1,1]\frac{\partial L}{\partial x} = [1, 1, 1, 1].
  • Scaled backward: this layer deliberately reports ss times the incoming gradient instead. With s=0.5s = 0.5: 0.5⋅1=0.50.5 \cdot 1 = 0.5 per element, giving [0.5, 0.5, 0.5, 0.5]. With s=−1.0s = -1.0: every entry flips sign, giving [-1.0, -1.0, -1.0, -1.0]. That is gradient reversal.
  • Notice: the gradient does not depend on the values 1,2,3,41, 2, 3, 4 at all, only on ss. The harness resets the stored gradient between runs; otherwise the second result would accumulate to 0.5+(−1.0)=−0.50.5 + (-1.0) = -0.5.

Constraints

  • Forward must be identity (return input unchanged)
  • Backward must scale gradient by given factor
  • Store scale using ctx.scale, not save_for_backward (scale is not a tensor)

More from PyTorch Advanced

PRO

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

Sign in to run your code against the test cases.