The inference intro gave one approximation — a weight GEMM over tokens has arithmetic intensity — 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 FLOPs and moves bytes between HBM and the chip. With peak compute (FLOP/s) and bandwidth (byte/s), and the two overlapped perfectly,
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 . Everything below is a matter of computing and for an operation and asking which side of 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):
| GPU | BF16 dense | FP8 dense | HBM | BF16 | FP8 |
|---|---|---|---|---|---|
| H100 SXM | 989 TFLOP/s | 1,979 TFLOP/s | 3.35 TB/s | 295 | 591 |
| H200 SXM | 989 | 1,979 | 4.8 TB/s | 206 | 412 |
| B200 (per GPU of an 8-GPU system) | 2,250 | 4,500 | 8 TB/s | 281 | 562 |
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 but not ) — 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 weight to token vectors. It does FLOPs (one multiply and one add per MAC) and, with an ideal kernel, reads the weight once ( bytes per element) and the activations in and out ( bytes):
So the GEMM reaches the ridge at the critical batch . On an H100 in BF16 that is tokens. Three consequences fall out directly:
- FP8 W8A8 leaves unchanged. doubles and halves: . Below 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 by 4× to : 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 = prompt tokens. Any prompt longer than a few hundred tokens is compute-bound; prefill cost is FLOPs, per token plus attention.
Decode attention has a fixed intensity
Decode attention is not a weight GEMM. For one new token at context length , per layer, each of query heads does a dot product with keys and a weighted sum of values, both of dimension : . It reads keys and values for each of KV heads: . Hence
cancels, and so does the batch: each sequence reads its own KV, so stacking sequences multiplies and alike. MHA in bf16 sits at , GQA with at — two orders of magnitude below the ridge, at any batch. The only levers are architectural (raise ; share the cache across heads) or the KV byte width (KV quantisation).
MLA (see attention & KV) is the extreme case. In the absorbed form all heads of DeepSeek-V3 read the same latent of numbers per token; scores cost and the output FLOPs per head per position. Our own count:
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 routed experts and top- routing, a decode step of tokens sends on average tokens to each expert. For DeepSeek-V3 (, ; report review) that is . Under uniform routing the fraction of experts touched at all is , so at small each touched expert gets about one token and its GEMM runs at . To bring the expert GEMMs to the ridge you need
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.
추론 입문은 근사 하나(토큰 개에 대한 가중치 GEMM의 산술 강도 )와 하한 하나(decode step은 가중치를 한 번 읽는 시간보다 빠를 수 없다)를 줬다. 이 트랙은 그것을 도구로 바꾼다. 이 레슨에서는 한 step 안의 모든 연산 종류를 한 장의 그림에 놓고 어떤 손잡이가 어떤 점을 움직이는지 본 뒤, 트랙 나머지(attention kernel, KV cache, 스케줄링, 양자화)를 재는 어휘(MFU, MBU, TTFT, TPOT, goodput)를 고정한다.
Roofline 모델
kernel 하나가 FLOPs를 하고 HBM과 칩 사이에서 바이트를 옮긴다. 최대 연산 속도 (FLOP/s)와 대역폭 (byte/s)가 있고 둘이 완벽히 겹친다면
이다. 가 **산술 강도(arithmetic intensity)**다. 로그–로그 그림에서 도달 가능 속도는 기울기 1의 사선(memory-bound)이 평평한 지붕(compute-bound)과 ridge point 에서 만나는 모양이다. 아래 내용은 모두 어떤 연산의 와 를 세고 그것이 의 어느 쪽에 떨어지는지 묻는 일이다. 이 트랙에서 쓰는 dense 수치는 다음과 같다(제조사 사양표. 표에 인쇄된 tensor core 수치는 2:4 sparsity 기준이라 dense는 절반이다).
| GPU | BF16 dense | FP8 dense | HBM | BF16 | FP8 |
|---|---|---|---|---|---|
| H100 SXM | 989 TFLOP/s | 1,979 TFLOP/s | 3.35 TB/s | 295 | 591 |
| H200 SXM | 989 | 1,979 | 4.8 TB/s | 206 | 412 |
| B200 (8-GPU 시스템의 GPU 1장) | 2,250 | 4,500 | 8 TB/s | 281 | 562 |
두 가지를 볼 것. 세대가 바뀌어도 BF16 ridge는 수백 FLOP/byte에 머문다. 칩 수준에서는 대역폭이 행렬곱 처리량을 대략 따라왔다. 그리고 정밀도를 낮추면 ridge가 올라간다(FP8은 를 두 배로 하지만 는 그대로다). 동시에 바이트당 피연산자 수도 두 배가 되므로, 다음 절의 결론은 미묘하다.
가중치 GEMM의 산술 강도와 critical batch
선형층은 가중치를 토큰 벡터 개에 곱한다. FLOPs는 (MAC마다 곱셈 하나, 덧셈 하나)이고, 이상적인 kernel이라면 가중치를 한 번 읽고(원소당 바이트) 활성값을 읽고 쓴다( 바이트).
따라서 GEMM은 critical batch 에서 ridge에 닿는다. H100 BF16이면 토큰이다. 여기서 세 가지가 바로 나온다.
- FP8 W8A8은 를 바꾸지 않는다. 는 두 배, 는 절반이므로 . 아래에서는 바이트가 절반이 되어 2배, 위에서는 FP8 tensor core 덕에 2배다. 교차점은 그대로다.
- Weight-only INT4(W4A16)는 를 4배 줄여 로 만든다. 바이트는 4배 줄지만 계산은 (역양자화 후) 여전히 BF16 peak로 돈다. weight-only 양자화는 작은 배치 decode용 기법이고, 큰 배치에서는 역양자화 비용 말고 얻는 것이 없다.
- Prefill은 = 프롬프트 토큰 수다. 수백 토큰이 넘는 프롬프트는 모두 compute-bound이고, prefill 비용은 FLOPs, 즉 토큰당 에 attention을 더한 것이다.
Decode attention의 산술 강도는 고정되어 있다
decode attention은 가중치 GEMM이 아니다. 문맥 길이 에서 새 토큰 하나에 대해 층마다 query head 개가 각각 key 개와 내적하고 value 개를 가중합한다(차원 ). 이다. 읽는 것은 KV head 개 각각의 key와 value 개씩, 다. 따라서
이 약분되고 배치도 약분된다. 시퀀스마다 자기 KV를 읽으므로 개를 쌓으면 와 가 똑같이 늘어난다. bf16 MHA는 , 인 GQA는 로, 배치가 얼마든 ridge보다 두 자릿수 아래다. 움직일 수 있는 손잡이는 아키텍처(를 키우거나 head들이 cache를 공유)와 KV 바이트 폭 (KV 양자화)뿐이다.
MLA(attention과 KV 참고)는 극단적인 경우다. absorb 형태에서 DeepSeek-V3의 개 head는 모두 토큰당 개 숫자로 된 같은 latent를 읽는다. head·위치당 score에 , 출력에 FLOPs가 든다. 직접 세면
으로 ridge에 가깝다. MLA decode kernel이 계산 kernel처럼, GQA decode kernel이 memcpy처럼 행동하는 숨은 이유다.
MoE: 모든 expert가 작은 배치를 본다
routed expert 개와 top- routing이면 토큰 개짜리 decode step에서 expert 하나에 평균 개 토큰이 간다. DeepSeek-V3(, ; 보고서 리뷰)는 다. 균등 routing이라면 한 번이라도 선택되는 expert 비율이 이므로, 작은 에서는 선택된 expert마다 토큰이 하나 정도이고 그 GEMM은 로 돈다. expert GEMM을 ridge까지 올리려면
이 필요하다. GPU 한 장은 그만큼의 동시 시퀀스 KV를 담지 못한다. DeepSeek-V3의 decode 배치가 expert를 320-GPU expert-parallel 그룹(EP320, 보고서 §3.4.2)에 펼치는 이유가 정확히 이것이다. GPU마다 expert 몇 개만 두고, all-to-all이 그룹 전체 배치의 토큰을 거기로 모은다. 그 거래의 통신 쪽은 MoE 서빙 병렬화에서 다룬다.
Things to try:
- 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 ; the red dot does not move.
- Switch to INT4 W4A16: the GEMM dots jump right by ~4× and drops to ~75. Switch to FP8 W8A8: the ridge moves right as much as the dots do; stays.
- Pick DeepSeek-V3: the red dot (MLA) sits near the ridge, while the violet routed-expert dot stays at until B is in the hundreds and reaches the ridge only around B ≈ 10K.
- 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, sequences at context , KV bytes per token , attention FLOPs per query–key pair ):
The memory term has a part that is shared across the batch (weights) and a part that is not (KV). They are equal at . For a 70B GQA model ( B = 320 KiB) at = 8K that is sequences — far below . So long-context decode is memory-bound at every batch size: past each extra sequence brings its own bytes, and throughput saturates at 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 ( 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 . 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 () and reports the fraction met.
Throughput is tokens/s summed over requests; per user it is , for the system . 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 ; goodput cannot, because grows with it.
해 볼 것:
- 기본값(70B GQA, H100, BF16, B = 16): 파란 decode GEMM 점은 ridge보다 한참 왼쪽, 빨간 attention 점은 그보다 더 왼쪽이다. B를 512로 끌면 파란 점은 근처에서 ridge를 넘는다. 빨간 점은 움직이지 않는다.
- INT4 W4A16으로 바꾸면 GEMM 점이 약 4배 오른쪽으로 뛰고 가 75 정도로 떨어진다. FP8 W8A8로 바꾸면 ridge가 점과 같은 만큼 오른쪽으로 가서 는 그대로다.
- DeepSeek-V3를 고르면 빨간 점(MLA)은 ridge 근처에 있지만, 보라색 routed expert 점은 B가 수백이 될 때까지 에 머물다 B ≈ 10K 근처에서야 ridge에 닿는다.
- B = 64에서 L을 128K로 올리고 아래 수치를 보라. KV 읽기가 가중치 읽기를 넘어서고, GEMM들이 멀쩡해도 step 전체의 MFU 상한이 떨어진다.
decode step 전체
step 전체(모든 층, 문맥 인 시퀀스 개, 토큰당 KV 바이트 , query–key 쌍당 attention FLOPs )를 더하면
이다. 메모리 항에는 배치가 나눠 쓰는 부분(가중치)과 나눠 쓰지 못하는 부분(KV)이 있다. 둘은 에서 같아진다. 70B GQA 모델( B = 320 KiB)을 = 8K로 돌리면 개 시퀀스로, 보다 한참 작다. 즉 긴 문맥 decode는 어떤 배치에서도 memory-bound다. 를 넘으면 시퀀스 하나가 늘 때마다 자기 바이트를 들고 오므로, 처리량은 늘지 않고 초당 토큰에서 포화한다. KV 크기(GQA → MLA, KV 양자화, sparse attention)가 가중치 크기만큼 중요한 이유가 이 부등식 하나다.
지표: 무엇을 재고 서로 어떻게 연결되나
MFU(model FLOPs utilisation; PaLM이 널리 알렸고 학습에서 46.2%를 보고했다): 달성한 모델 FLOP/s를 peak로 나눈 값. 모델에 필요한 FLOPs(토큰당 와 attention)만 센다. 재계산은 세지 않는다. prefill과 큰 배치 decode에서 쓸모 있다.
MBU(model bandwidth utilisation; Databricks): 달성 대역폭 / peak 대역폭. 달성 대역폭은 다. 그들의 예: 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는 대신 토큰마다 마감 시각()을 두고 지킨 비율을 보고한다.
처리량은 요청들을 합한 토큰/초다. 사용자 한 명에게는 , 시스템에는 이다. Goodput(DistServe)은 요청의 목표 비율(예: 90%)이 TTFT SLO와 TPOT SLO를 함께 만족하는 상태로 배포가 감당하는 최대 요청률이다. 실제로 용량을 잡을 때 쓰는 숫자다. 단순 처리량은 를 키우면 언제든 살 수 있지만 goodput은 그렇지 않다. 도 같이 커지기 때문이다.
Things to try (the model assumes ideal tensor parallelism with no communication cost, so read the absolute numbers as upper bounds):
- 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.
- 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.
- 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.
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 and achieved TFLOP/s flattening near the tensor-core peak past the ridge.
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).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?
. FP8 doubles ( vs ) and halves , so stays . Weight-only INT4 is different: the math stays at BF16 peak ( unchanged) while drops 4×, so falls to .
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 KiB GB, so . Bytes per step go from GB to GB: grows ×1.7 while the batch grows ×2, so throughput gains only ×1.17. Decode attention never becomes compute-bound with GQA ().
Summary
- Attainable FLOP/s ; the ridge is a few hundred FLOP/byte for BF16 on current GPUs.
- A weight GEMM over tokens has ; the critical batch is ~300 on H100 for both BF16 and FP8 W8A8, ~75 for INT4 W4A16.
- Decode attention has regardless of batch and context: GQA-8 at 8, MLA (absorbed) near 240.
- MoE expert GEMMs see tokens; reaching the ridge needs (~10K for DeepSeek-V3), hence large expert-parallel decode groups.
- Past 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을 가정하므로 절대값은 상한으로 읽는다):
- 기본값(H100 8장의 70B, 문맥 8K, SLO 16 ms): 곡선은 처음엔 평평하다가(가중치 읽기가 지배) KV 읽기가 커지면서 위로 꺾인다. 모든 형식에서 배치를 정하는 것은 메모리가 아니라 SLO다. 큰 점이 곡선 끝보다 앞에 있다. TTFT 수치도 볼 것. INT4 W4A16의 TTFT는 BF16과 같다(prefill은 BF16 peak에서 compute-bound). TTFT를 절반으로 줄이는 것은 FP8 W8A8뿐이다.
- 문맥을 64K–128K로 끌면 INT4 곡선이 BF16 대비 이점을 대부분 잃는다. 이제 바이트가 가중치가 아니라 KV이기 때문이다. KV를 fp8로 바꾸면 이점이 돌아온다.
- SLO를 5 ms 근처로 조이면 BF16은 맞는 배치가 아예 없다. 배치 1조차 140 GB를 8 × 3.35 TB/s로 읽어야 하기 때문이다. 빠져나갈 길은 replica당 GPU를 늘리거나(총 대역폭 증가) 바이트를 줄이는 것뿐이다.
직접 계산하기
아래 블록은 표를 다시 계산하고, GEMM 산술 강도 공식을 직접 센 값과 비교하고, 정밀도별 critical batch, decode attention 산술 강도, MoE의 expert당 토큰 곡선, 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에서 잰다. 작은 에서는 달성 TB/s가 HBM peak 근처이고, ridge를 넘으면 달성 TFLOP/s가 tensor core peak 근처에서 평평해질 것이다.
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).H100에서 dense 모델을 BF16에서 FP8 W8A8(FP8 가중치·활성값, FP8 tensor core)로 바꾸면, 가중치 GEMM이 compute-bound가 되는 critical decode batch B*는 어떻게 되나?
다. FP8은 를 두 배로( 대 ), 를 절반으로 만들므로 는 에 머문다. weight-only INT4는 다르다. 계산은 BF16 peak 그대로( 불변)인데 가 4배 줄어 가 로 떨어진다.
70B GQA 모델(bf16, 토큰당 KV 320 KiB)이 H200 8장에서 32K 문맥으로 decode한다. 배치를 32에서 64로 두 배 늘리면 대략…
32K 문맥에서 시퀀스 하나의 KV는 KiB GB이므로 이다. step당 바이트가 GB에서 GB로 늘어난다. 배치는 2배인데 이 1.7배가 되므로 처리량은 1.17배에 그친다. GQA decode attention은 결코 compute-bound가 되지 않는다().
정리
- 도달 가능 FLOP/s . ridge 는 현재 GPU의 BF16에서 수백 FLOP/byte다.
- 토큰 개에 대한 가중치 GEMM은 . critical batch 는 H100에서 BF16과 FP8 W8A8 모두 ~300, INT4 W4A16은 ~75다.
- decode attention은 배치와 문맥에 상관없이 다. GQA-8은 8, MLA(absorb)는 240 근처.
- MoE expert GEMM은 개 토큰을 본다. ridge에 닿으려면 (DeepSeek-V3는 ~10K)가 필요하고, 그래서 decode에 큰 expert-parallel 그룹을 쓴다.
- 를 넘으면 KV 읽기가 지배하고, 긴 문맥 decode는 memory-bound에 머문다.
- decode는 MBU로, prefill은 MFU로 잰다. TTFT와 TBT 꼬리(또는 fluidity)를 보고하고, 용량은 처리량이 아니라 goodput으로 잡는다.
더 읽을거리Further reading
- Williams, Waterman, Patterson, Roofline: An Insightful Visual Performance Model for Multicore Architectures (CACM, 2009) — roofline 모델의 원전. 산술 강도와 ridge point라는 두 개념이 전부다.The original roofline paper. Arithmetic intensity and the ridge point are the whole idea.
- Austin et al., How to Scale Your Model — All About Transformer Inference (JAX scaling book) — prefill/decode, 배치, KV 메모리, 병렬화를 roofline 산수로 끝까지 밀고 가는 장. 이 트랙의 가장 좋은 짝.Pushes prefill/decode, batching, KV memory and parallelism all the way through with roofline arithmetic. The best companion to this track.
- Chen (kipply), Transformer Inference Arithmetic (2022) — FLOPs·바이트·KV·통신량을 손으로 세는 법.How to count FLOPs, bytes, KV and communication by hand.
- Pope et al., Efficiently Scaling Transformer Inference (MLSys 2023) — 지연–비용 Pareto와 분할 전략을 분석적으로 모델링한 고전.The classic analytical model of the latency–cost Pareto frontier and partitioning strategies.
- Databricks (MosaicML), LLM Inference Performance Engineering: Best Practices (2023) — MBU의 정의와 TTFT/TPOT 실측.The definition of MBU, with TTFT/TPOT measurements.
- Agrawal et al., Etalon: Holistic Performance Evaluation Framework for LLM Inference Systems (2024) — TTFT·TBT·TPOT의 정의와, 평균 지표가 생성 중의 멈춤을 숨기는 이유. fluidity-index.Definitions of TTFT, TBT and TPOT, why averaged metrics hide stalls during generation, and the fluidity-index.
- Zhong et al., DistServe: Disaggregating Prefill and Decoding for Goodput-optimized LLM Serving (OSDI 2024) — TTFT·TPOT SLO를 함께 만족하는 최대 요청률로서의 goodput.Goodput as the maximum request rate that meets both the TTFT and the TPOT SLO.
- NVIDIA H100 / H200 / DGX B200 / HGX product pages (spec tables) — 그림의 GPU 수치 출처. 표의 tensor 수치는 2:4 sparsity 기준이라 dense는 절반이다.Source of the figure's GPU numbers. The tensor numbers in the tables assume 2:4 sparsity, so dense is half.