Implement Custom ReLU Autograd Function
Problem Statement
Implement a custom ReLU activation function using torch.autograd.Function.
Background
PyTorch allows creating custom differentiable operations by subclassing torch.autograd.Function. You must implement:
- forward(ctx, input): Compute the output and save tensors needed for backward
- backward(ctx, grad_output): Compute gradients w.r.t. inputs
Your Task
The starter code defines a CustomReLU class and test harness. Implement the forward method (compute ReLU and save what's needed for backpropagation) and the backward method (compute the gradient of ReLU with respect to its input). Use the convention that the gradient is where the input is (including exactly ) and passes the incoming gradient through where the input is .
Output Format
The function returns a dictionary with "output" (ReLU values) and "grad" (input gradients).
Example
None
{'output': [0.0, 0.0, 0.0, 1.0, 2.0], 'grad': [0.0, 0.0, 0.0, 1.0, 1.0]}- Input: the harness builds a fixed 1-D vector that tracks gradients, so the function takes no arguments.
- Forward: ReLU is applied element by element: , , , , , giving
[0.0, 0.0, 0.0, 1.0, 2.0]. - Upstream gradient: the loss is , so for every entry; the incoming gradient is all ones.
- Backward: by the chain rule, , where for and for . That yields =
[0.0, 0.0, 0.0, 1.0, 1.0]. - Notice: ReLU has no true derivative at ; the convention here treats it as , so the third gradient is
0.0even though that input sits on the kink. The derivative is exactly where the output is positive and where it is , so the gradient is a pattern scaled by the incoming gradient.
Constraints
- Must subclass torch.autograd.Function
- Must use ctx.save_for_backward
- Use @staticmethod for forward and backward