PyTorch tensors: the attention toolkit
- Read PyTorch code with what you know from NumPy, and the few names that change
- Read any transformer shape with five letters, B, T, C, H and d
- Say what a linear layer does to a tensor's shape, and write a small model class
- Split a token's numbers into heads with view then transpose, and merge them back with transpose then reshape
- Hide later tokens with a mask, and say what True means in the mask you pass
- Read a long line of model code from the inside out, one shape at a time
Tensor shapes for attention
Model coding rounds ask you to write attention, a small GPT or a KV cache in PyTorch. Most lines of those programs move a tensor from one shape to another, and a wrong move often runs with no error. This lesson's practice problem puts those moves in five small functions:
Write five functions in PyTorch, with no Python loops over batches, heads or positions.
Bis the number of sequences,Tthe tokens in each,Cthe channels per token,Hthe heads, andd = C // H.
split_heads(x, n_head):xis(B, T, C). Return(B, n_head, T, d), where headhat positiontholds channelsh * dtoh * d + d - 1of positiont. RaiseValueErrorwhenn_headdoesn't divideC.merge_heads(y):yis(B, H, T, d). Return(B, T, H * d), so that merging undoes the split.causal_softmax(scores):scoresis(..., T, T). Return softmax weights over the keys, with exactly 0 on every key after the query.append_greedy(idx, logits):idxis(B, T)token ids andlogitsis(B, T, V). Return(B, T + 1): each sequence with its top-scoring next token added at the end.qkv_heads(qkv, n_head):qkvis(B, T, 3C), the queries, then the keys, then the values. Return(q, k, v), each split into heads.
Call Returns split_heads(x, 2), withx=[[[0, 1, 2, 3], [10, 11, 12, 13]]][[[[0, 1], [10, 11]], [[2, 3], [12, 13]]]]merge_headsof that result[[[0, 1, 2, 3], [10, 11, 12, 13]]], thexyou started withcausal_softmax(torch.zeros(3, 3))rows [1, 0, 0],[0.5, 0.5, 0]and[0.33, 0.33, 0.33]append_greedy(idx, logits), withidx=[[0, 2]]and last-position scores[0.5, 0.1, 3.0][[0, 2, 2]]
This lesson teaches those moves one at a time, each with a small task: what changes from NumPy, the five letters that name every shape, then the split, the merge, the mask and one step of text generation. The whole problem comes back at the end, as the lesson's practice, from a blank file.
One wrong reshape keeps every shape and wrecks the text
Four of the tasks, split_heads, merge_heads, hide_future and append_greedy, put your function inside a small GPT trained on Shakespeare and show you what it writes. With all four right, it writes this:
ROMEO:
I will not some sorrow to the season.
LEONTES:
What should I will be so so sound the strength,
And then with the strong of the world that they shall
Put one classic bug in split_heads, a reshape where a transpose belongs, and the same model writes this:
ROMEO:
TI sthoustin madetharonorarinenininerarede tatiedes thenetinonanenenenen
Both runs have the same shapes, and nothing fails. By the end of Part 3 you'll see why, and how to catch it.
Already write PyTorch every day? Skip to Part 3, where the attention shapes start.
Tensors
Say you join a team that trains its models in PyTorch, and on day one someone sends you their attention code. Do you have to learn a new library before you can read it? Mostly not. A PyTorch tensor is the same grid of numbers as a NumPy array. Shapes, broadcasting, @, slicing and None all behave the way you know. What changes is a handful of names.
Here's the students' table from the NumPy lesson, now as a tensor:
import torch
from torch import nn
# Ana
scores = torch.tensor([[70., 80., 90.],
# Ben
[50., 100., 60.]])
print(scores.shape)
# each student's average
print(scores.mean(dim=1, keepdim=True))
torch.Size([2, 3])
tensor([[80.],
[70.]])
Same table, same row averages. The only new thing is the spelling: NumPy says axis and keepdims, and PyTorch says dim and keepdim, with no s. Your NumPy habit won't hurt you here, because PyTorch quietly accepts keepdims too. Still, most code you'll read says keepdim, so that's the one to recognize.
More NumPy names in PyTorch
| NumPy | PyTorch |
|---|---|
x.sum(axis=1, keepdims=True) | x.sum(dim=1, keepdim=True) |
np.swapaxes(k, -1, -2) | k.transpose(-2, -1) |
np.where(m, a, b), np.tril(a) | torch.where(m, a, b), torch.tril(a) |
np.concatenate([a, b], axis=1) | torch.cat([a, b], dim=1) |
np.random.default_rng(0) | torch.manual_seed(0) |
You don't need to memorize that table. Say what you want in words first, like add up each row and keep the row axis, and the right call follows. The thing that really matters is which axis.
Two small things show up everywhere:
print(scores.sum())
print(scores.sum().item())
tensor(450.)
450.0
A sum over everything is still a tensor, just one with no axes left. .item() turns it into a plain Python number, which is what you want when you print or log a loss.
In the editor, scores is the same table: Ana's row, then Ben's. Fill in student_totals, each student's total kept as a column, and test_totals, each test's total as one row of three numbers.
Karpathy normalizes the rows of a count table with sum(1, keepdim=True), reads PyTorch's broadcasting rules, then drops keepdim to show the bug: the code still runs, and it normalizes the columns instead of the rows.
Three things a tensor carries
The numbers aren't the whole story. Every tensor also knows three facts about itself. You need to know they exist, not their details.
What kind of number it holds. Token ids are whole numbers, int64. Weights and activations are decimals, float32. Masks are True and False, bool:
# the cat sat on the mat, as ids
ids = torch.tensor([0, 1, 2, 3, 0, 4])
print(ids.dtype, scores.dtype, (ids > 0).dtype)
torch.int64 torch.float32 torch.bool
The dot in 70. is what made the scores decimals. That tiny dot matters more than it looks. Only decimals can hold minus infinity, and attention uses minus infinity to hide tokens. Build your scores from whole numbers and the masking step stops with an error, so convert them with .float() first.
Where the numbers live. On the CPU or on a GPU. Every tensor in one operation has to be in the same place, and model.to("cuda") moves a whole model in one call.
Whether PyTorch is taking notes. During training, PyTorch records every operation so it can work out the gradients later. When you generate text or run a test, those notes only waste memory, and a with torch.no_grad(): block turns them off. Here nn.Linear(2, 2) is a tiny layer with weights to train. The Layers step covers it.
lin = nn.Linear(2, 2)
with torch.no_grad():
a = lin(torch.ones(1, 2))
b = lin(torch.ones(1, 2))
print(a.requires_grad, b.requires_grad)
False True
a was made inside the block, so it carries no history. b was made outside it, so it does.
The editor holds the ids from above and raw_scores, a 2 by 2 table of whole numbers. Fill in mask, True where an id is above 0, and scores_f, the same table as decimals.
Five letters
Open any transformer codebase and you'll find the same five letters everywhere: B, T, C, H and d. Once you can read them, a line like x.view(B, T, H, d) stops looking like noise. From here on the data is text: one pair of sentences, the cat sat on the mat, and the same words in another order.
# the cat sat on the mat
idx = torch.tensor([[0, 1, 2, 3, 0, 4],
# the mat sat on the cat
[0, 4, 2, 3, 0, 1]])
torch.manual_seed(0)
# 12 numbers for each token
x = torch.randn(2, 6, 12)
B, T, C = x.shape
H = 4
d = C // H
print(B, T, C, H, d)
2 6 12 4 3
Tap each letter to see its axis:
x.shape = (2, 6, 12)- B, batch: how many sentences go through together.
- T, time: how many tokens are in each sentence.
- C, channels: how many numbers describe each token.
Attention adds two more:
- H, heads: how many pieces each token's numbers get cut into.
- d, the size of one piece,
d = C // H.
Notice that every size here is different: 2, 6, 12, 4 and 3. That's on purpose, and it's a habit worth stealing for your own tests. Say you swap two axes by mistake. With all sizes different, you get a shape nothing else expects, and the very next line fails and points at the bug. Now imagine B and T were both 4. The swap would keep the shape, nothing would fail, and the numbers would be quietly wrong. Different sizes turn silent bugs into loud ones.
In the editor, x is the same (2, 6, 12) tensor. Read B, T and C from x.shape, then set d, the size of one head when H = 4.
Layers
nn.Linear(12, 8) is a layer that turns 12 numbers into 8. Hand it a tensor of any shape, as long as the last axis is 12, and it transforms every token's row:
# 12 numbers in, 8 out
lin = nn.Linear(12, 8)
print(lin(x).shape)
torch.Size([2, 6, 8])
Only the last axis changed. The 2 sentences and their 6 tokens passed straight through.
Inside, a linear layer is one matrix multiply plus a bias. Here's the detail that trips people up in interviews: PyTorch stores the weight out by in, (8, 12), not (12, 8). So the formula needs a transpose:
print(lin.weight.shape, lin.bias.shape)
print(torch.allclose(lin(x), x @ lin.weight.T + lin.bias))
torch.Size([8, 12]) torch.Size([8])
True
torch.allclose checks that two tensors match, up to tiny rounding. They do: the layer is exactly x @ lin.weight.T + lin.bias.
In the editor, x is the same (2, 6, 12) tensor. Build lin, a layer from 12 numbers to 8. Then store lin(x) in out, and the shape of lin.weight in w_shape.
Models
A model is a class with two methods:
class Proj(nn.Module):
def __init__(self, C: int) -> None:
super().__init__()
self.qkv = nn.Linear(C, 3 * C)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""x: (B, T, C). Returns (B, T, 3C): queries, keys, values."""
return self.qkv(x)
m = Proj(12)
print(m(x).shape)
torch.Size([2, 6, 36])
__init__builds the layers, and it starts withsuper().__init__().forwarddoes the math.- You call the model itself,
m(x), and that runsforward.
Any layer you store on self becomes part of the model, so its weights get trained and saved along with it.
But what about a tensor that should never train, like the triangle that hides later tokens? Say you store it as a plain attribute, self.mask = mask, and then call model.to("cuda"). The weights move to the GPU. The mask stays behind on the CPU, and the first forward pass fails because its tensors live in two places. The fix is self.register_buffer("mask", mask). A buffer moves and saves with the model, and it never trains. If that name escapes you in an interview, build the mask inside forward and say you'd build it once. That's a fine answer.
In the editor, write a second model the same way: MLP(C), the feed-forward part of a transformer block. It widens each position to 4 * C numbers, bends them with F.gelu, and narrows them back to C. F is torch.nn.functional, already imported in the editor, and F.gelu is the bend: it lets positive numbers through and pushes negative ones toward 0, so the two layers don't collapse into one.
Karpathy writes the smallest language model as a class: an nn.Embedding turns (B, T) ids into (B, T, C) scores, he reshapes them to (B*T, C) for the loss, and he predicts the starting loss, about 4.17.
Cut q, k and v apart
nn.Linear(C, 3 * C) makes the queries, the keys and the values in one go. They come out side by side on the last axis. split cuts them apart.
out = torch.arange(12).view(1, 2, 6)
q, k, v = out.split(2, dim=-1)
print(out)
print(q)
print(k)
print(v)
tensor([[[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]]])
tensor([[[0, 1],
[6, 7]]])
tensor([[[2, 3],
[8, 9]]])
tensor([[[ 4, 5],
[10, 11]]])
out[0] (2, 6)split(2, dim=-1) means: cut the last axis into pieces of size 2. Each token keeps its own row. Nothing is copied.
view(1, 2, 6) works like NumPy's reshape. Part 4 shows the one place where the two differ. chunk does the same as split with the other number: out.chunk(3, dim=-1) means three pieces. If you mix them up, out.split(3, dim=-1) gives two pieces of size 3, and q, k, v = ... fails because there are only two.
In the editor, out is a projection's output for 1 sentence of 3 tokens with C = 4, so each token has 3 * C = 12 numbers. Cut it into q, k and v with split, then into q2, k2 and v2 with chunk.
Split the heads: view, then transpose
Multi-head attention cuts each token's numbers into H pieces, one per head, and then runs attention on each head separately. For that, each head must become its own grid: one row per token.
To see where every number goes, label them. The tens digit is the token, the ones digit is the channel.
x = torch.tensor([[[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15]]])
B, T, C = x.shape
H = 3
d = C // H
v = x.view(B, T, H, d)
h = v.transpose(1, 2)
print(v.shape, h.shape)
print(h)
torch.Size([1, 2, 3, 2]) torch.Size([1, 3, 2, 2])
tensor([[[[ 0, 1],
[10, 11]],
[[ 2, 3],
[12, 13]],
[[ 4, 5],
[14, 15]]]])
Step through it, and try the reshape too:
x (B, T, C) = (1, 2, 6)Two steps, in this order:
view(B, T, H, d)cuts each token's row into H pieces. Each token's numbers stay together.transpose(1, 2)swaps the token axis and the head axis. Now each head is a small grid with one row per token.
Check it in the output: in every head, the first row only has tens digit 0, and the second row only tens digit 1. Each row is still one token. That's what attention needs.
Write split_heads(x, n_head): the view, then the transpose, for any x of shape (B, T, C). It's the first function of the practice problem, without its error check.
Write split_heads(x, n_head) for x of shape (B, T, C), reading B, T and C from x.shape. Return (B, n_head, T, d) with d = C // n_head, where head h at position t holds channels h * d to h * d + d - 1 of position t.
Raschka rewrites multi-head attention as one projection that view cuts into heads, so every head attends at once, then joins the heads back with contiguous().view and says why view needs the contiguous call.
Merge the heads: transpose back, then reshape
After attention you have one output per head, (B, H, T, d). To get back to (B, T, C), undo the two steps in reverse order: tokens back in front, then join each token's pieces.
y = h.contiguous()
z = y.transpose(1, 2)
print(z.reshape(B, T, C))
tensor([[[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15]]])
The rows come back exactly as they were.
Here h.contiguous() stands in for the output of attention: it copies h into a fresh tensor, laid out in memory in its current order. You only need to know one thing about why that matters. A transpose doesn't move any numbers. It changes the order in which PyTorch reads the same memory. After it, one token's numbers are no longer next to each other in memory. That has one consequence:
viewnever copies, so it can't join numbers that aren't next to each other. It raises an error.reshapecopies when it has to. It always works.
So after a transpose, join axes with reshape.
The quiet failure: you skip the transpose and write y.reshape(B, T, C) on the heads. What happens?
A triangle averages the past
A language model predicts each token from the tokens before it. So when sat looks around, it must not see on, the and mat. Attention does that with a mask.
Start with the shape of the idea: a lower triangle of ones, each row divided by its own sum.
X = torch.tensor([[[1., 2.], [3., 4.], [5., 6.]]])
tril = torch.tril(torch.ones(3, 3))
wei = tril / tril.sum(dim=1, keepdim=True)
print(wei)
print(wei @ X)
tensor([[1.0000, 0.0000, 0.0000],
[0.5000, 0.5000, 0.0000],
[0.3333, 0.3333, 0.3333]])
tensor([[[1., 2.],
[2., 3.],
[3., 4.]]])
wei (3, 3)Each row is the average of the token itself and every token before it. Above the diagonal everything is 0, so no token reads the future. Row 2 of the result is the average of [1, 2], [3, 4] and [5, 6], which is [3, 4].
The same triangle averages any rows in order, not only tokens. In the editor, X holds Ana's scores on four tests, in the order she took them, one row per test. Build tril, then wei, then avg, so that row t of avg is her average over tests 0 to t.
Hide the future with minus infinity
The triangle is attention with equal weights. Real attention gets its weights from a softmax over scores. The scores between tokens are called att here, so the name scores keeps meaning the students' test scores. The mask goes on att, before the softmax:
allowed = torch.tril(torch.ones(3, 3, dtype=torch.bool))
att = torch.zeros(3, 3)
masked = att.masked_fill(~allowed, float("-inf"))
print(masked)
print(masked.softmax(dim=-1))
Scores of all zeros, with every later key set to minus infinity. What does each row become after the softmax?
One step of text generation
A model that generates text adds one token per step. It returns logits of shape (B, T, V): for every sentence and every position, one score for each of the V tokens in the vocabulary. Only the last position predicts the next token.
idx = torch.tensor([[0, 2],
[1, 1]])
logits = torch.tensor([[[2.0, 0.0, 1.0],
[0.5, 0.1, 3.0]],
[[0.0, 1.0, 0.0],
[4.0, 2.0, 1.0]]])
last = logits[:, -1]
nxt = last.argmax(dim=-1, keepdim=True)
print(nxt)
print(torch.cat([idx, nxt], dim=1))
tensor([[2],
[0]])
tensor([[0, 2, 2],
[1, 1, 0]])
The largest last-position scores, 3.0 and 4.0, sit at ids 2 and 0, so those ids go on the end.
1last = logits[:, -1]2nxt = last.argmax(dim=-1, keepdim=True)3idx = torch.cat([idx, nxt], dim=1)Three moves: take the last position, pick the best token in each row, glue it on. Repeat them, and the text grows one token per step.
Without keepdim=True, the picks are a flat list, (2,). What does torch.cat([idx, picks], dim=1) do?
Read a long line from the inside out
Model code often packs several steps into one line. Read it from the inside out: find the innermost name, say its shape, then move out one call at a time and say the new shape.
q, k, v = (t.view(B, T, H, d).transpose(1, 2) for t in (q, k, v))
| Piece | What it does | Shape |
|---|---|---|
for t in (q, k, v) | takes the three tensors one at a time | (B, T, C) |
t.view(B, T, H, d) | cuts each token's numbers into heads | (B, T, H, d) |
.transpose(1, 2) | puts the heads in front | (B, H, T, d) |
q, k, v = ... | stores the three results under the same names | (B, H, T, d) each |
It's the head split from split_heads, done three times in one line. Here it is on numbers:
B, T, C, H = 1, 2, 6, 3
d = C // H
q = torch.arange(12.).view(B, T, C)
k, v = q + 100, q + 200
q, k, v = (t.view(B, T, H, d).transpose(1, 2) for t in (q, k, v))
for t in (q, k, v):
print(t.shape)
print(k[0, 1])
torch.Size([1, 3, 2, 2])
torch.Size([1, 3, 2, 2])
torch.Size([1, 3, 2, 2])
tensor([[102., 103.],
[108., 109.]])
Head 1 of the keys holds channels 2 and 3 of both tokens: 102 and 103 from token 0, 108 and 109 from token 1.
A chain of calls reads left to right instead, each call working on the result of the one before:
att = att.masked_fill(~mask, float("-inf")).softmax(dim=-1)
Flip the mask, write minus infinity where it's True, take the softmax over each row, store the result. The shape never changes.
The same habit finds bugs. Write the shape under each piece of a line. The piece whose shape surprises you is the bug.
In the editor, append_greedy(idx, logits) is the fourth function of the practice problem, written as one line, and it's wrong. Write the shape under each piece of that line, and fix it so it returns (B, T + 1).
This one-liner should append each sequence's greedy next token, the top-scoring id at the last position, to idx. idx is (B, T), logits is (B, T, V), and the result should be (B, T + 1). Read it inside out, write the shape under each piece, and fix it.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the five functions from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.
xis(B, T, C)and you need(B, H, T, d)heads. Which line is right?2.
yis the(B, H, T, d)output ofatt @ v. What doesy.transpose(1, 2).view(B, T, C)do?3.
allowed = torch.tril(torch.ones(3, 3, dtype=torch.bool)). What doesatt.masked_fill(allowed, float('-inf')).softmax(dim=-1)give?4.
qkvis(B, T, 3C)with C = 64. Which call gives q, k and v, each(B, T, C)?5.
logitsis(B, T, V). Which gives a(B, 1)tensor of greedy ids to append toidx?6.
lin = nn.Linear(512, 1536)andxis(8, 128, 512). What arelin.weight.shapeandlin(x).shape?
Practice
Sources (10)
- Tensor Attributes · PyTorch 2.15 documentation · Oct 28, 2026
“A torch.device is an object representing the device on which a torch.Tensor is or will be allocated.”
- no_grad · PyTorch 2.15 documentation · Oct 28, 2026
“Disabling gradient calculation is useful for inference, when you are sure that you will not call Tensor.backward().”
- Linear · PyTorch 2.15 documentation · Oct 28, 2026
“Applies an affine linear transformation to the incoming data”
- torch.nn.Module.register_buffer · PyTorch 2.15 documentation · Oct 28, 2026
“This is typically used to register a buffer that should not be considered a model parameter.”
- torch.split · PyTorch 2.15 documentation · Oct 28, 2026
“Splits the tensor into chunks. Each chunk is a view of the original tensor.”
- torch.Tensor.view · PyTorch 2.15 documentation · Oct 28, 2026
“Returns a new tensor with the same data as the self tensor but of a different shape.”
- torch.Tensor.stride · PyTorch 2.15 documentation · Oct 28, 2026
“Stride is the jump necessary to go from one element to the next one in the specified dimension dim.”
- torch.Tensor.contiguous · PyTorch 2.15 documentation · Oct 28, 2026
“Returns a contiguous in memory tensor containing the same data as self tensor.”
- torch.Tensor.masked_fill_ · PyTorch 2.15 documentation · Oct 28, 2026
“Fills elements of self tensor with value where mask is True. The shape of mask must be broadcastable with the shape of the underlying tensor.”
- torch.cat · PyTorch 2.15 documentation · Oct 28, 2026
“All tensors must either have the same shape (except in the concatenating dimension) or be a 1-D empty tensor with size (0,).”