Track VIII · Inference & Optimisation · 01/09

Roofline과 추론 지표The roofline and inference metrics

roofline 모델로 prefill·decode·attention·MoE expert GEMM이 각각 어디에 놓이는지 배치와 문맥 길이의 함수로 유도한다. critical batch, decode attention의 고정된 산술 강도, KV가 가중치 읽기를 넘어서는 지점을 계산하고, MFU·MBU·TTFT·TPOT·goodput을 정확히 정의한다.Use the roofline model to derive where prefill, decode, attention and MoE expert GEMMs land as functions of batch size and context length. Compute the critical batch, the fixed arithmetic intensity of decode attention and the point where KV reads overtake weight reads, and define MFU, MBU, TTFT, TPOT and goodput precisely.

45 분min inference · roofline · arithmetic intensity · MFU · MBU · TTFT · TPOT · goodput · MoE · MLA 먼저 볼 것:Before this: 추론 최적화Inference optimisation, Attention: query·key·valueAttention: query, key, value

The inference intro gave one approximation — a weight GEMM over nn tokens has arithmetic intensity ≈2n/b\approx 2n/b — and one bound — a decode step cannot be faster than reading the weights once. This track turns those into tools. In this lesson we place every kind of operation in a step on one chart, see which knob moves which point, and fix the vocabulary (MFU, MBU, TTFT, TPOT, goodput) that the rest of the track — attention kernels, KV cache, scheduling, quantisation — is measured in.

The roofline model

A kernel does WW FLOPs and moves QQ bytes between HBM and the chip. With peak compute π\pi (FLOP/s) and bandwidth β\beta (byte/s), and the two overlapped perfectly,

t  ≥  max⁡ ⁣(Wπ,  Qβ),attainable FLOP/s=min⁡(π,  β I),I=WQ.t \;\ge\; \max\!\Big(\frac{W}{\pi},\; \frac{Q}{\beta}\Big), \qquad \text{attainable FLOP/s} = \min(\pi,\; \beta\, I), \qquad I = \frac{W}{Q}.

II is the arithmetic intensity. On a log–log plot the attainable rate is a slanted line (slope 1, memory-bound) meeting a flat roof (compute-bound) at the ridge point I∗=π/βI^* = \pi/\beta. Everything below is a matter of computing WW and QQ for an operation and asking which side of I∗I^* it lands on. The dense numbers used throughout (vendor spec tables; the printed tensor-core figures are for 2:4 sparsity, so dense is half):

GPUBF16 denseFP8 denseHBMI∗I^* BF16I∗I^* FP8
H100 SXM989 TFLOP/s1,979 TFLOP/s3.35 TB/s295591
H200 SXM9891,9794.8 TB/s206412
B200 (per GPU of an 8-GPU system)2,2504,5008 TB/s281562

Two things to notice. Across generations the BF16 ridge stays at a few hundred FLOP/byte: bandwidth has roughly kept pace with matmul throughput at the chip level. And dropping precision raises the ridge (FP8 doubles π\pi but not β\beta) — the operand count per byte doubles too, which is why the next section’s conclusion is subtle.

Intensity of a weight GEMM, and the critical batch

A linear layer applies a K×NK \times N weight to mm token vectors. It does 2mKN2mKN FLOPs (one multiply and one add per MAC) and, with an ideal kernel, reads the weight once (bwb_w bytes per element) and the activations in and out (bab_a bytes):

IGEMM(m)=2mKNbwKN+ba m(K+N)  →  m ≪ K,N    2mbw.I_{\text{GEMM}}(m) = \frac{2mKN}{b_w KN + b_a\, m (K + N)} \;\xrightarrow{\;m \,\ll\, K,N\;}\; \frac{2m}{b_w}.

So the GEMM reaches the ridge at the critical batch m∗≈I∗bw/2m^* \approx I^* b_w / 2. On an H100 in BF16 that is 295⋅2/2≈300295 \cdot 2/2 \approx 300 tokens. Three consequences fall out directly:

  • FP8 W8A8 leaves m∗m^* unchanged. I∗I^* doubles and bwb_w halves: 591⋅1/2≈300591 \cdot 1/2 \approx 300. Below m∗m^* you get 2× from halving the bytes; above it, 2× from the FP8 tensor cores. The crossover does not move.
  • Weight-only INT4 (W4A16) cuts m∗m^* by 4× to ≈75\approx 75: bytes shrink 4× but the math still runs at BF16 peak (after dequantisation). Weight-only quantisation is a small-batch decode trick; at large batch it buys nothing but dequant overhead.
  • Prefill has mm = prompt tokens. Any prompt longer than a few hundred tokens is compute-bound; prefill cost is FLOPs, ≈2Nact\approx 2N_{\text{act}} per token plus attention.

Decode attention has a fixed intensity

Decode attention is not a weight GEMM. For one new token at context length LL, per layer, each of nhn_h query heads does a dot product with LL keys and a weighted sum of LL values, both of dimension dhd_h: W=4nhdhLW = 4 n_h d_h L. It reads LL keys and values for each of nkvn_{kv} KV heads: Q=2nkvdhL bkvQ = 2 n_{kv} d_h L\, b_{kv}. Hence

Iattndecode=4nhdhL2nkvdhL bkv=2gbkv,g=nhnkv.I_{\text{attn}}^{\text{decode}} = \frac{4 n_h d_h L}{2 n_{kv} d_h L\, b_{kv}} = \frac{2g}{b_{kv}}, \qquad g = \frac{n_h}{n_{kv}}.

LL cancels, and so does the batch: each sequence reads its own KV, so stacking BB sequences multiplies WW and QQ alike. MHA in bf16 sits at I=1I = 1, GQA with g=8g = 8 at I=8I = 8 — two orders of magnitude below the ridge, at any batch. The only levers are architectural (raise gg; share the cache across heads) or the KV byte width bkvb_{kv} (KV quantisation).

MLA (see attention & KV) is the extreme case. In the absorbed form all nh=128n_h = 128 heads of DeepSeek-V3 read the same latent of dc+dR=512+64d_c + d_R = 512 + 64 numbers per token; scores cost 2(dc+dR)2(d_c + d_R) and the output 2dc2 d_c FLOPs per head per position. Our own count:

IMLA=nh⋅2(2dc+dR)(dc+dR) bkv=128⋅2176576⋅2≈242(estimate, bf16 latent),I_{\text{MLA}} = \frac{n_h \cdot 2(2d_c + d_R)}{(d_c + d_R)\, b_{kv}} = \frac{128 \cdot 2176}{576 \cdot 2} \approx 242 \quad\text{(estimate, bf16 latent)},

within reach of the ridge. That is the hidden reason MLA decode kernels behave like compute kernels while GQA decode kernels behave like memcpy.

MoE: every expert sees a small batch

With EE routed experts and top-kk routing, a decode step of BB tokens sends on average Bk/EBk/E tokens to each expert. For DeepSeek-V3 (E=256E = 256, k=8k = 8; report review) that is B/32B/32. Under uniform routing the fraction of experts touched at all is 1−(1−k/E)B1 - (1 - k/E)^B, so at small BB each touched expert gets about one token and its GEMM runs at I≈2/bwI \approx 2/b_w. To bring the expert GEMMs to the ridge you need

BkE≈m∗  ⇒  B≈Ek m∗≈32×300≈104 tokens per step.\frac{Bk}{E} \approx m^* \;\Rightarrow\; B \approx \frac{E}{k}\, m^* \approx 32 \times 300 \approx 10^4 \text{ tokens per step}.

No single GPU holds that many concurrent sequences’ KV — which is exactly why DeepSeek-V3’s decode deployment spreads the experts over a 320-GPU expert-parallel group (EP320, report §3.4.2): every GPU holds a few experts, and the all-to-all gathers tokens from the whole group’s batch onto them. The communication side of that bargain is the subject of parallelism for MoE serving.

추론 입문은 근사 하나(토큰 nn개에 대한 가중치 GEMM의 산술 강도 ≈2n/b\approx 2n/b)와 하한 하나(decode step은 가중치를 한 번 읽는 시간보다 빠를 수 없다)를 줬다. 이 트랙은 그것을 도구로 바꾼다. 이 레슨에서는 한 step 안의 모든 연산 종류를 한 장의 그림에 놓고 어떤 손잡이가 어떤 점을 움직이는지 본 뒤, 트랙 나머지(attention kernel, KV cache, 스케줄링, 양자화)를 재는 어휘(MFU, MBU, TTFT, TPOT, goodput)를 고정한다.

Roofline 모델

kernel 하나가 WW FLOPs를 하고 HBM과 칩 사이에서 QQ 바이트를 옮긴다. 최대 연산 속도 π\pi(FLOP/s)와 대역폭 β\beta(byte/s)가 있고 둘이 완벽히 겹친다면

t  ≥  max⁡ ⁣(Wπ,  Qβ),도달 가능 FLOP/s=min⁡(π,  β I),I=WQt \;\ge\; \max\!\Big(\frac{W}{\pi},\; \frac{Q}{\beta}\Big), \qquad \text{도달 가능 FLOP/s} = \min(\pi,\; \beta\, I), \qquad I = \frac{W}{Q}

이다. II가 **산술 강도(arithmetic intensity)**다. 로그–로그 그림에서 도달 가능 속도는 기울기 1의 사선(memory-bound)이 평평한 지붕(compute-bound)과 ridge point I∗=π/βI^* = \pi/\beta에서 만나는 모양이다. 아래 내용은 모두 어떤 연산의 WW와 QQ를 세고 그것이 I∗I^*의 어느 쪽에 떨어지는지 묻는 일이다. 이 트랙에서 쓰는 dense 수치는 다음과 같다(제조사 사양표. 표에 인쇄된 tensor core 수치는 2:4 sparsity 기준이라 dense는 절반이다).

GPUBF16 denseFP8 denseHBMI∗I^* BF16I∗I^* FP8
H100 SXM989 TFLOP/s1,979 TFLOP/s3.35 TB/s295591
H200 SXM9891,9794.8 TB/s206412
B200 (8-GPU 시스템의 GPU 1장)2,2504,5008 TB/s281562

두 가지를 볼 것. 세대가 바뀌어도 BF16 ridge는 수백 FLOP/byte에 머문다. 칩 수준에서는 대역폭이 행렬곱 처리량을 대략 따라왔다. 그리고 정밀도를 낮추면 ridge가 올라간다(FP8은 π\pi를 두 배로 하지만 β\beta는 그대로다). 동시에 바이트당 피연산자 수도 두 배가 되므로, 다음 절의 결론은 미묘하다.

가중치 GEMM의 산술 강도와 critical batch

선형층은 K×NK \times N 가중치를 토큰 벡터 mm개에 곱한다. FLOPs는 2mKN2mKN(MAC마다 곱셈 하나, 덧셈 하나)이고, 이상적인 kernel이라면 가중치를 한 번 읽고(원소당 bwb_w 바이트) 활성값을 읽고 쓴다(bab_a 바이트).

IGEMM(m)=2mKNbwKN+ba m(K+N)  →  m ≪ K,N    2mbwI_{\text{GEMM}}(m) = \frac{2mKN}{b_w KN + b_a\, m (K + N)} \;\xrightarrow{\;m \,\ll\, K,N\;}\; \frac{2m}{b_w}

따라서 GEMM은 critical batch m∗≈I∗bw/2m^* \approx I^* b_w / 2에서 ridge에 닿는다. H100 BF16이면 295⋅2/2≈300295 \cdot 2/2 \approx 300토큰이다. 여기서 세 가지가 바로 나온다.

  • FP8 W8A8은 m∗m^*를 바꾸지 않는다. I∗I^*는 두 배, bwb_w는 절반이므로 591⋅1/2≈300591 \cdot 1/2 \approx 300. m∗m^* 아래에서는 바이트가 절반이 되어 2배, 위에서는 FP8 tensor core 덕에 2배다. 교차점은 그대로다.
  • Weight-only INT4(W4A16)는 m∗m^*를 4배 줄여 ≈75\approx 75로 만든다. 바이트는 4배 줄지만 계산은 (역양자화 후) 여전히 BF16 peak로 돈다. weight-only 양자화는 작은 배치 decode용 기법이고, 큰 배치에서는 역양자화 비용 말고 얻는 것이 없다.
  • Prefill은 mm = 프롬프트 토큰 수다. 수백 토큰이 넘는 프롬프트는 모두 compute-bound이고, prefill 비용은 FLOPs, 즉 토큰당 ≈2Nact\approx 2N_{\text{act}}에 attention을 더한 것이다.

Decode attention의 산술 강도는 고정되어 있다

decode attention은 가중치 GEMM이 아니다. 문맥 길이 LL에서 새 토큰 하나에 대해 층마다 query head nhn_h개가 각각 key LL개와 내적하고 value LL개를 가중합한다(차원 dhd_h). W=4nhdhLW = 4 n_h d_h L이다. 읽는 것은 KV head nkvn_{kv}개 각각의 key와 value LL개씩, Q=2nkvdhL bkvQ = 2 n_{kv} d_h L\, b_{kv}다. 따라서

Iattndecode=4nhdhL2nkvdhL bkv=2gbkv,g=nhnkvI_{\text{attn}}^{\text{decode}} = \frac{4 n_h d_h L}{2 n_{kv} d_h L\, b_{kv}} = \frac{2g}{b_{kv}}, \qquad g = \frac{n_h}{n_{kv}}

LL이 약분되고 배치도 약분된다. 시퀀스마다 자기 KV를 읽으므로 BB개를 쌓으면 WW와 QQ가 똑같이 늘어난다. bf16 MHA는 I=1I = 1, g=8g = 8인 GQA는 I=8I = 8로, 배치가 얼마든 ridge보다 두 자릿수 아래다. 움직일 수 있는 손잡이는 아키텍처(gg를 키우거나 head들이 cache를 공유)와 KV 바이트 폭 bkvb_{kv}(KV 양자화)뿐이다.

MLA(attention과 KV 참고)는 극단적인 경우다. absorb 형태에서 DeepSeek-V3의 nh=128n_h = 128개 head는 모두 토큰당 dc+dR=512+64d_c + d_R = 512 + 64개 숫자로 된 같은 latent를 읽는다. head·위치당 score에 2(dc+dR)2(d_c + d_R), 출력에 2dc2 d_c FLOPs가 든다. 직접 세면

IMLA=nh⋅2(2dc+dR)(dc+dR) bkv=128⋅2176576⋅2≈242(추정, bf16 latent)I_{\text{MLA}} = \frac{n_h \cdot 2(2d_c + d_R)}{(d_c + d_R)\, b_{kv}} = \frac{128 \cdot 2176}{576 \cdot 2} \approx 242 \quad\text{(추정, bf16 latent)}

으로 ridge에 가깝다. MLA decode kernel이 계산 kernel처럼, GQA decode kernel이 memcpy처럼 행동하는 숨은 이유다.

MoE: 모든 expert가 작은 배치를 본다

routed expert EE개와 top-kk routing이면 토큰 BB개짜리 decode step에서 expert 하나에 평균 Bk/EBk/E개 토큰이 간다. DeepSeek-V3(E=256E = 256, k=8k = 8; 보고서 리뷰)는 B/32B/32다. 균등 routing이라면 한 번이라도 선택되는 expert 비율이 1−(1−k/E)B1 - (1 - k/E)^B이므로, 작은 BB에서는 선택된 expert마다 토큰이 하나 정도이고 그 GEMM은 I≈2/bwI \approx 2/b_w로 돈다. expert GEMM을 ridge까지 올리려면

BkE≈m∗  ⇒  B≈Ek m∗≈32×300≈104 토큰/step\frac{Bk}{E} \approx m^* \;\Rightarrow\; B \approx \frac{E}{k}\, m^* \approx 32 \times 300 \approx 10^4 \text{ 토큰/step}

이 필요하다. GPU 한 장은 그만큼의 동시 시퀀스 KV를 담지 못한다. DeepSeek-V3의 decode 배치가 expert를 320-GPU expert-parallel 그룹(EP320, 보고서 §3.4.2)에 펼치는 이유가 정확히 이것이다. GPU마다 expert 몇 개만 두고, all-to-all이 그룹 전체 배치의 토큰을 거기로 모은다. 그 거래의 통신 쪽은 MoE 서빙 병렬화에서 다룬다.

Log–log roofline: attainable FLOP/s = min(peak, intensity × bandwidth). The knee is the ridge point peak/BW. Each dot is one kind of operation in a step. Drag the batch B: decode GEMMs slide right (the weight read is shared by B tokens) but decode attention does not move — every sequence reads its own KV. Pick the MoE model: routed-expert GEMMs see only ≈ B·k/E tokens each, so they stay memory-bound until B is in the thousands. Switch to INT4 W4A16 and the GEMM dots jump right (fewer bytes, same FLOPs); FP8 W8A8 moves both the dots and the ridge. 로그–로그 roofline: 도달 가능한 FLOP/s = min(peak, 산술 강도 × 대역폭). 꺾이는 점이 ridge point peak/BW다. 점 하나가 한 step 안의 연산 한 종류다. 배치 B를 끌면 decode GEMM은 오른쪽으로 간다(가중치 읽기를 B개 토큰이 나눠 쓴다). 그러나 decode attention은 움직이지 않는다. 시퀀스마다 자기 KV를 읽기 때문이다. MoE 모델을 고르면 routed expert GEMM은 expert당 ≈ B·k/E개 토큰만 받으므로 B가 수천이 될 때까지 memory-bound에 머문다. INT4 W4A16으로 바꾸면 GEMM 점이 오른쪽으로 뛰고(바이트는 줄고 FLOPs는 그대로), FP8 W8A8은 점과 ridge를 함께 옮긴다.

Things to try:

  1. Default (70B GQA, H100, BF16, B = 16): the blue decode-GEMM dot is far left of the ridge, the red attention dot further still. Drag B to 512: the blue dot crosses the ridge near B∗≈300B^* \approx 300; the red dot does not move.
  2. Switch to INT4 W4A16: the GEMM dots jump right by ~4× and B∗B^* drops to ~75. Switch to FP8 W8A8: the ridge moves right as much as the dots do; B∗B^* stays.
  3. Pick DeepSeek-V3: the red dot (MLA) sits near the ridge, while the violet routed-expert dot stays at I≈1I \approx 1 until B is in the hundreds and reaches the ridge only around B ≈ 10K.
  4. Set L to 128K at B = 64 and watch the readout: the KV read overtakes the weight read and the MFU ceiling of the whole step falls even though the GEMMs are fine.

A whole decode step

Summing over the step (all layers, BB sequences at context LL, KV bytes per token κ\kappa, attention FLOPs per query–key pair aa):

tstep(B)≈max⁡ ⁣(2BNact+BLaπ⏟compute,    Nbw+BLκβ⏟weights + KV).t_{\text{step}}(B) \approx \max\!\Big(\underbrace{\frac{2BN_{\text{act}} + BLa}{\pi}}_{\text{compute}},\;\; \underbrace{\frac{N b_w + BL\kappa}{\beta}}_{\text{weights + KV}}\Big).

The memory term has a part that is shared across the batch (weights) and a part that is not (KV). They are equal at Bkv=Nbw/(Lκ)B_{kv} = N b_w / (L\kappa). For a 70B GQA model (κ=2⋅80⋅8⋅128⋅2\kappa = 2 \cdot 80 \cdot 8 \cdot 128 \cdot 2 B = 320 KiB) at LL = 8K that is 140 GB/2.7 GB≈52140\,\text{GB} / 2.7\,\text{GB} \approx 52 sequences — far below B∗≈300B^* \approx 300. So long-context decode is memory-bound at every batch size: past BkvB_{kv} each extra sequence brings its own bytes, and throughput saturates at β/(Lκ)\beta / (L\kappa) tokens per second instead of growing. That one inequality is why KV size (GQA → MLA, KV quantisation, sparse attention) matters as much as weight size.

Metrics: what to measure and how they relate

MFU (model FLOPs utilisation; popularised by PaLM, which reported 46.2% for training): achieved model FLOP/s divided by peak. Count only the FLOPs the model needs (2Nact2N_{\text{act}} per token plus attention), not recomputation. Useful for prefill and large-batch decode.

MBU (model bandwidth utilisation; Databricks): achieved bandwidth over peak, with achieved bandwidth =(parameter bytes+KV bytes)/TPOT= (\text{parameter bytes} + \text{KV bytes}) / \text{TPOT}. Their worked example: a 7B model in 16-bit with TPOT 14 ms moves 14 GB in 14 ms = 1 TB/s, so MBU = 50% on a 2 TB/s part. In small-batch decode MFU is meaninglessly low (< 1%); MBU is the number to watch.

Latency, per request (definitions as in Etalon):

  • TTFT — arrival to first output token. Includes queueing and the whole prefill.
  • TBT — the gap between consecutive output tokens; one value per token.
  • TPOT — total decode time divided by the number of decode tokens, i.e. a per-request average of TBT.

Averages hide stalls: a single 10 s pause in a 1,000-token answer barely moves TPOT. Etalon’s fluidity-index instead sets a deadline for every token (Di=Dp+iDdD_i = D_p + i D_d) and reports the fraction met.

Throughput is tokens/s summed over requests; per user it is 1/TPOT1/\text{TPOT}, for the system B/tstepB/t_{\text{step}}. Goodput (DistServe) is the maximum request rate a deployment sustains while a target fraction (e.g. 90%) of requests meet both the TTFT and the TPOT SLO — the number you actually provision against. Raw throughput can always be bought by growing BB; goodput cannot, because tstept_{\text{step}} grows with it.

해 볼 것:

  1. 기본값(70B GQA, H100, BF16, B = 16): 파란 decode GEMM 점은 ridge보다 한참 왼쪽, 빨간 attention 점은 그보다 더 왼쪽이다. B를 512로 끌면 파란 점은 B∗≈300B^* \approx 300 근처에서 ridge를 넘는다. 빨간 점은 움직이지 않는다.
  2. INT4 W4A16으로 바꾸면 GEMM 점이 약 4배 오른쪽으로 뛰고 B∗B^*가 75 정도로 떨어진다. FP8 W8A8로 바꾸면 ridge가 점과 같은 만큼 오른쪽으로 가서 B∗B^*는 그대로다.
  3. DeepSeek-V3를 고르면 빨간 점(MLA)은 ridge 근처에 있지만, 보라색 routed expert 점은 B가 수백이 될 때까지 I≈1I \approx 1에 머물다 B ≈ 10K 근처에서야 ridge에 닿는다.
  4. B = 64에서 L을 128K로 올리고 아래 수치를 보라. KV 읽기가 가중치 읽기를 넘어서고, GEMM들이 멀쩡해도 step 전체의 MFU 상한이 떨어진다.

decode step 전체

step 전체(모든 층, 문맥 LL인 시퀀스 BB개, 토큰당 KV 바이트 κ\kappa, query–key 쌍당 attention FLOPs aa)를 더하면

tstep(B)≈max⁡ ⁣(2BNact+BLaπ⏟계산,    Nbw+BLκβ⏟가중치 + KV)t_{\text{step}}(B) \approx \max\!\Big(\underbrace{\frac{2BN_{\text{act}} + BLa}{\pi}}_{\text{계산}},\;\; \underbrace{\frac{N b_w + BL\kappa}{\beta}}_{\text{가중치 + KV}}\Big)

이다. 메모리 항에는 배치가 나눠 쓰는 부분(가중치)과 나눠 쓰지 못하는 부분(KV)이 있다. 둘은 Bkv=Nbw/(Lκ)B_{kv} = N b_w / (L\kappa)에서 같아진다. 70B GQA 모델(κ=2⋅80⋅8⋅128⋅2\kappa = 2 \cdot 80 \cdot 8 \cdot 128 \cdot 2 B = 320 KiB)을 LL = 8K로 돌리면 140 GB/2.7 GB≈52140\,\text{GB} / 2.7\,\text{GB} \approx 52개 시퀀스로, B∗≈300B^* \approx 300보다 한참 작다. 즉 긴 문맥 decode는 어떤 배치에서도 memory-bound다. BkvB_{kv}를 넘으면 시퀀스 하나가 늘 때마다 자기 바이트를 들고 오므로, 처리량은 늘지 않고 초당 β/(Lκ)\beta / (L\kappa) 토큰에서 포화한다. KV 크기(GQA → MLA, KV 양자화, sparse attention)가 가중치 크기만큼 중요한 이유가 이 부등식 하나다.

지표: 무엇을 재고 서로 어떻게 연결되나

MFU(model FLOPs utilisation; PaLM이 널리 알렸고 학습에서 46.2%를 보고했다): 달성한 모델 FLOP/s를 peak로 나눈 값. 모델에 필요한 FLOPs(토큰당 2Nact2N_{\text{act}}와 attention)만 센다. 재계산은 세지 않는다. prefill과 큰 배치 decode에서 쓸모 있다.

MBU(model bandwidth utilisation; Databricks): 달성 대역폭 / peak 대역폭. 달성 대역폭은 (매개변수 바이트+KV 바이트)/TPOT(\text{매개변수 바이트} + \text{KV 바이트}) / \text{TPOT}다. 그들의 예: 16비트 7B 모델이 TPOT 14 ms이면 14 ms에 14 GB를 옮기므로 1 TB/s, 2 TB/s 칩에서 MBU 50%다. 작은 배치 decode에서 MFU는 의미 없이 낮고(< 1%), 봐야 할 숫자는 MBU다.

지연, 요청 단위(정의는 Etalon을 따른다):

  • TTFT: 도착부터 첫 출력 토큰까지. 대기와 prefill 전체를 포함한다.
  • TBT: 연속한 출력 토큰 사이의 간격. 토큰마다 값이 하나다.
  • TPOT: 전체 decode 시간을 decode 토큰 수로 나눈 값. 즉 요청 단위의 TBT 평균이다.

평균은 멈춤을 숨긴다. 1,000토큰 답변 중 10초 멈춤 한 번은 TPOT를 거의 바꾸지 않는다. Etalon의 fluidity-index는 대신 토큰마다 마감 시각(Di=Dp+iDdD_i = D_p + i D_d)을 두고 지킨 비율을 보고한다.

처리량은 요청들을 합한 토큰/초다. 사용자 한 명에게는 1/TPOT1/\text{TPOT}, 시스템에는 B/tstepB/t_{\text{step}}이다. Goodput(DistServe)은 요청의 목표 비율(예: 90%)이 TTFT SLO와 TPOT SLO를 함께 만족하는 상태로 배포가 감당하는 최대 요청률이다. 실제로 용량을 잡을 때 쓰는 숫자다. 단순 처리량은 BB를 키우면 언제든 살 수 있지만 goodput은 그렇지 않다. tstept_{\text{step}}도 같이 커지기 때문이다.

Each curve sweeps the decode batch B (dots at powers of two) for one weight format: x = tokens/s per GPU, y = time per output token. The curve ends where the KV cache no longer fits. The big dot is the highest-throughput batch that still meets the TPOT SLO (dashed). Lengthen the context: the curves bend upward early (KV reads dominate) and end sooner (memory). Tighten the SLO: the best point slides down-left — latency is bought with throughput. 곡선 하나가 한 가중치 형식에서 decode 배치 B를 훑는다(점은 2의 거듭제곱). x = GPU당 토큰/초, y = 출력 토큰당 시간. KV cache가 더 이상 들어가지 않는 곳에서 곡선이 끝난다. 큰 점은 TPOT SLO(점선)를 지키는 가장 처리량 높은 배치다. 문맥을 늘리면 곡선이 일찍 위로 꺾이고(KV 읽기가 지배) 일찍 끝난다(메모리). SLO를 조이면 최적점이 왼쪽 아래로 미끄러진다. 지연을 처리량으로 사는 셈이다.

Things to try (the model assumes ideal tensor parallelism with no communication cost, so read the absolute numbers as upper bounds):

  1. Default (70B on 8× H100, 8K context, SLO 16 ms): each curve is flat at first (the weight read dominates) and bends up as KV reads take over. For every format the SLO, not memory, sets the batch: the big dot sits before the curve’s end. Note the TTFT readout: INT4 W4A16 has the same TTFT as BF16 (prefill is compute-bound at BF16 peak); only FP8 W8A8 halves it.
  2. Drag the context to 64K–128K: the INT4 curve loses most of its advantage over BF16, because the bytes are now KV, not weights. Switch KV to fp8 and it comes back.
  3. Tighten the SLO to ~5 ms: BF16 finds no batch at all, because even batch 1 must read 140 GB over 8 × 3.35 TB/s. The only ways out are more GPUs per replica (more aggregate bandwidth) or fewer bytes.

Computing it yourself

The block below recomputes the table, checks the GEMM-intensity formula against a direct count, finds the critical batch per precision recipe, the decode-attention intensities, the MoE token-per-expert curve, and the MBU example.

NumPy Roofline arithmetic: ridge, critical batch, attention and MoE intensity, MBU
import numpy as np

# dense peak FLOP/s and HBM bandwidth (vendor sheets, sparse numbers halved)
gpus = {"H100 SXM": (989e12, 1979e12, 3.35e12),
        "H200 SXM": (989e12, 1979e12, 4.8e12),
        "B200":     (2250e12, 4500e12, 8.0e12)}
print("ridge point (FLOP/byte)    BF16    FP8")
for name, (bf16, fp8, bw) in gpus.items():
    print(f"  {name:<10}            {bf16 / bw:6.0f} {fp8 / bw:6.0f}")

def gemm_intensity(m, K, N, bw, ba):
    """[m x K] @ [K x N]: 2mKN FLOPs; weights read once (bw bytes each), activations in + out (ba bytes)."""
    return 2 * m * K * N / (bw * K * N + ba * m * (K + N))

# check the closed form against a direct count for one shape
m, K, N = 16, 8192, 8192
flops = (m * N) * (2 * K)                          # one length-K dot product (K mul + K add) per output
bytes_ = 2 * (K * N) + 2 * (m * K) + 2 * (m * N)
print(f"\nGEMM m={m}: counted I = {flops / bytes_:.2f}, formula = {gemm_intensity(m, K, N, 2, 2):.2f}, 2m/b = {2 * m / 2:.0f}")

# critical decode batch B*: the m at which a weight GEMM reaches the ridge (H100)
bf16, fp8, bw = gpus["H100 SXM"]
recipes = {"BF16 (W16A16)": (2, 2, bf16), "FP8 (W8A8)": (1, 1, fp8), "INT4 weight-only (W4A16)": (0.5, 2, bf16)}
print("\nH100 critical batch B* (d = 8192 square GEMM):")
for name, (bw_, ba_, peak) in recipes.items():
    Bs = 1
    while gemm_intensity(Bs, 8192, 8192, bw_, ba_) < peak / bw:
        Bs += 1
    print(f"  {name:<26} B* = {Bs:4d}   (approx ridge*b_w/2 = {peak / bw * bw_ / 2:.0f})")

# decode attention: FLOPs and bytes both scale with context, so intensity is a constant of the architecture
def attn_intensity(n_h, n_kv, d_h, b_kv):
    return (4 * n_h * d_h) / (2 * n_kv * d_h * b_kv)
print("\ndecode attention intensity (bf16 KV):")
print(f"  MHA (g=1)          {attn_intensity(64, 64, 128, 2):6.1f}")
print(f"  GQA 64/8 (g=8)     {attn_intensity(64, 8, 128, 2):6.1f}")
dc, dR, nh = 512, 64, 128                          # DeepSeek-V3 MLA, absorbed: all heads read one latent
print(f"  MLA absorbed       {nh * 2 * (2 * dc + dR) / ((dc + dR) * 2):6.1f}")

# MoE: tokens reaching each routed expert per decode step
E, k = 256, 8
print("\nMoE (256 routed experts, top-8), uniform routing:")
for B in [1, 64, 1024, 8192, 32768]:
    touched = 1 - (1 - k / E) ** B
    m_e = B * k / (E * touched)
    print(f"  B={B:6d}: experts touched {touched * 100:5.1f}%  tokens/expert {m_e:7.1f}  I={gemm_intensity(m_e, 7168, 2048, 2, 2):6.1f}")

# MBU and MFU from a measurement (Databricks example: 7B, 16-bit, TPOT 14 ms, 2 TB/s peak)
N, b, tpot, peak_bw = 7e9, 2, 14e-3, 2e12
mbu = (N * b) / tpot / peak_bw
print(f"\nMBU = {(N * b) / tpot / 1e12:.2f} TB/s / {peak_bw / 1e12:.0f} TB/s = {mbu:.0%}")
B, peak_flops = 1, 312e12                          # an A100-class BF16 peak, to match the 2 TB/s example
print(f"MFU at batch {B} = {2 * N * B / tpot / peak_flops:.2%}  (decode at small batch: MBU is the metric that matters)")
 

The PyTorch microbenchmark below measures the same curve on a real GPU. Expect achieved TB/s near the HBM peak at small mm and achieved TFLOP/s flattening near the tensor-core peak past the ridge.

PyTorch PyTorch: measure a GEMM's roofline on your GPU 로컬에서 실행run locally (pip install torch)
import torch

def bench(m, k=8192, n=8192, dtype=torch.bfloat16, iters=50):
    """Time an [m x k] @ [k x n] GEMM; report achieved TFLOP/s and TB/s (weights are 128 MiB > L2, so they come from HBM)."""
    a = torch.randn(m, k, device="cuda", dtype=dtype)
    w = torch.randn(k, n, device="cuda", dtype=dtype)
    for _ in range(5):
        a @ w                                            # warm-up (cuBLAS heuristics, clocks)
    start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    torch.cuda.synchronize()
    start.record()
    for _ in range(iters):
        a @ w
    end.record()
    torch.cuda.synchronize()
    t = start.elapsed_time(end) / 1e3 / iters           # seconds per GEMM
    flops = 2 * m * k * n
    nbytes = a.element_size() * (k * n + m * k + m * n)
    return flops / t / 1e12, nbytes / t / 1e12

for m in [1, 8, 32, 128, 256, 512, 2048, 8192]:
    tf, tb = bench(m)
    print(f"m={m:5d}  {tf:7.1f} TFLOP/s  {tb:5.2f} TB/s")
# Expect TB/s near the HBM peak (and TFLOP/s growing ~linearly in m) for small m,
# then TFLOP/s flattening near the tensor-core peak once m passes the ridge (~300 on H100).
 
확인 문제Check yourself

On an H100, moving a dense model from BF16 to FP8 W8A8 (FP8 weights and activations, FP8 tensor cores) changes the critical decode batch B* at which weight GEMMs become compute-bound how?

m∗≈I∗bw/2m^* \approx I^* b_w / 2. FP8 doubles I∗=π/βI^* = \pi/\beta (591591 vs 295295) and halves bwb_w, so m∗m^* stays ≈300\approx 300. Weight-only INT4 is different: the math stays at BF16 peak (I∗I^* unchanged) while bwb_w drops 4×, so m∗m^* falls to ≈75\approx 75.

확인 문제Check yourself

A 70B GQA model (bf16, 320 KiB of KV per token) decodes at 32K context on 8 H200s. Doubling the batch from 32 to 64 roughly ...

At 32K context each sequence’s KV is 32768⋅32032768 \cdot 320 KiB ≈10.7\approx 10.7 GB, so Bkv=140/10.7≈13B_{kv} = 140/10.7 \approx 13. Bytes per step go from 140+32⋅10.7≈483140 + 32 \cdot 10.7 \approx 483 GB to 140+64⋅10.7≈826140 + 64 \cdot 10.7 \approx 826 GB: tstept_{\text{step}} grows ×1.7 while the batch grows ×2, so throughput gains only ×1.17. Decode attention never becomes compute-bound with GQA (I=8I = 8).

Summary

  • Attainable FLOP/s =min⁡(π,βI)= \min(\pi, \beta I); the ridge I∗=π/βI^* = \pi/\beta is a few hundred FLOP/byte for BF16 on current GPUs.
  • A weight GEMM over mm tokens has I≈2m/bwI \approx 2m/b_w; the critical batch m∗≈I∗bw/2m^* \approx I^* b_w/2 is ~300 on H100 for both BF16 and FP8 W8A8, ~75 for INT4 W4A16.
  • Decode attention has I=2g/bkvI = 2g/b_{kv} regardless of batch and context: GQA-8 at 8, MLA (absorbed) near 240.
  • MoE expert GEMMs see Bk/EBk/E tokens; reaching the ridge needs B≈(E/k) m∗B \approx (E/k)\,m^* (~10K for DeepSeek-V3), hence large expert-parallel decode groups.
  • Past Bkv=Nbw/(Lκ)B_{kv} = Nb_w/(L\kappa) the KV read dominates and long-context decode stays memory-bound.
  • Measure decode with MBU, prefill with MFU; report TTFT, TBT tails (or fluidity), and provision on goodput, not throughput.

해 볼 것(이 모델은 통신 비용 없는 이상적 tensor parallelism을 가정하므로 절대값은 상한으로 읽는다):

  1. 기본값(H100 8장의 70B, 문맥 8K, SLO 16 ms): 곡선은 처음엔 평평하다가(가중치 읽기가 지배) KV 읽기가 커지면서 위로 꺾인다. 모든 형식에서 배치를 정하는 것은 메모리가 아니라 SLO다. 큰 점이 곡선 끝보다 앞에 있다. TTFT 수치도 볼 것. INT4 W4A16의 TTFT는 BF16과 같다(prefill은 BF16 peak에서 compute-bound). TTFT를 절반으로 줄이는 것은 FP8 W8A8뿐이다.
  2. 문맥을 64K–128K로 끌면 INT4 곡선이 BF16 대비 이점을 대부분 잃는다. 이제 바이트가 가중치가 아니라 KV이기 때문이다. KV를 fp8로 바꾸면 이점이 돌아온다.
  3. SLO를 5 ms 근처로 조이면 BF16은 맞는 배치가 아예 없다. 배치 1조차 140 GB를 8 × 3.35 TB/s로 읽어야 하기 때문이다. 빠져나갈 길은 replica당 GPU를 늘리거나(총 대역폭 증가) 바이트를 줄이는 것뿐이다.

직접 계산하기

아래 블록은 표를 다시 계산하고, GEMM 산술 강도 공식을 직접 센 값과 비교하고, 정밀도별 critical batch, decode attention 산술 강도, MoE의 expert당 토큰 곡선, MBU 예제를 구한다.

NumPy Roofline 산수: ridge, critical batch, attention·MoE 산술 강도, MBU
import numpy as np

# dense peak FLOP/s and HBM bandwidth (vendor sheets, sparse numbers halved)
gpus = {"H100 SXM": (989e12, 1979e12, 3.35e12),
        "H200 SXM": (989e12, 1979e12, 4.8e12),
        "B200":     (2250e12, 4500e12, 8.0e12)}
print("ridge point (FLOP/byte)    BF16    FP8")
for name, (bf16, fp8, bw) in gpus.items():
    print(f"  {name:<10}            {bf16 / bw:6.0f} {fp8 / bw:6.0f}")

def gemm_intensity(m, K, N, bw, ba):
    """[m x K] @ [K x N]: 2mKN FLOPs; weights read once (bw bytes each), activations in + out (ba bytes)."""
    return 2 * m * K * N / (bw * K * N + ba * m * (K + N))

# check the closed form against a direct count for one shape
m, K, N = 16, 8192, 8192
flops = (m * N) * (2 * K)                          # one length-K dot product (K mul + K add) per output
bytes_ = 2 * (K * N) + 2 * (m * K) + 2 * (m * N)
print(f"\nGEMM m={m}: counted I = {flops / bytes_:.2f}, formula = {gemm_intensity(m, K, N, 2, 2):.2f}, 2m/b = {2 * m / 2:.0f}")

# critical decode batch B*: the m at which a weight GEMM reaches the ridge (H100)
bf16, fp8, bw = gpus["H100 SXM"]
recipes = {"BF16 (W16A16)": (2, 2, bf16), "FP8 (W8A8)": (1, 1, fp8), "INT4 weight-only (W4A16)": (0.5, 2, bf16)}
print("\nH100 critical batch B* (d = 8192 square GEMM):")
for name, (bw_, ba_, peak) in recipes.items():
    Bs = 1
    while gemm_intensity(Bs, 8192, 8192, bw_, ba_) < peak / bw:
        Bs += 1
    print(f"  {name:<26} B* = {Bs:4d}   (approx ridge*b_w/2 = {peak / bw * bw_ / 2:.0f})")

# decode attention: FLOPs and bytes both scale with context, so intensity is a constant of the architecture
def attn_intensity(n_h, n_kv, d_h, b_kv):
    return (4 * n_h * d_h) / (2 * n_kv * d_h * b_kv)
print("\ndecode attention intensity (bf16 KV):")
print(f"  MHA (g=1)          {attn_intensity(64, 64, 128, 2):6.1f}")
print(f"  GQA 64/8 (g=8)     {attn_intensity(64, 8, 128, 2):6.1f}")
dc, dR, nh = 512, 64, 128                          # DeepSeek-V3 MLA, absorbed: all heads read one latent
print(f"  MLA absorbed       {nh * 2 * (2 * dc + dR) / ((dc + dR) * 2):6.1f}")

# MoE: tokens reaching each routed expert per decode step
E, k = 256, 8
print("\nMoE (256 routed experts, top-8), uniform routing:")
for B in [1, 64, 1024, 8192, 32768]:
    touched = 1 - (1 - k / E) ** B
    m_e = B * k / (E * touched)
    print(f"  B={B:6d}: experts touched {touched * 100:5.1f}%  tokens/expert {m_e:7.1f}  I={gemm_intensity(m_e, 7168, 2048, 2, 2):6.1f}")

# MBU and MFU from a measurement (Databricks example: 7B, 16-bit, TPOT 14 ms, 2 TB/s peak)
N, b, tpot, peak_bw = 7e9, 2, 14e-3, 2e12
mbu = (N * b) / tpot / peak_bw
print(f"\nMBU = {(N * b) / tpot / 1e12:.2f} TB/s / {peak_bw / 1e12:.0f} TB/s = {mbu:.0%}")
B, peak_flops = 1, 312e12                          # an A100-class BF16 peak, to match the 2 TB/s example
print(f"MFU at batch {B} = {2 * N * B / tpot / peak_flops:.2%}  (decode at small batch: MBU is the metric that matters)")
 

아래 PyTorch microbenchmark는 같은 곡선을 실제 GPU에서 잰다. 작은 mm에서는 달성 TB/s가 HBM peak 근처이고, ridge를 넘으면 달성 TFLOP/s가 tensor core peak 근처에서 평평해질 것이다.

PyTorch PyTorch: 내 GPU에서 GEMM의 roofline 재기 로컬에서 실행run locally (pip install torch)
import torch

def bench(m, k=8192, n=8192, dtype=torch.bfloat16, iters=50):
    """Time an [m x k] @ [k x n] GEMM; report achieved TFLOP/s and TB/s (weights are 128 MiB > L2, so they come from HBM)."""
    a = torch.randn(m, k, device="cuda", dtype=dtype)
    w = torch.randn(k, n, device="cuda", dtype=dtype)
    for _ in range(5):
        a @ w                                            # warm-up (cuBLAS heuristics, clocks)
    start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    torch.cuda.synchronize()
    start.record()
    for _ in range(iters):
        a @ w
    end.record()
    torch.cuda.synchronize()
    t = start.elapsed_time(end) / 1e3 / iters           # seconds per GEMM
    flops = 2 * m * k * n
    nbytes = a.element_size() * (k * n + m * k + m * n)
    return flops / t / 1e12, nbytes / t / 1e12

for m in [1, 8, 32, 128, 256, 512, 2048, 8192]:
    tf, tb = bench(m)
    print(f"m={m:5d}  {tf:7.1f} TFLOP/s  {tb:5.2f} TB/s")
# Expect TB/s near the HBM peak (and TFLOP/s growing ~linearly in m) for small m,
# then TFLOP/s flattening near the tensor-core peak once m passes the ridge (~300 on H100).
 
확인 문제Check yourself

H100에서 dense 모델을 BF16에서 FP8 W8A8(FP8 가중치·활성값, FP8 tensor core)로 바꾸면, 가중치 GEMM이 compute-bound가 되는 critical decode batch B*는 어떻게 되나?

m∗≈I∗bw/2m^* \approx I^* b_w / 2다. FP8은 I∗=π/βI^* = \pi/\beta를 두 배로(591591 대 295295), bwb_w를 절반으로 만들므로 m∗m^*는 ≈300\approx 300에 머문다. weight-only INT4는 다르다. 계산은 BF16 peak 그대로(I∗I^* 불변)인데 bwb_w가 4배 줄어 m∗m^*가 ≈75\approx 75로 떨어진다.

확인 문제Check yourself

70B GQA 모델(bf16, 토큰당 KV 320 KiB)이 H200 8장에서 32K 문맥으로 decode한다. 배치를 32에서 64로 두 배 늘리면 대략…

32K 문맥에서 시퀀스 하나의 KV는 32768⋅32032768 \cdot 320 KiB ≈10.7\approx 10.7 GB이므로 Bkv=140/10.7≈13B_{kv} = 140/10.7 \approx 13이다. step당 바이트가 140+32⋅10.7≈483140 + 32 \cdot 10.7 \approx 483 GB에서 140+64⋅10.7≈826140 + 64 \cdot 10.7 \approx 826 GB로 늘어난다. 배치는 2배인데 tstept_{\text{step}}이 1.7배가 되므로 처리량은 1.17배에 그친다. GQA decode attention은 결코 compute-bound가 되지 않는다(I=8I = 8).

정리

  • 도달 가능 FLOP/s =min⁡(π,βI)= \min(\pi, \beta I). ridge I∗=π/βI^* = \pi/\beta는 현재 GPU의 BF16에서 수백 FLOP/byte다.
  • 토큰 mm개에 대한 가중치 GEMM은 I≈2m/bwI \approx 2m/b_w. critical batch m∗≈I∗bw/2m^* \approx I^* b_w/2는 H100에서 BF16과 FP8 W8A8 모두 ~300, INT4 W4A16은 ~75다.
  • decode attention은 배치와 문맥에 상관없이 I=2g/bkvI = 2g/b_{kv}다. GQA-8은 8, MLA(absorb)는 240 근처.
  • MoE expert GEMM은 Bk/EBk/E개 토큰을 본다. ridge에 닿으려면 B≈(E/k) m∗B \approx (E/k)\,m^*(DeepSeek-V3는 ~10K)가 필요하고, 그래서 decode에 큰 expert-parallel 그룹을 쓴다.
  • Bkv=Nbw/(Lκ)B_{kv} = Nb_w/(L\kappa)를 넘으면 KV 읽기가 지배하고, 긴 문맥 decode는 memory-bound에 머문다.
  • decode는 MBU로, prefill은 MFU로 잰다. TTFT와 TBT 꼬리(또는 fluidity)를 보고하고, 용량은 처리량이 아니라 goodput으로 잡는다.

더 읽을거리Further reading