Track III · LLM Fundamentals · 06/07

추론 최적화Inference optimisation

LLM 추론이 왜 prefill은 계산에, decode는 메모리 대역폭에 묶이는지 산술 강도로 설명하고, KV cache 크기 공식과 GQA, continuous batching, PagedAttention, 양자화, MoE가 각각 어떤 병목을 푸는지 계산한다. speculative decoding의 수락 규칙이 target 분포를 정확히 보존함을 유도하고 시뮬레이션으로 확인한다.Explain with arithmetic intensity why LLM prefill is bound by compute and decode by memory bandwidth, and work out the KV-cache size formula and which bottleneck GQA, continuous batching, PagedAttention, quantisation and MoE each relieve. Derive that the acceptance rule of speculative decoding preserves the target distribution exactly, and confirm it by simulation.

40 분min inference · KV cache · GQA · batching · PagedAttention · quantization · speculative decoding · MoE · roofline 먼저 볼 것:Before this: GPT를 바닥부터GPT from scratch, 디코딩Decoding

Training happens once; inference happens every day. And from the post-training point of view inference is not someone else’s problem: most of the time in RL training is rollout generation, that is, inference. This lesson sums up “why LLM inference is slow” with two hardware-level calculations and maps each practical technique to the one it addresses. A broader overview is in the note Inference optimisation.

Prefill and decode: arithmetic intensity

Generation has two phases.

  • Prefill: process the TT prompt tokens in a single forward pass and store each layer’s K and V. The matrix multiplications act on an input of size T×dT \times d.
  • Decode: after that, each step produces one token per sequence. The input is 1×d1 \times d.

They use the same weights but behave completely differently. The number that separates them is the arithmetic intensity, the number of operations per byte read from memory. A GPU has both a compute rate (FLOP/s) and a memory bandwidth (byte/s), and their ratio is called the ridge point. Below the ridge the compute units sit idle waiting for data (memory-bound); above it, compute is the bottleneck (compute-bound). This picture is called the roofline model.

For a model with NN parameters and bb bytes per weight, processing nn tokens in a step takes about 2Nn2Nn operations and reads NbNb bytes of weights, so

arithmetic intensity≈2NnNb=2nb(with bf16, b=2⇒≈n)\text{arithmetic intensity} \approx \frac{2Nn}{Nb} = \frac{2n}{b} \quad (\text{with bf16, } b = 2 \Rightarrow \approx n)

Prefill has n=Tn = T (thousands), so it is compute-bound. In decode nn is the batch size BB, so with a small batch the arithmetic intensity is in single digits. A datacentre GPU’s ridge in bf16 is a few hundred FLOP/byte (e.g. about 1,000 TFLOP/s ÷ 3.35 TB/s ≈ 300), so decode at batch 1 uses less than 1% of the GPU’s compute. The lower bound on a decode step’s time is not the computation but “the time to read all the weights once”.

tstep≳Nb+(KV cache reads)memory bandwidtht_{\text{step}} \gtrsim \frac{N b + (\text{KV cache reads})}{\text{memory bandwidth}}

An 8B model in bf16 on one 3.35 TB/s GPU gives 16 GB ÷ 3.35 TB/s ≈ 4.8 ms, so a single sequence gets at most about 200 tokens per second. Almost every inference optimisation either shrinks the numerator of this formula (quantisation, GQA, MoE), lets more tokens share the same read (batching, speculative decoding), or saves memory to make the batch larger (PagedAttention).

→ Go deeper: The roofline and inference metrics works out the critical batch for each kind of layer and how TTFT, TPOT and throughput relate.

KV cache

At decode step tt, the new token’s query must attend to the keys and values of all previous positions. Re-running the forward pass over the earlier tokens every time would cost O(t)O(t) full computations per step, so we store K and V for every layer and only append the new token’s. This is the KV cache. Its size is

KV bytes/token=2×nlayer×nkv_head×dhead×bytes\text{KV bytes/token} = 2 \times n_{\text{layer}} \times n_{\text{kv\_head}} \times d_{\text{head}} \times \text{bytes}

The leading 2 is for K and V. With 32 layers, 8 KV heads, head dimension 128 and bf16, that is 2⋅32⋅8⋅128⋅2=131,0722 \cdot 32 \cdot 8 \cdot 128 \cdot 2 = 131{,}072 bytes, 128 KiB per token. A single 128K-token context takes 16 GiB, on a par with the weights. And every sequence in the batch has its own KV cache.

MQA and GQA reduce this size directly. The original multi-head attention (MHA) has a K, V head for every query head. MQA (Shazeer, 2019) has all query heads share a single K, V head, and GQA (Ainslie et al., 2023) splits the query heads into gg groups that each share a K, V. The KV cache shrinks by nhead/nkv_headn_{\text{head}}/n_{\text{kv\_head}} (4× for 32 → 8). MQA can lose some quality; GQA keeps quality close to MHA and has become the standard in recent models.

→ Go deeper: on the architecture side, Attention and KV: MHA → GQA → MLA covers MLA, sliding windows and sinks; on the serving side, KV-cache management and Long-context serving cover paging, prefix caching, offload and million-token contexts.

학습은 한 번이지만 추론은 매일이다. 그리고 사후학습 관점에서도 추론은 남의 일이 아니다. RL 학습 시간의 대부분은 rollout 생성, 즉 추론이다. 이 레슨은 “왜 LLM 추론이 느린가”를 하드웨어 수준의 계산 두 개로 정리하고, 실전 기법들이 그중 무엇을 푸는지 하나씩 대응시킨다. 더 넓은 정리는 노트 추론 최적화에 있다.

Prefill과 decode: 산술 강도

생성은 두 단계로 이루어진다.

  • Prefill: 프롬프트 TT개 토큰을 한 번의 forward로 처리하고 각 층의 K, V를 저장한다. 행렬곱이 T×dT \times d 크기의 입력에 대해 일어난다.
  • Decode: 그 뒤로는 한 step에 시퀀스당 토큰 하나를 만든다. 입력이 1×d1 \times d이다.

같은 가중치를 쓰는데 성격이 완전히 다르다. 이를 가르는 숫자가 산술 강도(arithmetic intensity), 즉 메모리에서 읽은 바이트당 연산 수다. GPU는 초당 연산 능력(FLOP/s)과 초당 메모리 대역폭(byte/s)을 함께 가지는데, 이 둘의 비를 ridge point라 한다. 산술 강도가 ridge보다 낮으면 계산 유닛이 데이터를 기다리며 놀고(memory-bound), 높으면 계산이 병목이다(compute-bound). 이 그림을 roofline 모델이라 부른다.

매개변수 NN개, 가중치 한 개에 bb바이트인 모델로 한 step에 토큰 nn개를 처리하면 연산은 약 2Nn2Nn, 가중치 읽기는 NbNb바이트이므로

산술 강도≈2NnNb=2nb(bf16이면 b=2⇒≈n)\text{산술 강도} \approx \frac{2Nn}{Nb} = \frac{2n}{b} \quad (\text{bf16이면 } b = 2 \Rightarrow \approx n)

이다. prefill은 n=Tn = T(수천)이라 compute-bound다. decode는 nn이 배치 크기 BB라서, 배치가 작으면 산술 강도가 한 자릿수다. 데이터센터급 GPU의 ridge는 bf16 기준으로 수백 FLOP/byte(예: 약 1,000 TFLOP/s ÷ 3.35 TB/s ≈ 300)이므로, 배치 1의 decode는 GPU 연산 능력의 1% 미만만 쓴다. decode의 step 시간 하한은 연산이 아니라 “가중치를 한 번 다 읽는 시간”이다.

tstep≳Nb+(KV cache 읽기)메모리 대역폭t_{\text{step}} \gtrsim \frac{N b + (\text{KV cache 읽기})}{\text{메모리 대역폭}}

8B 모델을 bf16으로 3.35 TB/s GPU 한 장에 올리면 16 GB ÷ 3.35 TB/s ≈ 4.8 ms, 시퀀스 하나는 많아야 초당 약 200 토큰이다. 거의 모든 추론 최적화는 이 식의 분자를 줄이거나(양자화, GQA, MoE), 같은 읽기를 더 많은 토큰이 나눠 쓰게 하거나(배칭, speculative decoding), 메모리를 아껴서 배치를 키우는(PagedAttention) 것이다.

→ 더 깊이: Roofline과 추론 지표에서 층 종류별 critical batch와 TTFT·TPOT·처리량의 관계를 계산한다.

KV 캐시(KV cache)

decode step tt에서 새 토큰의 query는 이전 모든 위치의 key, value와 attention해야 한다. 매번 앞의 토큰들을 다시 forward하면 step마다 O(t)O(t)번의 전체 계산이 들므로, 층마다 K와 V를 저장해 두고 새 토큰의 것만 추가한다. 이것이 KV cache다. 크기는

KV 바이트/토큰=2×nlayer×nkv_head×dhead×바이트\text{KV 바이트/토큰} = 2 \times n_{\text{layer}} \times n_{\text{kv\_head}} \times d_{\text{head}} \times \text{바이트}

앞의 2는 K와 V다. 32층, KV head 8개, head 차원 128, bf16이면 2⋅32⋅8⋅128⋅2=131,0722 \cdot 32 \cdot 8 \cdot 128 \cdot 2 = 131{,}072바이트, 토큰당 128 KiB다. 128K 토큰 문맥 하나면 16 GiB로 가중치와 맞먹는다. 그리고 KV cache는 배치의 모든 시퀀스마다 따로 있다.

MQA와 GQA는 이 크기를 직접 줄인다. 원래 multi-head attention(MHA)은 query head마다 K, V head가 있다. MQA(Shazeer, 2019)는 모든 query head가 K, V head 하나를 공유하고, GQA(Ainslie et al., 2023)는 query head들을 gg개 그룹으로 나눠 그룹마다 K, V를 공유한다. KV cache는 nhead/nkv_headn_{\text{head}}/n_{\text{kv\_head}}배 줄어든다(32 → 8이면 4배). MQA는 품질 손실이 있을 수 있고, GQA는 MHA에 가까운 품질을 유지해서 최근 모델의 표준이 되었다.

→ 더 깊이: 아키텍처 쪽은 Attention과 KV: MHA → GQA → MLA가 MLA, sliding window, sink를 다루고, 서빙 쪽은 KV cache 관리와 긴 문맥 서빙이 paging, prefix caching, offload, 백만 토큰 문맥을 다룬다.

Top bar: how much of GPU memory (red line) the weights (blue) and the KV cache (amber) take. KV cache = 2 · layers · KV heads · head dim · bytes × tokens × batch. Raise the context to 128K or pick MHA and the KV becomes larger than the weights. Bottom curve: an upper bound on throughput (tokens/s), assuming one decode step reads all the weights and every sequence's KV from memory once. Growing the batch shares the weight read across sequences, so throughput rises until the KV read grows large or memory overflows (grey). 위 막대: 가중치(파랑)와 KV cache(주황)가 GPU 메모리(빨간 선)를 얼마나 차지하는지. KV cache = 2 · 층 · KV head · head 차원 · 바이트 × 토큰 수 × 배치. 문맥을 128K로 늘리거나 MHA를 골라 보면 가중치보다 KV가 커진다. 아래 곡선: decode 한 step이 가중치 전부와 모든 시퀀스의 KV를 메모리에서 한 번 읽는다고 보고 계산한 처리량 상한(토큰/초). 배치를 늘리면 가중치 읽기를 여러 시퀀스가 나눠 써서 처리량이 오르다가, KV 읽기가 커지거나 메모리가 넘치면(회색) 멈춘다.

Things to check in the figure:

  1. In the default setting (8B GQA, 8K context, batch 16) the KV cache is about as large as the weights. Raise the context to 128K and memory overflows with just a few sequences in the batch.
  2. Switch the model to MHA and, with the same setting, the KV becomes 4× larger and the maximum batch drops sharply.
  3. In the lower curve, throughput rises almost proportionally as the batch grows, because many sequences share the weight read. As the batch gets large, KV reads dominate and the curve flattens. The usable range is up to the batch memory allows (before the grey region).
  4. Switch the weights to int4 and throughput at batch 1 becomes almost 4× that of bf16, because at small batch the weight read is everything. With a large batch and a long context the KV dominates and the gain shrinks; there, switching the KV to fp8 helps instead.
  5. At batch 1, MoE reads only the active parameters (13B) and is much faster than 70B dense, but all of the total parameters (47B) must sit in memory. As the batch grows, almost every expert is picked by some token, and in the end the full weights are read.

Batching and memory management

Continuous batching (Orca, Yu et al., 2022) removes finished sequences and inserts waiting requests at every decode step, so the GPU always runs a full batch even though response lengths vary. PagedAttention (Kwon et al., 2023, vLLM) splits the KV cache into small fixed-size blocks managed by a per-sequence block table, like an operating system’s virtual memory, which removes almost all fragmentation so a larger batch fits in the same memory. The same blocks make prefix sharing easy: requests with a common system prompt, or several samples from one prompt, reference a single copy of the prompt’s KV.

→ Go deeper: Batching and scheduling (continuous batching, chunked prefill, prefill–decode disaggregation) and KV-cache management (paging, prefix caching, offload, eviction).

Quantisation

Representing weights, activations and KV with fewer bits removes a different bottleneck depending on what is quantised. Weight-only quantisation (int8/int4, GPTQ, AWQ) shrinks the weight bytes bb, so memory-bound decode speeds up almost proportionally; weight + activation (W8A8, fp8) runs the matrix multiplications on low-precision tensor cores and speeds up compute-bound prefill and large-batch decode, although outlier channels in LLM activations make it harder. Quantising the KV cache (fp8, etc.) cuts the reads and memory that dominate at long context and large batch.

→ Go deeper: Quantisation covers FP8/MX/NVFP4 formats, weight-only PTQ, SmoothQuant-style outlier handling and low-precision rollouts in RL.

Speculative decoding

Because decode is memory-bound, verifying one token or five takes almost the same time, one target-model forward (the weight read dominates). So let a cheap draft model qq first propose γ\gamma tokens, and have the large target model pp verify them all at once in a single forward. The problem is the output distribution: if we simply accept what the draft proposes, we get the distribution of qq, not pp. Leviathan et al. (2023) and Chen et al. (2023) showed that the following acceptance rule gives exactly the same distribution as sampling from pp.

  1. The draft proposes x∼qx \sim q.
  2. Accept with probability min⁡ ⁣(1,  p(x)/q(x))\min\!\big(1,\; p(x)/q(x)\big).
  3. On rejection, draw anew from the residual distribution   p′(x)=max⁡(0, p(x)−q(x))∑x′max⁡(0, p(x′)−q(x′))  \;p'(x) = \dfrac{\max(0,\, p(x) - q(x))}{\sum_{x'} \max(0,\, p(x') - q(x'))}\; and discard the draft tokens after it.
  4. If all γ\gamma are accepted, draw one more bonus token from the target’s distribution at the last position.

Why it is exact. Add up the probability that token xx is output at one position. Via the accept path it is q(x)min⁡(1,p(x)/q(x))=min⁡(p(x),q(x))q(x)\min(1, p(x)/q(x)) = \min(p(x), q(x)). The total probability of rejection is

β=∑x′q(x′)(1−min⁡(1,p(x′)q(x′)))=1−∑x′min⁡(p(x′),q(x′))=∑x′max⁡(0, p(x′)−q(x′))\beta = \sum_{x'} q(x')\Big(1 - \min\big(1, \tfrac{p(x')}{q(x')}\big)\Big) = 1 - \sum_{x'} \min(p(x'), q(x')) = \sum_{x'} \max(0,\, p(x') - q(x'))

(the last equality follows from ∑p=∑q=1\sum p = \sum q = 1), and the probability that xx comes out via the reject path is β⋅p′(x)=max⁡(0,p(x)−q(x))\beta \cdot p'(x) = \max(0, p(x) - q(x)). Together,

P(output=x)=min⁡(p(x),q(x))+max⁡(0, p(x)−q(x))=p(x)P(\text{output} = x) = \min(p(x), q(x)) + \max(0,\, p(x) - q(x)) = p(x)

Whatever qq we use, the output follows pp. The quality of qq only affects speed.

Expected speed. The acceptance probability at one position is α=∑xmin⁡(p(x),q(x))=1−TV(p,q)\alpha = \sum_x \min(p(x), q(x)) = 1 - \mathrm{TV}(p, q). Approximating it as an independent α\alpha at every position, the probability that one target forward yields at least ii tokens is the probability that the first i−1i-1 drafts are all accepted, αi−1\alpha^{i-1} (i=1,…,γ+1i = 1, \dots, \gamma+1; even if the first token is rejected, resampling still yields one). Hence

E[tokens per target forward]=∑i=1γ+1αi−1=1−αγ+11−α\mathbb{E}[\text{tokens per target forward}] = \sum_{i=1}^{\gamma+1} \alpha^{i-1} = \frac{1 - \alpha^{\gamma+1}}{1 - \alpha}

If one draft call costs cc times a target call, a step takes γc+1\gamma c + 1 units of time, so the wall-clock speed-up is roughly 1−αγ+1(1−α)(γc+1)\frac{1 - \alpha^{\gamma+1}}{(1 - \alpha)(\gamma c + 1)}. The higher α\alpha, the more a long γ\gamma pays off; with a low α\alpha, a long γ\gamma only adds discarded drafts.

그림에서 확인할 것:

  1. 기본 설정(8B GQA, 8K 문맥, 배치 16)에서 KV cache가 가중치와 비슷한 크기다. 문맥을 128K로 늘리면 배치 몇 개로도 메모리가 넘친다.
  2. 모델을 MHA로 바꾸면 같은 설정에서 KV가 4배가 되고 최대 배치가 크게 줄어든다.
  3. 아래 곡선에서 배치를 늘리면 처리량이 거의 비례해서 오른다. 가중치 읽기를 여러 시퀀스가 나눠 쓰기 때문이다. 배치가 커지면 KV 읽기가 지배적이 되어 곡선이 눕는다. 메모리가 허락하는 배치(회색 영역 전)까지가 실제로 쓸 수 있는 구간이다.
  4. 가중치를 int4로 바꾸면 배치 1의 처리량이 bf16의 거의 4배가 된다. 작은 배치에서는 가중치 읽기가 전부이기 때문이다. 배치가 크고 문맥이 길면 KV가 지배적이라 이득이 줄고, 대신 KV를 fp8로 바꾸는 것이 효과가 있다.
  5. MoE는 배치 1에서 활성 매개변수(13B)만 읽어 70B dense보다 훨씬 빠르지만, 메모리에는 총 매개변수(47B)를 전부 올려야 한다. 배치가 커지면 거의 모든 expert가 어떤 토큰에게든 선택되어 결국 전체 가중치를 읽게 된다.

배칭과 메모리 관리

Continuous batching(Orca, Yu et al., 2022)은 decode step마다 끝난 시퀀스를 빼고 대기 중인 요청을 넣어, 응답 길이가 제각각이어도 GPU가 늘 꽉 찬 배치로 돌게 한다. PagedAttention(Kwon et al., 2023, vLLM)은 운영체제의 가상 메모리처럼 KV cache를 작은 고정 크기 블록으로 나눠 시퀀스별 블록 테이블로 관리하므로 단편화가 거의 사라지고 같은 메모리에 더 큰 배치가 들어간다. 같은 블록 덕분에 prefix 공유도 쉬워진다. 시스템 프롬프트가 같은 요청들이나 한 프롬프트에서 뽑은 여러 샘플이 프롬프트의 KV 한 벌을 참조한다.

→ 더 깊이: 배칭과 스케줄링(continuous batching, chunked prefill, prefill–decode 분리)과 KV cache 관리(paging, prefix caching, offload, eviction).

양자화

가중치·활성값·KV를 더 적은 비트로 표현하면, 무엇을 양자화하느냐에 따라 다른 병목이 풀린다. Weight-only 양자화(int8/int4, GPTQ·AWQ)는 가중치 바이트 bb를 줄여 memory-bound인 decode를 거의 비례해서 빠르게 하고, weight + activation(W8A8, fp8)은 행렬곱을 저정밀 텐서 코어로 돌려 compute-bound인 prefill과 큰 배치 decode를 빠르게 하지만 LLM 활성값의 outlier 채널 때문에 더 어렵다. KV cache를 양자화하면(fp8 등) 긴 문맥과 큰 배치에서 지배적인 KV 읽기와 메모리가 줄어든다.

→ 더 깊이: 양자화에서 FP8/MX/NVFP4 포맷, weight-only PTQ, SmoothQuant식 outlier 처리, RL의 저정밀 rollout을 다룬다.

추측 디코딩(Speculative decoding)

decode는 memory-bound라서 토큰 하나를 검증하든 다섯 개를 검증하든 target 모델 forward 한 번의 시간이 거의 같다(가중치 읽기가 지배적이니까). 그렇다면 싼 draft 모델 qq가 γ\gamma개 토큰을 먼저 제안하고, 큰 target 모델 pp가 그것을 한 번의 forward로 한꺼번에 검증하면 된다. 문제는 출력 분포다. draft가 제안한 것을 그냥 받아들이면 pp가 아니라 qq의 분포가 된다. Leviathan et al.(2023)과 Chen et al.(2023)은 다음 수락 규칙이 pp에서 정확히 샘플링한 것과 같은 분포를 준다는 것을 보였다.

  1. draft가 x∼qx \sim q를 제안한다.
  2. 확률 min⁡ ⁣(1,  p(x)/q(x))\min\!\big(1,\; p(x)/q(x)\big)로 수락한다.
  3. 거절하면 잔차 분포   p′(x)=max⁡(0, p(x)−q(x))∑x′max⁡(0, p(x′)−q(x′))  \;p'(x) = \dfrac{\max(0,\, p(x) - q(x))}{\sum_{x'} \max(0,\, p(x') - q(x'))}\;에서 새로 뽑고, 그 뒤의 draft 토큰은 버린다.
  4. γ\gamma개가 모두 수락되면 target의 마지막 위치 분포에서 보너스 토큰 하나를 더 뽑는다.

왜 정확한가. 한 위치에서 토큰 xx가 출력될 확률을 더하자. 수락 경로로는 q(x)min⁡(1,p(x)/q(x))=min⁡(p(x),q(x))q(x)\min(1, p(x)/q(x)) = \min(p(x), q(x)). 거절될 전체 확률은

β=∑x′q(x′)(1−min⁡(1,p(x′)q(x′)))=1−∑x′min⁡(p(x′),q(x′))=∑x′max⁡(0, p(x′)−q(x′))\beta = \sum_{x'} q(x')\Big(1 - \min\big(1, \tfrac{p(x')}{q(x')}\big)\Big) = 1 - \sum_{x'} \min(p(x'), q(x')) = \sum_{x'} \max(0,\, p(x') - q(x'))

이고(마지막 등호는 ∑p=∑q=1\sum p = \sum q = 1에서 나온다), 거절 경로로 xx가 나올 확률은 β⋅p′(x)=max⁡(0,p(x)−q(x))\beta \cdot p'(x) = \max(0, p(x) - q(x))다. 합치면

P(출력=x)=min⁡(p(x),q(x))+max⁡(0, p(x)−q(x))=p(x)P(\text{출력} = x) = \min(p(x), q(x)) + \max(0,\, p(x) - q(x)) = p(x)

이다. 어떤 qq를 써도 출력은 pp를 따른다. qq의 품질은 속도에만 영향을 준다.

기대 속도. 한 위치의 수락 확률은 α=∑xmin⁡(p(x),q(x))=1−TV(p,q)\alpha = \sum_x \min(p(x), q(x)) = 1 - \mathrm{TV}(p, q)다. 위치마다 독립적으로 α\alpha라고 근사하면, 한 번의 target forward가 적어도 ii개 토큰을 내놓을 확률은 처음 i−1i-1개 draft가 모두 수락될 확률 αi−1\alpha^{i-1}이다(i=1,…,γ+1i = 1, \dots, \gamma+1; 첫 토큰은 거절되어도 재샘플로 하나는 나온다). 따라서

E[target forward당 토큰]=∑i=1γ+1αi−1=1−αγ+11−α\mathbb{E}[\text{target forward당 토큰}] = \sum_{i=1}^{\gamma+1} \alpha^{i-1} = \frac{1 - \alpha^{\gamma+1}}{1 - \alpha}

이다. draft 한 번의 비용이 target의 cc배라면 step 하나에 γc+1\gamma c + 1 단위의 시간이 들므로 wall-clock 속도 향상은 대략 1−αγ+1(1−α)(γc+1)\frac{1 - \alpha^{\gamma+1}}{(1 - \alpha)(\gamma c + 1)}이다. α\alpha가 높을수록 긴 γ\gamma가 이득이고, α\alpha가 낮으면 긴 γ\gamma는 버려지는 draft만 늘린다.

Left: the target p (blue outline) and the draft q (amber); the area where they overlap (violet) is the per-token acceptance probability α = Σ min(p, q). Right: at every step the draft proposes γ tokens and the target verifies them in one forward pass. ■ accepted, ■ rejected followed by ■ resampled, and a ■ bonus token when all are accepted. Raise λ and q resembles p, α grows, and tokens per step increase along the formula (1 − αγ+1)/(1 − α). The frequency of output tokens (black ticks on the left) matches p regardless of λ. 왼쪽: target p(파랑 윤곽)와 draft q(주황), 둘이 겹치는 부분(보라)의 넓이가 토큰당 수락 확률 α = Σ min(p, q)다. 오른쪽: step마다 draft가 γ개를 제안하고 target이 한 번의 forward로 검증한다. ■ 수락, ■ 거절 뒤 ■ 재샘플, 모두 수락되면 ■ 보너스 토큰. λ를 올리면 q가 p를 닮아 α가 커지고 step당 토큰이 공식 (1 − αγ+1)/(1 − α)를 따라 늘어난다. 출력 토큰의 빈도(왼쪽 검은 눈금)는 λ와 무관하게 p와 같다.

Things to check in the figure:

  1. Press 5000 steps at once: the measured tokens per step match the formula within sampling error (about ±0.02). This simulation uses the same p,qp, q regardless of context, so the assumption “an independent α\alpha at every position” holds exactly.
  2. Lower λ to 0 to make the draft terrible: the black ticks on the left (output frequencies) still sit on the blue outline (p). Only the speed drops.
  3. Raise γ to 8: when α is high, tokens per step grow a lot, but when α is around 0.5 they barely grow. Raising the draft cost c shortens the optimal γ.

→ Go deeper: Speculative decoding in depth extends this to draft trees, lossless tree verification, where drafts come from, and where speculation stops paying at large batch.

MoE: total versus active parameters

Mixture-of-Experts splits the MLP into EE experts, and a router picks only the top-kk for each token to compute. Computation per token is proportional to the active parameters (the shared part + kk experts), while memory must hold all the total parameters. So MoE gives good quality per training and inference FLOP but uses a lot of memory, and, as we saw above, it is fast in small-batch decode by reading only the active experts, but that advantage shrinks as the batch grows. For large MoEs, expert parallelism, which places the experts across several GPUs, and the all-to-all communication it entails become the centre of inference design.

→ Go deeper: Anatomy of MoE for routing, shared experts and load balancing; The roofline for why every expert sees a small batch; Parallelism for serving, and MoE for wide expert parallelism and dispatch/combine. To see how real models combine MoE with their attention and KV choices, follow the lineages (DeepSeek, Qwen, Kimi, Nemotron) and Design choices compared.

Computing it yourself

NumPy KV cache size and a roofline estimate for decode
import numpy as np

def kv_bytes_per_token(n_layer, n_kv_head, d_head, nbytes=2):
    return 2 * n_layer * n_kv_head * d_head * nbytes       # K and V

configs = {"8B GQA (kv=8)": (32, 8, 128, 8e9), "8B MHA (kv=32)": (32, 32, 128, 8e9),
           "70B GQA (kv=8)": (80, 8, 128, 70e9)}
GiB = 2**30
print("model             KV/token  KV(8K ctx)  KV(128K ctx)  weights(bf16)")
for name, (L, kv, hd, N) in configs.items():
    t = kv_bytes_per_token(L, kv, hd)
    print(f"{name:<16} {t / 1024:6.0f}KiB  {t * 8192 / GiB:8.2f}GiB  {t * 131072 / GiB:9.1f}GiB  {N * 2 / GiB:8.1f}GiB")

# roofline: rough specs of one accelerator (assumed)
peak_flops, bw = 989e12, 3.35e12                           # bf16 dense FLOP/s, HBM byte/s
print(f"\nridge point = {peak_flops / bw:.0f} FLOP/byte")
N, b = 8e9, 2
for n_tok, what in [(1, "decode, batch 1"), (64, "decode, batch 64"), (2048, "prefill, 2048 tokens")]:
    intensity = 2 * N * n_tok / (N * b)
    t_mem, t_cmp = N * b / bw, 2 * N * n_tok / peak_flops
    bound = "memory" if t_mem > t_cmp else "compute"
    print(f"{what:<18} intensity {intensity:6.0f}  t_mem={t_mem * 1e3:5.2f}ms  t_compute={t_cmp * 1e3:6.2f}ms  → {bound}-bound")
print(f"\n8B bf16, batch-1 decode bound ≈ {bw / (N * b):.0f} tokens/s (ignoring KV reads)")
 

Next we implement speculative sampling as is and check two things: (1) whether tokens per step match the formula for context-independent p,qp, q, and (2) whether, even for a bigram model whose distribution changes with context, the joint distribution of generated sequences equals the target’s. For comparison we also compute the case where draft proposals are accepted unconditionally.

NumPy Speculative sampling: checking distribution preservation and expected speed
import random
R = random.Random(0)

def draw(dist):                       # fast sampling from a small distribution
    u, acc = R.random(), 0.0
    for i, w in enumerate(dist):
        acc += w
        if u < acc:
            return i
    return len(dist) - 1

def spec_step(p_of, q_of, ctx, gamma):
    """Draft proposes gamma tokens → target verifies them at once. Returns the list of output tokens."""
    drafts, qs, c = [], [], ctx
    for _ in range(gamma):
        qd = q_of(c); x = draw(qd); drafts.append(x); qs.append(qd); c = x
    out, c = [], ctx
    for x, qd in zip(drafts, qs):
        pd = p_of(c)                                   # in practice all of these come from one target forward
        if R.random() < min(1.0, pd[x] / qd[x]):
            out.append(x); c = x
        else:
            res = [max(0.0, a - b) for a, b in zip(pd, qd)]
            z = sum(res)
            out.append(draw([r / z for r in res]))
            return out
    out.append(draw(p_of(c)))                          # all accepted: bonus token
    return out

# (1) context-independent p, q: tokens per step vs (1 - α^(γ+1)) / (1 - α)
p = np.array([0.42, 0.25, 0.15, 0.10, 0.05, 0.03])
q = 0.6 * p + 0.4 * np.array([0.05, 0.10, 0.10, 0.15, 0.25, 0.35])
alpha = np.minimum(p, q).sum()
for gamma in [1, 3, 6]:
    n_tok, n_step, counts = 0, 4000, np.zeros(len(p))
    for _ in range(n_step):
        out = spec_step(lambda c: p, lambda c: q, 0, gamma)
        n_tok += len(out); np.add.at(counts, out, 1)
    print(f"α={alpha:.3f} γ={gamma}: tokens/step measured {n_tok / n_step:.3f} / formula {(1 - alpha**(gamma + 1)) / (1 - alpha):.3f}"
          f"   max error of output freq. {np.abs(counts / n_tok - p).max():.3f}")

# (2) context-dependent bigram: compare joint distributions of 3-token sequences
V = 3
P = np.array([[0.7, 0.2, 0.1], [0.1, 0.3, 0.6], [0.3, 0.3, 0.4]])    # target  p(x_t | x_{t-1})
Q = np.array([[0.3, 0.4, 0.3], [0.5, 0.25, 0.25], [0.2, 0.6, 0.2]])  # draft
exact = {(a, b, c): P[0, a] * P[a, b] * P[b, c] for a in range(V) for b in range(V) for c in range(V)}
draft_only = {k: Q[0, k[0]] * Q[k[0], k[1]] * Q[k[1], k[2]] for k in exact}

def spec_generate(n, gamma=3):
    seq = [0]
    while len(seq) - 1 < n:
        seq += spec_step(lambda c: P[c], lambda c: Q[c], seq[-1], gamma)
    return tuple(seq[1:n + 1])

M = 6000
emp = {}
for _ in range(M):
    s = spec_generate(3)
    emp[s] = emp.get(s, 0) + 1
tv_spec = 0.5 * sum(abs(emp.get(k, 0) / M - v) for k, v in exact.items())
tv_draft = 0.5 * sum(abs(draft_only[k] - v) for k, v in exact.items())
print(f"\nJoint distribution of all 27 3-token sequences, total variation distance:")
print(f"  speculative sampling vs target : {tv_spec:.3f}  (noise level for {M} samples)")
print(f"  accepting the draft as is      : {tv_draft:.3f}")
 
확인 문제Check yourself

A model with 32 layers, 8 KV heads and head dimension 128 stores its KV cache in fp8 (1 byte). How large is the KV cache of one sequence with a 32K-token context?

Per token, 2⋅32⋅8⋅128⋅1=65,5362 \cdot 32 \cdot 8 \cdot 128 \cdot 1 = 65{,}536 bytes = 64 KiB. With 32K = 32,768 tokens, 64 KiB×32,768=2 GiB64\,\text{KiB} \times 32{,}768 = 2\,\text{GiB}. In bf16 it would be 4 GiB, and with MHA (32 KV heads) in bf16, 16 GiB.

확인 문제Check yourself

In speculative decoding with acceptance probability α = 0.8 and draft length γ = 4, what is the expected number of tokens per target forward?

1−αγ+11−α=1−0.850.2=1−0.3280.2≈3.36\frac{1 - \alpha^{\gamma+1}}{1 - \alpha} = \frac{1 - 0.8^5}{0.2} = \frac{1 - 0.328}{0.2} \approx 3.36. The maximum is γ+1=5\gamma + 1 = 5 (all accepted + bonus). Ignoring the draft cost, decode becomes about 3.4× faster.

Summary

  • Prefill processes TT tokens at once and is compute-bound; decode handles as many tokens per step as the batch size and is memory-bandwidth-bound. The yardsticks are the arithmetic intensity ≈ 2n/b2n/b and the GPU’s ridge point.
  • KV cache = 2⋅nlayer⋅nkv_head⋅dhead⋅2 \cdot n_{\text{layer}} \cdot n_{\text{kv\_head}} \cdot d_{\text{head}} \cdot bytes / token. With long contexts and large batches it outgrows the weights. GQA and MQA shrink it by sharing heads.
  • Continuous batching keeps the batch full at all times; PagedAttention removes KV memory waste and shares prefixes.
  • Quantisation relieves different bottlenecks (decode, prefill, long context) depending on what it shrinks (weights, activations, KV).
  • Speculative decoding: accept with min⁡(1,p/q)\min(1, p/q), resample from (p−q)+(p-q)_+ on rejection. The output follows pp exactly, and the expected tokens per forward are (1−αγ+1)/(1−α)(1-\alpha^{\gamma+1})/(1-\alpha).
  • In MoE, compute scales with the active parameters and memory with the total parameters.

그림에서 확인할 것:

  1. 5000 step 즉시를 누르면 측정된 step당 토큰이 공식과 표본 오차(±0.02 정도) 안에서 맞는다. 이 시뮬레이션은 문맥과 무관하게 같은 p,qp, q를 쓰므로 “위치마다 독립적으로 α\alpha” 가정이 정확히 성립한다.
  2. λ를 0으로 내려 draft를 엉망으로 만들어도 왼쪽 검은 눈금(출력 빈도)은 여전히 파란 윤곽(p)에 붙어 있다. 속도만 떨어진다.
  3. γ를 8까지 올리면 α가 높을 때는 step당 토큰이 크게 늘지만, α가 0.5 근처면 거의 늘지 않는다. draft 비용 c를 올리면 최적 γ가 짧아진다.

→ 더 깊이: Speculative decoding 심화에서 draft tree, 무손실 tree 검증, draft의 출처, 큰 배치에서 speculation이 손해가 되는 지점까지 넓힌다.

MoE: 총 매개변수와 활성 매개변수

Mixture-of-Experts는 MLP를 EE개의 expert로 나누고, router가 토큰마다 top-kk개만 골라 계산한다. 토큰당 연산은 활성 매개변수(공유 부분 + kk개 expert)에 비례하고, 메모리는 총 매개변수를 다 올려야 한다. 그래서 MoE는 학습·추론 FLOPs 대비 품질이 좋지만 메모리를 많이 먹고, 앞에서 본 것처럼 작은 배치의 decode에서는 활성 expert만 읽어 빠르다가 배치가 커지면 그 이점이 줄어든다. 큰 MoE는 expert를 여러 GPU에 나눠 두는 expert parallelism과 그에 따른 all-to-all 통신이 추론 설계의 중심이 된다.

→ 더 깊이: routing, shared expert, 부하 균형은 MoE 해부, expert마다 배치가 작아지는 이유는 Roofline, wide expert parallelism과 dispatch/combine은 서빙을 위한 병렬화와 MoE에서 다룬다. 실제 모델이 MoE를 attention·KV 선택과 어떻게 묶는지는 계보 레슨(DeepSeek, Qwen, Kimi, Nemotron)과 설계 선택 비교에서 볼 수 있다.

직접 계산하기

NumPy KV cache 크기와 decode의 roofline 어림
import numpy as np

def kv_bytes_per_token(n_layer, n_kv_head, d_head, nbytes=2):
    return 2 * n_layer * n_kv_head * d_head * nbytes       # K와 V

configs = {"8B GQA (kv=8)": (32, 8, 128, 8e9), "8B MHA (kv=32)": (32, 32, 128, 8e9),
           "70B GQA (kv=8)": (80, 8, 128, 70e9)}
GiB = 2**30
print("모델              KV/토큰   KV(8K문맥)  KV(128K문맥)  가중치(bf16)")
for name, (L, kv, hd, N) in configs.items():
    t = kv_bytes_per_token(L, kv, hd)
    print(f"{name:<16} {t / 1024:6.0f}KiB  {t * 8192 / GiB:8.2f}GiB  {t * 131072 / GiB:9.1f}GiB  {N * 2 / GiB:8.1f}GiB")

# roofline: 가속기 하나의 대략적인 사양(가정)
peak_flops, bw = 989e12, 3.35e12                           # bf16 dense FLOP/s, HBM byte/s
print(f"\nridge point = {peak_flops / bw:.0f} FLOP/byte")
N, b = 8e9, 2
for n_tok, what in [(1, "decode, 배치 1"), (64, "decode, 배치 64"), (2048, "prefill, 2048 토큰")]:
    intensity = 2 * N * n_tok / (N * b)
    t_mem, t_cmp = N * b / bw, 2 * N * n_tok / peak_flops
    bound = "memory" if t_mem > t_cmp else "compute"
    print(f"{what:<18} 산술 강도 {intensity:6.0f}  t_mem={t_mem * 1e3:5.2f}ms  t_compute={t_cmp * 1e3:6.2f}ms  → {bound}-bound")
print(f"\n8B bf16, 배치 1 decode 상한 ≈ {bw / (N * b):.0f} 토큰/초 (KV 읽기 무시)")
 

다음은 speculative sampling을 그대로 구현해 두 가지를 확인한다. (1) 문맥과 무관한 p,qp, q에서 step당 토큰 수가 공식과 맞는지, (2) 문맥에 따라 분포가 바뀌는 bigram 모델에서도 생성된 시퀀스의 결합분포가 target과 같은지. 비교를 위해 draft 제안을 무조건 받아들이는 경우도 계산한다.

NumPy speculative sampling: 분포 보존과 기대 속도 검증
import random
R = random.Random(0)

def draw(dist):                       # 작은 분포에서 빠른 샘플링
    u, acc = R.random(), 0.0
    for i, w in enumerate(dist):
        acc += w
        if u < acc:
            return i
    return len(dist) - 1

def spec_step(p_of, q_of, ctx, gamma):
    """draft가 gamma개 제안 → target이 한 번에 검증. 출력 토큰 리스트를 반환."""
    drafts, qs, c = [], [], ctx
    for _ in range(gamma):
        qd = q_of(c); x = draw(qd); drafts.append(x); qs.append(qd); c = x
    out, c = [], ctx
    for x, qd in zip(drafts, qs):
        pd = p_of(c)                                   # 실제로는 target forward 한 번에 전부 나온다
        if R.random() < min(1.0, pd[x] / qd[x]):
            out.append(x); c = x
        else:
            res = [max(0.0, a - b) for a, b in zip(pd, qd)]
            z = sum(res)
            out.append(draw([r / z for r in res]))
            return out
    out.append(draw(p_of(c)))                          # 모두 수락: 보너스 토큰
    return out

# (1) 문맥 무관 p, q: step당 토큰 vs (1 - α^(γ+1)) / (1 - α)
p = np.array([0.42, 0.25, 0.15, 0.10, 0.05, 0.03])
q = 0.6 * p + 0.4 * np.array([0.05, 0.10, 0.10, 0.15, 0.25, 0.35])
alpha = np.minimum(p, q).sum()
for gamma in [1, 3, 6]:
    n_tok, n_step, counts = 0, 4000, np.zeros(len(p))
    for _ in range(n_step):
        out = spec_step(lambda c: p, lambda c: q, 0, gamma)
        n_tok += len(out); np.add.at(counts, out, 1)
    print(f"α={alpha:.3f} γ={gamma}: step당 토큰 측정 {n_tok / n_step:.3f} / 공식 {(1 - alpha**(gamma + 1)) / (1 - alpha):.3f}"
          f"   출력 빈도 최대 오차 {np.abs(counts / n_tok - p).max():.3f}")

# (2) 문맥 의존 bigram: 3토큰 시퀀스의 결합분포 비교
V = 3
P = np.array([[0.7, 0.2, 0.1], [0.1, 0.3, 0.6], [0.3, 0.3, 0.4]])    # target  p(x_t | x_{t-1})
Q = np.array([[0.3, 0.4, 0.3], [0.5, 0.25, 0.25], [0.2, 0.6, 0.2]])  # draft
exact = {(a, b, c): P[0, a] * P[a, b] * P[b, c] for a in range(V) for b in range(V) for c in range(V)}
draft_only = {k: Q[0, k[0]] * Q[k[0], k[1]] * Q[k[1], k[2]] for k in exact}

def spec_generate(n, gamma=3):
    seq = [0]
    while len(seq) - 1 < n:
        seq += spec_step(lambda c: P[c], lambda c: Q[c], seq[-1], gamma)
    return tuple(seq[1:n + 1])

M = 6000
emp = {}
for _ in range(M):
    s = spec_generate(3)
    emp[s] = emp.get(s, 0) + 1
tv_spec = 0.5 * sum(abs(emp.get(k, 0) / M - v) for k, v in exact.items())
tv_draft = 0.5 * sum(abs(draft_only[k] - v) for k, v in exact.items())
print(f"\n3토큰 시퀀스 27가지의 결합분포, total variation 거리:")
print(f"  speculative sampling vs target : {tv_spec:.3f}  (표본 {M}개의 잡음 수준)")
print(f"  draft를 그대로 받아들이면       : {tv_draft:.3f}")
 
확인 문제Check yourself

32층, KV head 8개, head 차원 128인 모델의 KV cache를 fp8(1바이트)로 저장한다. 문맥 32K 토큰 시퀀스 하나의 KV cache는?

토큰당 2⋅32⋅8⋅128⋅1=65,5362 \cdot 32 \cdot 8 \cdot 128 \cdot 1 = 65{,}536바이트 = 64 KiB. 32K = 32,768 토큰이면 64 KiB×32,768=2 GiB64\,\text{KiB} \times 32{,}768 = 2\,\text{GiB}. bf16이었다면 4 GiB, MHA(KV head 32)에 bf16이었다면 16 GiB다.

확인 문제Check yourself

speculative decoding에서 수락 확률 α = 0.8, draft 길이 γ = 4일 때 target forward 한 번당 기대 토큰 수는?

1−αγ+11−α=1−0.850.2=1−0.3280.2≈3.36\frac{1 - \alpha^{\gamma+1}}{1 - \alpha} = \frac{1 - 0.8^5}{0.2} = \frac{1 - 0.328}{0.2} \approx 3.36. 최대치는 γ+1=5\gamma + 1 = 5(모두 수락 + 보너스)다. draft 비용을 무시하면 decode가 약 3.4배 빨라진다.

정리

  • Prefill은 토큰 TT개를 한 번에 처리해 compute-bound, decode는 step당 토큰이 배치 크기만큼이라 memory-bandwidth-bound다. 기준은 산술 강도 ≈ 2n/b2n/b와 GPU의 ridge point.
  • KV cache = 2⋅nlayer⋅nkv_head⋅dhead⋅2 \cdot n_{\text{layer}} \cdot n_{\text{kv\_head}} \cdot d_{\text{head}} \cdot 바이트 / 토큰. 긴 문맥과 큰 배치에서는 가중치보다 커진다. GQA·MQA가 이를 head 공유로 줄인다.
  • Continuous batching은 배치를 늘 꽉 채우고, PagedAttention은 KV 메모리 낭비를 없애고 prefix를 공유한다.
  • 양자화는 무엇을 줄이느냐(가중치·활성값·KV)에 따라 decode, prefill, 긴 문맥 중 다른 병목을 푼다.
  • Speculative decoding: min⁡(1,p/q)\min(1, p/q)로 수락, 거절 시 (p−q)+(p-q)_+에서 재샘플. 출력은 정확히 pp를 따르고, forward당 기대 토큰은 (1−αγ+1)/(1−α)(1-\alpha^{\gamma+1})/(1-\alpha).
  • MoE는 연산은 활성 매개변수, 메모리는 총 매개변수에 비례한다.

더 읽을거리Further reading