P1.C10 drew the graph of and ran a backward pass by hand: at , the slopes are and . Here is the same calculation in PyTorch.
import torch
x = torch.tensor(1.0, requires_grad=True)
y = torch.tensor(2.0, requires_grad=True)
f = (x + y) * torch.sin(x)
f.backward()
print(x.grad, y.grad)
tensor(2.4624) tensor(0.8415)
The same numbers, with no derivative written by hand. But call f.backward() once more (on a fresh f) and x.grad will not show again. Why? Answering that, and the other questions a PyTorch beginner meets in the first week, is this lesson.
PyTorch does not run in the browser, so the code here runs in a notebook. Open the notebook in Colab (free; no GPU needed). The same file is on GitHub; both links work once the repository’s latest version is published. Every output in this lesson was copied from a run of that notebook on a CPU with PyTorch 2.9.1. The last digits of float32 numbers, and the exact wording of error messages, can differ a little in other versions. Part 1 of the site (P1.C10, P1.B14) explains the ideas; this lesson is about the library. NumPy itself is P2.2 and P2.3.
Tensors: NumPy arrays with extra powers
A tensor is a block of numbers with a fixed shape, exactly the idea of P1.B14. A PyTorch tensor is much like a NumPy array, with three extras: it can live on a GPU, it can record how it was computed (for gradients), and PyTorch’s layers and losses are written for it.
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([1, 2, 3])
print(a.dtype, b.dtype)
print(torch.tensor([1, 2.5]).dtype)
print(torch.tensor(np.array([1.0, 2.0])).dtype)
print(a.shape, a.size(), a.ndim, a.numel())
torch.float32 torch.int64
torch.float32
torch.float64
torch.Size([3]) torch.Size([3]) 1 3
Every tensor has a dtype (the type of its numbers), a shape (a.shape, or a.size(), the same thing), a number of axes (.ndim) and a number of entries (.numel()). The defaults to remember:
| You write | dtype you get |
|---|---|
a Python float, torch.tensor([1.0, 2.0]) | float32 (the default float type) |
a Python int, torch.tensor([1, 2, 3]), torch.arange(6) | int64 |
| a list with ints and floats | float32 |
a NumPy float64 array | float64 (the dtype is kept) |
NumPy’s default float is float64; PyTorch’s is float32 (torch.get_default_dtype()). Neural networks use float32 or smaller because it is faster and uses half the memory, and P1.G1 explains the formats. The difference causes a classic bug: a float64 NumPy array turned into a tensor and fed to a float32 layer or matrix product raises a dtype error (see the bug list below). Elementwise + does not raise; it silently gives float64. Use .float(), .double() or .to(torch.float32) to change a dtype.
Use .item() to get a plain Python number out of a one-entry tensor (loss.item()), for printing and logging.
Shapes, indexing and broadcasting
These work as in NumPy, and the rules are those of P1.B14 (and P2.3 in practice).
T = torch.arange(12).reshape(3, 4)
print(T[1], T[:, 1], T[T > 8])
col = torch.tensor([[10], [20], [30]])
row = torch.tensor([1, 2, 3, 4])
print((col + row).shape)
tensor([4, 5, 6, 7]) tensor([1, 5, 9]) tensor([ 9, 10, 11])
torch.Size([3, 4])
The first line shows a row, a column and a boolean mask. The (3, 1) tensor plus the (4,) tensor broadcast to (3, 4): the sizes are matched from the right, and a size of 1 is stretched.
view, reshape and shared memory
reshape and view give the same entries a new shape. A view shares the memory of the original, so a change to one shows in the other. A transpose is also a view: it changes how the memory is read (the strides), not the memory. After that, the entries are no longer in one straight run in memory (the tensor is not contiguous), and view can fail, while reshape copies when it has to.
v = T.view(4, 3)
v[0, 0] = 99
print(T[0, 0])
Tt = T.T
print(Tt.is_contiguous())
try:
Tt.view(12)
except RuntimeError as e:
print("RuntimeError:", str(e).split(".")[0])
print(Tt.reshape(12))
tensor(99)
False
RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces)
tensor([99, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11])
The change made through v showed up in T. The advice that follows: use reshape unless you need the guarantee of sharing, and remember that reshape does not tell you whether it copied. As in P1.B14, a reshape keeps the row-major order of the entries; to swap axes use transpose, permute or .T.
Tensors and NumPy: who shares memory?
Moving between NumPy and PyTorch is constant in practice (loading data, plotting). The rule to remember is about memory:
torch.from_numpy(a)andt.numpy()share memory with the other object. No copy is made, and a change to one is a change to the other.torch.tensor(a)copies.
n = np.array([1.0, 2.0, 3.0])
shared = torch.from_numpy(n)
copied = torch.tensor(n)
n[0] = 100.0
print(shared)
print(copied)
back = shared.numpy()
back[1] = -5.0
print(shared, n)
tensor([100., 2., 3.], dtype=torch.float64)
tensor([1., 2., 3.], dtype=torch.float64)
tensor([100., -5., 3.], dtype=torch.float64) [100. -5. 3.]
Sharing is fast (no copy of a large array), and a bug if you did not expect it. Note that the float64 dtype was kept.
There is a second rule: .numpy() only works on a CPU tensor that does not require gradients, because NumPy knows nothing about GPUs or graphs.
w = torch.tensor([1.0, 2.0], requires_grad=True)
try:
w.numpy()
except RuntimeError as e:
print("RuntimeError:", e)
print(w.detach().cpu().numpy())
RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
[1. 2.]
The safe habit is t.detach().cpu().numpy(): cut it from the graph, move it to the CPU, convert it. (detach is explained below.) The result still shares memory with t when t is already on the CPU; call .copy() (or .clone() first) if you will edit it.
Devices: CPU, GPU
A tensor lives on one device: "cpu", "cuda" (an NVIDIA GPU), or "mps" (the GPU in Apple-silicon Macs). A GPU does many multiplications at once, which is why neural networks are trained on it (P2.7). You move a tensor with .to(device), or create it there with device=. The usual line, which makes the code run anywhere, is:
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
x = torch.ones(3).to(device)
y = torch.ones(3, device=device)
print(device, (x + y).device)
cpu cpu
(This run was on a CPU. In Colab, choose Runtime, then Change runtime type, then a GPU, and it prints cuda cuda:0.) Two rules follow:
- Both operands of an operation must be on the same device. Adding a CPU tensor to a GPU tensor raises an error that starts with “Expected all tensors to be on the same device”. The fix is to
.to(device)the data and the model alike. - Copying between devices has a cost, so keep the data on the GPU while you work, and move it back only to print or plot (
.cpu(), which is the “cpu” step in the safe habit above).
Autograd: record, then differentiate
Make a tensor with requires_grad=True and PyTorch records every operation on it as the forward pass runs. The record is the graph of P1.C10, built as the code executes (which is why ordinary if and for work). Each result remembers the operation that made it, in grad_fn.
x = torch.tensor(1.0, requires_grad=True)
y = torch.tensor(2.0, requires_grad=True)
f = (x + y) * torch.sin(x)
print(f)
print(f.grad_fn.name())
print(x.is_leaf, f.is_leaf, x.grad)
f.backward()
print(x.grad, y.grad)
print(x.grad.item(), y.grad.item())
tensor(2.5244, grad_fn=<MulBackward0>)
MulBackward0
True False None
tensor(2.4624) tensor(0.8415)
2.4623780250549316 0.8414709568023682
Read it line by line:
fis , as in P1.C10, and it carriesgrad_fn=<MulBackward0>: it was made by a multiplication, and it knows how to send a gradient back through one.xandyare leaf tensors: you created them, no operation made them.fis not a leaf.- Before
backward(),x.gradisNone: nothing has been computed. f.backward()runs the backward pass of P1.C10 fromf, starting with a gradient of 1, and stores the result inx.gradandy.grad: and , the sum of two paths into as in P1.C10.- The last line shows the float32 digits. float32 keeps about seven digits, so is right to the digits of P1.C10.
Three rules summarise what autograd does:
backward()is called on a scalar (one number, usually the loss). That is the “one output, many inputs” case where reverse mode wins (P1.C10). For a non-scalar, see the deeper box.- Only leaf tensors with
requires_grad=Trueget a.grad. The gradient at an in-between value is computed on the way and then thrown away. (If you need one, call.retain_grad()on it beforebackward(); asking a non-leaf for.gradgivesNoneand aUserWarning.) - Only floating-point tensors can require gradients.
torch.tensor([1, 2, 3], requires_grad=True)raises “Only Tensors of floating point and complex dtype can require gradients”.
You set requires_grad=True on the parameters (the things you will change), not on the data.
The P4.8 neuron
P4.8 runs one neuron by hand: , target , , , with and . There and .
xin, target = 2.0, 3.0
w = torch.tensor(1.5, requires_grad=True)
b = torch.tensor(-1.0, requires_grad=True)
yhat = w * xin + b
loss = (yhat - target) ** 2
print(yhat.item(), loss.item())
loss.backward()
print(w.grad, b.grad)
2.0 1.0
tensor(-4.) tensor(-2.)
, , and the gradients are and , the numbers of the hand computation: and . loss.backward() here does exactly the backward pass that P4.8 walks through.
Autograd with matrices
The nodes of a real network hold whole tensors, and the local rules are the matrix rules of P1.C11. Autograd applies them for you. For and a loss whose gradient at is , P1.C11’s rules say the gradient with respect to is and with respect to it is .
W = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], requires_grad=True)
x = torch.tensor([1.0, 0.0, -1.0], requires_grad=True)
g = torch.tensor([1.0, 2.0])
v = W @ x
loss = (g * v).sum()
loss.backward()
print(v)
print(W.grad)
print(x.grad)
tensor([-2., -2.], grad_fn=<MvBackward0>)
tensor([[ 1., 0., -1.],
[ 2., 0., -2.]])
tensor([ 9., 12., 15.])
Here with and has rows and , which is W.grad, and , which is x.grad. The library has no special code for this example: every node has its own backward rule.
Gradients accumulate
Back to the hook. A call to backward() adds to .grad. It does not replace it. It follows the same rule as the fan-out of P1.C10, where gradients arriving at one value add, only here the additions happen across calls.
t = torch.tensor(3.0, requires_grad=True)
(t * t).backward()
print(t.grad)
(t * t).backward()
print(t.grad)
t.grad.zero_()
(t * t).backward()
print(t.grad)
t.grad = None
print(t.grad)
tensor(6.)
tensor(12.)
tensor(6.)
None
The slope of at 3 is . The second call added another and gave . After t.grad.zero_() (reset in place) the next call gives again. Setting t.grad = None (drop it) also works. A training loop therefore resets the gradients once per step, before backward() (P2.7’s optimizer has optimizer.zero_grad() for this). Forgetting is the most common PyTorch beginner bug, and it does not raise an error: the numbers are simply wrong, as the loop below shows.
Accumulation is not always a nuisance: adding up the gradients of several small batches before one update is a real technique (gradient accumulation), used when a whole batch does not fit in memory.
no_grad, detach and inference_mode
Recording a graph costs memory and time. You do not want one when you only use a model (evaluation), and you do not want the update step recorded either (it is not part of the function being differentiated).
w = torch.tensor(2.0, requires_grad=True)
z = w * 3
print(z.requires_grad, z.grad_fn.name())
with torch.no_grad():
z2 = w * 3
print(z2.requires_grad, z2.grad_fn)
with torch.inference_mode():
z3 = w * 3
print(z3.requires_grad)
d = z.detach()
print(d.requires_grad, d.item())
True MulBackward0
False None
False
False 6.0
- Inside
with torch.no_grad():nothing is recorded: the result hasrequires_grad=Falseand nograd_fn. Use it for evaluation and for parameter updates. torch.inference_mode()is a stricter version for pure inference. It can be faster, but a tensor made inside it cannot be used later in a computation that autograd records (PyTorch raises “Inference tensors cannot be saved for backward”).t.detach()returns a tensor with the same data that is cut off from the graph. It shares memory witht, so editing the detached tensor in place changes the original.
So no_grad is a context that switches recording off for the operations inside it, while detach cuts one tensor out of a graph that already exists. (No gradient flows back through a detached tensor, so detach is also a way to stop the backward pass at a chosen point.)
A manual gradient-descent loop
Now the P0.2 line. The data are , the model is , the loss is the mean of the squared errors, we start at , and use . P0.2 found a loss of and slopes and ; one step gives , .
xs = torch.tensor([1.0, 2.0, 3.0])
ys = torch.tensor([2.0, 3.0, 7.0])
w = torch.tensor(1.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
eta = 0.05
pred = w * xs + b
loss = ((pred - ys) ** 2).mean()
print(loss.item())
loss.backward()
print(w.grad.item(), b.grad.item())
6.0
-10.0 -4.0
The loss is and autograd’s gradient is , matching the by-hand numbers of P0.2 (the formulas are and ). Now the loop: forward, backward, update inside no_grad, reset.
w = torch.tensor(1.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
for step in range(200):
loss = ((w * xs + b - ys) ** 2).mean()
loss.backward()
with torch.no_grad():
w -= eta * w.grad
b -= eta * b.grad
w.grad = None
b.grad = None
if step in (0, 1, 9, 199):
print(f"after {step + 1:3d} steps: w={w.item():.3f} b={b.item():.3f}")
print("final loss:", ((w * xs + b - ys) ** 2).mean().item())
after 1 steps: w=1.500 b=0.200
after 2 steps: w=1.727 b=0.280
after 10 steps: w=1.958 b=0.232
after 200 steps: w=2.446 b=-0.876
final loss: 0.5022006034851074
After one step, and , exactly the first update of P0.2. After 200 steps the line is near , , the best line of P0.2, and the loss is , close to the lowest possible .
Why the no_grad? w is a leaf that requires gradients, and PyTorch refuses to change such a tensor in place when the change would be recorded (the error says “a leaf Variable that requires grad is being used in an in-place operation”). Inside no_grad the in-place update is allowed, and it is not recorded. The tempting alternative, w = w - eta * w.grad outside no_grad, makes a new non-leaf w that is attached to the old graph, and the next backward() leaves w.grad as None.
What happens without the reset
Remove the two grad = None lines and run two steps:
w = torch.tensor(1.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
for step in range(2):
loss = ((w * xs + b - ys) ** 2).mean()
loss.backward()
print(f"step {step + 1}: w.grad={w.grad.item():.3f}")
with torch.no_grad():
w -= eta * w.grad
b -= eta * b.grad
step 1: w.grad=-10.000
step 2: w.grad=-14.533
The correct gradient on the second step is (the loop above used it to reach ). Here the old was still there, so the step used and overshoots. There is no error, only a loop that takes wrong steps.
Check a gradient with finite differences
P1.C4 and P4.8 check a gradient by nudging the input, and the check is worth knowing in PyTorch too. This browser cell does it in NumPy for the loss above at , and compares it with the formulas. (PyTorch does not run in the browser, so the cell is the NumPy version of what gradcheck does, see the box below.)
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The central differences give , the same as autograd and the formulas; the one-sided step with gives , a little off, as P1.C1 explains. Try changing w, b and h.
Common bugs, in one list
- Training gets worse for no clear reason, no error. Cause: gradients not reset, so they accumulate. Fix: reset every step (
grad = None, oroptimizer.zero_grad()in P2.7). .numpy()raises “Can’t call numpy() on Tensor that requires grad”. Cause: the tensor is part of a graph. Fix:t.detach().cpu().numpy().- “Expected all tensors to be on the same device”. Cause: data on the CPU, model on the GPU, or the reverse. Fix:
.to(device)for both. - dtype error such as “expected both vectors to have same dtype, but found Float and Double” (also “mat1 and mat2 must have the same dtype” in
nn.Linear). Cause: a matrix product or layer got float32 and float64, often because a NumPy float64 array was converted. (Elementwise+or*does not fail: it silently promotes to float64.) Fix:.float()or.to(torch.float32). backward()raises “grad can be implicitly created only for scalar outputs”. Cause: the output is not a scalar. Fix: reduce it to a scalar (.sum(),.mean()), or passgradient(deeper box).w.gradisNone. Cause:wis not a leaf, orrequires_gradis off. Fix: create it as a leaf withrequires_grad=True; do not rebind it withw = w - ...(that also gives a warning).- “Trying to backward through the graph a second time”. Cause: the saved values were freed by the first
backward(). Fix: rebuild the graph with a new forward pass (deeper box). - “Only Tensors of floating point and complex dtype can require gradients”. Cause: an integer tensor. Fix: use a float tensor.
Go deeper
Go deeper retain_graph: backward twice through one graph
By default PyTorch frees the saved values of a graph when backward() finishes, because they are only needed for that one pass (and they take memory, P1.C10). A second backward() through the same graph then fails. Call backward(retain_graph=True) to keep them.
s = torch.tensor(3.0, requires_grad=True)
u = s * s
u.backward()
try:
u.backward()
except RuntimeError as e:
print("RuntimeError:", str(e).split("(")[0].strip())
u2 = s * s
u2.backward(retain_graph=True)
u2.backward()
print(s.grad)RuntimeError: Trying to backward through the graph a second time
tensor(18.)s.grad is : the first (successful) call gave 6 and then two calls on the second graph gave 6 each, added together. In a normal loop you rebuild the graph with each forward pass, so you rarely need retain_graph.
Go deeper backward() on a non-scalar needs a gradient
Reverse mode starts with a gradient of 1 at a single output (P1.C10). For a vector output PyTorch does not know which single number you want to differentiate, so it asks. You supply a gradient argument, the weight given to each output entry, and PyTorch backpropagates .
p = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
q = p ** 2
try:
q.backward()
except RuntimeError as e:
print("RuntimeError:", e)
q.backward(torch.ones(3))
print(p.grad)RuntimeError: grad can be implicitly created only for scalar outputs
tensor([2., 4., 6.])With all weights 1 this is the same as calling q.sum().backward(), and gives . (This is the of P1.C10: one backward pass gives one weighted sum of the rows of the Jacobian.)
Go deeper In-place operations can break backward
A node often saves a value for its backward rule (the sine saves its input, the exponential saves its output). If you then change that value in place (add_, +=, x[0] = ...), the saved value is wrong, and PyTorch notices (each tensor has a version counter) and raises an error.
r = torch.tensor(0.5, requires_grad=True)
e = torch.exp(r)
e.add_(1.0)
try:
e.backward()
except RuntimeError as err:
print("RuntimeError:", str(err).split(":")[0])RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operationThe derivative of is itself, so the backward rule needed the output, and the in-place add_ changed it. The fix is to write e = e + 1.0 (a new tensor). The error is a feature: it replaces a silently wrong gradient. The update w -= ... inside no_grad is safe because it happens outside the recorded graph.
Go deeper gradcheck: let PyTorch compare with finite differences
P4.8 says to check a hand-written backward rule with finite differences. PyTorch has a function for it, torch.autograd.gradcheck, which compares autograd’s gradient with a numerical one. It needs float64 inputs, because float32 does not have the digits to make a small difference reliable.
def fn(a, b):
return ((a * 2.0 + b - 1.5) ** 2).sum()
a64 = torch.tensor([0.3, -1.2], dtype=torch.float64, requires_grad=True)
b64 = torch.tensor([0.5, 0.7], dtype=torch.float64, requires_grad=True)
print(torch.autograd.gradcheck(fn, (a64, b64)))TrueYou rarely need it for built-in operations, which PyTorch has tested. It is for the backward rule of a new operation you write yourself.
Go deeper float32 against float64
P1.G1 shows how the formats are stored. float32 keeps about 7 decimal digits, float64 about 16. That has visible effects:
x32 = torch.tensor(0.1)
x64 = torch.tensor(0.1, dtype=torch.float64)
print(f"{x32.item():.20f}")
print(f"{x64.item():.20f}")
print((torch.tensor(1e8) + 1 == torch.tensor(1e8)).item())
print((torch.tensor(1e8, dtype=torch.float64) + 1 == torch.tensor(1e8, dtype=torch.float64)).item())0.10000000149011611938
0.10000000000000000555
True
FalseMixing the two behaves differently for different operations:
a32 = torch.tensor([1.0, 2.0])
b64 = torch.tensor([1.0, 2.0], dtype=torch.float64)
print((a32 + b64).dtype)
try:
torch.ones(2, 2) @ torch.ones(2, 2, dtype=torch.float64)
except RuntimeError as e:
print("RuntimeError:", str(e).split(",")[0])torch.float64
RuntimeError: expected m1 and m2 to have the same dtypeElementwise + silently promotes to float64, but the matrix product raises an error. Neither format stores 0.1 exactly, and float32 is off in the eighth digit. In float32, adding to changes nothing (the gap between neighbouring float32 numbers near is larger than 1); in float64 it does. For the same reason, a gradient computed in float32 differs from the float64 one in its last digits: for the graph at the start of this lesson, float32 gives and float64 gives . That is normal rounding, not a bug. Use float64 for gradient checks and float32 (or smaller, P1.G1) for training.
Quiz
Check your understanding
What is the dtype of
torch.tensor([1, 2, 3])?Python ints give
int64in PyTorch. A float32 tensor needs at least one Python float in the list ([1.0, 2, 3]), a float64 tensor needs a NumPy float64 array ordtype=torch.float64, andint32has to be asked for explicitly.You run
n = np.array([1.0, 2.0]), thent = torch.from_numpy(n), thenn[0] = 5.0. What doesthold?torch.from_numpyshares memory with the array, so the change shows in the tensor. The copy would come fromtorch.tensor(n). Nothing is broadcast, and changing the array afterwards is allowed.For , you call
(t * t).backward()twice on two fresh graphs, with no reset in between, and then printt.grad. What do you see?The slope of at 3 is 6, and each backward pass adds its 6 to
.grad, so after two passes it is 12. The value 6 would be the result with a reset between the calls (or with a single call). The value 3 is the value of , not a slope, and 36 would come from multiplying 6 by 6 instead of adding.Why is the parameter update
w -= eta * w.gradwritten insidewith torch.no_grad():?The update is not part of the function being differentiated, so it must stay out of the graph, and an in-place change to a tracked leaf is an error. Saving time and memory is a side effect, not the reason.
no_graddoes not reset gradients (that isgrad = Noneorzero_grad), and it does not change any dtype.You call
.numpy()on a tensor withrequires_grad=Trueand get an error. What is the standard fix?detachremoves the tensor from the graph (NumPy knows nothing about graphs) andcpumakes sure the data is not on a GPU. Settingrequires_gradto True is what caused the error.from_numpyconverts in the other direction, andbackwardneeds a scalar and has nothing to do with the conversion.After
loss.backward(), which tensors have a non-None.gradby default?By default PyTorch keeps gradients only on leaf tensors that require them (the parameters). In-between values are computed and dropped unless you call
retain_grad(). The loss is a non-leaf with no.grad, and the device does not matter.
Exercises
- Predict the dtype of each:
torch.tensor([1, 2]),torch.tensor([1, 2.5]),torch.arange(4),torch.tensor(np.array([1.5])).Show answer
int64,float32,int64,float64. Python ints giveint64, a list with a float givesfloat32,arangeof ints givesint64, and a NumPy float64 array keeps its dtype. - Use autograd to find the slope of at . What should you see, and why must
xbe a float?Show answer
x = torch.tensor(2.0, requires_grad=True); (x ** 3).backward(); print(x.grad)givestensor(12.), since . An integer tensor cannot require gradients. tis 3.0 withrequires_grad=True. You call(t * t).backward()three times with no reset. What ist.grad?Show answer
18: each call adds 6.- A student writes
w = w - eta * w.grad(nono_grad, no in-place operator) in the loop and finds thatw.gradisNoneon the next step. Why?Show answer
The right-hand side is a recorded operation, so the newwis a non-leaf result of the graph, not a leaf. Only leaves keep a.grad, so it isNone. Usewith torch.no_grad(): w -= eta * w.grad. - Compute by hand the gradient of the P0.2 loss (data ) at , , and say what the first update with gives.
Show answer
The errors are . and . The update gives , . - Write the one-line conditional that picks
cuda, thenmps, thencpu, and name two objects you must move to it before training.Show answer
Test for CUDA first (torch.cuda.is_available()), then for thempsbackend, and fall back to"cpu", as in the lesson. Move the model (its parameters) and every batch of data with.to(device). T = torch.arange(6).reshape(2, 3). Why doesT.T.view(6)fail whileT.T.reshape(6)works, and what does the second give?Show answer
The transpose is a view with swapped strides, so its entries are not in one run in memory, andviewcannot flatten it without copying.reshapecopies when it must. The result istensor([0, 3, 1, 4, 2, 5]), the entries read column by column.- For the neuron of P4.8 (, target 3, , ), write the PyTorch code for the gradients, then say what they become if the target is 5.
Show answer
As in the lesson, the code ends withloss.backward()and readsw.grad,b.grad. With target 5 the error is , so and .
Next: P2.7 puts this into the PyTorch training loop with nn.Module, Dataset, DataLoader, an optimizer (which does the no_grad update and the reset for you) and the GPU. P4.8 shows what backward() does step by step, and P4.9 builds a small autograd engine yourself.