When working with gradients in PyTorch, the key metric is the gradient values themselves. These values show how much each model parameter should change to reduce the error. Accessing .grad helps us understand if the model is learning properly. If gradients are zero or very small, the model might not learn well. If gradients are too large, the model might be unstable.
Gradient access (.grad) in PyTorch - Model Metrics & Evaluation
For gradient access, we don't use a confusion matrix. Instead, we look at the gradient tensor values. For example, after a backward pass, a parameter's gradient might look like this:
tensor([[ 0.01, -0.02],
[ 0.00, 0.03]])
This shows how much each parameter will update. Monitoring these values helps detect issues like vanishing or exploding gradients.
Think of gradients like directions on a map. If the directions are too weak (small gradients), you might not move enough to reach your goal (slow learning). If directions are too strong (large gradients), you might overshoot or get lost (unstable learning). The tradeoff is to have gradients that are just right -- strong enough to learn but not too strong to cause problems.
- Good: Gradients have moderate values, not zero, not extremely large. They change smoothly during training.
- Bad: Gradients are all zeros (no learning), or very large values (causing unstable updates), or NaN values (training breaks).
- Forgetting to call
optimizer.zero_grad()beforebackward()causes gradients to accumulate unexpectedly. - Accessing
.gradbeforebackward()returnsNonebecause gradients are not computed yet. - Not detaching tensors properly can cause memory leaks when accessing gradients.
- Ignoring gradient clipping can lead to exploding gradients and unstable training.
Your model's parameters have gradients that are all zeros after backward(). Is your model learning? Why or why not?
Answer: No, the model is not learning because zero gradients mean no updates will happen to the parameters. This could be due to a bug, such as missing loss calculation, or the model output not depending on the parameters.
Practice
.grad attribute of a PyTorch tensor represent?Solution
Step 1: Understand the role of
The.gradin PyTorch.gradattribute stores the gradient of the tensor computed during backpropagation.Step 2: Differentiate from other tensor properties
The tensor's value, shape, and data type are stored in other attributes, not.grad.Final Answer:
The gradient of the tensor after backpropagation -> Option CQuick Check:
.grad= gradient after backward() [OK]
- Confusing .grad with the tensor's value
- Expecting .grad before calling backward()
- Mixing .grad with tensor shape or dtype
x after backpropagation?Solution
Step 1: Recall the correct attribute for gradients
PyTorch stores gradients in the.gradattribute, accessed asx.grad.Step 2: Identify incorrect syntax
Methods likegradient()orget_grad()do not exist for tensors.Final Answer:
grad = x.grad -> Option AQuick Check:
Use.gradattribute, not methods [OK]
.grad attribute, not functions [OK]- Trying to call .grad as a function
- Using incorrect method names
- Accessing .gradient instead of .grad
import torch x = torch.tensor(2.0, requires_grad=True) y = x ** 3 z = y + 4 z.backward() print(x.grad)
What will be the output of
print(x.grad)?Solution
Step 1: Compute the derivative of
Givenzwith respect toxy = x^3andz = y + 4, the derivative isdz/dx = dy/dx = 3x^2.Step 2: Calculate the gradient at
Plugging inx=2.0x=2,3 * (2)^2 = 3 * 4 = 12. So,x.gradwill betensor(12.).Final Answer:
tensor(12.) -> Option BQuick Check:
Derivative 3x^2 at x=2 = 12 [OK]
- Forgetting to call backward() before accessing .grad
- Calculating derivative incorrectly
- Confusing y and z derivatives
import torch x = torch.tensor(3.0, requires_grad=True) y = x ** 2 print(x.grad)
But the output is
None. Why?Solution
Step 1: Check if backward() was called
Gradients are computed only after callingbackward()on the output tensor.Step 2: Confirm
Sincerequires_grad=Trueand missing backward()xhasrequires_grad=True, the missing step is callingy.backward().Final Answer:
You forgot to cally.backward()to compute gradients -> Option AQuick Check:
Call backward() before accessing .grad [OK]
- Expecting .grad before backward()
- Confusing requires_grad flag
- Thinking .grad auto-updates without backward()
import torch x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True) y = (x ** 2).sum() y.backward() print(x.grad)
What will be the output of
print(x.grad)?Solution
Step 1: Understand the function and gradient
The function isy = sum(x_i^2). The gradient ofywith respect tox_iisdy/dx_i = 2x_i.Step 2: Calculate gradients for each element
Forx = [1, 2, 3], gradients are[2*1, 2*2, 2*3] = [2, 4, 6].Final Answer:
tensor([2., 4., 6.]) -> Option DQuick Check:
Gradient of x^2 is 2x element-wise [OK]
- Confusing sum of squares with squares of sums
- Forgetting element-wise gradient
- Expecting None without backward()
Ready to prove it?
Pass the test and this pattern moves unknown
