1. Home
  2. Explore
  3. Computer Science
  4. Building Large Language Models

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Building Large Language Models

Building Large Language Models: Comprehensive Study Notes

Pre-Training

Pre-training is the foundational phase where a language model is trained to model the statistics of internet text. This creates a base model that understands language structure, facts, and reasoning patterns before any specialized tuning.

The Task of Language Modeling

A language model defines a probability distribution over sequences of tokens (words or subwords). Given a sentence like "the mouse ate the cheese," the model assigns a probability reflecting how likely a human would utter that sequence. A grammatically incorrect sentence ("the mouse at cheese") receives a lower probability, and a semantically absurd sentence ("the cheese ate the mouse") receives an even lower probability — demonstrating that the model captures both syntactic and semantic knowledge.

A language model models P(x1,x2,...,xL)P(x_1, x_2, ..., x_L)P(x1​,x2​,...,xL​) — the probability of a sequence of LLL tokens.

Autoregressive language models decompose this joint probability using the chain rule:

P(x1,...,xL)=∏t=1LP(xt∣x1,...,xt−1)P(x_1, ..., x_L) = \prod_{t=1}^{L} P(x_t | x_1, ..., x_{t-1})P(x1​,...,xL​)=∏t=1L​P(xt​∣x1​,...,xt−1​)

This decomposition involves no approximation — it is mathematically exact. The model predicts the next token given all previous tokens (the context). During training, the model compares its prediction to the actual next token and adjusts weights to increase the probability of the correct token.

During inference, generation proceeds token by token in a loop: predict the next token, append it to the context, predict again. This sequential nature makes generation slower for longer outputs.

The training objective is cross-entropy loss:

L=−log⁡P(target token∣context)\mathcal{L} = -\log P(\text{target token} | \text{context})L=−logP(target token∣context)

Minimizing this loss is equivalent to maximizing the log-likelihood of the training data. The model's output layer has dimensionality equal to the vocabulary size, and after a softmax, it produces a probability distribution over all possible next tokens.

Tokenization

Tokenization converts raw text into discrete units (tokens) that the model processes. This step is critically important yet often underappreciated.

Why not use words directly? Words fail for typos (a misspelled word has no token), for languages without spaces (like Thai), and for handling punctuation consistently. Character-level tokenization would work theoretically but produces very long sequences, and transformer complexity grows quadratically with sequence length.

Tokens are typically around 3-4 characters each, balancing vocabulary size and sequence length.

Byte Pair Encoding (BPE) is the most common tokenization algorithm:

  1. Start with a large corpus of text

  2. Assign each unique character its own token

  3. Iteratively find the most frequent pair of adjacent tokens and merge them into a new token

  4. Repeat until reaching a desired vocabulary size

Smaller character-level tokens are retained alongside the merged tokens so that rare words or typos can still be represented character by character.

Challenges with tokenizers:

  • Math: Numbers like "327" may become a single token, preventing the model from learning compositional arithmetic

  • Code: Special formatting (e.g., 4-space indentation in Python) can be tokenized inconsistently

  • Many researchers believe tokenizers are a temporary necessity and hope future architectures will allow character-level processing with efficient handling of long sequences

Evaluation: Perplexity

Perplexity measures how well a language model predicts a sequence. It is the exponentiated average per-token loss:

Perplexity=21L∑tlosst\text{Perplexity} = 2^{\frac{1}{L} \sum_{t} \text{loss}_t}Perplexity=2L1​∑t​losst​
  • Perfect prediction: perplexity = 1 (the model is certain about every token)

  • Random guessing: perplexity = vocabulary size (the model hesitates equally among all tokens)

Perplexity represents the number of tokens the model is "hesitating between" at each step.

Historically, perplexity on standard datasets dropped from ~70 tokens (2017) to less than 10 tokens (2023), reflecting dramatic improvement. However, perplexity is no longer the primary academic benchmark because it depends heavily on the tokenizer — different tokenizers produce different vocabulary sizes, making cross-model comparisons unreliable. It remains useful during development for tracking training progress.

Academic Benchmarks

Modern evaluation aggregates performance across many NLP benchmarks:

  • HELM (Stanford): Comprehensive evaluation across multiple tasks

  • Open LLM Leaderboard (Hugging Face): Standardized comparison

MMLU (Massive Multitask Language Understanding) is the most common benchmark. It contains multiple-choice questions across domains like college medicine, physics, and astronomy. For example: "What is true for Type Ia supernovae?" with four answer choices.

Evaluation methods for MMLU:

  1. Likelihood-based: Compute the probability of each answer choice given the question; select the most likely one

  2. Constrained generation: Prompt the model with "A, B, C, or D" and only consider the probability of those four tokens

Evaluation challenges:

  • Prompting inconsistencies: Different research groups use different evaluation methods, producing different results for the same model (e.g., LLaMA 65B scored 63.7% on one benchmark and 48.8% on another)

  • Train-test contamination: Models may have seen benchmark questions during pre-training. One detection trick: if a language model assigns higher likelihood to test examples in the original (non-randomized) order versus a randomized order, the data was likely in the training set

Training Data

The common claim "train on all of the internet" vastly oversimplifies an enormous engineering challenge.

Data sources: The Common Crawl dataset contains ~250 billion web pages (about 1 petabyte of data) and is updated monthly.

Raw web pages are messy. A typical HTML page includes navigation menus, boilerplate headers/footers, ads, and incomplete sentences — not the clean text desired for training.

Data processing pipeline:

  1. Text extraction: Parse HTML to extract main content. Math extraction is particularly challenging

  2. Filter undesirable content: Remove NSFW content, hate speech, personally identifiable information (PII). Companies maintain extensive blocklists and train small classifiers for automated filtering

  3. Deduplication: Remove duplicate content (same headers/footers appearing thousands of times, identical paragraphs from common sources). This must be done at enormous scale

  4. Heuristic filtering: Rule-based quality checks — e.g., outlier token distributions, unusually short or long documents, unusual word length distributions

  5. Model-based filtering: Train a classifier on high-quality references (e.g., Wikipedia-linked pages) to distinguish quality content from random web pages

  6. Domain classification: Categorize data into domains (code, books, entertainment, etc.) and upweight or downweight certain categories. Training on more code improves reasoning abilities; books are typically upweighted; entertainment is downweighted

  7. High-quality end-of-training mix: Reduce the learning rate and "overfit" on very high-quality data (Wikipedia, curated human data) at the end of training

Scale of data:

  • Academic benchmarks started at ~150 billion tokens (~800 GB)

  • Modern best models train on ~15 trillion tokens (about 100-1000x larger)

  • LLaMA 2: 2 trillion tokens; LLaMA 3: 15 trillion tokens; GPT-4: estimated ~13 trillion tokens

Open problems in data collection:

  • Efficient processing at scale

  • Optimal domain balancing

  • Synthetic data generation (creating training data from LLMs themselves)

  • Multimodal data usage

  • Competitive secrecy (companies don't disclose their data mixtures)

  • Copyright liability concerns

Scaling Laws

Scaling laws describe predictable relationships between model performance and three factors: compute budget, dataset size, and model size.

More data and larger models always improve performance — overfitting does not occur at modern scales.

When plotted on log-log axes, the test loss follows a linear relationship with compute, dataset size, and parameter count. This means one can predict future performance improvements given expected increases in compute.

Practical application: resource allocation Given $10,000 GPUs for one month:

  • Old approach: Train many models for 1 day each, pick the best one (wastes compute)

  • New approach:

    1. Find a scaling recipe (e.g., larger models need lower learning rates)

    2. Tune hyperparameters on small models of varying sizes

    3. Fit scaling laws to extrapolate performance at larger scales

    4. Train the final large model for the remaining compute

Architecture comparisons with scaling laws: Train different architectures (e.g., Transformer vs. LSTM) at multiple small scales, fit scaling laws, and extrapolate which architecture will perform better at the target scale. This reveals that minor architectural differences (activations, normalization schemes) mainly affect the intercept — these differences can be overcome by training slightly longer or waiting for better hardware. Data quality, however, significantly affects the scaling slope.

Chinchilla scaling law: The optimal allocation for minimizing loss given a fixed compute budget is 20 tokens per parameter. However, considering inference costs (smaller models are cheaper to serve), the practical ratio for deployed models is closer to 150 tokens per parameter.

Cost example: LLaMA 3 400B

  • Parameters: 45 billion

  • Data: 15.6 trillion tokens (ratio ~40:1)

  • FLOPs: 6×N×D=6×45B×15.6T=3.8×10256 \times N \times D = 6 \times 45B \times 15.6T = 3.8 \times 10^{25}6×N×D=6×45B×15.6T=3.8×1025 flops

  • Hardware: 16,000 H100 GPUs

  • Time: ~70 days (26-30 million GPU hours)

  • Compute cost: ~52million(at52 million (at52million(at2/hour rental)

  • Total cost including salaries: ~$75 million

  • Carbon emissions: ~4,000 tons CO2 equivalent (about 2,000 round-trip flights from JFK to London)

The "bitter lesson": compute always gets cheaper, so architectures that efficiently leverage computation matter more than clever algorithmic innovations. Simple systems done well at scale outperform complex architectures.


Post-Training (Alignment)

Post-training transforms a pre-trained language model — which models all internet text — into an AI assistant that follows instructions and avoids harmful outputs.

Why Post-Training Is Needed

A pure language model like GPT-3, when asked "Explain the moon landing to a six-year-old," might complete with "Explain the theory of gravity to a six-year-old" — because on the internet, one question is often followed by another related question, not an answer. This is not useful assistant behavior.

Alignment teaches the model to follow user instructions and adhere to designer preferences (helpfulness, harmlessness, honesty).

Supervised Fine Tuning (SFT)

SFT fine-tunes the pre-trained model on human-written question-answer pairs using the same language modeling loss (next-token prediction).

Data collection: Humans write desired answers to diverse prompts. Example prompt: "Write a short introduction about the relevance of the term monopsony." Human-written answer: "Monopsony refers to a market structure..."

Key finding — data quantity matters little: The LIMA paper showed that scaling SFT data from 2,000 to 32,000 examples provides negligible improvement. This suggests SFT primarily teaches the model format (what type of user to emulate) rather than new knowledge — the knowledge was already present in pre-training.

Synthetic data scaling: The Alpaca paper demonstrated using a strong LLM (GPT-3) to generate 52,000 instruction-output pairs from just 175 human-written examples, then fine-tuning LLaMA 7B on this data. This approach reduces human effort dramatically.

Limitations of SFT:

  • Behavioral cloning: The model is bound by human generation ability, even though humans may recognize better outputs than they can produce

  • Hallucination risk: If a human provides a factually plausible answer that the model never saw during pre-training, the model learns to fabricate rather than recall actual knowledge

  • Expense: Collecting high-quality human-written answers is costly

Reinforcement Learning from Human Feedback (RLHF)

RLHF addresses SFT's limitations by optimizing for human preferences rather than cloning human demonstrations.

Pipeline:

  1. For each instruction, have the model generate two candidate answers

  2. Human labelers select which answer is preferred

  3. Train the model to generate more of the preferred answers

Reward models: Instead of using a binary reward (preferred/not preferred), a reward model is trained to produce continuous scores. Using the Bradley-Terry model:

P(answer A preferred over answer B)=eR(A)eR(A)+eR(B)P(\text{answer A preferred over answer B}) = \frac{e^{R(A)}}{e^{R(A)} + e^{R(B)}}P(answer A preferred over answer B)=eR(A)+eR(B)eR(A)​

The reward model is trained to maximize the likelihood of the observed human preferences. Continuous rewards provide richer feedback than binary signals.

Reinforcement learning optimization: The language model acts as a policy in an RL framework. The reward from the reward model guides optimization using PPO (Proximal Policy Optimization). A regularization term prevents over-optimization (reward hacking) since the reward model imperfectly captures human preferences.

After RLHF, the model no longer models a probability distribution — it is optimized to produce the single best response, not to capture all possible human answers.

Challenges with PPO:

  • Complex implementation (clipping, rollouts, multiple loss terms)

  • Unstable training

  • Poorly documented in practice

  • Requires training a separate reward model

Direct Preference Optimization (DPO)

DPO simplifies RLHF by eliminating the separate reward model and RL training loop. Instead, it directly optimizes the language model using only the preference data.

Core idea: Maximize the probability of generating preferred answers while minimizing the probability of generating dispreferred answers. Under certain assumptions, DPO's global optimum is equivalent to PPO's.

LDPO=−log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))\mathcal{L}_{\text{DPO}} = -\log \sigma \left( \beta \log \frac{\pi_{\theta}(y_w | x)}{\pi_{\text{ref}}(y_w | x)} - \beta \log \frac{\pi_{\theta}(y_l | x)}{\pi_{\text{ref}}(y_l | x)} \right)LDPO​=−logσ(βlogπref​(yw​∣x)πθ​(yw​∣x)​−βlogπref​(yl​∣x)πθ​(yl​∣x)​)

Where ywy_wyw​ is the preferred response, yly_lyl​ is the dispreferred response, and πref\pi_{\text{ref}}πref​ is a reference model.

Advantages: DPO uses standard maximum likelihood training — much simpler, more stable, and equally effective as PPO. It is now the standard approach in both open-source and industry.

Data for Alignment

Human data challenges:

  • Slow and expensive: Collecting preferences is costly

  • Difficult judgments: Comparing two good answers is genuinely hard (e.g., two descriptions of self-driving cars)

  • Bias toward length: Humans prefer longer answers, causing RLHF models to produce increasingly verbose outputs

  • Annotator distribution shift: The demographics and values of annotators affect model behavior

  • Crowdsourcing ethics: Annotators are often poorly paid and must process toxic content

Synthetic preference data: Using LLMs as judges instead of humans provides:

  • ~50x cheaper than human annotation

  • Higher agreement with the majority human vote than humans themselves achieve (humans agree with each other ~66% of the time on binary preference tasks)

  • Models have lower variance than humans, compensating for any systematic bias

Practical solutions: Human-LLM collaboration (humans edit LM-generated answers) and active learning (humans label only where the model is uncertain) combine the strengths of both approaches.

Evaluating Aligned Models

Evaluating post-trained models is fundamentally different from evaluating pre-trained models:

  • Cannot use perplexity or validation loss: RLHF models are policies, not distributions — they don't produce meaningful likelihoods for evaluation

  • Open-ended outputs: There is no single correct answer, making automated evaluation difficult

  • Diverse tasks: Users ask questions spanning generation, QA, summarization, coding, and more

Chatbot Arena: The most trusted evaluation method. Users interact blindly with two chatbots, ask questions, and vote on which response is better. After hundreds of thousands of votes, models are ranked. Drawback: users tend to be tech-savvy, skewing the question distribution.

LM-as-judge evaluation (AlpacaEval): Use a strong LLM (e.g., GPT-4) to compare model outputs against a baseline. Benefits: takes <3 minutes and <$10 per evaluation. Achieves 98% correlation with Chatbot Arena.

Important caveat — length bias: LLM judges prefer longer outputs. When GPT-4 is asked to be verbose, its win rate against itself jumps from 50% to 64.4%; when asked to be concise, it drops to 20%. Calibration techniques (regression analysis) can control for this bias.


Systems: Efficient Training

Compute is the primary bottleneck for training LLMs. GPUs are expensive and scarce — even with $10 million, one cannot immediately purchase the best GPUs. Additionally, connecting multiple GPUs introduces communication overhead.

GPU Fundamentals

  • GPUs optimize for throughput (many parallel operations), CPUs optimize for latency

  • GPUs are optimized for fast matrix multiplication — operations not expressible as matrix multiplies are ~10x slower

  • Memory bandwidth lags behind compute: GPUs often sit idle waiting for data

  • Memory hierarchy: Closer to compute = faster access but less capacity; further = slower but more capacity

Model FLOPs Utilization (MFU): The ratio of observed throughput to theoretical maximum. Reaching 50% MFU is considered excellent (Meta's LLaMA training achieved ~45%). This means even for major companies, GPUs spend half their time waiting for data.

Low Precision Training

Reducing numerical precision speeds up computation and reduces memory:

  • Standard deep learning uses 32-bit floats (FP32)

  • Mixed precision training: Store master weights in FP32, convert to FP16 for matrix multiplications, compute in FP16, update master weights in FP32

  • FP16 computation is faster and uses less memory/bandwidth

  • The learning process is robust to precision loss — small numerical errors don't significantly affect training

Using FP16 for computation with FP32 for weight storage is the standard approach.

Operator Fusion

Each PyTorch operation moves data from GPU memory to compute units, processes it, and moves it back. A sequence of operations:

x1 = cos(x)
x2 = sin(x1)

Moves data to compute for cos, back to memory, to compute for sin, back to memory — multiple round trips.

Operator fusion combines multiple operations into a single kernel that reads data once, performs all computations, and writes the result once. torch.compile() automatically performs this optimization, typically doubling model speed by rewriting PyTorch code into optimized CUDA C++.


Further Topics and Study

Many important topics were not covered in detail:

  • Inference optimization: Serving models efficiently to millions of users

  • Architectures: Transformers and their variants

  • Multimodality: Integrating text, images, audio, and video

  • Safety and misuse: Content moderation, jailbreaking, bias

  • UI innovation: The simple chat interface was itself a breakthrough

  • Data scarcity: The internet may not contain enough data for future models

  • Legal issues: Copyright and data collection legality

Recommended courses:

  • CS224n: Background on language models and historical context

  • CS324: In-depth reading on large language models

  • CS336: Build an LLM from scratch (heavy workload)

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent