Pidoku

Tensor Layouts and Memory

Module 11 Lesson 11.g 1h 15m Difficulty 4/5

Prerequisites 3.b, 10.c, 6.b


Before you start: words you need#

WordPlain meaning
LayoutThe rule that maps a tensor’s logical position, such as [token, head, dim], to a place in one flat block of memory.
StrideHow many elements you jump in memory to move one step along a dimension (10.c).
ContiguousStored in plain row-major order with no gaps: the last dimension has stride 1.
ViewA new shape and strides over the same memory, made without copying.
Coalesced accessThe 32 threads of a warp reading neighbouring addresses, so the hardware serves them in a few wide transactions (6.b).
NHD / HNDTwo KV cache orders: tokens then heads then dims, or heads then tokens then dims.
PrepackingRearranging weights once at load time into the order a specific kernel reads fastest.
AlignmentAn address being a multiple of some size (often 16 bytes), which wide vector loads need.

1. What is it?#

Layout is how a tensor’s elements are placed in memory. A tensor of shape (tokens, heads, head_dim) is, physically, one long row of bytes. Which dimension changes fastest as you walk along that row is a choice, and different choices make the same kernel run at very different speeds.

Logical:   K for 16 tokens, 8 heads, 128 dims
Physical:  16 × 8 × 128 numbers in one flat buffer

NHD:  token 0 [head 0 dims 0..127][head 1 dims 0..127]...  token 1 [...]
HND:  head 0 [token 0 dims 0..127][token 1 dims 0..127]...  head 1 [...]

Both hold the same numbers. One is fast to write a new token into; the other is fast to read one head across many tokens.

Facts checked on 12 November 2026.


2. Why does it matter?#

Because GPUs read memory in wide chunks for a whole warp at once. If the 32 threads of a warp read 32 neighbouring values, one memory transaction serves them all. If they read values 4 KB apart, each needs its own transaction and most of every chunk fetched is wasted. 6.b covers the hardware rule and how to measure it; the summary is:

The dimension that neighbouring threads walk along must be the one with stride 1.

So every kernel has a preferred layout, and the job is to give it that layout without paying for a copy on every request. That is why the KV cache layout, the weight layout and the order of activation dimensions are real engineering decisions, not details.


3. Simple analogy#

A warehouse’s shelving plan. The stock is the same either way. If items that are picked together sit together, a picker fills an order in one walk down one aisle. If they are scattered, the picker crosses the warehouse for every item. The shelving plan is the layout; the picker’s walks are memory transactions.

Re-shelving the whole warehouse (a .contiguous() copy) fixes it, but costs a full day of work, so you want to do it once, at opening, not for every order.


4. Tiny example: a transpose is free, reading it is not#

The program builds a 4096 × 4096 matrix, makes a transposed view of it (only the strides swap), and times summing the original, the view and a contiguous copy. It runs on a CPU, where the same effect comes from cache lines (3.b) instead of warp transactions.

Go
// layout.go — one tensor, two memory orders. A transpose only swaps strides,
// but the code that reads the transposed view now walks memory with a big stride.
package main

import (
	"fmt"
	"time"
)

// view is a shape plus strides over a flat buffer, like a PyTorch tensor.
type view struct {
	data         []float32
	rows, cols   int
	rStep, cStep int // strides, in elements
}

func (v view) at(i, j int) float32 { return v.data[i*v.rStep+j*v.cStep] }

func (v view) t() view { // transpose: swap shape and strides, copy nothing
	return view{v.data, v.cols, v.rows, v.cStep, v.rStep}
}

func (v view) contiguous() view { // materialise in row-major order: one full copy
	out := make([]float32, v.rows*v.cols)
	for i := 0; i < v.rows; i++ {
		for j := 0; j < v.cols; j++ {
			out[i*v.cols+j] = v.at(i, j)
		}
	}
	return view{out, v.rows, v.cols, v.cols, 1}
}

func sumRows(v view) float32 { // reads in the view's logical row order
	var acc [8]float32 // eight running sums, so the adds do not wait on each other
	for i := 0; i < v.rows; i++ {
		base := i * v.rStep
		for j := 0; j < v.cols; j += 8 {
			for u := 0; u < 8; u++ {
				acc[u] += v.data[base+(j+u)*v.cStep]
			}
		}
	}
	return acc[0] + acc[1] + acc[2] + acc[3] + acc[4] + acc[5] + acc[6] + acc[7]
}

func timeIt(f func()) time.Duration {
	f()
	t0 := time.Now()
	for k := 0; k < 5; k++ {
		f()
	}
	return time.Since(t0) / 5
}

func main() {
	const n = 4096
	x := view{make([]float32, n*n), n, n, n, 1}
	for i := range x.data {
		x.data[i] = float32(i % 7)
	}
	xt := x.t()
	fmt.Printf("x   shape (%d, %d) strides (%d, %d)\n", x.rows, x.cols, x.rStep, x.cStep)
	fmt.Printf("x.T shape (%d, %d) strides (%d, %d)   same buffer: %v\n",
		xt.rows, xt.cols, xt.rStep, xt.cStep, &xt.data[0] == &x.data[0])

	var c view
	a := timeIt(func() { sumRows(x) })
	b := timeIt(func() { sumRows(xt) })
	m := timeIt(func() { c = xt.contiguous() })
	d := timeIt(func() { sumRows(c) })
	fmt.Printf("\nsum x             (stride 1)    %6.1f ms\n", a.Seconds()*1e3)
	fmt.Printf("sum x.T as a view (stride %d) %6.1f ms\n", n, b.Seconds()*1e3)
	fmt.Printf("x.T.contiguous()  (one copy)    %6.1f ms\n", m.Seconds()*1e3)
	fmt.Printf("sum the copy      (stride 1)    %6.1f ms\n", d.Seconds()*1e3)
}

Output on an Apple M-series laptop (your times will differ, the ratios will not much):

x   shape (4096, 4096) strides (4096, 1)
x.T shape (4096, 4096) strides (1, 4096)   same buffer: true

sum x             (stride 1)       9.1 ms
sum x.T as a view (stride 4096)   58.8 ms
x.T.contiguous()  (one copy)      85.4 ms
sum the copy      (stride 1)       7.8 ms

Making the transposed view cost nothing: same buffer, swapped strides. Reading it in row order was about 6.5 times slower, because each step jumps 16 KB. Copying it into a contiguous layout fixed the read but cost more than ten fast sums. The cost of a transpose is deferred, not avoided, and the copy that fixes it is worth paying only if the result is read many times.

On a GPU the same experiment in PyTorch, x.transpose(1, 2) fed into a kernel that expects contiguous input, shows the same pattern: either the kernel reads with a large stride, or PyTorch inserts a copy kernel for you.


5. Technical explanation#

Strides in PyTorch#

Python
x = torch.empty(16, 8, 128)      # (tokens, heads, dim), strides (1024, 128, 1)
y = x.transpose(0, 1)            # (heads, tokens, dim), strides (128, 1024, 1): a view
y.is_contiguous()                # False
z = y.contiguous()               # a real copy, strides (2048, 128, 1)

view, transpose, permute, expand and slicing only change metadata. contiguous(), reshape of a non-contiguous tensor, and many kernels that insist on contiguous input make a copy. In a profile, unexpected copies show up as copy_ or elementwise kernels with no arithmetic; each is a full read and write of the tensor.

Activations in a serving engine: no batch dimension#

Training code uses (batch, seq_len, hidden). Serving engines do not. With continuous batching (12.j) every step is a flat list of tokens from many requests, so activations are (num_tokens, hidden), and per-request boundaries live in a separate offsets array (query_start_loc in vLLM, cu_seqlens in FlashAttention). This layout has no padding at all, and it is why varlen kernels exist (11.j).

KV cache layouts#

The KV cache is written once per token and read on every later step, by a kernel that walks one head across many tokens. The two basic orders:

NHD  [num_blocks, block_size, num_kv_heads, head_dim]
     writing a new token: one contiguous write of heads × dims          ✓
     reading one head over a block: jumps of heads × dims per token     ✗

HND  [num_blocks, num_kv_heads, block_size, head_dim]
     writing a new token: one short write per head, scattered           ✗
     reading one head over a block: contiguous                          ✓

Reads vastly outnumber writes, so the read side usually wins, but the real answer is “whatever the attention kernel was written for”. In vLLM v0.32.0 the attention backend decides the cache shape (18.c). The FlashInfer backend supports both NHD and HND, chosen with VLLM_KV_CACHE_LAYOUT, and its Blackwell trtllm-gen decode kernels require HND. vLLM’s original paged-attention kernel used a further-split key layout so that each thread’s reads were 16-byte vector loads; 12.l shows it. Different backends, different shapes, same principle: the layout is chosen for the kernel’s access pattern.

Weight layouts#

nn.Linear stores W as (out_features, in_features), row-major.
y = x @ W.T  →  a GEMM that reads both inputs along K: the "TN" case libraries like best.

Merged weights   q, k, v (and gate, up) concatenated along out_features at load (11.c)
Sharded weights  tensor parallelism splits W by rows or columns across GPUs (14.c)
Packed formats   4-bit weights packed two per byte, with a scale per group (13.c)
Prepacked        reordered at load into the exact order a kernel's inner loop wants

Marlin (W4A16 GEMM) rearranges weights at load time so that unpacking and feeding the tensor cores is branch-free and every load is a wide, coalesced read; vLLM’s Machete kernel for Hopper does the same for its own tile shapes. The general pattern: pay the layout cost once at load, never per request.

Image layouts#

For image convolutions, PyTorch’s default NCHW (channels before height and width) is not what tensor-core kernels want; NHWC (“channels last”) puts the channels of one pixel side by side, which is the dimension a convolution-as-GEMM reduces over (11.d).

Padding and alignment#

Tensor cores    dimensions in multiples of 8 (16-bit) or 16 (8-bit), ideally of the tile size
Vector loads    16-byte aligned addresses, or the kernel falls back to narrow loads
Vocabulary      vLLM pads the LM head's vocabulary to a multiple of 64
                (151,936 is already one; 151,937 would become 152,000)
Shared memory   pad or "swizzle" tile layouts so a warp's accesses avoid bank conflicts (6.b)

Modern kernel libraries (CUTLASS’s CuTe, Triton) describe layouts, including swizzles, as composable functions from coordinates to addresses, so a kernel author states the layout rather than hand-computing offsets.


6. Under the hood: measure it#

On a GPU, Nsight Compute reports how many 32-byte sectors each warp’s load touched (6.b):

Shell
ncu --metrics l1tex__t_sectors_pipe_lsu_mem_global_op_ld.sum,\
l1tex__t_requests_pipe_lsu_mem_global_op_ld.sum ./your_program

About 4 sectors per request (for 4-byte loads) means fully coalesced; about 32 means every thread fetched its own sector. In a PyTorch program, torch.profiler with stack traces shows where each copy_ kernel came from in your Python code.


7. Performance implications#

ProblemTypical cost
Uncoalesced global loadsup to 8–32 times the bytes actually needed
Shared-memory bank conflictsthe access serialised, up to 32 ways
Misaligned pointersnarrow loads instead of 16-byte ones
An unneeded .contiguous()one full read and write of the tensor, every call
KV layout that does not match the attention kernela slow or fallback path for the largest decode cost
Awkward GEMM dimensionstile waste, sometimes no tensor-core path at all (11.c)

8. Production implications#

  • Do layout work at load time. Merging, sharding, packing and prepacking weights; choosing the KV cache layout. None of it belongs in the request path.
  • Match the KV layout to the attention backend. If you change backends (18.c) the cache shape may change with it; KV transfer between machines (14.k) must agree on it too.
  • Watch for copy kernels in profiles. Some are necessary; many come from one stray transpose in model code.
  • Keep custom heads and adapters tensor-core friendly. Base models are designed with good dimensions; additions often are not.

9. Common mistakes#

  1. Choosing a layout for readability. The kernel does not care how it looks.
  2. Thinking transpose is free, full stop. It is free until something reads it.
  3. Calling .contiguous() per request on something that could have been laid out once.
  4. Copying a KV layout from a paper without checking your kernel’s access pattern.
  5. Moving KV caches between engines or backends with different layouts without converting.
  6. Ignoring alignment. A slice that starts one element in can turn every 16-byte load into eight 2-byte loads.

10. Hands-on exercise#

  1. Run layout.go. Change n to 512 and to 8192. How does the view-versus-copy gap change as the matrix stops or starts fitting in cache?
  2. Change sumRows back to a single accumulator. Why does the gap almost disappear? (Hint: what is the loop waiting for now?)
  3. In PyTorch on a GPU, sum x, x.transpose(1, 2) and x.transpose(1, 2).contiguous() for a (8, 32, 4096, 128) BF16 tensor and report GB/s for each.
  4. Write a small Triton decode-attention kernel (6.e) for NHD and HND caches and time both at 4,096 tokens, 8 KV heads, head size 128.
  5. Profile a Hugging Face model’s forward pass and find every copy kernel. Trace each to a line of Python. How many could be removed?

11. Interview questions#

  1. What is a stride, and why is transpose free?
  2. Why do serving engines use (num_tokens, hidden) activations instead of (batch, seq, hidden)?
  3. Compare NHD and HND KV cache layouts. Which would you choose, and what decides it?
  4. Why do quantized GEMM kernels prepack their weights at load time?
  5. What does .contiguous() cost, and when is it worth paying?
  6. How would you check whether a kernel’s memory accesses are coalesced?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

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