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
None
{'grad_half': [0.5, 0.5, 0.5, 0.5], 'grad_reverse': [-1.0, -1.0, -1.0, -1.0]}- Input: the harness builds . Each run passes and a plain number (first , then ) through
GradientScale, then sums the result into the loss . - Forward: the map is the identity, , so and . The value of changes nothing here.
- Plain chain rule: and , so a plain identity gives .
- Scaled backward: this layer deliberately reports times the incoming gradient instead. With : per element, giving
[0.5, 0.5, 0.5, 0.5]. With : 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 at all, only on . The harness resets the stored gradient between runs; otherwise the second result would accumulate to .
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)