0
0
PyTorchml~10 mins

Dynamic computation graph advantage 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 with gradient tracking enabled.

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
BTrue
CFalse
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Setting requires_grad to False will not track gradients.
Using None or 0 will cause errors or no gradient tracking.
2fill in blank
medium

Complete the code to perform a dynamic computation where the number of operations depends on input size.

PyTorch
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
result = 0
for i in range(x.size(0)):
    result += x[i] * [1]
Drag options to blanks, or click blank then click option'
A2
Bx
Ci
Dresult
Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed number like 2 makes the graph static.
Using the whole tensor x or result causes errors or wrong calculations.
3fill in blank
hard

Fix the error in the code to correctly compute gradients with a dynamic graph.

PyTorch
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
result = 0
for i in range(x.size(0)):
    result += x[i] * i
result.[1]()
Drag options to blanks, or click blank then click option'
Abackward
Bbackprop
Cgrad
Dcompute_grad
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'grad' or 'backprop' are not valid PyTorch methods.
Not calling backward() means gradients won't be computed.
4fill in blank
hard

Fill both blanks to create a dynamic computation graph that sums squares of input elements greater than 2.

PyTorch
import torch
x = torch.tensor([1.0, 3.0, 4.0], requires_grad=True)
result = 0
for val in x:
    if val [1] 2:
        result += val [2] 2
result.backward()
Drag options to blanks, or click blank then click option'
A>
B**
C*
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' changes the condition.
Using '*' instead of '**' multiplies by 2 instead of squaring.
5fill in blank
hard

Fill all three blanks to build a dynamic graph that creates a dictionary of squares for even numbers in a list.

PyTorch
numbers = [1, 2, 3, 4, 5]
squares = { [1]: [2] for [3] in numbers if [3] % 2 == 0 }
Drag options to blanks, or click blank then click option'
Anum
Bnum ** 2
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently causes errors.
Using multiplication instead of exponentiation changes the result.