Pidoku

Convolutions

Module 11 Lesson 11.d 45 min Difficulty 2/5

Prerequisites 11.c, 2.h


Before you start: words you need#

WordPlain meaning
ConvolutionSliding a small set of learned weights (a filter) along an input and taking a weighted sum at each position.
Filter (kernel)The small weight array that slides, e.g. 3 × 3 for images or 4 taps for a sequence. Not the same as a GPU kernel.
ChannelOne “layer” of an input, such as the red part of an image or one feature of a hidden vector.
StrideHow far the filter moves each step. Stride 2 halves the output size.
DepthwiseEach channel has its own filter and channels never mix. Very cheap, and memory bound.
CausalEach output may only look at the current and earlier positions, never later ones.
im2col“Image to columns”: copying every patch the filter will see into one row of a matrix, so the whole convolution becomes one GEMM.
Patch embeddingThe first layer of a vision transformer: cut the image into squares and project each square to a vector.

1. What is it?#

A convolution slides a small filter over an input and computes a dot product at each position.

Input (3×3)        Filter (2×2)       Output (2×2)
1 2 3              1  0               each output = sum of 4 products
4 5 6        *     0 -1         →     -4 -4
7 8 9                                 -4 -4

Two properties define it: weight sharing (the same filter at every position) and locality (each output depends only on a small neighbourhood).

Convolutions are not the core of a text LLM, but in 2026 they appear in four places an inference engineer meets: vision encoders, audio front ends, the linear-attention layers of hybrid models, and image-generation models.

Facts checked on 12 November 2026.


2. Why does it matter?#

For images, a useful feature (an edge, a texture) means the same thing anywhere in the frame. A fully connected layer would learn a separate detector for every position; a convolution shares one across all of them. The same idea works for sound over time and for nearby tokens in a sequence.

For inference, convolutions come in two very different cost profiles:

  • Wide image convolutions reuse every input pixel and every weight many times. They are compute bound: the friendliest workload a GPU has.
  • Depthwise and short 1-D convolutions do a handful of multiply-adds per value loaded. They are memory bound, like decode.

Knowing which one you are looking at tells you how to make it faster.


3. Simple analogy#

A rubber stamp. You have one stamp (the filter) and press it at every position on a page. The stamp never changes, only where you press it. That is weight sharing.

im2col is photocopying every patch of the page the stamp will land on, laying the copies out in a grid, and then stamping the whole grid in one go. More paper, but one fast operation.


4. Tiny example: direct, im2col, and four real cases#

The program computes the 2×2 example both ways, then the arithmetic intensity (FLOPs per byte, 2.f) of four convolutions you meet in real serving.

Go
// conv.go — a convolution computed directly, then as im2col + matrix multiply,
// then the arithmetic intensity of the convolutions an inference engine meets in 2026.
package main

import "fmt"

func main() {
	x := [][]float64{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} // 3x3 input, one channel
	k := [][]float64{{1, 0}, {0, -1}}                 // 2x2 filter

	// 1. Direct: slide the filter over every position.
	direct := make([]float64, 0, 4)
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			var s float64
			for di := 0; di < 2; di++ {
				for dj := 0; dj < 2; dj++ {
					s += x[i+di][j+dj] * k[di][dj]
				}
			}
			direct = append(direct, s)
		}
	}

	// 2. im2col: copy each 2x2 patch into a row, then one matrix-vector product.
	var cols [][]float64
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			cols = append(cols, []float64{x[i][j], x[i][j+1], x[i+1][j], x[i+1][j+1]})
		}
	}
	flatK := []float64{k[0][0], k[0][1], k[1][0], k[1][1]}
	gemm := make([]float64, 0, 4)
	for _, row := range cols {
		var s float64
		for c := range row {
			s += row[c] * flatK[c]
		}
		gemm = append(gemm, s)
	}
	fmt.Println("direct :", direct)
	fmt.Println("im2col :", gemm, "from a", len(cols), "x", len(flatK), "matrix (9 inputs became 16)")

	// 3. Arithmetic intensity (FLOP per byte, BF16 = 2 bytes) of real cases.
	type c struct {
		name         string
		flops, bytes float64
	}
	const b = 2.0
	C := 10240.0 // Qwen3.5-27B linear-attention conv channels
	cases := []c{
		{"3x3 conv, 256 ch, 56x56 (ResNet)", 2 * 56 * 56 * 256 * 256 * 9,
			b * (56*56*256 + 256*256*9 + 56*56*256)},
		{"ViT patch embed, 448x448 image", 2 * 784 * 1536 * 1152,
			b * (784*1536 + 1536*1152 + 784*1152)},
		{"causal conv1d k=4, 1 decode token", 2 * 4 * C,
			b * (4*C + 3*C + 3*C + C + C)}, // weights, read state, write state, in, out
		{"decode GEMV 4096x4096", 2 * 4096 * 4096,
			b * (4096*4096 + 4096 + 4096)},
	}
	fmt.Println()
	for _, x := range cases {
		fmt.Printf("%-36s %9.3f GFLOP %7.2f MB %7.1f FLOP/byte\n",
			x.name, x.flops/1e9, x.bytes/1e6, x.flops/x.bytes)
	}
}

Output:

direct : [-4 -4 -4 -4]
im2col : [-4 -4 -4 -4] from a 4 x 4 matrix (9 inputs became 16)

3x3 conv, 256 ch, 56x56 (ResNet)         3.699 GFLOP    4.39 MB   842.5 FLOP/byte
ViT patch embed, 448x448 image           2.775 GFLOP    7.75 MB   357.8 FLOP/byte
causal conv1d k=4, 1 decode token        0.000 GFLOP    0.25 MB     0.3 FLOP/byte
decode GEMV 4096x4096                    0.034 GFLOP   33.57 MB     1.0 FLOP/byte

Same answer both ways; im2col needed 16 numbers to hold 9, because neighbouring patches overlap. Then the table: a 3×3 image convolution does over 800 FLOPs per byte, well past the H100’s ridge point of about 295. The short causal convolution inside a hybrid LLM’s decode step does a third of a FLOP per byte. Same word, opposite ends of the roofline (6.a).


5. Technical explanation#

The FLOP count#

FLOPs = 2 × H_out × W_out × C_in × C_out × K_h × K_w

The 2 is one multiply and one add per filter weight per output position.

How a convolution becomes a GEMM#

Input   (C_in, H, W)               → im2col → (H_out·W_out, C_in·K_h·K_w)
Weights (C_out, C_in, K_h, K_w)    → reshape → (C_in·K_h·K_w, C_out)

Convolution = im2col_matrix @ weight_matrix        ← one GEMM (11.c)

The price is memory: overlapping patches are copied, about K_h·K_w times (9 times for 3×3). The gain is that the convolution runs on the best GEMM kernels there are. The other strategies:

  • Implicit GEMM. Compute the im2col addresses on the fly inside the GEMM kernel, so the big matrix never exists. This is what cuDNN and CUTLASS mostly do.
  • Winograd. For small filters such as 3×3, a change of basis cuts the multiplications by about 2.25 times, at the cost of more additions and slightly worse rounding.
  • FFT. Worth it only for large filters, which modern networks rarely use.
  • Direct. Hand-written kernels for special shapes, especially depthwise.

The variants#

Standard           C_in × C_out × K × K weights; mixes channels and space
Pointwise (1×1)    C_in × C_out; exactly a GEMM over channels
Depthwise          C × K × K; one filter per channel, no mixing; memory bound
Depthwise-separable  depthwise then pointwise (MobileNet); 8-9x fewer FLOPs
Grouped            channels split into G groups
Dilated            gaps in the filter; wider view for the same weights
Transposed         "upsampling" convolution, used in decoders (VAEs)
Strided, non-overlapping   stride = filter size; each patch seen once: a GEMM in disguise

Depthwise convolutions are memory bound, even though they are convolutions. Mobile networks cut FLOPs by 8–9 times with them, and the wall-clock gain is much smaller, because time was never set by FLOPs. The same lesson applies all through LLM decode.

Where convolutions appear in a 2026 serving stack#

1. Vision encoders. A vision transformer’s first layer is a convolution with stride equal to its filter size, which cuts the image into non-overlapping patches. In Qwen3-VL and Qwen3.5 it is a Conv3d with filter and stride (2, 16, 16): 2 frames by 16 × 16 pixels, with a still image treated as two identical frames. A 448 × 448 image becomes 28 × 28 = 784 patches, and a later step merges each 2 × 2 group, so the language model sees 196 image tokens. Because patches do not overlap, this “convolution” is one GEMM (section 4: 358 FLOP/byte). The rest of the encoder is an ordinary transformer (18.h).

2. Audio front ends. Whisper large-v3 turns 30 seconds of audio into 128 mel-frequency channels and runs two Conv1d layers with filter size 3, the second with stride 2, giving the encoder 1,500 positions. Speech models built on Whisper-style encoders inherit this.

3. Hybrid linear-attention layers. This is the one that surprises people. Hybrid models replace most attention layers with a linear-attention or state-space layer (12.g), and those layers start with a short depthwise causal Conv1d over the projected q, k and v channels. In Qwen3.5-27B, 48 of its 64 layers are Gated DeltaNet layers with linear_conv_kernel_dim: 4 over 10,240 channels; Qwen3-Next and Mamba-2-style hybrids do the same. At decode time each step convolves one new token with the last three, so the engine must keep those three inputs per request per layer: a conv state of about 3 MB per request for Qwen3.5-27B in BF16, managed beside the KV cache (17.i). It is a tiny, memory-bound operation, done by dedicated kernels such as causal-conv1d.

4. Image generation. Diffusion U-Nets are convolution-heavy, and even transformer-based diffusion models usually decode their output through a convolutional VAE decoder.


6. Under the hood: cuDNN chooses the algorithm#

cuDNN has many algorithms per convolution shape. PyTorch can time them and keep the fastest:

Python
torch.backends.cudnn.benchmark = True   # time candidate algorithms per new shape, cache the winner

That helps when shapes are fixed and hurts when they vary, because every new shape is timed again. A vision encoder that accepts images of any size sees many shapes; either bucket the sizes (11.j) or leave this off.

For the decode-time causal conv1d in hybrid models, engines do not call cuDNN at all. They use a fused kernel that reads the saved conv state, applies the 4 taps, writes the output and shifts the state, in one pass.


7. Performance implications#

  • Image convolutions are compute bound. Use tensor cores and lower precision for the compute benefit; batch images together.
  • Depthwise and short causal convolutions are memory bound. Fusing them with neighbours matters more than their FLOP count.
  • Channels-last layout (NHWC) suits tensor cores for image convolutions. NCHW forces a transpose or a slower kernel: model.to(memory_format=torch.channels_last) (11.g).
  • A vision encoder is a fixed cost per image, independent of the text. For short text with large images it can be most of the prefill time.

8. Production implications#

  • Profile the vision encoder separately in a vision-language model. Image-heavy requests can spend a large share of their prefill there.
  • Avoid encoding the same image twice. In a multi-turn chat, a prefix-cache hit (12.m) that covers the image’s tokens can skip both the encoder and the prefill for them. Within one request, vLLM’s encoder cache holds the image embeddings until they are used (18.h).
  • Limit image resolution at the gateway. Image tokens grow with pixel count; a 4K image can turn into thousands of tokens.
  • Budget memory for conv state in hybrid models. It is per request, like KV cache, but fixed in size rather than growing with context.

9. Common mistakes#

  1. Saying “LLMs don’t use convolutions”. Hybrid 2026 models do, in most of their layers, and multimodal models do at their inputs.
  2. Assuming fewer FLOPs means faster for depthwise convolutions. They are memory bound.
  3. Using NCHW with tensor cores for image convolutions. It silently takes a slower path.
  4. Turning on cudnn.benchmark with varying shapes. It re-times algorithms over and over.
  5. Leaving the vision encoder out of capacity planning for a vision-language model.
  6. Forgetting conv state when sizing memory for a hybrid model.

10. Hands-on exercise#

  1. Run conv.go. Extend the im2col part to a 3 × 3 filter on a 5 × 5 input and count how many numbers the im2col matrix holds compared with the input.
  2. Add a fifth case: a depthwise 3 × 3 convolution with 256 channels on 56 × 56. Where does it sit between the ResNet convolution and the GEMV?
  3. Work out how many image tokens Qwen3-VL produces for a 1920 × 1080 image (round each side down to a multiple of 32), and how much prefill that adds for Qwen3-VL-8B.
  4. Compute the conv state per request for Qwen3-Next-80B-A3B from its config.json (linear_conv_kernel_dim, key and value head counts and sizes, number of linear layers).
  5. On a GPU, time a ResNet block in NCHW and channels-last BF16 and report the ratio.

11. Interview questions#

  1. How does a convolution become a GEMM, and what does that cost?
  2. Why are image convolutions compute bound while depthwise convolutions are memory bound?
  3. Why is a vision transformer’s patch embedding “a GEMM in disguise”?
  4. Where does a convolution appear inside a hybrid linear-attention LLM, and what state does it force the engine to keep?
  5. What does Winograd convolution trade?
  6. Why does cudnn.benchmark hurt with variable image sizes?

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