Autograd Function with Multiple Outputs
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
None
{'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]}- The input
x = [-3.0, -1.0, 0.0, 2.0, 4.0]is passed through the custom autograd functionSplitAndScale. - The function splits the input into two tensors:
positive = x.clamp(min=0) * 2andnegative = x.clamp(max=0) * -1, resulting inpositive = [0.0, 0.0, 0.0, 4.0, 8.0]andnegative = [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 , 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