BasicsPyTorchActivationsGoogleMetaAmazon
Problem
Implement basic_relu(x) to apply the Rectified Linear Unit ReLU(x)=max(0,x) elementwise to any PyTorch tensor x without modifying x in place.
Why It Matters: ReLU is the classic deep learning nonlinearity that breaks linear collapse across stacked layers while avoiding sigmoid/tanh gradient saturation for positive activations.
Function Signature
import torch
def basic_relu(x: torch.Tensor) -> torch.Tensor:
"""Apply ReLU(x) = max(0, x) elementwise."""
Sample Input & Output
Example 1: Mixed Negative, Zero & Positive Values
Input:
x = torch.tensor([-2.0, 0.0, 3.5])
Expected Output:
tensor([0.0, 0.0, 3.5])
Explanation: Negative values are clamped to 0.0, while 0.0 and positive values pass through unchanged.
Example 2: 2D All-Negative Matrix
Input:
x = torch.tensor([[-1.5, -0.1], [-10.0, 2.0]])
Expected Output:
tensor([[0.0, 0.0], [0.0, 2.0]])
Explanation: ReLU preserves the exact (2, 2) tensor shape and zeroes every negative entry.
Constraints & Edge Cases
- Preserve input tensor shape and autograd graph.
- Must work for tensors of any rank (1D, 2D, 3D, etc.).
- Do not mutate the input tensor in place (avoid
.clamp_(min=0.0)).
Constraints & Evaluation Criteria
- Preserve input tensor shape and autograd graph.
Hints
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[-2.0, 0.0, 3.5]
Expected Output / Criteria
[0.0, 0.0, 3.5]