0
0
PyTorchml~10 mins

requires_grad flag in PyTorch - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a tensor that tracks gradients.

PyTorch
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=[1])
Drag options to blanks, or click blank then click option'
ANone
BFalse
CTrue
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using False disables gradient tracking, so gradients won't be computed.
Using None or 0 are invalid values for requires_grad.
2fill in blank
medium

Complete the code to stop gradient tracking on a tensor.

PyTorch
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
x = x.detach()
x.requires_grad = [1]
Drag options to blanks, or click blank then click option'
ATrue
BNone
C0
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Setting requires_grad to True keeps tracking gradients.
Using None or 0 are not valid boolean values for requires_grad.
3fill in blank
hard

Fix the error in the code to enable gradient tracking on a new tensor copied from x.

PyTorch
import torch
x = torch.tensor([1.0, 2.0, 3.0])
y = x.clone()
y.requires_grad = [1]
Drag options to blanks, or click blank then click option'
ATrue
BNone
CFalse
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving requires_grad as False means no gradients will be tracked.
Using None or 0 are invalid for requires_grad.
4fill in blank
hard

Fill both blanks to create a tensor with gradient tracking and then disable it.

PyTorch
import torch
x = torch.tensor([4.0, 5.0], requires_grad=[1])
x.requires_grad = [2]
Drag options to blanks, or click blank then click option'
ATrue
BFalse
CNone
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Setting requires_grad to None or 0 causes errors.
Not disabling gradient tracking when needed.
5fill in blank
hard

Fill all three blanks to create a tensor, clone it with gradients, and then disable gradients on the clone.

PyTorch
import torch
x = torch.tensor([7.0, 8.0], requires_grad=[1])
y = x.clone()
y.requires_grad = [2]
z = y.detach()
z.requires_grad = [3]
Drag options to blanks, or click blank then click option'
ATrue
BFalse
CNone
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Not enabling gradients on the clone.
Not disabling gradients after detaching.