PIXELBANKv9.1.0
Menu

Custom Gradient Scaling Function

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:
  • We define a custom gradient scaling function GradientScale that acts as an identity function in the forward pass, but scales the gradient by a factor in the backward pass.
  • We create an input tensor [1.0, 2.0, 3.0, 4.0] with requires_grad=True, apply GradientScale with scale=0.5, and then compute the sum of the output and call .backward(). This results in gradients being scaled by 0.5, so the gradients are [0.5,0.5,0.5,0.5][0.5, 0.5, 0.5, 0.5].
  • We zero the gradients, apply GradientScale with scale=-1.0 (gradient reversal), and then compute the sum of the output and call .backward(). This results in gradients being scaled by -1.0, so the gradients are [−1.0,−1.0,−1.0,−1.0][-1.0, -1.0, -1.0, -1.0].
  • The final output is a dictionary containing the two sets of gradients: {"grad_half": [0.5, 0.5, 0.5, 0.5], "grad_reverse": [-1.0, -1.0, -1.0, -1.0]}.

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)
🔒

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.