PyTorch Autograd Basics: Compute dy/dx With .backward()

Basics
BasicsPyTorchAutogradGoogleMetaAmazon

Problem

Using PyTorch autograd (.backward()), implement poly_value_and_grad(x_val) for the polynomial y=3x2+2x+1y = 3x^2 + 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.0y = 3(2)^2 + 2(2) + 1 = 17.0, and dydx=6x+2=6(2)+2=14.0\frac{dy}{dx} = 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.0y = 3(-1)^2 + 2(-1) + 1 = 2.0, and dydx=6(−1)+2=−4.0\frac{dy}{dx} = 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=0x = 0, the constant term gives y=1.0y = 1.0 and the linear slope gives dydx=2.0\frac{dy}{dx} = 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 computing y.
  • Extract scalar Python floats via float(y.item()) and float(x.grad.item()).

Constraints & Evaluation Criteria

  • Return `(y_val, grad_val)` as Python floats using PyTorch autograd.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
x_val = 2.0
Expected Output / Criteria
(17.0, 14.0)