v9.1.1
Menu

Custom Polynomial Activation Function

mediumFREECustom Autograd FunctionsPyTorch Advanced

Problem Statement

Create a custom autograd function that implements a polynomial activation: f(x) = x² + 2x + 1.

Background

Sometimes you need activation functions not available in PyTorch. By subclassing torch.autograd.Function, you can define both the forward computation and its derivative for backpropagation.

Your Task

The starter code defines a PolyActivation class and test harness. Implement the forward method to compute f(x) = x² + 2x + 1, and the backward method to compute the correct derivative. Think about what the derivative of this polynomial is.

Output Format

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

Example

Input
None
Output
{'output': [4.0, 9.0, 16.0, 0.0], 'grad': [4.0, 6.0, 8.0, 0.0]}
Reasoning
  • Input: the harness builds a fixed 1-D tensor of four values, 1,2,3,−11, 2, 3, -1, and reports two things per element: the activation value and the gradient flowing back to it.
  • Forward: f(x)=x2+2x+1=(x+1)2f(x) = x^2 + 2x + 1 = (x+1)^2, so f(1)=4f(1) = 4, f(2)=9f(2) = 9, f(3)=16f(3) = 16, f(−1)=0f(-1) = 0, giving [4.0, 9.0, 16.0, 0.0].
  • Backward: the harness adds the four outputs into one scalar L=∑if(xi)L = \sum_i f(x_i), so the upstream gradient at each output is 11. By the chain rule ∂L/∂xi=1⋅f′(xi)\partial L / \partial x_i = 1 \cdot f'(x_i) with f′(x)=2x+2f'(x) = 2x + 2: 4,6,8,04, 6, 8, 0, giving [4.0, 6.0, 8.0, 0.0].
  • Output: a dictionary with keys output and grad, each a list of floats rounded to 1 decimal place.
  • Notice that x=−1x = -1 is the parabola's minimum, so value and slope are both 00 there. Also, the derivative must be evaluated at the original input xx, not at f(x)f(x): using f(1)=4f(1) = 4 would give 1010 instead of 44.

Constraints

  • Must use torch.autograd.Function
  • Forward: x^2 + 2x + 1
  • Backward: 2x + 2

More from PyTorch Advanced

solution.py

Test results

Sign in to run your code against the test cases.