The requires_grad flag tells PyTorch if it should track changes to a tensor so it can learn from them. This helps the model improve by adjusting values during training.
requires_grad flag in PyTorch
tensor = torch.tensor(data, requires_grad=True) # or requires_grad=False
Set requires_grad=True if you want PyTorch to track operations on this tensor.
Set requires_grad=False to stop tracking and save memory.
x that PyTorch will track for gradients.import torch x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y that will not track gradients.y = torch.tensor([4.0, 5.0, 6.0], requires_grad=False)
x to stop tracking gradients.x.requires_grad_(False)This program creates a tensor x that tracks gradients. It computes a simple function and then calculates gradients of z with respect to x. The gradients show how much z changes if x changes.
import torch # Create a tensor with requires_grad=True x = torch.tensor([2.0, 3.0], requires_grad=True) # Define a simple function y = x^2 + 3x y = x**2 + 3*x # Compute the sum to get a scalar output z = y.sum() # Compute gradients z.backward() # Print gradients of x print(x.grad)
Gradients are only computed for tensors with requires_grad=True.
You can turn off gradient tracking temporarily using with torch.no_grad(): for inference.
Changing requires_grad after tensor creation can be done with tensor.requires_grad_(True or False).
requires_grad tells PyTorch to track operations for learning.
Set it to True for tensors you want to update during training.
Set it to False to save memory or freeze parts of a model.
Practice
requires_grad=True on a PyTorch tensor do?Solution
Step 1: Understand the purpose of requires_grad
The flagrequires_grad=Truetells PyTorch to remember all operations on the tensor so it can compute gradients later.Step 2: Identify what happens when requires_grad is True
This tracking is essential for training models because gradients are used to update weights.Final Answer:
It tells PyTorch to track operations on the tensor for gradient calculation. -> Option AQuick Check:
requires_grad=True means track gradients [OK]
- Thinking requires_grad freezes the tensor
- Confusing requires_grad with tensor conversion
- Assuming it deletes the tensor
Solution
Step 1: Recall the correct argument name
The correct argument to enable gradient tracking isrequires_grad=True.Step 2: Check each option
torch.tensor([1.0, 2.0, 3.0], requires_grad=True) usesrequires_grad=True, which is correct. Options C and D use invalid argument names, and B disables gradient tracking.Final Answer:
torch.tensor([1.0, 2.0, 3.0], requires_grad=True) -> Option CQuick Check:
Use requires_grad=True to track gradients [OK]
- Using incorrect argument names like grad or track_grad
- Setting requires_grad to False by mistake
- Forgetting to set requires_grad at tensor creation
import torch x = torch.tensor([2.0, 3.0], requires_grad=True) y = x * 2 y.backward(torch.tensor([1.0, 1.0])) print(x.grad)
Solution
Step 1: Understand the operations and gradient flow
y = x * 2 means each element in x is multiplied by 2. The gradient of y with respect to x is 2 for each element.Step 2: Apply backward with gradient vector
Calling y.backward with tensor([1.0, 1.0]) sums gradients weighted by 1. So x.grad will be tensor([2., 2.]).Final Answer:
tensor([2., 2.]) -> Option AQuick Check:
Gradient of 2*x is 2 [OK]
- Expecting gradient to be the original tensor values
- Confusing output with input tensor
- Forgetting to call backward()
import torch x = torch.tensor([1.0, 2.0, 3.0]) y = x * 3 y.backward()
Solution
Step 1: Check requires_grad flag on x
x was created without requires_grad=True, so it does not track gradients. This means y also does not track gradients, causing backward() to fail.Step 2: Understand backward() requirements
The error occurs because tensors need grad_fn (from requires_grad=True) to call backward(). Additionally, non-scalar tensors need a gradient argument, so calling backward() without it on a vector tensor causes an error.Final Answer:
The tensor y is not a scalar, so backward() cannot be called. -> Option DQuick Check:
Non-scalar tensors require gradient argument in backward() [OK]
- Forgetting requires_grad=True on tensors before backward()
- Ignoring requires_grad flag importance
- Not providing gradient argument for vector tensors
Solution
Step 1: Understand how to freeze layers
Freezing means stopping gradient calculation for parameters by setting theirrequires_gradto False.Step 2: Check correct way to set requires_grad
Parameters are tensors inside the layer. We must setparam.requires_grad = Falsefor each parameter. for param in model.layer1.parameters(): param.requires_grad = False does this correctly.Final Answer:
for param in model.layer1.parameters(): param.requires_grad = False -> Option BQuick Check:
Set requires_grad=False on parameters to freeze [OK]
- Trying to set requires_grad on the whole layer object
- Setting requires_grad=True instead of False
- Confusing grad attribute with requires_grad
Ready to prove it?
Pass the test and this pattern moves unknown
