Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 2: Programming Toolkit

PyTorch tensors and autograd

P2.640 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Almost all modern deep-learning code is written with PyTorch tensors. The data, the weights and the activations are tensors, and the gradients that training needs come from autograd, so you write the forward pass and never derive a gradient by hand.

  • A training loop is forward pass, loss, backward(), update, and backward() is autograd. Knowing what it does (and what it adds up) is how you avoid the most common training bugs. (P2.7: The PyTorch training loop)
  • Backpropagation by hand and PyTorch's loss.backward() give the same numbers; this lesson shows the library side of the numbers P4.8 computes. (P4.8: Backpropagation: step by step with numbers)
  • Moving weights and data to a GPU with .to(device) is how every large model is trained, and the memory it needs is counted in P10.B4. (P10.B4: Counting compute and memory, coming soon)
  • Building a tiny autograd engine yourself is easier once you have seen what the real one does. (P4.9: Build an autograd engine from scratch)

Before this: Tensors, shapes and broadcasting, Computational graphs and automatic differentiation, How a machine "learns"

After this lesson you can

  • Create tensors, read their dtype, shape and device, and predict the dtype of a result
  • Say when a tensor and a NumPy array share memory, and convert between them safely
  • Use requires_grad, backward() and .grad, and say which tensors get a .grad
  • Explain why gradients accumulate, reset them, and use torch.no_grad() for updates and evaluation
  • Write a manual gradient-descent loop that reproduces the numbers of P0.2, and recognise the common autograd bugs

P1.C10 drew the graph of f(x,y)=(x+y)sin⁡xf(x,y)=(x+y)\sin x and ran a backward pass by hand: at x=1x=1, y=2y=2 the slopes are 2.46242.4624 and 0.84150.8415. 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 2.46242.4624 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 writedtype 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 floatsfloat32
a NumPy float64 arrayfloat64 (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) and t.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:

  • f is 2.52442.5244, as in P1.C10, and it carries grad_fn=<MulBackward0>: it was made by a multiplication, and it knows how to send a gradient back through one.
  • x and y are leaf tensors: you created them, no operation made them. f is not a leaf.
  • Before backward(), x.grad is None: nothing has been computed.
  • f.backward() runs the backward pass of P1.C10 from f, starting with a gradient of 1, and stores the result in x.grad and y.grad: 2.46242.4624 and 0.84150.8415, the sum of two paths into xx as in P1.C10.
  • The last line shows the float32 digits. float32 keeps about seven digits, so 2.4623780…2.4623780\ldots is right to the digits of P1.C10.

Three rules summarise what autograd does:

  1. 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.
  2. Only leaf tensors with requires_grad=True get 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 before backward(); asking a non-leaf for .grad gives None and a UserWarning.)
  3. 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: x=2x=2, target y=3y=3, w=1.5w=1.5, b=−1b=-1, with y^=wx+b\hat y=wx+b and L=(y^−y)2L=(\hat y-y)^2. There ∂L/∂w=−4\partial L/\partial w=-4 and ∂L/∂b=−2\partial L/\partial b=-2.

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.)

y^=2\hat y=2, L=1L=1, and the gradients are −4-4 and −2-2, the numbers of the hand computation: 2(y^−y)⋅x=2(−1)⋅2=−42(\hat y-y)\cdot x=2(-1)\cdot2=-4 and 2(y^−y)=−22(\hat y-y)=-2. 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 v=Wx\mathbf{v}=\mathbf{W}\mathbf{x} and a loss whose gradient at v\mathbf{v} is g\mathbf{g}, P1.C11’s rules say the gradient with respect to W\mathbf{W} is gx⊤\mathbf{g}\mathbf{x}^\top and with respect to x\mathbf{x} it is W⊤g\mathbf{W}^\top\mathbf{g}.

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 gx⊤\mathbf{g}\mathbf{x}^\top with g=(1,2)\mathbf{g}=(1,2) and x=(1,0,−1)\mathbf{x}=(1,0,-1) has rows (1,0,−1)(1,0,-1) and (2,0,−2)(2,0,-2), which is W.grad, and W⊤g=(1+8, 2+10, 3+12)=(9,12,15)\mathbf{W}^\top\mathbf{g}=(1+8,\,2+10,\,3+12)=(9,12,15), 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 t2t^2 at 3 is 66. The second call added another 66 and gave 1212. After t.grad.zero_() (reset in place) the next call gives 66 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 has requires_grad=False and no grad_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 with t, 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 (1,2),(2,3),(3,7)(1,2),(2,3),(3,7), the model is y^=wx+b\hat y=wx+b, the loss is the mean of the squared errors, we start at w=1w=1, b=0b=0 and use η=0.05\eta=0.05. P0.2 found a loss of 66 and slopes −10-10 and −4-4; one step gives w=1.5w=1.5, b=0.2b=0.2.

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 66 and autograd’s gradient is (−10,−4)(-10,-4), matching the by-hand numbers of P0.2 (the formulas are 2N∑i(wxi+b−yi) xi\frac{2}{N}\sum_i(wx_i+b-y_i)\,x_i and 2N∑i(wxi+b−yi)\frac{2}{N}\sum_i(wx_i+b-y_i)). 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, w=1.5w=1.5 and b=0.2b=0.2, exactly the first update of P0.2. After 200 steps the line is near w=2.5w=2.5, b=−1b=-1, the best line of P0.2, and the loss is 0.5020.502, close to the lowest possible 0.50.5.

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 −4.533-4.533 (the loop above used it to reach w=1.727w=1.727). Here the old −10-10 was still there, so the step used −14.533-14.533 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 (w,b)=(1,0)(w,b)=(1,0), 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.)

Try it: check the gradient (-10, -4) by nudging

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The central differences give (−10.0,−4.0)(-10.0, -4.0), the same as autograd and the formulas; the one-sided step with h=0.01h=0.01 gives −9.9533-9.9533, 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, or optimizer.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 pass gradient (deeper box).
  • w.grad is None. Cause: w is not a leaf, or requires_grad is off. Fix: create it as a leaf with requires_grad=True; do not rebind it with w = 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 6+6+6=186+6+6=18: 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 ∑igi qi\sum_i g_i\,q_i.

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 2p2p. (This is the u⊤J\mathbf{u}^\top\mathbf{J} 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 operation

The derivative of er\mathrm{e}^r is er\mathrm{e}^r 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)))
True

You 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
False

Mixing 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 dtype

Elementwise + 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 11 to 10810^8 changes nothing (the gap between neighbouring float32 numbers near 10810^8 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 2.46237802.4623780 and float64 gives 2.46237792.4623779. That is normal rounding, not a bug. Use float64 for gradient checks and float32 (or smaller, P1.G1) for training.

Quiz

Check your understanding

  1. What is the dtype of torch.tensor([1, 2, 3])?

  2. You run n = np.array([1.0, 2.0]), then t = torch.from_numpy(n), then n[0] = 5.0. What does t hold?

  3. For t=3t=3, you call (t * t).backward() twice on two fresh graphs, with no reset in between, and then print t.grad. What do you see?

  4. Why is the parameter update w -= eta * w.grad written inside with torch.no_grad():?

  5. You call .numpy() on a tensor with requires_grad=True and get an error. What is the standard fix?

  6. After loss.backward(), which tensors have a non-None .grad by default?

Exercises

  1. Predict the dtype of each: torch.tensor([1, 2]), torch.tensor([1, 2.5]), torch.arange(4), torch.tensor(np.array([1.5])).
    Show answerint64, float32, int64, float64. Python ints give int64, a list with a float gives float32, arange of ints gives int64, and a NumPy float64 array keeps its dtype.
  2. Use autograd to find the slope of y=x3y=x^3 at x=2x=2. What should you see, and why must x be a float?
    Show answerx = torch.tensor(2.0, requires_grad=True); (x ** 3).backward(); print(x.grad) gives tensor(12.), since 3x2=123x^2=12. An integer tensor cannot require gradients.
  3. t is 3.0 with requires_grad=True. You call (t * t).backward() three times with no reset. What is t.grad?
    Show answer18: each call adds 6.
  4. A student writes w = w - eta * w.grad (no no_grad, no in-place operator) in the loop and finds that w.grad is None on the next step. Why?
    Show answerThe right-hand side is a recorded operation, so the new w is a non-leaf result of the graph, not a leaf. Only leaves keep a .grad, so it is None. Use with torch.no_grad(): w -= eta * w.grad.
  5. Compute by hand the gradient of the P0.2 loss (data (1,2),(2,3),(3,7)(1,2),(2,3),(3,7)) at w=2w=2, b=0b=0, and say what the first update with η=0.05\eta=0.05 gives.
    Show answerThe errors are 0,1,−10,1,-1. ∂L/∂w=23(0⋅1+1⋅2−1⋅3)=−23\partial\mathcal L/\partial w=\frac{2}{3}(0\cdot1+1\cdot2-1\cdot3)=-\frac{2}{3} and ∂L/∂b=23(0+1−1)=0\partial\mathcal L/\partial b=\frac{2}{3}(0+1-1)=0. The update gives w=2+0.05⋅23≈2.033w=2+0.05\cdot\frac23\approx2.033, b=0b=0.
  6. Write the one-line conditional that picks cuda, then mps, then cpu, and name two objects you must move to it before training.
    Show answerTest for CUDA first (torch.cuda.is_available()), then for the mps backend, and fall back to "cpu", as in the lesson. Move the model (its parameters) and every batch of data with .to(device).
  7. T = torch.arange(6).reshape(2, 3). Why does T.T.view(6) fail while T.T.reshape(6) works, and what does the second give?
    Show answerThe transpose is a view with swapped strides, so its entries are not in one run in memory, and view cannot flatten it without copying. reshape copies when it must. The result is tensor([0, 3, 1, 4, 2, 5]), the entries read column by column.
  8. For the neuron of P4.8 (x=2x=2, target 3, w=1.5w=1.5, b=−1b=-1), write the PyTorch code for the gradients, then say what they become if the target is 5.
    Show answerAs in the lesson, the code ends with loss.backward() and reads w.grad, b.grad. With target 5 the error is y^−y=2−5=−3\hat y-y=2-5=-3, so ∂L/∂w=2(−3)⋅2=−12\partial L/\partial w=2(-3)\cdot2=-12 and ∂L/∂b=2(−3)=−6\partial L/\partial b=2(-3)=-6.

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.

Key takeaways

  • A tensor is an array of numbers with a dtype (float32 for Python floats, int64 for Python ints), a shape and a device (cpu, cuda, mps). Indexing, slicing and broadcasting follow the NumPy rules. Both operands of an operation must be on the same device.
  • torch.from_numpy and .numpy() share memory with the array; torch.tensor(a) copies. A tensor that requires gradients must be detached first: t.detach().cpu().numpy().
  • requires_grad=True makes PyTorch record the graph while the forward pass runs. loss.backward() on a scalar runs the backward pass and fills .grad on the leaf tensors. For f=(x+y)sin⁡xf=(x+y)\sin x at (1,2)(1,2) it gives 2.46242.4624 and 0.84150.8415, the numbers of P1.C10.
  • Gradients accumulate: each backward() adds to .grad. Reset them before every step (.grad = None, .grad.zero_(), or optimizer.zero_grad() in P2.7).
  • Do parameter updates and evaluation inside torch.no_grad(), so nothing is recorded. .detach() cuts one tensor out of the graph (it still shares its memory).
  • A manual loop on the P0.2 line (data (1,2),(2,3),(3,7)(1,2),(2,3),(3,7), η=0.05\eta=0.05) starts at loss 66 with gradient (−10,−4)(-10,-4), moves to w=1.5w=1.5, b=0.2b=0.2 after one step, and ends near w=2.446w=2.446, b=−0.876b=-0.876 after 200 steps.
  • float32 is the default and about 7 decimal digits; float64 about 16. Use float64 when you check gradients.
Found a mistake? Tell us