Pidoku

Tensors, Shapes, and Broadcasting

Module 10 Lesson 10.c 1h Difficulty 2/5

Prerequisites 10.a, 10.b, 2.b


Before you start: four words#

WordPlain meaning
TensorAn array with any number of dimensions. A scalar has 0, a vector 1, a matrix 2; a batch of matrices has 3, and so on.
Axis (or dimension)One of those directions. A tensor of shape (2, 8, 64) has three axes, of sizes 2, 8 and 64.
RankHow many axes a tensor has. (2, 8, 64) has rank 3.
BroadcastingThe rule that lets you combine tensors of different shapes by reusing the smaller one, without copying it.

1. What is it?#

A tensor is an n-dimensional array of numbers. Broadcasting is the rule that lets an operation between two tensors of different shapes work without explicitly copying data:

(3, 1) + (1, 4)  →  (3, 4)      both are stretched to (3, 4) — virtually, not by copying

The practical skill this lesson builds is shape fluency. Most bugs in model code are shape bugs, and most model code becomes readable the moment you can name every axis.


2. Why does it exist?#

So that “add this bias vector to every row” does not require making a copy of the bias for every row. That saves memory and, more importantly, memory bandwidth — the bias is read once and reused from fast storage. In inference, where most operations are limited by memory bandwidth (2.e), not copying is a real speedup.


3. Simple analogy#

A stencil. You have one stencil (the bias vector) and 10,000 sheets of paper (the batch). You do not make 10,000 copies of the stencil; you reuse the one you have. Broadcasting is the array-programming version of reusing the stencil.


4. Tiny example#

Go
package main

import "fmt"

func main() {
	X := [][]int{
		{1, 2, 3},
		{4, 5, 6},
	} // (2, 3)
	b := []int{10, 20, 30} // (3,)

	// "Broadcasting": b is reused for every row. No copy of b is ever made.
	for _, row := range X {
		for j := range row {
			row[j] += b[j]
		}
	}
	fmt.Println(X) // [[11 22 33] [14 25 36]]
}

The broadcasting rule, which NumPy, PyTorch and JAX all share:

Line the shapes up from the RIGHT. For each pair of sizes:
  - equal             → fine
  - one of them is 1  → stretch it to match the other
  - one is missing    → treat it as 1
  - otherwise         → ERROR

  (2, 3)      (2, 3)      (2, 1, 3)      (5, 4)
+ (   3)   +  (2, 1)   +  (   4, 1)   +  (   3)
---------   ---------   ------------   ---------
  (2, 3)      (2, 3)      (2, 4, 3)      ERROR (4 vs 3)

The classic trap — a row plus a column:

Go
a := []int{1, 2, 3}         // shape (3,)   — a row
b := [][]int{{1}, {2}, {3}} // shape (3, 1) — a column

// A broadcasting library "adds" these by stretching both: every b[i] meets every a[j].
out := make([][]int, len(b))
for i := range b {
	for j := range a {
		out[i] = append(out[i], a[j]+b[i][0])
	}
}
fmt.Println(out) // [[2 3 4] [3 4 5] [4 5 6]] — shape (3, 3). Probably not what you wanted!

You wanted to add two length-3 vectors and got a 3 × 3 table. In model code this produces a plausible-looking tensor and silently wrong results. The defence is to check shapes explicitly.


5. Technical explanation#

The shapes of LLM inference (learn these)#

The letters: B batch size, S sequence length (tokens), d hidden size, h number of query heads, h_kv number of key/value heads, d_head size of each head, d_ff feed-forward size, V vocabulary size. 10.h and 10.i explain what each piece is; for now, learn the shapes.

input_ids            (B, S)              integers: one token ID per position
embeddings           (B, S, d)
                     ───── the "residual stream": (B, S, d) between every layer ─────
after q_proj         (B, S, h·d_head)    → view → (B, S, h, d_head) → transpose → (B, h, S, d_head)
after k_proj, v_proj (B, S, h_kv·d_head) → (B, h_kv, S, d_head)
                     h_kv < h in grouped-query attention (GQA), used by almost all
                     current models: several query heads share one K/V head (12.g)
KV cache             paged:      (num_blocks, block_size, h_kv, d_head) per layer, for K and V (12.l)
                     contiguous: (B, h_kv, S_max, d_head)
attention scores     (B, h, S_q, S_k)    ← never create this in full if you can avoid it (13.l)
attention output     (B, h, S, d_head) → (B, S, d)
ffn gate / up        (B, S, d_ff)
ffn down             (B, S, d)
logits               (B, S, V)           when every position is scored
                     (B, 1, V)           decode, or prefill keeping only the last position

Two real examples, so the letters have numbers (from the published model configs):

Llama 3.1 8B:   d = 4,096, layers = 32, h = 32, h_kv = 8, d_head = 128, d_ff = 14,336, V = 128,256
Qwen3 32B:      d = 5,120, layers = 64, h = 64, h_kv = 8, d_head = 128, d_ff = 25,600, V = 151,936

Models with multi-head latent attention (MLA, DeepSeek-style) store a compressed “latent” vector per token instead of separate K and V heads, so their cache shape differs (12.g).

Reshape, view, transpose, permute — which ones cost#

Python
t = torch.randn(2, 8, 64)

t.view(2, 512)          # free IF the memory is contiguous; errors otherwise
t.reshape(2, 512)       # free if possible, silently COPIES if not
t.transpose(1, 2)       # free — swaps strides; the result is non-contiguous
t.permute(2, 0, 1)      # free — a general transpose
t.contiguous()          # COPIES — a full read and write of the tensor

“Free” means only the shape and strides change (2.b); the numbers stay where they are.

The pattern that costs you: a transpose (free) followed by a view (needs contiguous memory) forces a contiguous() copy. In attention code this can happen in every layer at every step. It shows up in profiles as unexplained copy_ kernels (6.d).

The usual attention reshape:

Python
# (B, S, d) → (B, h, S, d_head)
q = q.view(B, S, h, d_head).transpose(1, 2)
# after attention: (B, h, S, d_head) → (B, S, d)
out = out.transpose(1, 2).contiguous().view(B, S, d)   # ← this .contiguous() is a real copy

Fused attention kernels (FlashAttention, FlashInfer) accept and return layouts that avoid some of these copies (13.l).

Head layout: [B, h, S, D] vs [B, S, h, D]#

This is a genuine engineering decision:

[B, h, S, D]  — "head-major": each head's sequence is contiguous.
                Good for: per-head attention maths. Common in reference code.

[B, S, h, D]  — "token-major": all heads for one token are contiguous.
                Good for: appending one new token's K and V (one contiguous write),
                          and fixed-size pages of KV cache.
                Used by most fused and paged attention kernels.

vLLM’s paged KV cache uses a token-major layout inside each block so that the attention kernel reads memory efficiently (6.b) and a new token’s K and V land together (17.e). That choice is a measurable part of decode speed.


6. Under the hood#

Broadcasting is implemented without copying, by giving the broadcast axis a stride of 0:

b has shape (3,) with stride (1,)
broadcast to (2, 3): shape (2, 3), stride (0, 1)
                                          ↑
                      stride 0 means "don't move in memory when the row index changes"

So the same 3 values are read again for every row — and because they are reused, they stay in cache or registers. Broadcasting is genuinely cheap.

Where it stops being cheap is when the result is huge. (B, 1, S, S) * (B, h, 1, 1) produces a full (B, h, S, S) tensor — exactly the attention-score tensor you were trying not to create.


7. Performance implications#

  • Reshapes and transposes are free; contiguous() is not. On a (B, h, S, d_head) tensor it reads and writes every element: about B·S·d × 2 bytes × 2 of memory traffic at 16 bits.
  • Broadcasting avoids copies — good — but check that it is not producing a huge result.
  • Layout decides whether memory reads are efficient (6.b). The same kernel can be 2–5x faster with a friendly layout.
  • Non-contiguous tensors can block fusion. A compiler or kernel may fall back to a slower general path (11.h).

8. Production implications#

  • Assert shapes in custom code. assert x.shape == (B, S, d), x.shape catches a broadcasting bug immediately instead of three layers later.
  • Log shapes on error paths. When a request fails, the shape is usually the clue.
  • Choose the KV layout for your attention kernel, not to match the reference code.
  • Avoid .contiguous() in the hot path when a kernel that accepts strided input exists.

9. Common mistakes#

Silent broadcasting. (3,) + (3, 1) giving (3, 3). Assert shapes.

Using reshape when you meant view. reshape silently copies; you lose a performance guarantee and gain a hidden allocation.

Transposing, then viewing. Forces a copy.

Mixing up (B, S, h, D) and (B, h, S, D). Valid shapes, wrong results.

Forgetting that decode has S = 1. Code written assuming S > 1 may index incorrectly.

Creating (B, h, S, S) in full. At B = 8, h = 32, S = 8,192 in 16-bit precision that is 8 × 32 × 8,192 × 8,192 × 2 bytes ≈ 34 GB — per layer.


10. Hands-on exercise#

A. Broadcasting drills. For each pair, state the result shape or ERROR without running it:

(5,4)+(1,);  (5,4)+(4,);  (5,4)+(5,);  (15,3,5)+(15,1,5);
(8,1,6,1)+(7,1,5);  (2,3)+(3,2);  (B,h,S,S)*(B,1,1,S)

Then check them in NumPy or PyTorch. (Answers: (5,4); (5,4); ERROR; (15,3,5); (8,7,6,5); ERROR; (B,h,S,S).)

B. The cost of contiguous. On a GPU, time t.transpose(1,2).contiguous() against t.clone() for t = torch.randn(8, 32, 4096, 128, device='cuda'). Are they the same cost? Why?

C. Layout benchmark. Compute attention scores for both [B, h, S, D] and [B, S, h, D] layouts and time them. Which is faster on your hardware, and why?

D. Annotate a real model. Take a small transformer implementation (for example nanoGPT’s model.py, or the Llama model in Hugging Face Transformers) and add a shape comment to every line of the forward pass. It is the most useful hour you can spend before Module 12.


11. Interview questions#

  1. State the broadcasting rules.
  2. Which of view, reshape, transpose, permute and contiguous copy memory?
  3. Why does q.view(B,S,h,D).transpose(1,2) not copy, while the reverse operation does?
  4. Compare [B,h,S,D] and [B,S,h,D] KV layouts. When would you choose each?
  5. Give the shape of every intermediate tensor in one transformer layer, with GQA.
  6. How large is the attention-score tensor at B = 8, h = 32, S = 8,192 in 16-bit precision, and why does that matter?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in