Track VIII Inference & Optimisation

추론과 추론 최적화Inference & Optimisation

roofline부터 FlashAttention, KV cache 관리, 배칭·PD 분리, 양자화, speculative decoding, MoE 서빙, RL rollout용 추론까지.From the roofline to FlashAttention, KV-cache management, batching and prefill/decode disaggregation, quantisation, speculative decoding, MoE serving and inference for RL rollouts.

9개 레슨9 lessons약 7.3시간~7.3 h 진행Progress 0 / 9
  1. 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.

    inference · roofline · arithmetic intensity · MFU · MBU · TTFT · TPOT · goodput · MoE · MLA
    45 분min
  2. Attention kernelAttention kernels

    online softmax를 유도하고 그 결합 연산 하나로 FlashAttention의 tiling, 역전파 재계산, Flash-Decoding의 split-KV, fused linear cross-entropy를 모두 설명한다. IO 복잡도를 세고, FA2·FA3·FA4가 각각 어떤 하드웨어 병목(비행렬곱 FLOPs, 비동기성, 지수함수 처리량) 때문에 바뀌었는지 사이클 단위로 계산한다.Derive online softmax and use its single merge operation to explain FlashAttention's tiling and backward recomputation, Flash-Decoding's split-KV and fused linear cross-entropy. Count the IO complexity, and work out cycle by cycle which hardware bottleneck (non-matmul FLOPs, asynchrony, exponential throughput) drove FA2, FA3 and FA4.

    attention · FlashAttention · online softmax · IO complexity · Flash-Decoding · split-KV · Hopper · Blackwell · paged attention · fused cross-entropy
    50 분min
  3. KV cache 관리KV-cache management

    KV cache를 메모리 관리 문제로 다룬다. paging이 예약·내부 단편화를 어떻게 없애는지, hash chain과 radix tree prefix cache가 GRPO 그룹과 multi-turn agent의 prefill을 얼마나 줄이는지 시뮬레이션하고, 공유 KV 저장소로의 offload, KV 양자화(KIVI), 축출(StreamingLLM, H2O)을 계산과 코드로 비교한다.Treat the KV cache as a memory-management problem. Simulate how paging removes reservation and internal fragmentation and how hash-chain and radix-tree prefix caches cut prefill for GRPO groups and multi-turn agents; compare offload to a shared KV store, KV quantisation (KIVI) and eviction (StreamingLLM, H2O) with arithmetic and code.

    KV cache · PagedAttention · prefix caching · RadixAttention · Mooncake · offload · KV quantization · KIVI · StreamingLLM · H2O · agents
    45 분min
  4. 배칭과 스케줄링Batching and scheduling

    스케줄러가 매 iteration 무엇을 step에 넣는지가 TTFT·TBT·처리량을 어떻게 맞바꾸는지 이산 사건 시뮬레이터로 본다. 정적 배칭, continuous batching(Orca), chunked prefill(Sarathi-Serve), prefill/decode 분리(DistServe, Splitwise, Mooncake)를 같은 요청 trace와 같은 GPU 수로 비교하고, TBT SLO에서 token budget을, 작업 부하에서 P:D 비율을 유도한다.Use a discrete-event simulator to see how what the scheduler puts into each iteration trades TTFT, TBT and throughput. Compare static batching, continuous batching (Orca), chunked prefill (Sarathi-Serve) and prefill/decode disaggregation (DistServe, Splitwise, Mooncake) on the same request trace and the same number of GPUs, and derive the token budget from a TBT SLO and the P:D ratio from the workload.

    serving · continuous batching · chunked prefill · disaggregation · goodput · SLO · TTFT · TBT · scheduling
    45 분min
  5. 양자화Quantisation

    균일 양자화의 오차가 outlier에 왜 그렇게 약한지 유도하고, 그에 대한 세 가지 답을 구현해 비교한다. 오차 보정(GPTQ), 활성값을 고려한 scaling(AWQ), 활성값 outlier의 이전(SmoothQuant). FP8 E4M3/E5M2, MXFP4, NVFP4의 block scaling을 비트당 오차로 비교하고, RL rollout을 FP8이나 4비트로 돌릴 때(FP8-RL, QAT) 학습–추론 불일치가 어떻게 생기고 처리되는지 본다.Derive why uniform quantisation error is so sensitive to outliers, then implement and compare three answers - error compensation (GPTQ), activation-aware scaling (AWQ) and migrating activation outliers (SmoothQuant). Compare the block scaling of FP8 E4M3/E5M2, MXFP4 and NVFP4 by error per bit, and see how running RL rollouts in FP8 or 4 bits (FP8-RL, QAT) creates and handles train–inference mismatch.

    quantization · GPTQ · AWQ · SmoothQuant · FP8 · MXFP4 · NVFP4 · QAT · low-precision RL · rollout
    50 분min
  6. Speculative decoding 심화Speculative decoding in depth

    수락 길이를 위치별 조건부 수락률로 일반화하고, 트리 draft의 기대 길이가 노드 값의 합이며 최적 트리가 상위 m개 노드라는 것을 유도한다. 트리 검증이 target 분포를 정확히 보존하는 재귀적 rejection을 증명하고 NumPy로 정확히 확인한 뒤, Medusa·EAGLE-1/2/3·MTP drafter를 비교하고 배치가 커지면 왜 speculation이 손해가 되는지 roofline으로 계산한다.Generalise acceptance length to per-position conditional acceptance rates, derive that a draft tree's expected length is the sum of its node values and that the best tree is the top-m nodes, prove that recursive rejection on a tree preserves the target distribution exactly (and check it exactly in NumPy), compare Medusa, EAGLE-1/2/3 and MTP drafters, and compute with a roofline why speculation turns into a loss as the batch grows.

    speculative decoding · EAGLE · Medusa · MTP · tree attention · rejection sampling · batching · roofline
    50 분min
  7. 서빙을 위한 병렬화와 MoEParallelism for serving, and MoE

    TP·PP·DP·EP가 토큰 하나당 무엇을 얼마나 주고받는지 바이트 단위로 유도하고, MLA가 왜 attention을 DP로 돌리게 만드는지, 왜 큰 MoE는 수백 GPU에 걸친 wide EP로 서빙되는지(GPU당 메모리, expert당 토큰, 산술 강도)를 계산한다. expert 부하 불균형을 샘플링 잡음과 인기 편중으로 나눠 보고 redundant expert와 EPLB가 어느 쪽을 고치는지 확인한 뒤, DeepSeek의 공개 서빙 구성과 SGLang·vLLM 재현을 읽는다.Derive, in bytes, what TP, PP, DP and EP exchange per token; why MLA pushes attention to data parallelism; and why large MoEs are served with wide EP across hundreds of GPUs (memory per GPU, tokens per expert, arithmetic intensity). Split expert load imbalance into sampling noise and popularity skew and see which one redundant experts and EPLB fix, then read DeepSeek's published serving setup and the SGLang and vLLM re-implementations.

    inference · tensor parallel · pipeline parallel · expert parallel · MoE · all-to-all · DeepEP · EPLB · DP attention · MLA · prefill-decode disaggregation · DeepSeek
    50 분min
  8. 긴 문맥 서빙Long-context serving

    1M 토큰에서 무엇이 터지는지(KV 저장 O(T), prefill attention O(T²), decode KV 읽기 O(T))를 계산하고, attention이 선형 부분을 넘는 교차점 T*를 유도한다. chunked prefill, context parallelism(ring attention, pass-KV vs pass-Q, zigzag 샤딩), sparse·linear·SWA attention 모델의 서빙 문제(상태 스냅샷, indexer 스캔), KV 압축과 offload의 손익분기를 다루고, ring attention이 full attention과 정확히 같음을 NumPy로 확인한다.Work out what breaks at 1M tokens (KV storage O(T), prefill attention O(T²), decode KV reads O(T)) and derive the crossover T* where attention overtakes the linear layers. Then chunked prefill, context parallelism (ring attention, pass-KV vs pass-Q, zigzag sharding), the serving problems of sparse, linear and sliding-window attention models (state snapshots, indexer scans), and the break-even of KV compression and offload — with a NumPy check that ring attention equals full attention exactly.

    long context · context parallelism · ring attention · chunked prefill · KV offload · sparse attention · linear attention · DSA · prefix caching
    50 분min
  9. RL을 위한 추론Inference for RL

    RL 학습 루프 안의 추론 엔진을 해부한다. rollout 길이의 긴 꼬리가 동기 배치의 활용률을 어떻게 깎는지 유도하고 over-sampling·partial rollout의 대가(길이 편향, staleness)를 비교한다. 같은 가중치에서도 엔진과 trainer의 logprob이 왜 다른지(배치에 따른 reduction 순서, 커널·정밀도 차이, MoE routing)를 bf16 NumPy 실험으로 보이고, batch-invariant 커널과 결정적 샘플링, weight sync 전략을 계산한다.An anatomy of the inference engine inside the RL loop. Derive how the long tail of rollout lengths eats the utilisation of a synchronous batch, and compare the price of over-sampling and partial rollouts (length bias, staleness). Show with bf16 NumPy experiments why engine and trainer logprobs differ even at identical weights (batch-dependent reduction order, kernel and precision differences, MoE routing), then work through batch-invariant kernels, deterministic sampling and weight-sync strategies.

    RL · rollout · vLLM · SGLang · batch invariance · determinism · weight sync · partial rollout · training-inference mismatch
    50 분min