TensorTonic/llm-optimization-handbook
À propos
Make LLMs faster, cheaper and smaller: inference fundamentals, quantization, KV cache, speculative decoding, GPU kernels and serving, with hands-on problems.
IA et apprentissage automatiqueProgression mesurée des étoiles
- in 24h
- 0
- in 7 days
- Historique en cours
- in 15 days
- Historique en cours
- in 1 month
- Historique en cours
Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.
README.md
OriginalLLM Optimization Handbook
This is a roadmap for making large language models faster, cheaper and smaller to run. It covers 48 topics across seven stages, from how a single request moves through the GPU to running a model in production.
Every topic links to a short explanation and to practice problems where you implement the idea in Python, CUDA or Triton and check your code against tests. Most optimization advice is easy to repeat and hard to apply, and writing the quantizer or the scheduler yourself is the quickest way to see what each technique actually changes.
Table of Contents
- Who this is for
- How to use this roadmap
- Stage 1: Inference Fundamentals
- Stage 2: Quantization
- Stage 3: KV Cache and Attention
- Stage 4: Speculative Decoding and MoE
- Stage 5: GPU Kernels
- Stage 6: Batching and Parallelism
- Stage 7: Serving in Production
- What's next
Who this is for
This roadmap is for anyone who wants to understand why LLM inference is slow and what each optimization does about it.
- If you are an ML engineer moving into inference, go through the stages in order and do at least one problem per topic.
- If you are preparing for inference or ML systems interviews, the first three stages and the batching stage cover most of the questions that come up.
- If you already serve models in production, use the tables as a checklist and focus on the topics you have only ever used through a library flag.
You need to be comfortable with Python and know roughly how a transformer works. You do not need prior GPU programming experience until Stage 5.
How to use this roadmap
Optimization works as a loop. You measure a request, find the bottleneck, apply the technique that targets that bottleneck, and measure again while checking that output quality did not drop. Stage 1 gives you the vocabulary for that loop, and every later stage attacks one of the four bottlenecks it introduces.
For each topic, read the explanation first, then solve one or two of the practice problems. Topics without a practice link are still worth reading, because later topics and real deployments depend on them.
Stage 1: Inference Fundamentals
A request has two phases. Prefill reads the whole prompt in one parallel pass, and decode produces one token at a time while rereading the weights and the cache on every step. This stage explains why those phases hit different limits and how to measure speed in a way that holds up.
| Topic | Read | Practice |
|---|---|---|
| How a request is served | What Is an Inference Server? | |
| Attention in the forward pass | Attention in LLMs | Causal Masking for Attention, Scaled Dot-Product Attention |
| Prefill, decode and the roofline | What is inference engineering? | Analyze Prefill and Decode with the Roofline Model |
| Model memory and GPU count | The GPU memory budget | Estimate Model Memory and Minimum GPU Count |
| Token sampling | How to Build an Inference Server | Temperature, Top-k, and Top-p Sampling |
| TTFT, TPOT, ITL and throughput | Latency, throughput, and cost | Compute TTFT, TPOT, ITL, and Token Throughput |
| Latency percentiles | Latency, throughput, and cost | Percentiles / Quantiles, Calculate P50, P95, and P99 Inference Latency |
Stage 2: Quantization
Decode is usually limited by how many bytes it reads per token, so storing weights in fewer bits makes it faster and lets a larger model fit on the same GPU. The work is in choosing scales that keep the error small, since a few large outlier values can ruin a naive scheme.
| Topic | Read | Practice |
|---|---|---|
| Number formats and mixed precision | Mixed Precision Training: FP16 vs BF16 | Mixed-Precision Training Memory Accountant |
| Symmetric INT8 quantization | What is quantization? | Symmetric INT8 Quantization |
| Per-channel scales | What is quantization? | Per-Channel Weight Quantization |
| Group-wise INT4 quantization | Quantize a Language Model to 4 Bits | Group-Wise INT4 Quantization |
| FP8 block quantization | What is quantization? | Block-Wise FP8 Quantization |
| Outliers, GPTQ and AWQ | LLM Quantization Explained: INT8, INT4, GPTQ and AWQ | |
| 4-bit fine-tuning with QLoRA | QLoRA Explained |
Stage 3: KV Cache and Attention
During decode, the model keeps the keys and values of every previous token so it does not recompute them. That cache often takes more memory than the weights at long context, and most modern attention variants exist to shrink it, store it in blocks or read it with fewer trips to GPU memory.
| Topic | Read | Practice |
|---|---|---|
| The KV cache | What is the KV cache? | Decode Attention with a KV Cache, Autoregressive Decoding with a KV Cache |
| Sizing the cache | KV Cache in LLMs | Plan KV-Cache Capacity, Calculate KV Cache Memory for MHA, MQA, GQA, and MLA |
| Multi-query attention | Attention in LLMs | Multi-Query Attention (MQA) |
| Grouped-query attention | Attention in LLMs | Causal Grouped-Query Attention, Grouped-Query Attention (GQA) |
| Multi-head latent attention | KV Cache in LLMs | Multi-Head Latent Attention (MLA) |
| RoPE during decoding | RoPE: Rotary Position Embedding Explained | RoPE: Rotary Query and Key Embeddings, Rotary Position Embeddings for Decoding |
| FlashAttention and online softmax | FlashAttention Explained, Write FlashAttention Step by Step | Blockwise Online Softmax, FlashAttention with Online Softmax |
| PagedAttention | PagedAttention Explained | PagedAttention Block Allocation |
| Prefix caching | PagedAttention Explained | Find Reusable Prefixes in a KV Trie, Prefix Cache Matching and Reuse |
Stage 4: Speculative Decoding and MoE
Decode spends most of each step waiting on memory, which leaves spare compute. Speculative decoding uses it to check several drafted tokens in one pass without changing the output distribution, and mixture-of-experts models use sparse routing so each token only runs a small part of a very large model.
| Topic | Read | Practice |
|---|---|---|
| Draft and verify | Speculative Decoding in LLMs Explained | Perform Exact Speculative Sampling, Speculative Decoding and Token Verification |
| Acceptance rate and real speedup | Speculative Decoding in LLMs Explained | |
| Draft-free variants such as Medusa and EAGLE | Speculative Decoding in LLMs Explained | |
| Top-k expert routing | Mixture of Experts (MoE) in LLMs Explained | Top-k MoE Router with Load Statistics, Sparse MoE Top-k Expert Routing |
| Token dispatch and aggregation | Mixture of Experts (MoE) in LLMs Explained | MoE Token Dispatch and Expert Aggregation |
Stage 5: GPU Kernels
Every technique above eventually runs as a GPU kernel, and fused kernels are where many of the real gains come from. The goal of this stage is to load data from GPU memory once, reuse it from fast on-chip memory and write the result once, first in CUDA and then in Triton.
| Topic | Read | Practice |
|---|---|---|
| Threads, blocks and warps | How to Learn CUDA | Vector Addition as a CUDA Kernel, GPU Occupancy Calculator |
| Memory coalescing and shared memory | How to Learn CUDA | Global-Memory Coalescing Counter, Shared-Memory Bank Conflict Analyzer |
| Tiled matrix multiplication | CUDA study plan | Tiled Matrix Multiplication as a CUDA Kernel |
| Reductions and softmax | CUDA study plan | Softmax as a CUDA Kernel, Online Softmax Kernel in Triton |
| Writing kernels in Triton | Triton study plan | Vector Addition in Triton, Tiled Matrix Multiplication in Triton |
| Kernel fusion | Triton study plan | Fused Matmul + Bias + ReLU in Triton, RMSNorm Forward in Triton |
| Attention kernels | Write FlashAttention Step by Step | FlashAttention Forward Kernel in Triton, KV Cache Append in Triton |
Stage 6: Batching and Parallelism
A single request leaves most of the GPU idle, so a server earns its throughput by scheduling many requests together. This stage covers how batches are formed and reshaped every step, and how a model is split across GPUs when it no longer fits on one.
| Topic | Read | Practice |
|---|---|---|
| Dynamic batching | How to Build an Inference Server | Dynamic Request Batching |
| Continuous batching | PagedAttention Explained | Simulate Continuous Decode Batching, Simulate Continuous Batching |
| Chunked prefill | What is inference engineering? | Simulate Chunked Prefill Scheduling |
| Prefill and decode disaggregation | What is inference engineering? | Simulate Disaggregated Prefill and Decode Serving |
| Cache-aware request routing | LLM serving and RAG | Route Cache-Aware Prefill Requests |
| Collective communication | Calculate Collective Effective Bandwidth, Simulate Distributed Collectives | |
| Tensor parallelism | Reconstruct a Column-Parallel MLP Layer, Calculate Tensor Parallel Communication Cost | |
| Expert parallelism | Mixture of Experts (MoE) in LLMs Explained | Expert Parallel Routing Across GPUs |
Stage 7: Serving in Production
A fast model only helps if the whole system stays fast under real traffic. This stage is about building and benchmarking the server, finding where GPU time goes, and turning throughput at your latency target into a cost you can plan around.
| Topic | Read | Practice |
|---|---|---|
| Building an inference server | Build an LLM Inference Server From Scratch | |
| Benchmarking method | Latency, throughput, and cost | |
| Profiling GPU time | What is inference engineering? | Measure Kernel Timeline Utilization |
| Throughput and cost under a latency target | Latency, throughput, and cost | Optimize Throughput and Cost Under a Latency SLO |
| Rollouts and monitoring | Fallbacks and model rollouts |
What's next
Once the stages above feel familiar, the Cracking Inference study plan collects the inference problems from this roadmap in one place, and the LLM Internals pages explain each mechanism visually. To put the pieces together, build an inference server or quantize a language model to 4 bits end to end.
These optimizations are easier to reason about once you have written the model they speed up, and the How to Build an LLM from Scratch guide walks through building a small one stage by stage.
If you want to write the fused kernels from Stage 5 yourself, the How to Learn Triton guide explains how to learn Triton step by step.
License
MIT
Explorer des projets similaires
Chargement…