Skip to content

Module 23

Anurag Prasad edited this page Nov 8, 2026 · 9 revisions

Module 23 — Large Language Models and Multimodal Deep Learning

⬅️ Module 22 · 🗺️ Curriculum · 🏠 Home · Module 24 ➡️

Level: Advanced · Prerequisites: Modules 03, 14, 15, 22 · Time: about 10–12 hours

On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading


Overview and learning goals

Large language models (LLMs) are decoder-only Transformers trained to predict the next token on internet-scale text, then aligned to follow instructions. Remarkably, scale yields broad capabilities. This module covers tokenisation, the autoregressive objective, scaling laws and compute accounting, efficient inference (KV cache, GQA, FlashAttention), decoding, alignment (SFT, RLHF, DPO), retrieval and multimodal extension, and known limitations.

After this module you should be able to:

  • explain BPE tokenisation and compute perplexity from cross-entropy;
  • derive the $6ND$ training-compute rule and state scaling-law findings (Kaplan, Chinchilla);
  • estimate KV-cache memory and explain MQA/GQA and FlashAttention;
  • compare decoding strategies and write the RLHF reward-model and DPO losses;
  • describe multimodal architectures (CLIP, ViT, LLaVA-style) and failure modes such as hallucination.

Beginner: the big picture

An LLM is a very large autocomplete. It reads tokens (word pieces) and outputs a probability distribution over the next token; sampling from it repeatedly generates text. Pretraining on trillions of tokens teaches grammar, facts and reasoning patterns; instruction tuning and preference optimisation then teach it to behave as a helpful assistant.

flowchart LR
    T["Raw text corpus"] --> TK["Tokeniser (BPE)"] --> PT["Pretraining: next-token prediction"] --> BASE["Base model"]
    BASE --> SFT["Supervised fine-tuning on instructions"] --> PO["Preference optimisation: RLHF / DPO"] --> AS["Aligned assistant"]
    AS --> INF["Inference: KV cache + sampling"]
    RET["Retrieval (RAG), tools"] --> INF
Loading

Core concepts and derivations

Tokenisation: BPE and sub-words

Word vocabularies explode and cannot handle rare words; characters make sequences too long. Byte-pair encoding (Sennrich et al. 2016) starts from characters (or bytes) and repeatedly merges the most frequent adjacent pair into a new token until the vocabulary has the target size $V$ (32k–200k). Example corpus: "low"×5, "lower"×2 → pair counts $(l,o)=7,(o,w)=7,(w,e)=2,(e,r)=2$; merge $(l,o)\to$lo, then $(\text{lo},w)\to$low, then low+e... Variants: byte-level BPE (no unknown tokens), SentencePiece/unigram LM (Kudo & Richardson 2018). Tokenisation affects cost, multilingual fairness and arithmetic/spelling behaviour.

Autoregressive language modelling and perplexity

$P(x_1,\dots,x_T)=\prod_tP(x_t\mid x_{<t})$, trained by minimising the average cross-entropy $\mathcal{L}=-\frac1T\sum_t\ln P_\theta(x_t\mid x_{<t})$ with causal attention (Module 14) and teacher forcing (all positions predicted in parallel). Perplexity $=e^{\mathcal{L}}$ — the effective number of equally likely choices per token. Loss is tokeniser-dependent; compare bits-per-byte across tokenisers.

Scaling laws and compute-optimal training

Kaplan et al. (2020) found test loss follows power laws in parameters $N$, data $D$ and compute $C$, e.g. $L(N)\propto N^{-\alpha_N}$ with $\alpha_N\approx0.076$. Compute accounting: a forward pass costs about $2N$ FLOPs per token (one multiply–add per parameter) and the backward pass about twice that, so

$$ C\approx6,N,D\ \text{FLOPs}. $$

Hoffmann et al. (2022, "Chinchilla") showed that for a fixed budget $C$ one should scale $N$ and $D$ roughly equally, giving about 20 training tokens per parameter — earlier models were under-trained. Because inference cost scales with $N$ for every query, practitioners often train smaller models on more tokens than compute-optimal. Scaling laws are empirical regularities for loss, not guarantees for each downstream capability.

Efficient inference: KV cache, MQA/GQA, FlashAttention

During generation, keys and values of past tokens do not change, so they are cached. KV-cache memory per sequence:

$$ \text{bytes}=2\cdot n_{layers}\cdot T\cdot n_{kv}\cdot d_{head}\cdot b, $$

($2$ for K and V, $b$ bytes per element). Multi-query attention (Shazeer 2019, $n_{kv}=1$) and grouped-query attention (Ainslie et al. 2023, $1<n_{kv}<n_{heads}$) share K/V across query heads, shrinking the cache and bandwidth with little quality loss. FlashAttention (Dao et al. 2022) computes exact attention in tiles that stay in fast on-chip memory, avoiding materialising the $T\times T$ matrix and making attention IO-efficient. Other techniques: quantisation (Module 24), speculative decoding, continuous batching, paged KV caches, sliding-window attention, Mixture-of-Experts (activate a few expert FFNs per token — more parameters at constant FLOPs).

Decoding strategies

Given logits $\mathbf{z}$: greedy (argmax), temperature $\operatorname{softmax}(\mathbf{z}/\tau)$ ($\tau<1$ sharper, $>1$ flatter), top-$k$ (sample among the $k$ most likely), top-$p$/nucleus (smallest set with cumulative probability $\ge p$; Holtzman et al. 2020), beam search (good for translation, poor for open-ended text — repetitive/generic). Greedy and beam can degenerate into repetition; sampling needs truncation to avoid the unreliable low-probability tail.

Instruction tuning and alignment: SFT, RLHF, DPO

  1. SFT: fine-tune on (instruction, response) pairs with cross-entropy (Module 22).
  2. RLHF (Christiano et al. 2017; Ouyang et al. 2022): collect human preference pairs ($y_w\succ y_l$), train a reward model with the Bradley–Terry loss $L_{RM}=-\ln\sigma\bigl(r_\phi(x,y_w)-r_\phi(x,y_l)\bigr)$, then optimise the policy with PPO (Schulman et al. 2017) on $r_\phi(x,y)-\beta,D_{KL}(\pi_\theta\Vert\pi_{ref})$ — the KL keeps the policy close to the SFT model and limits reward hacking.
  3. DPO (Rafailov et al. 2023) eliminates the explicit reward model and RL loop. Since the optimum of the KL-regularised objective satisfies $r(x,y)=\beta\ln\frac{\pi^\star(y|x)}{\pi_{ref}(y|x)}+\text{const}(x)$, plugging into Bradley–Terry gives

$$ L_{DPO}=-\mathbb{E}\Bigl[\ln\sigma\Bigl(\beta\ln\tfrac{\pi_\theta(y_w|x)}{\pi_{ref}(y_w|x)}-\beta\ln\tfrac{\pi_\theta(y_l|x)}{\pi_{ref}(y_l|x)}\Bigr)\Bigr]. $$

Newer variants include RL from verifiable rewards (for math/code), AI-feedback and rule-based preference data, and rejection-sampling fine-tuning.

Retrieval-augmented generation and tools

Parametric knowledge is stale and unverifiable. RAG (Lewis et al. 2020) retrieves relevant documents (dense embeddings, Module 17; vector search) and conditions generation on them, enabling citations and updates without retraining. Tool use / agents let the model call code interpreters, search and APIs; reliability depends on structured outputs and verification.

Multimodal models

  • CLIP (Module 17): joint image–text embedding via contrastive loss.
  • Vision Transformer: split an image into $P\times P$ patches, linearly embed them as tokens (Dosovitskiy et al. 2021).
  • LLaVA-style VLMs: a vision encoder produces patch features; a projector maps them into the LLM's token-embedding space; the LLM is tuned on image–instruction data (Liu et al. 2023). Flamingo-style models interleave via cross-attention. Audio, video and "any-to-any" models follow the same pattern: encode each modality to tokens, process with a shared Transformer.

Hallucination, evaluation and limitations

LLMs produce fluent but false statements because they optimise plausibility, not truth (Ji et al. 2023 survey). Mitigations: retrieval and citation, calibrated abstention, verification and tool use, better data, preference training against fabricated claims. Evaluate with held-out benchmarks and contamination checks, human preference/arena comparisons, task-specific evals and red-teaming (Module 24). Other limits: context-window utilisation, prompt sensitivity, reasoning/planning errors, bias, privacy (memorisation) and safety (jailbreaks).

Worked example

Perplexity. Average loss $2.0$ nats/token → perplexity $e^{2}=7.39$. Temperature. Logits $(2,1,0)$: $\tau=1\to(0.665,0.245,0.090)$; $\tau=0.5\to(0.867,0.117,0.016)$; $\tau=2\to(0.506,0.307,0.186)$. Training compute. $N=7\times10^9$, $D=10^{12}$ tokens: $C=6ND=4.2\times10^{22}$ FLOPs. On accelerators sustaining $2\times10^{14}$ FLOP/s each (about 40% utilisation of a $5\times10^{14}$ peak) this is $2.1\times10^{8}$ accelerator-seconds $\approx58{,}000$ accelerator-hours. The Chinchilla heuristic would call $20N=1.4\times10^{11}$ tokens compute-optimal; $10^{12}$ is deliberately "over-trained" to cheapen inference. KV cache. $n_{layers}=32$, $T=4096$, $n_{kv}=32$, $d_{head}=128$, fp16 ($b=2$): $2\cdot32\cdot4096\cdot32\cdot128\cdot2$ bytes $=2.0$ GiB per sequence; with GQA $n_{kv}=8$ it is $0.5$ GiB. Bradley–Terry. Reward margin $r_w-r_l=1$: $P(y_w\succ y_l)=\sigma(1)=0.731$, loss $=0.313$.

Implementation

import torch, torch.nn.functional as F

def sample(logits, temperature=1.0, top_k=None, top_p=None):
    logits = logits / max(temperature, 1e-6)
    if top_k: logits = logits.masked_fill(logits < logits.topk(top_k)[0][..., -1:], -float('inf'))
    if top_p:
        sl, idx = logits.sort(descending=True); cp = sl.softmax(-1).cumsum(-1)
        drop = cp - sl.softmax(-1) > top_p                           # keep tokens until mass >= p
        sl = sl.masked_fill(drop, -float('inf')); logits = torch.full_like(logits, -float('inf')).scatter(-1, idx, sl)
    return torch.multinomial(logits.softmax(-1), 1)

def dpo_loss(pi_w, pi_l, ref_w, ref_l, beta=0.1):                    # sequence log-probs, shape (B,)
    return -F.logsigmoid(beta * ((pi_w - ref_w) - (pi_l - ref_l))).mean()

def kv_cache_gib(layers, T, n_kv, d_head, bytes_=2): return 2 * layers * T * n_kv * d_head * bytes_ / 2**30
print(kv_cache_gib(32, 4096, 32, 128), kv_cache_gib(32, 4096, 8, 128))          # 2.0, 0.5

Advanced topics

  • Mixture-of-Experts routing, load balancing and expert parallelism; long-context training and evaluation (Module 15).
  • Parallelism for training: data, tensor, pipeline, sequence and ZeRO/FSDP sharding; mixed-precision (bf16/FP8).
  • Reasoning models: chain-of-thought, test-time compute scaling, process/outcome reward models, RL with verifiable rewards.
  • Data: deduplication, quality filtering, synthetic data, contamination; curricula and annealing.
  • Mechanistic interpretability and sparse autoencoders (Module 16) on activations.
  • Safety: adversarial prompts/jailbreaks, data poisoning, privacy leakage, watermarking, evaluations of dangerous capabilities.
  • Emergent abilities debate: apparent discontinuities can depend on metric choice (Schaeffer et al. 2023).

Pitfalls and best practices

  • Comparing perplexities across different tokenisers.
  • Evaluating on benchmarks that leaked into the training data.
  • Using greedy/beam search for creative generation, or high temperature for factual QA.
  • Ignoring prompt format/chat-template mismatches between training and inference.
  • Treating fluent answers as verified; no citations ≠ no hallucination.
  • Underestimating KV-cache memory when planning serving batch sizes.

Conceptual questions and answers

Q1. Why sub-word tokenisation?

It balances vocabulary size and sequence length, represents rare/new words as pieces, and avoids unknown tokens (especially with byte-level BPE).

Q2. Derive the $6ND$ rule.

Each parameter takes part in one multiply–add (2 FLOPs) per token in the forward pass; the backward pass needs gradients w.r.t. activations and weights, about $2\times$ the forward cost ($4N$). Total $6N$ per token × $D$ tokens.

Q3. What did Chinchilla change?

It showed models should be trained on about 20 tokens per parameter for compute-optimality; many earlier large models were too large for their data.

Q4. Why is the KV cache needed and what dominates its size?

It avoids recomputing keys/values for all prior tokens at every step; its size scales with layers × sequence length × KV heads × head dimension × batch.

Q5. How does GQA help?

Several query heads share one K/V head, cutting cache size and memory bandwidth (e.g. 4× for 8 KV vs 32 query heads) with small quality loss.

Q6. Compare top-$k$ and top-$p$ sampling.

Top-$k$ uses a fixed number of candidates; top-$p$ adapts the candidate set size to the distribution's entropy (few when the model is confident, more when uncertain).

Q7. What does the KL term do in RLHF?

It keeps the policy near the reference model, limiting reward hacking and preserving fluency and general capabilities.

Q8. How does DPO relate to RLHF?

DPO re-parameterises the reward as a log-ratio of policy to reference, so the Bradley–Terry preference loss can be optimised directly without a separate reward model or RL.

Q9. Why do LLMs hallucinate?

They are trained to produce plausible continuations, not to verify truth; gaps in knowledge are filled with likely-sounding text, and calibration of confidence is imperfect.

Q10. How do vision-language models connect images to an LLM?

A vision encoder turns the image into patch embeddings; a projector (linear/MLP/cross-attention) maps them into the LLM's embedding space as extra "tokens".

Sources and further reading

  • Sennrich, R., Haddow, B., & Birch, A. (2016). Neural machine translation of rare words with subword units. ACL. arXiv:1508.07909.
  • Kudo, T., & Richardson, J. (2018). SentencePiece. EMNLP (Demos). arXiv:1808.06226.
  • Brown, T., et al. (2020). Language models are few-shot learners. NeurIPS. arXiv:2005.14165.
  • Kaplan, J., et al. (2020). Scaling laws for neural language models. arXiv:2001.08361.
  • Hoffmann, J., et al. (2022). Training compute-optimal large language models. arXiv:2203.15556.
  • Touvron, H., et al. (2023). LLaMA: open and efficient foundation language models. arXiv:2302.13971.
  • Shazeer, N. (2019). Fast Transformer decoding: one write-head is all you need. arXiv:1911.02150.
  • Ainslie, J., et al. (2023). GQA: training generalized multi-query Transformer models. EMNLP. arXiv:2305.13245.
  • Dao, T., et al. (2022). FlashAttention. NeurIPS. arXiv:2205.14135.
  • Holtzman, A., et al. (2020). The curious case of neural text degeneration. ICLR. arXiv:1904.09751.
  • Christiano, P., et al. (2017). Deep reinforcement learning from human preferences. NeurIPS. arXiv:1706.03741.
  • Ouyang, L., et al. (2022). Training language models to follow instructions with human feedback. NeurIPS. arXiv:2203.02155.
  • Schulman, J., et al. (2017). Proximal policy optimization algorithms. arXiv:1707.06347.
  • Rafailov, R., et al. (2023). Direct preference optimization. NeurIPS. arXiv:2305.18290.
  • Lewis, P., et al. (2020). Retrieval-augmented generation for knowledge-intensive NLP tasks. NeurIPS. arXiv:2005.11401.
  • Liu, H., et al. (2023). Visual instruction tuning (LLaVA). NeurIPS. arXiv:2304.08485.
  • Alayrac, J.-B., et al. (2022). Flamingo. NeurIPS. arXiv:2204.14198.
  • Ji, Z., et al. (2023). Survey of hallucination in natural language generation. ACM Computing Surveys, 55(12).
  • Schaeffer, R., Miranda, B., & Koyejo, S. (2023). Are emergent abilities of large language models a mirage? NeurIPS. arXiv:2304.15004.

⬅️ Module 22 · 🗺️ Curriculum · 🏠 Home · Module 24 ➡️

🎓 Deep Learning Hub

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths

❓ Question bank · 📖 Glossary · 📚 References

Jump to module:

01 02 03 04 05 06 07 08 09 10 11 12

13 14 15 16 17 18 19 20 21 22 23 24

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally