Unit 2 of 9
Tensors, shapes, and the forward pass
What you’ll learn
- Read a tensor’s shape, dtype, and strides, and say what every axis means.
- Follow the shape of every matrix multiplication in one Llama 3.1 8B layer.
- Count a model’s parameters from config.json and turn them into bytes of weights and FLOPs per token.
- Explain why a transpose makes a tensor non-contiguous, and catch a head split that has the right shape but the wrong contents.
What a model's shapes tell you
Someone asks you whether Llama 3.1 8B fits on a 24 GB GPU, and how fast it could possibly generate text. You have not downloaded it yet. You can still answer, because both questions depend only on the shapes of the model’s weight matrices, and those shapes are listed in its config.json.
Shapes also explain a class of bugs that no error message catches. A model that splits its attention heads with the wrong reshape runs without complaint and produces fluent nonsense. The shapes all match; the numbers inside them are in the wrong places.
By the end of this lesson you will be able to read any tensor’s shape and memory layout, follow one transformer layer matrix by matrix, and calculate three numbers for a real model: its parameter count (8.03 billion for Llama 3.1 8B), the memory its weights need (about 16 GB in BF16), and the arithmetic each token costs (about 16 billion floating-point operations).
Read every axis of a tensor
A tensor is an array of numbers with three properties you should always know: its shape (the size of each axis), its dtype (the number format of each element), and its device (CPU or GPU memory). Weights, the activations flowing between layers, and the KV cache are all tensors.
The dtype sets how many bytes each element takes. FP32 uses 4 bytes. BF16 (bfloat16) and FP16 use 2, and BF16 is the format most models ship in. FP8 and INT8 use 1 byte. The quantization lesson compares these formats; here you only need their sizes.
Every axis has a meaning, and you should be able to name it. Activations in a language model usually have shape (batch, sequence, hidden): which request, which token position, and which feature of that token. For Llama 3.1 8B the hidden size is 4,096, so two requests of 10 tokens each form a tensor of shape (2, 10, 4096) holding 81,920 numbers.
Most of a model’s work is matrix multiplication, and its shape rule is short: the inner dimensions must match and disappear. A (3, 4) matrix times a (4, 2) matrix gives (3, 2). Each output value is a dot product of one row of the left matrix with one column of the right.
A linear layer computes y = xW + b. The last axis of x (its features) must equal the first axis of W, and the result has W’s second axis as its new feature size. Every other axis passes through untouched, so a layer with W of shape (4096, 1024) maps (2, 10, 4096) to (2, 10, 1024): same requests, same tokens, new features. The bias b has one value per output feature and is added to every token.
One tiny linear layer
- Input x, shape (1, 2)
[2, 3] - Weights W, shape (2, 1), and bias b
W = [[1], [2]], b = [0.5] - Inner dimensions match and disappear
(1, 2) @ (2, 1) → (1, 1) - The single output
2 × 1 + 3 × 2 + 0.5 = 8.5
Resulty = [8.5], shape (1, 1)
Follow the shapes through one layer
Llama 3.1 8B is a stack of 32 identical decoder layers. Each takes a tensor of shape (S, 4096) for S tokens and returns the same shape, which is what lets the layers stack. A batch axis in front would pass through every step unchanged, so it is left out below. The attention lesson explains what each step computes; here you follow only the shapes.
The table lists every weight matrix in the layer in the y = xW convention. Two numbers from config.json explain most of it: the hidden size (4,096) and the MLP’s intermediate_size (14,336). The K and V projections are narrower because the model has only 8 KV heads of 128 features, so 8 × 128 = 1,024 outputs instead of 4,096.
| Matrix | Input | Weight (in, out) | Output | Parameters |
|---|---|---|---|---|
q_proj | (S, 4096) | (4096, 4096) | (S, 4096) | 16,777,216 |
k_proj | (S, 4096) | (4096, 1024) | (S, 1024) | 4,194,304 |
v_proj | (S, 4096) | (4096, 1024) | (S, 1024) | 4,194,304 |
o_proj | (S, 4096) | (4096, 4096) | (S, 4096) | 16,777,216 |
gate_proj | (S, 4096) | (4096, 14336) | (S, 14336) | 58,720,256 |
up_proj | (S, 4096) | (4096, 14336) | (S, 14336) | 58,720,256 |
down_proj | (S, 14336) | (14336, 4096) | (S, 4096) | 58,720,256 |
Attention itself has no weights, but it has two matrix multiplications of its own. First, the model splits Q into 32 heads of 128 features, shape (32, S, 128), and K and V into 8 heads, (8, S, 128). Each group of 4 query heads shares one KV head. Scores are Q times K transposed: (32, S, 128) @ (32, 128, S) gives (32, S, S), one score for every pair of tokens in every head. Multiplying those weights by V gives (32, S, 128), which is joined back into (S, 4096).
That (32, S, S) tensor is why long prompts are expensive. At S = 8,192 it holds 32 × 8,192 × 8,192 = 2,147,483,648 numbers, 4 GiB in BF16, for one layer of one request. Fast attention kernels never store it; the section on real engines comes back to this.
Count parameters, bytes, and FLOPs for Llama 3.1 8B
With the layer table in hand, counting the whole model is bookkeeping. Add the seven matrices, add the two RMSNorm weight vectors (4,096 values each), multiply by 32 layers, then add the parts outside the layers: the embedding table that turns token IDs into vectors, a final RMSNorm, and the output layer (often called the LM head) that turns the last vector into one score per vocabulary entry.
Parameters in Llama 3.1 8B, from config.json
- Attention per layer: q, k, v, o
16,777,216 + 4,194,304 + 4,194,304 + 16,777,216 = 41,943,040 - MLP per layer: gate, up, down
3 × 4,096 × 14,336 = 176,160,768 - RMSNorm weights per layer
2 × 4,096 = 8,192 - One layer
41,943,040 + 176,160,768 + 8,192 = 218,112,000 - All 32 layers
218,112,000 × 32 = 6,979,584,000 - Embedding table: vocabulary × hidden size
128,256 × 4,096 = 525,336,576 - Output layer (not shared with the embedding)
4,096 × 128,256 = 525,336,576 - Final RMSNorm
4,096 - Total
6,979,584,000 + 525,336,576 × 2 + 4,096 = 8,030,261,248
Result8.03 billion parameters, matching the count Hugging Face reports for the checkpoint
Bytes follow directly: parameters times bytes per element. In BF16 the weights take 8,030,261,248 × 2 = 16,060,522,496 bytes, about 16.06 GB (14.96 GiB). That answers the opening question. The weights alone fit on a 24 GB GPU, leaving about 8 GB for the KV cache and working memory, and they take a fifth of an 80 GB H100.
| Format | Bytes per parameter | Weights |
|---|---|---|
| FP32 | 4 | 32.1 GB |
| BF16 | 2 | 16.1 GB |
| FP8 or INT8 | 1 | 8.0 GB |
| INT4 | 0.5 | 4.0 GB |
Arithmetic per token follows from the same count. A matrix multiplication uses each weight once per token for one multiply and one add, so a token costs about 2 floating-point operations (FLOPs) per parameter. The embedding lookup is the exception: it copies one row and does no math.
FLOPs for one token through Llama 3.1 8B
- Rule of thumb: 2 × all parameters
2 × 8.03 billion ≈ 16.1 billion FLOPs - Weights used in matrix multiplications
6,979,321,856 in the layers + 525,336,576 in the output layer = 7,504,658,432 - More precise: 2 × those weights
2 × 7.50 billion ≈ 15.0 billion FLOPs
ResultAbout 15 to 16 GFLOPs per token, plus attention over the context
Now compare that with the hardware. An H100 SXM does about 989 TFLOPS of dense BF16 math and reads memory at 3.35 TB/s. Generating one token for one request needs the math and a full read of the weights, and the two take very different times.
One decode step for one request on an H100 SXM, idealized
- Math: 15.0 GFLOPs at 989 TFLOPS
15.0 × 10⁹ / 989 × 10¹² ≈ 15 µs - Weight read: 16.06 GB at 3.35 TB/s
16.06 × 10⁹ / 3.35 × 10¹² ≈ 4.8 ms - Ratio
4.8 ms / 15 µs ≈ 320
ResultThe math units sit idle more than 99% of the time
One token does about 1 FLOP per byte of weights it reads, while the GPU can do about 295 FLOPs in the time it reads one byte (989 / 3.35). A pass over the weights only keeps the math units busy when it processes roughly 300 tokens at once. Prefill of a long prompt does that naturally; decode does not, which is why the batching lesson groups many requests into each step.
Strides, contiguity, and why reshape and transpose differ
Memory is one long line of bytes, so a tensor needs a rule for where each element lives. That rule is its strides: how far to jump in memory to move one step along each axis. In the grid above, stored row by row in FP32, moving to the next token skips 4 elements (16 bytes) and moving to the next feature skips 1 element (4 bytes). Its strides are (16, 4) in bytes, as NumPy reports them. PyTorch reports the same layout as (4, 1), in elements.
Find token 1, feature 2 in memory
- Offset = index × stride, summed over axes
1 × 16 + 2 × 4 = 24 bytes - In elements
24 / 4 = element 6, the value shown in the grid
A tensor is contiguous when walking it in order (last axis fastest) visits memory in order, with no gaps and no jumps back. Many operations can then treat it as one flat buffer, and GPU kernels often require that.
Reshape and transpose both give you a new shape, but they do different things:
- A reshape keeps the elements in their memory order and regroups them. Reshaping the
(3, 4)grid to(4, 3)gives rows[0, 1, 2],[3, 4, 5], and so on. It is free when the input is contiguous, because only the strides change. - A transpose swaps axes. The transposed grid has rows
[0, 4, 8],[1, 5, 9], and so on. It is also free at first: NumPy and PyTorch swap the strides to(4, 16)and point at the same memory. But the result is no longer contiguous, because consecutive elements of a row sit 16 bytes apart. - The cost arrives later. An operation that needs contiguous input, such as a flattening reshape or many GPU kernels, must first copy the transposed tensor into a new buffer in the new order.
Attention needs both operations. Q comes out of q_proj as (B, S, 4096), but attention wants one (S, 128) matrix per head, so the heads axis must come before the sequence axis: (B, 32, S, 128). The correct recipe is a reshape that splits the features, (B, S, 32, 128), followed by a transpose of the sequence and head axes. The tempting shortcut, a single reshape straight to (B, 32, S, 128), succeeds because the element counts match, and produces garbage.
Both versions have shape (1, 2, 3, 2). That is the central lesson about reshapes: a reshape that returns the expected dimensions proves only that the element count is compatible. It says nothing about whether each axis still means what you think. To check meaning, follow one identifiable element, as the figure does, and confirm it lands in the right token and head.
The browser lab at the end of this lesson, “Follow one feature into its head”, lets you do that interactively. Pick a sequence length, a head count, and an element, predict where it lands, then switch on the tempting wrong reshape and watch the same element land somewhere else.
Try it: shapes, strides, parameters, and a forward pass
You need Python 3.9 or later and NumPy. The first script builds the (3, 4) grid, then compares reshape with transpose and the correct head split with the wrong one:
import numpy as np
# One sequence: 3 tokens, 4 features each, stored as FP32 (4 bytes per value).
x = np.arange(12, dtype=np.float32).reshape(3, 4)
show = lambda a: a.astype(int).tolist() # print element numbers without ".0"
print("x:", show(x), "strides:", x.strides)
r = x.reshape(4, 3) # regroup the same 12 values
t = x.T # swap the two axes
print("reshape(4, 3):", show(r), "strides:", r.strides)
print("transpose: ", show(t), "strides:", t.strides)
print("both are views:", np.shares_memory(x, r), np.shares_memory(x, t))
print("transpose is contiguous:", t.flags["C_CONTIGUOUS"])
flat = t.reshape(-1) # not in memory order, so NumPy must copy
print("flattened transpose:", show(flat), "copy:", not np.shares_memory(x, flat))
# Split 4 features into 2 heads of width 2: (B, S, D) -> (B, H, S, Dh)
batch, seq, dim, heads = 1, 3, 4, 2
h = np.arange(batch * seq * dim).reshape(batch, seq, dim)
right = h.reshape(batch, seq, heads, dim // heads).transpose(0, 2, 1, 3)
wrong = h.reshape(batch, heads, seq, dim // heads)
print("right", right.shape, "head 0:", right[0, 0].tolist())
print("wrong", wrong.shape, "head 0:", wrong[0, 0].tolist())x: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] strides: (16, 4)
reshape(4, 3): [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] strides: (12, 4)
transpose: [[0, 4, 8], [1, 5, 9], [2, 6, 10], [3, 7, 11]] strides: (4, 16)
both are views: True True
transpose is contiguous: False
flattened transpose: [0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11] copy: True
right (1, 2, 3, 2) head 0: [[0, 1], [4, 5], [8, 9]]
wrong (1, 2, 3, 2) head 0: [[0, 1], [2, 3], [4, 5]]Read the output line by line. The reshape and the transpose are both views (True True): neither copied anything. Only the transpose has jumping strides (4, 16) and is not contiguous, and flattening it forces a copy. The last two lines are the figure above in numbers: the same shape, and a different head 0.
In NumPy 2.5, the version this course uses, you can make the hidden copy loud: t.reshape(-1, copy=False) raises ValueError: Unable to avoid creating a copy while reshaping. In PyTorch, .view() behaves that way by default, and .contiguous() makes the copy explicit.
The second script turns the counting section into a tool. Replace the dictionary with the fields from any Llama-style model’s config.json:
# Count parameters, bytes, and FLOPs per token from config.json fields.
config = { # meta-llama/Llama-3.1-8B/config.json
"hidden_size": 4096,
"intermediate_size": 14336,
"num_hidden_layers": 32,
"num_attention_heads": 32,
"num_key_value_heads": 8,
"vocab_size": 128256,
"tie_word_embeddings": False,
}
d = config["hidden_size"]
ffn = config["intermediate_size"]
layers = config["num_hidden_layers"]
head_dim = d // config["num_attention_heads"]
kv_width = config["num_key_value_heads"] * head_dim
attention = d * d + 2 * d * kv_width + d * d # q, k, v, o projections
mlp = 3 * d * ffn # gate, up, down projections
norms = 2 * d # two RMSNorm weight vectors per layer
embedding = config["vocab_size"] * d
lm_head = 0 if config["tie_word_embeddings"] else config["vocab_size"] * d
total = embedding + layers * (attention + mlp + norms) + d + lm_head
print(f"attention per layer: {attention:>13,}")
print(f"MLP per layer: {mlp:>13,}")
print(f"embedding table: {embedding:>13,}")
print(f"total parameters: {total:>13,}")
print(f"BF16 weights: {2 * total / 1e9:.2f} GB ({2 * total / 2**30:.2f} GiB)")
matmul = layers * (attention + mlp) + lm_head # the lookup does no math
print(f"FLOPs per token, 2 x parameters: {2 * total / 1e9:.1f} billion")
print(f"FLOPs per token, matmuls only: {2 * matmul / 1e9:.1f} billion")
# One token on an H100 SXM: time for the math versus time to read the weights
print(f"math at 989 TFLOPS: {2 * matmul / 989e12 * 1e6:.0f} microseconds")
print(f"read at 3.35 TB/s: {2 * total / 3.35e12 * 1e3:.1f} milliseconds")attention per layer: 41,943,040
MLP per layer: 176,160,768
embedding table: 525,336,576
total parameters: 8,030,261,248
BF16 weights: 16.06 GB (14.96 GiB)
FLOPs per token, 2 x parameters: 16.1 billion
FLOPs per token, matmuls only: 15.0 billion
math at 989 TFLOPS: 15 microseconds
read at 3.35 TB/s: 4.8 millisecondsIf your total is off by about 525 million, check tie_word_embeddings: models that share the embedding table with the output layer store that matrix once. If it is off by a factor near 4 in the attention line, you probably used the query head count for K and V.
The last script puts the pieces together: a two-layer forward pass that ends in probabilities. Its first column of W1 and its bias are the tiny layer from the worked example above, so the first hidden feature should come out as 8.5:
import numpy as np
# A two-layer forward pass: (1, 2) -> Linear -> ReLU -> Linear -> softmax
x = np.array([[2.0, 3.0]]) # 1 token, 2 input features
W1 = np.array([[1.0, -1.0, 0.0],
[2.0, -0.5, 0.5]]) # (in=2, out=3)
b1 = np.array([0.5, 0.0, 0.0])
W2 = np.array([[0.4, -0.1],
[1.0, 1.0],
[-0.5, 0.2]]) # (in=3, out=2)
b2 = np.array([0.0, 0.1])
h = x @ W1 + b1 # (1, 2) @ (2, 3) -> (1, 3)
print("linear 1:", h, h.shape)
h = np.maximum(h, 0.0) # ReLU zeroes negative features, shape unchanged
print("ReLU: ", h)
logits = h @ W2 + b2 # (1, 3) @ (3, 2) -> (1, 2)
print("logits: ", logits, logits.shape)
z = logits - logits.max(axis=-1, keepdims=True) # stable softmax, last axis
probs = np.exp(z) / np.exp(z).sum(axis=-1, keepdims=True)
print("probabilities:", probs.round(4), "sum:", probs.sum())
print("predicted class:", probs.argmax(axis=-1))linear 1: [[ 8.5 -3.5 1.5]] (1, 3)
ReLU: [[8.5 0. 1.5]]
logits: [[ 2.65 -0.45]] (1, 2)
probabilities: [[0.9569 0.0431]] sum: 1.0
predicted class: [0]Every line keeps the batch-of-one row axis and changes only the feature axis: 2 features, then 3, then 2 scores. ReLU sets the negative hidden feature, −3.5, to 0 without changing the shape. The softmax runs over axis=-1, the scores, so the two probabilities sum to 1. A language model’s forward pass has the same outline with a vocabulary-sized last layer: 128,256 scores per position for Llama 3.1 8B instead of 2.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| The model runs but writes fluent nonsense after you ported attention | Heads were split with a single reshape instead of reshape plus transpose. | Reshape to (B, S, H, Dh), then transpose to (B, H, S, Dh). Track one element to confirm. |
| A weight looks backwards when you load a checkpoint | PyTorch’s nn.Linear stores weights as (out, in). | Read k_proj.weight of shape (1024, 4096) as 4,096 inputs to 1,024 outputs. |
.T scrambles a batched tensor | On a NumPy array, .T reverses every axis, not just the last two. | Use swapaxes(-1, -2) or name the axes in transpose. |
RuntimeError: view size is not compatible with input tensor's size and stride | .view() was called on a transposed, non-contiguous tensor. | Use .reshape(), or call .contiguous() first if you want the copy to be visible. |
| Memory spikes in an innocent-looking reshape | The input was not contiguous, so the reshape copied it. | Check strides or is_contiguous() and move the transpose to where the copy is cheapest. |
| Probabilities do not sum to 1 per token | Softmax ran over the batch or sequence axis. | Normalize over the vocabulary axis, axis=-1. |
| Your parameter count is 0.5 billion too high or too low | The embedding and output layer were counted once when they are separate, or twice when they are tied. | Read tie_word_embeddings in config.json. |
How real engines use shapes
Production engines run the same matrices you counted, but arrange them for the hardware. Four patterns come up constantly.
- Fused projections. vLLM 0.28.0 loads
q_proj,k_proj, andv_projinto oneqkv_projmatrix with 4,096 + 1,024 + 1,024 = 6,144 outputs, runs one matrix multiplication, and splits the result. It fusesgate_projandup_projinto onegate_up_projwith 28,672 outputs the same way. One large multiplication uses the GPU better than three small ones. - A flat token axis. vLLM’s model code takes the tokens of every scheduled request concatenated along one axis, so hidden states have shape
(num_tokens, 4096)rather than(B, S, 4096). Requests of different lengths sit end to end instead of being padded to the longest one. - Attention without the score matrix. FlashAttention computes exact attention in tiles held in fast on-chip memory and never writes the
(heads, S, S)score tensor to GPU memory. That is how an 8,192-token prompt avoids the 4 GiB per layer you calculated earlier. - Split weights across GPUs. With tensor parallelism over 4 GPUs, each GPU holds a quarter of the Q, K, and V output columns: 8 query heads and 2 KV heads. The split follows the head axis, so every GPU still sees whole heads.
When you evaluate a model for serving, measure against the numbers in this lesson. Weight memory should match parameters times bytes per parameter to within a few percent. The time for one decode step at batch size 1 should sit somewhat above weights divided by memory bandwidth (4.8 ms for Llama 3.1 8B on an H100), never below it.
Go deeperWhat the 2 × parameters rule leaves out
The rule counts the weight multiplications only. Attention adds work that depends on context length: for each new token, every layer computes a score against every earlier position (Q times K) and a weighted sum of their values (weights times V). Each costs 2 × 4,096 FLOPs per earlier position, so attention adds 4 × 4,096 × 32 = 524,288 FLOPs per token of context.
Attention FLOPs for one new token, Llama 3.1 8B
- Per earlier position, per layer
2 × 4,096 (scores) + 2 × 4,096 (values) = 16,384 - Across 32 layers
16,384 × 32 = 524,288 - With 8,192 tokens of context
524,288 × 8,192 ≈ 4.3 billion FLOPs
ResultAbout 29% on top of the 15 GFLOPs of weight math at 8K context
Two other details matter in practice. The output layer is large: a full (S, 4096) @ (4096, 128256) for a long prompt would produce 128,256 scores for every position, so engines apply it only to the positions they sample from, usually the last. And x @ W.T never copies W: matrix multiplication libraries such as cuBLAS accept a flag that says an input is transposed and read it through its strides, which is why PyTorch can store weights as (out, in) at no cost.
Cheat sheet
- Know every tensor’s shape, dtype, and device, and name each axis:
(batch, sequence, hidden). - Matrix multiplication: inner dimensions match and disappear.
y = xWchanges only the last axis. - Llama 3.1 8B: 8,030,261,248 parameters, about 16.06 GB in BF16, 70% of them in the MLPs.
- Parameters = sum of matrix sizes from
config.json; bytes = parameters × bytes per element. - FLOPs per token ≈ 2 × parameters (15 to 16 billion for Llama 3.1 8B), plus attention over the context.
- One decode step at batch 1 is bound by reading the weights: about 4.8 ms on an H100, versus 15 µs of math.
- Reshape regroups elements in memory order; transpose swaps axes and leaves a non-contiguous view.
- A reshape that returns the right shape proves only that the element count matches. Track one element to check meaning.
Walkthrough
Split one layer's features into attention heads
Browser lab
Follow one feature into its head
(B, S, D) → (B, H, S, Dh)Input · (1, 3, 4)
Split · (1, 3, 2, 2)
Transpose · (1, H, S, Dh)
Predict its flattened index in the final tensor.
Knowledge check