BasicsPyTorchAutogradGoogleMetaAmazon
Problem
Using PyTorch autograd (.backward()), implement poly_value_and_grad(x_val) for the polynomial y=3x2+2x+1 and return (y_float, grad_float) as a tuple of standard Python floats.
Why It Matters: Understanding requires_grad=True, .backward(), and .grad is the foundation of custom loss functions, gradient debugging, and training loops in PyTorch.
Function Signature
import torch
def poly_value_and_grad(x_val: float) -> tuple[float, float]:
"""Compute y = 3x^2 + 2x + 1 and dy/dx using PyTorch autograd."""
Sample Input & Output
Example 1: Positive Input x = 2.0
Input:
x_val = 2.0
Expected Output:
(17.0, 14.0)
Explanation: y=3(2)2+2(2)+1=17.0, and dxdy=6x+2=6(2)+2=14.0.
Example 2: Negative Input x = -1.0
Input:
x_val = -1.0
Expected Output:
(2.0, -4.0)
Explanation: y=3(−1)2+2(−1)+1=2.0, and dxdy=6(−1)+2=−4.0.
Example 3: Zero Input x = 0.0
Input:
x_val = 0.0
Expected Output:
(1.0, 2.0)
Explanation: At x=0, the constant term gives y=1.0 and the linear slope gives dxdy=2.0.
Constraints & Edge Cases
- Return
(y_val, grad_val)as Python floats using PyTorch autograd. - Create
x = torch.tensor(float(x_val), dtype=torch.float32, requires_grad=True)before computingy. - Extract scalar Python floats via
float(y.item())andfloat(x.grad.item()).
Constraints & Evaluation Criteria
- Return `(y_val, grad_val)` as Python floats using PyTorch autograd.
Hints
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
x_val = 2.0
Expected Output / Criteria
(17.0, 14.0)