v9.1.1
Menu

Implement Custom ReLU Autograd Function

easyFREECustom Autograd FunctionsPyTorch Advanced

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 00 where the input is ≤0\le 0 (including exactly 00) and passes the incoming gradient through where the input is >0> 0.

Output Format

The function returns a dictionary with "output" (ReLU values) and "grad" (input gradients).

Example

Input
None
Output
{'output': [0.0, 0.0, 0.0, 1.0, 2.0], 'grad': [0.0, 0.0, 0.0, 1.0, 1.0]}
Reasoning
  • Input: the harness builds a fixed 1-D vector x=[−2,−1,0,1,2]x = [-2, -1, 0, 1, 2] that tracks gradients, so the function takes no arguments.
  • Forward: ReLU is f(x)=max⁡(0,x)f(x) = \max(0, x) applied element by element: max⁡(0,−2)=0\max(0,-2)=0, max⁡(0,−1)=0\max(0,-1)=0, max⁡(0,0)=0\max(0,0)=0, max⁡(0,1)=1\max(0,1)=1, max⁡(0,2)=2\max(0,2)=2, giving [0.0, 0.0, 0.0, 1.0, 2.0].
  • Upstream gradient: the loss is L=∑if(xi)L = \sum_i f(x_i), so ∂L∂f(xi)=1\frac{\partial L}{\partial f(x_i)} = 1 for every entry; the incoming gradient is all ones.
  • Backward: by the chain rule, ∂L∂xi=∂L∂f(xi)⋅f′(xi)\frac{\partial L}{\partial x_i} = \frac{\partial L}{\partial f(x_i)} \cdot f'(x_i), where f′(x)=1f'(x) = 1 for x>0x > 0 and 00 for x≤0x \le 0. That yields 1⋅[0,0,0,1,1]1 \cdot [0, 0, 0, 1, 1] = [0.0, 0.0, 0.0, 1.0, 1.0].
  • Notice: ReLU has no true derivative at x=0x = 0; the convention here treats it as 00, so the third gradient is 0.0 even though that input sits on the kink. The derivative is 11 exactly where the output is positive and 00 where it is 00, so the gradient is a 0/10/1 pattern scaled by the incoming gradient.

Constraints

  • Must subclass torch.autograd.Function
  • Must use ctx.save_for_backward
  • Use @staticmethod for forward and backward

Learn this in

More from PyTorch Advanced

solution.py

Test results

Sign in to run your code against the test cases.