Lecture 11: Efficiency in LLMs

How do we make LLMs cheaper to train and faster to serve — without losing quality? Our last regular lecture follows one question, where do the time and memory go?, from efficient attention and Mixture of Experts through quantization, LoRA and ZeRO to the KV cache, speculative decoding, FlashAttention and vLLM. Watch it in short chapters with English and Chinese subtitles, follow the lecture map below, then try the ideas in Colab.

📅 Dec. 4th, 2026 🎥 chapters · min 🖼 slides 💬 EN + 中文 subtitles 🧭 Lecture map 💻 Colab notebooks ⬇ Slides (PDF)
Transcript follows the video · click a sentence to jump · Shift + ←/→ jumps between slides

1The lecture map

Where do the time and memory go — and how do we get the same quality for far less?

Four acts, eleven chapters. First why efficiency decides who can build and use LLMs; then two ways to change the model (efficient architectures and compression); then two ways to change how we run it: cheaper training and faster serving. Keep the four costs from slide 2 in mind — FLOPs, bytes moved, bytes stored and communication — because every trick attacks one of them. Click a chapter to watch it.

IWhy
Demand grows faster than hardware
IIChange the model
Cheaper attention, sparse FFNs, fewer bits, smaller students
IIITrain it cheaper
Train fewer parameters; split the rest across GPUs
IVServe it faster
Fewer bytes per token, more tokens per pass
Chapter by chapter what each chapter covers, and the question it leaves for the next
  1. IWhyDemand grows faster than hardware
  2. 1

    Why Efficiency? Scaling Laws, Costs and the Memory Gap

    Scaling laws reward ever more compute, model size grows far faster than GPU memory, and frontier models are expensive to use. The methods split into changes within the Transformer and changes that work on any trained network — and for LLMs, memory and communication join FLOPs as the costs that matter.

    → Where inside a Transformer is the work we could avoid?
  3. IIChange the modelCheaper attention, sparse FFNs, fewer bits, smaller students
  4. 2

    Redundancy and Efficient Attention: Sparse, GQA and MLA

    Trained weights are low-rank and attention heads and FFN neurons are decomposable, so there is redundancy to remove. Sparse patterns (Longformer, Big Bird) let each token attend to fewer tokens; MQA, GQA and MLA store fewer keys and values per token.

    → Attention is cheaper — what about the FFN, which holds most of the parameters?
  5. 3

    Mixture of Experts: Routing, Experts and DeepSeekMoE

    A router sends each token to only a few expert FFNs: the capacity of a huge model at the compute of a small one. Top-k and hash routing, fine-grained and shared experts, load-balancing losses, DeepSeekMoE and DeepSeek-V2, and upcycling a dense model into an MoE.

    → What if the model is already trained, and simply too big?
  6. 4

    Quantization: Fewer Bits per Weight

    Snap every weight to a small integer grid with a scale and a zero point. Outliers stretch the grid, so LLM.int8() keeps them in FP16, and GPTQ and AWQ make 4-bit work. INT8 is almost free; INT4 is the sweet spot for local models.

    → We kept every weight, just with fewer bits — do we need every weight at all?
  7. 5

    Pruning and Knowledge Distillation

    Pruning removes weights, heads or whole layers; only structured pruning makes dense hardware faster, and the model needs to recover afterwards, as in LLM-Shearing. Distillation trains a small student on a teacher's soft labels — and for LLMs, mostly on the teacher's generated data.

    → The model is smaller — but how do we afford to train and adapt it?
  8. IIITrain it cheaperTrain fewer parameters; split the rest across GPUs
  9. 6

    Parameter-Efficient Fine-Tuning: LoRA, Adapters, Modules

    Freeze the pre-trained model and learn a thin update: LoRA's B·A trains about 0.4% of a 4096×4096 matrix and merges back with zero latency. Adapters and prefix-tuning insert parameters elsewhere, and small modules might be composed like Lego bricks.

    → What if the model itself does not fit on one GPU?
  10. 7

    Distributed Training: Data and Model Parallelism, ZeRO

    Data parallelism copies the model and splits the data; model parallelism splits the model. Mixed-precision Adam needs 16 bytes per parameter — 112 GB for a 7B model — and ZeRO shards optimizer states, gradients and weights so memory per GPU falls with the number of GPUs.

    → Training happens once — inference runs billions of times. What makes it slow?
  11. IVServe it fasterFewer bytes per token, more tokens per pass
  12. 8

    Inference Bottlenecks, the KV Cache and PagedAttention

    Prefill is compute-bound, decoding is memory-bound. The KV cache grows with every token and, not the weights, limits the batch size; PagedAttention stores it in small blocks like virtual memory, cutting the waste from 60–80% to under 4%.

    → Memory is under control — but each request still makes one big pass per token.
  13. 9

    Speculative Decoding: Draft, Verify, Stay Exact

    A small draft model proposes several tokens and the large model checks them all in one pass. Accept with probability min(1, q/p), otherwise resample from the normalized max(0, q−p): the output distribution is exactly the big model's, typically 2–3× faster.

    → Fewer big passes — but where does the time go inside one pass?
  14. 10

    FlashAttention: Tiling and the Online Softmax

    Standard attention writes the N×N score matrix to slow HBM and reads it back. FlashAttention computes attention tile by tile in on-chip SRAM, using a running max and sum to merge softmax blocks exactly: more FLOPs, 9× fewer bytes moved, 5.7× faster.

    → We have all the building blocks — how does a real serving engine combine them?
  15. 11

    Serving with vLLM and the Road Ahead

    vLLM looks like an operating system: a scheduler with continuous batching, a block manager with page tables, copy-on-write sharing for parallel sampling and beam search, and preemption. The outlook: sparse and hybrid attention, low-bit formats, disaggregated serving and efficient reasoning.

2Try it in Colab

Three short notebooks turn the lecture's arithmetic into experiments. Click Open in Colab, then Runtime → Run all. Each ends with exercises. All three run on the free CPU runtime with small models (SmolLM2-135M, GPT-2); no GPU needed.

Notebook 1 · Chapters 2 & 8 · ~5–10 min

The KV cache: a memory calculator and GQA

  • Reproduce slide 117: one 4K-token LLaMA-2-70B request needs 10.7 GB of KV cache with MHA, 1.34 GB with GQA
  • Read seven open models' configs: GQA saves 4–8×, DeepSeek's MLA about 57×
  • Qwen2.5-7B on an 80 GB GPU at 8K context: 137 requests fit instead of 19
  • Measure a real cache, time decoding with and without it, and see why sharing K/V heads after training breaks GPT-2
Open in Colab .ipynb · CPU
Notebook 2 · Chapter 4 · ~5–10 min

Quantize a small model and watch its perplexity

  • Watch one outlier round every other INT4 weight to zero
  • SmolLM2-135M on WikiText-2: INT8 costs +0.4% perplexity; INT4 goes from broken (one scale per tensor) to +39% (groups of 64)
  • Find activation outliers above 2,000 and keep them in full precision, as LLM.int8() does
Open in Colab .ipynb · CPU
Notebook 3 · Chapters 6–7 · ~5–10 min

LoRA parameter counts and training memory

  • LoRA rank 8 on a 4096×4096 matrix: 65,536 parameters, 0.39%
  • Redo the memory bill for a 7B model: 112 GB for full fine-tuning, ~15 GB with LoRA, ~4 GB with QLoRA (before activations)
  • Reproduce ZeRO's 120 / 31.4 / 16.6 / 1.9 GB per GPU
  • Write LoRA from scratch, train it on CPU, and merge B·A back into W
Open in Colab .ipynb · CPU

3Concept index

Key terms of the lecture. Each link opens the video at the slide where the idea is explained.

5Quotes & reading

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."

Donald Knuth, Structured Programming with go to Statements, ACM Computing Surveys (1974)
The lecture's method: first ask where the time and memory go, then optimize the critical part.

"The biggest lesson that can be read from 70 years of AI research is that general methods that leverage computation are ultimately the most effective, and by a large margin."

Rich Sutton, The Bitter Lesson (2019)
If quality is bought with compute (slide 6), every saving buys a better model.

"We argue that a missing principle is making attention algorithms IO-aware — accounting for reads and writes between levels of GPU memory."

Tri Dao et al., FlashAttention (NeurIPS 2022)
Bytes moved, not FLOPs — the lesson of Chapter 10.

"Many insects have a larval form that is optimized for extracting energy and nutrients from the environment and a completely different adult form that is optimized for the very different requirements of traveling and reproduction."

Geoffrey Hinton, Oriol Vinyals and Jeff Dean, Distilling the Knowledge in a Neural Network (2015)
Train big, deploy small: the idea behind distillation and compression (Chapters 4–5).

Further reading

6About this video

This is an AI-narrated version of the lecture. The slides are the ones used in class. The spoken script was written from the slides with AI assistance and is read in an AI clone of Prof. Benyou Wang's voice (MiniMax speech synthesis); the picture in the corner is a still photo. The red dot points at what is being discussed. When the narration and the slides disagree, trust the slides and the in-class lecture — and please tell us, so we can fix it.
CSC5051/CSC6052/MDS5110 Natural Language Processing · CUHK-Shenzhen · Fall 2026 · Back to the course page