v9.1.1
Menu

Autograd Function with Multiple Outputs

mediumPROCustom Autograd FunctionsPyTorch Advanced

Problem Statement

Create a custom autograd function that returns multiple outputs from the forward pass.

Background

Some operations produce multiple results. Your custom function must handle gradients for each output separately, combining them correctly in the backward pass.

Your Task

The starter code defines a SplitAndScale class and test harness. Implement a function that separates positive and negative values from the input, scaling each appropriately. In the backward pass, handle the gradients from both outputs and combine them into a single gradient for the input.

Output Format

The function returns a dictionary with "positive", "negative", and "grad" keys.

Example

Input
None
Output
{'positive': [0.0, 0.0, 0.0, 4.0, 8.0], 'negative': [3.0, 1.0, 0.0, 0.0, 0.0], 'grad': [-1.0, -1.0, 0.0, 2.0, 2.0]}
Reasoning
  • The input x = [-3.0, -1.0, 0.0, 2.0, 4.0] is passed through the custom autograd function SplitAndScale.
  • The function splits the input into two tensors: positive = x.clamp(min=0) * 2 and negative = x.clamp(max=0) * -1, resulting in positive = [0.0, 0.0, 0.0, 4.0, 8.0] and negative = [3.0, 1.0, 0.0, 0.0, 0.0].
  • The function then computes the sum of both outputs, and calls backward to calculate the gradients. The gradients are computed as grad={gradpos⋅2if x>0gradneg⋅−1if x<00if x=0grad = \begin{cases} grad_{pos} \cdot 2 & \text{if } x > 0 \\ grad_{neg} \cdot -1 & \text{if } x < 0 \\ 0 & \text{if } x = 0 \end{cases}, resulting in a gradient of [-1.0, -1.0, 0.0, 2.0, 2.0].
  • The final output is a dictionary containing the positive output, negative output, and the gradient of the input.

Constraints

  • Must return two tensors from forward
  • Handle gradients for both outputs in backward
  • Use ctx.save_for_backward

More from PyTorch Advanced

PRO

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

Sign in to run your code against the test cases.