Stanford Online
Transitioning foundational models from raw autoregressive pre-training to structured reasoning requires combining preference alignment, parameter-efficient adaptation, and reinforcement learning.
AI-assisted summary of Stanford CME 295 Transformers & LLMs | Fall 2026 | Lecture 3 - LLM training — original source. Check the original for full context.
Source published:
Key ideas
- The foundation model paradigm replaces fragmented, task-specific architectures with unified pre-training followed by sequential adaptation stages, with modern frontiers scaling pre-training corpora up to 30 trillion tokens. (3:36)
- Extending context windows during midtraining relies on modifying RoPE base frequencies via techniques like YaRN to prevent degradation caused by unseen position rotations, paired with best-fit document packing. (24:31)
- Reasoning models replace sparse or uncalibrated human preference tuning with deterministic verification, utilizing algorithms like Group Relative Policy Optimization (GRPO) and On-Policy Distillation (OPD) to drive test-time chain-of-thought exploration. (79:07)
- Multi-stage post-training RL pipelines risk catastrophic forgetting across reasoning and conversational domains, which frontier architectures mitigate through cross-stage on-policy distillation against prior checkpoints. (99:59)
Detailed notes
## Background Published on YouTube by Stanford Online on October 15, 2026, this video records Lecture 3 of the Stanford CME 295 course on Transformers and LLMs taught by Adjunct Professors Afshine Amidi and Shervine Amidi. The lecture provides an in-depth walkthrough of large language model training, spanning pretraining, cross-entropy loss, midtraining, supervised fine-tuning, parameter-efficient adaptations, preference alignment, and emergent reasoning methods.
## TL;DR The lecture provides a comprehensive technical overview of the end-to-end training pipeline for modern large language models. The instructors explain the foundations of autoregressive pretraining, cross-entropy loss derivation, and context extension techniques such as RoPE frequency interpolation during midtraining. They then unpack supervised fine-tuning and parameter-efficient methods like LoRA before dissecting preference tuning paradigms, including Bradley-Terry reward modeling, RLHF, and DPO. The session concludes with recent breakthroughs in reasoning elicitation, detailing verifiable rewards, Group Relative Policy Optimization (GRPO), on-policy distillation, and concrete architectural lessons from models like GLM-4 and GLM-5.
## Atmosphere & style The presentation maintains a polished, rigorously academic atmosphere that seamlessly integrates theoretical derivations with practical engineering intuition. Afshine and Shervine Amidi teach with a measured, accessible cadence, breaking down mathematical concepts from first principles while frequently challenging students to consider the physical computational trade-offs behind each technique. The delivery is lucid and candid, moving smoothly from chalkboard-style loss functions to nuanced discussions on industry topics such as model collapse, synthetic data distillation disputes, and open-weight transparency.
## Bulletin - [03:36](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=216s) The foundation model paradigm replaces fragmented, task-specific architectures with unified pre-training followed by sequential adaptation stages, with modern frontiers scaling pre-training corpora up to 30 trillion tokens. - [24:31](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=1471s) Extending context windows during midtraining relies on modifying RoPE base frequencies via techniques like YaRN to prevent degradation caused by unseen position rotations, paired with best-fit document packing. - [01:19:07](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=4747s) Reasoning models replace sparse or uncalibrated human preference tuning with deterministic verification, utilizing algorithms like Group Relative Policy Optimization (GRPO) and On-Policy Distillation (OPD) to drive test-time chain-of-thought exploration. - [01:39:59](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5999s) Multi-stage post-training RL pipelines risk catastrophic forgetting across reasoning and conversational domains, which frontier architectures mitigate through cross-stage on-policy distillation against prior checkpoints.
## Key takeaways - [05:28](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=328s) Pre-training relies on autoregressive next-token prediction and teacher forcing, which introduces an inherent exposure mismatch between ground-truth training inputs and purely model-generated inference sequences. - [10:33](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=633s) Joint sequence probability decomposes via the chain rule, requiring negative log-likelihood transformation and sequence length normalization to avoid severe numerical underflow during optimization. - [14:01](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=841s) Raw cross-entropy loss cannot be directly compared across different tokenizers; bits per byte (BPB) provides a standardized metric by normalizing loss using the token-to-byte ratio. - [16:21](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=981s) In data-constrained regimes, training up to four epochs over high-quality data yields measurable performance gains rather than causing premature degradation. - [22:06](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=1326s) Midtraining retains next-token prediction while shifting data distributions toward long-form code, technical literature, and frequency-adjusted positional embeddings to expand context capabilities. - [34:04](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=2044s) Supervised fine-tuning (SFT) transforms base completion models into instruction-following assistants by computing cross-entropy loss solely over assistant response tokens while masking prompt tokens. - [40:51](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=2451s) Low-Rank Adaptation (LoRA) freezes the base parameters and injects trainable low-rank rank-decomposition matrices, with modern practice prioritizing feed-forward network blocks where the bulk of compute and capacity reside. - [46:37](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=2797s) Pairwise human preference comparisons are vastly more reliable than pointwise absolute scoring, forming the empirical foundation of the Bradley-Terry preference probability formulation. - [01:01:49](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=3709s) Reinforcement Learning from Human Feedback (RLHF) optimizes a generative policy against a frozen reward model while penalizing KL divergence from an SFT reference checkpoint to prevent reward hacking. - [01:05:38](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=3938s) Direct Preference Optimization (DPO) derives an analytical solution that optimizes preferences directly through the policy log-ratios relative to a reference model, bypassing an explicit reward model. - [01:19:07](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=4747s) Verifiable reasoning domains such as mathematics and programming bypass human reward models entirely by leveraging unit tests and exact ground-truth outputs for deterministic evaluation. - [01:20:56](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=4856s) Group Relative Policy Optimization (GRPO) computes advantages by comparing a sampled group of candidate completions against their internal baseline rather than relying on a separate critic network. - [01:23:31](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5011s) On-Policy Distillation (OPD) bridges sparse sequence-level reinforcement learning and dense token-level supervised learning by evaluating teacher signals over the student model's own on-policy generations. - [01:27:50](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5270s) Model collapse emerges when networks recursively train on finite or synthetic generations, systematically shedding rare long-tail distributions of human language and thought. - [01:39:59](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5999s) Frontier open-weight post-training frameworks divide reinforcement learning into specialized tracks—reasoning, agentic tool execution, and general alignment—to balance verifiable problem-solving with conversational nuance.
## Detailed walkthrough ### [00:05](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5s) Recap of Architectural Scaling, Chinchilla, and Efficient Attention
The lecture opens with enthusiasm as the instructors set out the agenda: moving beyond architecture to explore how to actually train large language models so that they align with end goals. Before diving into the training pipeline, the speaker reviews the key architectural concepts established in previous lectures. In Lecture 1, the foundational transformer was introduced, featuring both an encoder and a decoder. In Lecture 2, removing the encoder altogether yielded a simpler, decoder-only setup that reframed generative problems into a pure text-to-text formulation. Scaling these decoder-only models across parameter count and training token volume revealed consistent performance improvements described by empirical scaling laws.
However, compute budgets are finite. The speaker revisits a central takeaway from the Chinchilla paper: compute must be allocated optimally between model size and training data. Historically, many scaled-up architectures were severely undertrained because they failed to maintain the required ratio—roughly 20 tokens of training data for every single model parameter. The speaker also reviews methods introduced to keep large architectures computationally viable:
- **Mixture of Experts (MoE):** Rather than activating every parameter on every forward pass, MoE dynamically routes tokens to specific expert sub-networks located inside the feed-forward layers, where the vast majority of compute takes place. - **RoPE (Rotary Position Embeddings):** Replacing absolute position embeddings by injecting positional information directly within the attention mechanism itself. - **Attention Variants:** Moving away from standard global attention toward sliding-window attention to manage context length. - **Grouped-Query Attention (GQA):** Sharing key and value heads across multiple query heads to dramatically reduce the memory footprint of KV caches during sequence decoding. - **Modern Normalization:** Adopting updated normalization strategies to stabilize deep network activations.
[03:36](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=216s) The Paradigm Shift: From Task-Specific Models to Pre-training
The discussion turns to the first stage of the modern LLM training pipeline: pre-training. To motivate why pre-training exists, the speaker contrasts modern practices with traditional machine learning paradigms from roughly fifteen years ago. Historically, practitioners trained narrow models strictly on a per-use-case basis—one bespoke model for spam detection, another for sentiment analysis, and yet another for machine translation. Each system learned language patterns entirely from scratch for its isolated task.
```mermaid flowchart TD accTitle: Paradigm Shift from Task-Specific Modeling to LLM Pre-training accDescr: Diagram contrasting traditional per-task training with the two-stage pre-training and task adaptation framework.
subgraph Traditional["Traditional ML (circa 15 years ago)"] direction TB T1["Spam Detection Data"] --> M1["Spam Classifier"] T2["Sentiment Data"] --> M2["Sentiment Classifier"] T3["Translation Pairs"] --> M3["Translation Model"] end
subgraph Modern["Modern Foundation Paradigm"] direction TB Data["Massive Web Data (Text, Code, Math)"] --> PT["Pre-trained Base LLM (Language Model)"] PT --> SFT["Task Specialization / Fine-Tuning"] SFT --> App1["Spam / Sentiment / Translation / General Chat"] end ```
The breakthrough of modern foundation models lies in transfer learning: conducting a single, massive, general-purpose pre-training stage to learn the fundamental structure of language, math, and code. Once acquired, that base knowledge is adapted or specialized for downstream objectives. The speaker notes: “Actually the idea behind what we want to do is to do a one-time big what we call pre-training to learn about language and then start from there if we want to specialize that for a specific use case.” Large language models have proven sufficiently general that they can often handle diverse tasks with minimal or no explicit re-training.
[05:28](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=328s) Next-Token Prediction, Teacher Forcing, and Masked Self-Attention
During pre-training, the model is exposed to vast corpora assembled across the internet: English and multilingual web text, source code across languages like Python, mathematical derivations, and scientific articles. The learning objective across all this varied data is next-token prediction. An arbitrary tokenizer breaks raw text into tokens. Conceptually, the model receives a beginning-of-sequence token, predicts the first textual token, feeds that prediction forward to predict the second token, and repeats this iteratively across the whole document.
```mermaid flowchart LR accTitle: Next-Token Prediction with Masked Attention accDescr: Sequence flow showing input tokens passing through masked self-attention to generate next-token prediction probabilities under teacher forcing.
subgraph Inputs["Observed Sequence Context"] BOS["[BOS]"] --> X1["x₁"] X1 --> X2["x₂"] X2 --> Dots["..."] Dots --> Xprev["x_(t-1)"] end
subgraph Core["Model Forward Pass"] Xprev --> MaskedAttn["Masked Self-Attention (Decoders)"] MaskedAttn --> Probs["P_θ(x_t | x₁...x_(t-1))"] end
subgraph Objective["Supervision (Teacher Forcing)"] GroundTruth["True token: x_t"] -.->|"Cross-Entropy Loss"| Probs end ```
In practice, training does not proceed token by token sequentially. Because the ground-truth sequence is already known, the entire sequence is fed into the network simultaneously and computed as parallel matrix multiplications. This relies on teacher forcing: regardless of what probability distribution the network outputs at step $t$, the input presented to step $t+1$ is strictly the true historical token from the training document.
Two student questions prompt further clarification during the lecture: - **Exposure mismatch during inference:** A student points out that teacher forcing creates an inherent discrepancy between training and real-world generation, because during actual inference the model must consume its own potentially flawed outputs rather than clean ground truth. The instructor affirms the critique: “The question is: well, if you teacher force the model to learn a certain way, it is not actually having things it is generating itself as input. So there is a mismatch between training and inference. So that’s an excellent point and we will see actually how we can solve that later on.” - **Empty prompts at sequence starts:** Another student asks whether models are provided a prompt at the very beginning when only the beginning-of-sequence token is present. The instructor confirms that no prompt is used during base pre-training; receiving only the start token simply trains the model on the prior distribution of which tokens naturally open documents.
Crucially, parallel training over the full context without leaking future tokens is made possible by masked self-attention. The causal mask zeroes out attention weights for all positions after the current position, ensuring that the prediction for any position depends solely on earlier tokens and the token itself.
[10:33](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=633s) First-Principles Derivation of the Cross-Entropy Loss
The speaker transitions from the intuitive framing of next-token prediction to a rigorous first-principles derivation of the standard LLM training objective. The overarching statistical goal is maximum likelihood estimation: finding a set of model parameters $\theta$ that maximizes the probability assigned by the model to the observed training sequences.
For an arbitrary sequence of $n$ tokens $X = (x_1, x_2, \dots, x_n)$, the joint probability under parameterization $\theta$ is:
$$P_\theta(X) = P_\theta(x_1, x_2, \dots, x_n)$$
Applying the chain rule of probability decomposes this joint probability into a product of autoregressive conditional probabilities:
$$P_\theta(x_1, \dots, x_n) = P_\theta(x_1) \cdot P_\theta(x_2 \mid x_1) \cdots P_\theta(x_n \mid x_1, \dots, x_{n-1}) = \prod_{t=1}^n P_\theta(x_t \mid x_1, \dots, x_{t-1})$$
The speaker emphasizes the numerical hazard of directly optimizing this product: “The problem with maximizing the product of probabilities which are each in between zero and one is that the product tends to zero. So it can lead to numerical instabilities.” Multiplying thousands of probabilities bounded between 0 and 1 causes severe underflow. To eliminate underflow and simplify optimization, standard practice applies the monotonic natural logarithm to convert the product into a summation:
$$\log P_\theta(X) = \sum_{t=1}^n \log P_\theta(x_t \mid x_1, \dots, x_{t-1})$$
Because standard deep learning optimization algorithms are formulated as minimization problems, the objective is inverted by taking the negative log-likelihood. Finally, to ensure the loss remains invariant to the length of the input sequence rather than scaling linearly with token count, the sum is normalized by the total number of tokens $n$, arriving at the canonical cross-entropy loss function:
$$\mathcal{L}(\theta) = -\frac{1}{n} \sum_{t=1}^n \log P_\theta(x_t \mid x_1, \dots, x_{t-1})$$
[14:01](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=841s) Cross-Entropy Loss and Bits per Byte (BPB)
The predicted probability $P_\theta$ comes directly from the output of the model's final layer, where $\theta$ represents the network parameters, $x_t$ is the target token, $x_{<t}$ denotes the preceding context tokens, and $T$ is the total sequence length. Rather than memorizing the mathematical expression for cross-entropy loss, the speaker urges students to understand it intuitively from first principles: “So all that to say that you will find the cross entropy loss in a lot of places and just instead of memorizing this formula just think of it from first principles is just you trying to find parameters theta that maximize the probability of your model seeing the training data.”
However, a subtle complication arises when evaluating or comparing models: cross-entropy loss values are fundamentally tied to the choice of tokenizer. Because different tokenizers segment identical text into varying numbers of tokens, the raw loss values across models with distinct vocabularies are not directly comparable. To achieve a tokenizer-independent metric, practitioners rescale the loss into bits per byte (BPB). This normalization multiplies the standard cross-entropy loss by the ratio of tokens to bytes ($T / B$, where $B$ is the total byte count of the input text) and scales it by $\frac{1}{\log(2)}$ to convert the units into information-theoretic bits. Addressing an audience question regarding the variable $B$, the speaker clarifies that $B$ simply counts the raw bytes in the input text, reflecting the byte-level representation of characters.
```mermaid flowchart LR accTitle: Cross-Entropy Loss to Bits per Byte Conversion accDescr: Diagram showing how standard cross-entropy loss is scaled by sequence lengths and log base 2 to produce tokenizer-independent bits per byte. A["Raw Cross-Entropy Loss"] --> B["Scale by (Tokens / Bytes)"] B --> C["Scale by 1 / log(2)"] C --> D["Bits per Byte (BPB)"] ```
- $P_\theta$: Probability distribution over vocabulary predicted by the final model layer. - $x_t$: Target token at index $t$. - $x_{<t}$: History of preceding tokens up to time $t-1$. - $T$: Total number of tokens in the sequence. - $B$: Total number of raw input bytes. - BPB Formula scaling factor: $\frac{T}{B} \times \frac{1}{\log(2)}$.
---
[16:21](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=981s) Decoder-Only Masking and Pretraining Data Regimes
A student asks whether masked self-attention—used to prevent tokens from attending to subsequent future positions—applies only to decoders or if it is also relevant for encoders. The speaker clarifies that standard auto-regressive pretraining operates strictly in a decoder-only regime: “So here in this case we don't have an encoder and we only have a decoder and our goal is to predict the next token. We need to make sure that when we predict the next token, we can only rely on the things that we have decoded so far to mimic the inference setup.” Encoder-only architectures cannot perform step-by-step auto-regressive generation unless altered significantly, a topic reserved for lecture 8.
The discussion then moves to pretraining corpora. Building modern LLMs requires vast corpora comprising trillions—and increasingly tens of trillions—of tokens drawn from the open web, code repositories, mathematics, and scientific literature. Addressing a previous lecture's question about whether data can ever be repeated during pretraining, the speaker points to empirical studies examining data-constrained regimes. When fresh tokens are limited, models benefit from multiple training epochs over identical data rather than stopping early: “The question is would you rather stop the training or is it worth for you actually training multiple times on the same tokens and the answer in this case is actually yes up to four times.” Repeating high-quality data up to four epochs yields clear performance gains without degrading general capabilities.
---
[19:16](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=1156s) Data Mixture Strategies and Pretraining Scale
Careful data mixture design has become as critical as model architecture. To disentangle whether benchmark gains stem from architectural tweaks or cleaner data, benchmarks like DataComp-LM standardize model parameters so researchers can isolate the exact contribution of data quality. When determining the precise recipe—such as the proportion of code versus general web text—practitioners often run proxy experiments by training small auxiliary models on diverse candidate mixtures and extrapolating the optimal ratio for large-scale training.
```mermaid flowchart TD accTitle: Pretraining Data Mixture and Scaling Pipeline accDescr: Pipeline showing data curation, small model mixture searches, and massive scale pretraining. subgraph Sourcing ["Data Sourcing & Cleaning"] W["Web Text"] C["Code Repositories"] M["Math & Science"] end subgraph Selection ["Mixture Optimization"] Proxy["Train Small Proxy Models"] Search["Evaluate Data Mixtures (e.g., DataComp-LM)"] end subgraph Pretraining ["Scale Pretraining"] Scale["Train Base Model (Trillions of Tokens)"] end Sourcing --> Selection Proxy --> Search Search --> Scale ```
The data curation pipelines powering top open-weight models are massive engineering endeavors. Citing OLMo 2 (or OLMo-style open pipelines) and GLM-4/GLM-5 as examples, the speaker notes that pretraining now reaches mind-boggling magnitudes: - GLM-4/GLM-5 was trained on 30 trillion tokens as a modern point of reference. - Designing data mixes frequently involves searching over combinations (e.g., 20% code, 50% web text) evaluated via small models before scaling. - The underlying infrastructure and distributed computing required to train across tens of trillions of tokens will be explored in depth during Lecture 5.
---
[22:06](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=1326s) Midtraining: Domain Injection and Long Context Adaptation
While traditional LLM development proceeded directly from pretraining to alignment, modern recipes insert an intermediate phase termed *midtraining*. This phase retains next-token prediction objectives but shifts data distribution to achieve two distinct goals: domain knowledge injection and sequence length extension. Domain injection feeds the model specialized, curated datasets rich in code, reasoning chains, and mathematical proofs.
The second core driver of midtraining is long-context training. Standard pretraining runs on relatively short sequence lengths—often around 4,000 tokens—for computational efficiency. However, downstream deployment demands contexts reaching 128k, 200k, or more tokens. Because Rotary Position Embeddings (RoPE) rely on rotational angles calculated relative to sequence indices, directly exposing a model to long contexts at inference without preparation causes substantial degradation: “the reality is that your model actually has never seen the rotations of these longer sequences. So it may get confused.”
- Midtraining retains standard next-token prediction loss. - Injects specialized domains (e.g., advanced coding, scientific literature, formal proofs). - Expands typical base pretraining lengths (e.g., 4k tokens) up to 128k–200k tokens.
---
[24:31](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=1471s) RoPE Frequency Scaling, Interpolation, and YaRN
To bridge the gap between short pretraining windows and massive target contexts, engineers adapt Rotary Position Embeddings rather than introducing newly learned positional weights. Naive extrapolation forces the network to process unseen, high-magnitude rotational position differences. Instead, methods such as YaRN apply frequency interpolation, effectively compressing long sequence distances back into the familiar rotational range observed during short-context pretraining.
Responding to student questions about how target context windows are determined and executed, the instructor explains that target context sizes are planned in advance. Models adopt curriculum learning: pretraining initiates on short windows (e.g., 4k tokens), midtraining extends sequences to predetermined targets (such as 128k or 200k tokens) using modified RoPE frequencies, and those modified frequencies carry through downstream inference: “So they would initially train the model for short context on some frequencies and then they perform mid training, they perform long context training in which they tweak a little bit the frequencies and then they use these frequencies for inference and so on.” Answering a follow-up on whether methods like YaRN replace the RoPE architecture entirely, the speaker clarifies that the core RoPE structure remains intact; only the underlying base frequencies are rescaled to match the domain of familiar rotations.
[27:38](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=1658s) Challenges of Long-Context Training and Knowledge Cutoffs
Scaling context length from a baseline of 4,000 tokens up to hundreds of thousands of tokens introduces substantial computational and data engineering hurdles. Because standard Transformer architectures rely on self-attention, where every token attends to every other token, computational complexity scales quadratically ($O(n^2)$) with sequence length. Beyond compute, generating and curating high-quality training data that demands true long-range reasoning is exceedingly difficult. The training objective requires the model to learn to leverage information positioned far back in the context window to predict a token deep in the sequence. Sourcing or synthesizing naturally occurring observations where a correct token prediction strictly depends on distant past context requires non-trivial data curation.
Once a foundation model completes pretraining, mid-training, and long-context adaptation—at the expense of significant capital—it emerges with extensive general world knowledge, natural language understanding, and coding capabilities. However, that knowledge remains static, permanently bounded by a fixed knowledge cutoff date. If a user queries the model regarding events occurring after that cutoff, the base model cannot answer natively because that information was absent during training.
```mermaid flowchart LR accTitle: Base Pretraining Stages and Cutoff accDescr: Progression from pretraining through mid-training to long-context training, resulting in a static knowledge base.
subgraph Pipeline["Pretraining Pipeline"] PT["General Pretraining"] --> MT["Domain Mid-Training"] MT --> LC["Long-Context Scaling"] end
LC --> Base["Base Foundation Model"] Base --> KO["Fixed Knowledge Cutoff Date"] ```
- **Computational Scaling**: Self-attention incurs an $O(n^2)$ computational overhead, making scaling from 4,000 to hundreds of thousands of tokens computationally expensive. - **Data Dependency Bottleneck**: Models must be provided observations specifically designed so that future token predictions necessitate resolving dependencies situated far in the preceding context. - **Knowledge Cutoff Example**: As an illustrative hypothetical, a model like “GPT-6 Astra” trained up to April 30, 2026, possesses zero internal awareness of real-world events occurring after that date.
---
[30:39](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=1839s) The Autocomplete Failure and the Need for Supervised Fine-Tuning (SFT)
A base model fresh out of pretraining, mid-training, and long-context training operates purely via autoregressive next-token prediction. It has not been conditioned to act as a conversational assistant. To illustrate this limitation, the lecturer presents a hypothetical prompt to the class: *“Can I put my teddy bear in the washer?”* Instead of answering the user's practical query, a raw base model merely autocompletes text in the style of internet prose: *“Teddy bears are often made of materials like polyester and cotton with plastic eyes and sometimes small accessories.”*
The lecturer emphasizes the fundamental limitation of base models for interactive applications:
> “Is it useful? No, it's not useful. So, we're not done. This was pre-training. Now, let's go into the next stage, which is trying to make our LLM useful.”
To convert a next-token text autocompletion engine into a practical assistant, practitioners turn to Supervised Fine-Tuning (SFT). SFT alters the model's behavioral alignment by exposing it to curated input-output pairs $(x, y)$, where $x$ represents an instruction or prompt and $y$ denotes the target response. Although the optimization objective remains standard cross-entropy over tokens, the structural formulation differs: the model is conditioned on the full prompt $x$, but the loss function strictly penalizes errors on the generated response tokens $y$.
```mermaid flowchart TD accTitle: SFT Loss Masking Flow accDescr: Conditioning on prompt input x without loss calculation, calculating cross-entropy loss solely over response tokens y.
subgraph Inputs["Input Sequence"] X["Instruction Prompt (x)"] Y["Target Response (y)"] end
subgraph ForwardPass["Transformer Forward Pass"] X -->|"Prompt Masked (Zero Loss)"| LLM["LLM"] Y -->|"Autoregressive Prediction"| LLM end
LLM --> CE["Cross-Entropy Loss on y_t given (x, y_<t)"] ```
---
[34:04](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=2044s) SFT Mechanics, Loss Masking, and Data Regimes
Addressing a student question regarding how SFT differs conceptually from mid-training, the lecturer clarifies that mid-training involves continuing next-token prediction over raw corpora of higher-quality or specialized domain text (such as mathematics or code) without an explicit instruction-following format. SFT, by contrast, explicitly conditions the network on an input prompt $x$ and models the conditional probability of target response tokens $y = (y_1, y_2, \dots, y_T)$:
$$\mathcal{L}_{\text{SFT}}(\theta) = - \sum_{t=1}^{T} \log P_\theta(y_t \mid x, y_{<t})$$
In response to another student asking whether predicting the input prompt is penalized during backpropagation, the lecturer confirms that the loss across prompt tokens $x$ is masked out completely:
> “The question is, do you penalize predicting the input? The answer is no. You only penalize predicting the output. You don't care about the input. The input is given to you.”
The dataset volume required for SFT is substantially smaller than pretraining: - **Domain-Specific SFT**: Narrow specialized tasks (such as generating poetry in a distinct meter or style) can be achieved with hundreds to thousands of targeted examples. - **General Assistant Tuning**: Broad instruction-following capabilities spanning varied domains typically require on the order of millions of high-quality paired examples—orders of magnitude less data than the trillions of tokens digested during pretraining.
When evaluated on the earlier prompt (*“Can I put my teddy bear in the washer?”*), an instruction-tuned SFT model provides an actionable answer: *“No, it might get damaged. Try hand washing instead.”*
---
[38:42](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=2322s) SFT Challenges and the Motivation for LoRA
While SFT aligns base models into direct assistants, it introduces critical training challenges: 1. **Data Quality and Behavioral Mimicry**: Because models mirror the stylistic and behavioral nuances of their SFT datasets, low-quality demonstrations degrade outputs immediately. 2. **Distributional Bias**: Skewed prompt mixtures cause the network to overfit specific phrasing, tones, or response lengths, harming zero-shot generalization on unseen formats. 3. **Compute and Memory Constraints**: Modern LLMs span tens to hundreds of billions of parameters. Updating all model weights across full parameter matrices during fine-tuning demands vast GPU memory for optimizer states, gradients, and checkpoints.
Because the underlying model already possesses rich syntactic, semantic, and factual knowledge from pretraining, modifying every single weight matrix to steer conversational behavior is fundamentally redundant:
> “The idea behind LoRa is you actually probably don't need to update all the weights of your model in order to behave a certain way because you're you're almost there already.”
This insight motivates parameter-efficient fine-tuning (PEFT) methods, leading directly into Low-Rank Adaptation (LoRA), which freezes the original model parameters and injects low-rank trainable weight matrices into the network architecture.
[40:51](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=2451s) Low-Rank Adaptation (LoRA) Mechanics and Efficiency
The discussion continues on Low-Rank Adaptation (LoRA) and how it alters model updates. Instead of updating the full weight tensor, the weight matrix is decomposed into the pre-trained, already learned weights $W_0$ plus tunable parameters. These tunable parameters live in much lower-rank matrices—denoted as $B$ and $A$—which dramatically cuts the parameter count required during fine-tuning. This parameter reduction makes training vastly more computationally efficient while achieving roughly on-par performance with full fine-tuning, depending on dataset size and task complexity.
Beyond compute savings during training, LoRA provides massive storage advantages when serving multiple tasks. In a production environment with several distinct use cases—such as spam detection, sentiment analysis, or translation—an engineer does not need to duplicate and store the full set of model weights for every single downstream application. Instead, the pre-trained base model $W_0$ is stored once, and each task only requires saving its unique low-rank adapters ($B$ and $A$). As the instructor summarizes: “So in other words, if you didn’t use LoRA, you would have to store all the weights for the first one, all the weights for the second one, and so on. But here you only need to store the delta.”
The architectural targets for LoRA have also evolved since the method was introduced: - **Original recommendation:** The original LoRA authors proposed injecting the low-rank adaptation matrices solely into the self-attention layers of the Transformer. - **Current best practice:** Subsequent empirical studies and experiments across diverse datasets demonstrate that adapting the feed-forward neural network (FFN / MLP) blocks yields substantial performance gains. Because the feed-forward layers contain a majority of the model’s parameters and account for most of the raw compute, adapting them provides higher expressive capacity. - **Recommended reading:** A notable write-up (referenced from Thinking Machines / similar technical publications) is highlighted in the course slides for students seeking a deeper dive into optimal LoRA parameter placement.
```mermaid flowchart LR accTitle: LoRA Weight Decomposition Flow accDescr: Diagram showing how a pre-trained base model combines with task-specific low-rank delta matrices to produce adapted outputs. subgraph Base["Frozen Shared Base"] W0["Base Weights W0<br/>(Frozen)"] end subgraph Adapters["Task-Specific Low-Rank Adapters"] direction TB Spam["Spam Task:<br/>B_spam * A_spam"] Sent["Sentiment Task:<br/>B_sent * A_sent"] Trans["Translation Task:<br/>B_trans * A_trans"] end W0 --> Spam W0 --> Sent W0 --> Trans ```
---
[43:40](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=2620s) Student Q&A: Serving Adapters vs. Full Fine-Tuning
A student asks how an incoming prompt is routed to the correct weights when multiple LoRA adapters exist. The instructor clarifies that for a general-purpose conversational assistant, teams do not typically deploy fragmented task-specific checkpoints; instead, they train a single unified model that absorbs as much breadth and instruction-following capability as possible. Multiple adapter matrices are reserved for bespoke, highly specialized applications where a general model cannot suffice.
Another student questions why one would bother with parameter-efficient techniques like LoRA during Supervised Fine-Tuning (SFT) given that SFT datasets are around $10^6$ examples—orders of magnitude smaller than pre-training corpora. The instructor provides two practical justifications. First, hardware limitations prevent most practitioners and independent researchers from updating hundreds of billions of parameters: “Well, people who want to fine-tune, they usually people like you and I, we don’t have super big hardware and so we cannot afford having to tune billions and hundreds of billions of parameters.” Second, the foundational base model already contains the world knowledge; re-tuning every parameter introduces unnecessary degrees of freedom when the target behavior only requires small steering adjustments.
The Q&A wraps up with two points on industry divergence and parameter update cadence: - **Model differentiation across companies:** Whether models diverge at this stage depends on underlying architectural choices and proprietary data mixtures, with the exact dataset composition being the decisive differentiator. - **Update cadence:** Weight updates depend heavily on business constraints. When long, complex system prompts become too expensive or token-heavy for production APIs, fine-tuning the weights once to permanently bake in the desired behavior saves considerable inference cost over time.
---
[46:37](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=2797s) The Need for Preference Tuning and Negative Guidance
Up to this point, LLM training focused on acquiring knowledge via pre-training and learning to follow task templates via SFT. However, SFT alone only demonstrates what the model *should* do, leaving a critical gap in teaching it what *not* to do. The instructor illustrates this shortfall with a failure mode:
> Prompt: *“Suggest a new activity I could do with my teddy bear.”* > LLM output: *“Well, I suggest you actually do not spend time with the teddy bear.”*
While technically a syntactically valid completion, this unhelpful or dismissive output is not what users want. SFT trains the model via next-token prediction on curated demonstrations without accounting for the fact that the training tokens were externally forced onto the model rather than generated from its own probability distribution. To prevent undesirable behaviors, systems require preference alignment. When a model consistently misbehaves, it often reveals artifacts or low-quality demonstrations unintentionally included in the SFT training mixture.
Human feedback can theoretically be formatted in three scoring paradigms: 1. **Pointwise scoring:** Assigning an absolute quality score to an individual response in isolation. This approach is notoriously unreliable because human evaluators struggle to maintain calibrated absolute judgment scales across disparate prompts. 2. **Listwise ranking:** Presenting a prompt alongside a ranked list of candidate responses ordered from most preferred to least preferred. 3. **Pairwise comparisons:** Presenting a single prompt alongside two candidate responses (one positive/chosen, one negative/rejected). Pairwise comparison is the industry standard because relative human judgment is vastly more consistent: “So as a human it is much simpler for you to figure out that something is better than something else as opposed to stating that something is good in absolute scale.”
---
[51:37](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=3097s) Reward Modeling and Reinforcement Learning from Human Feedback (RLHF)
To align language models using preference data at scale, practitioners cannot rely on humans to grade every new output the model might generate. The solution is a two-stage alignment framework powered by **Reward Modeling** and **Reinforcement Learning from Human Feedback (RLHF)**:
1. **Reward Modeling:** Train a separate model (the reward model) on collected pairwise human preference comparisons so it learns to score any arbitrary prompt-response pair, assigning higher scalar rewards to helpful, benign responses and lower rewards to poor or harmful ones. 2. **Policy Optimization (RLHF):** Optimize the generative language model against the learned reward model using reinforcement learning, maximizing generated outputs that earn high reward scores while penalizing generations that receive low scores.
The instructor highlights why the technique earned its name: “Because in the first stage where you want to learn how to distinguish good from bad, you are training your reward model on human preference data.”
Reinforcement learning formulations introduce significant mathematical machinery compared to standard supervised learning. The lecture concludes by framing this overview as an intuitive conceptual primer, setting expectations that the rigorous mathematical derivation—including policy gradients and optimization objectives—will be unpacked in depth during the following lecture.
[54:04](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=3244s) Reward Modeling and the Bradley-Terry Formulation
Preference tuning proceeds in two core stages: reward modeling followed by reinforcement learning. In the reward modeling phase, the objective is to teach a model how to distinguish between good and bad responses given a specific prompt. For any input prompt paired with candidate answers, the reward model must output a scalar judgment indicating whether the response is desirable.
To mathematically express the preference between responses, practitioners standardly adopt the Bradley-Terry model. This formulation states that the probability of a candidate response $y_i$ being preferred over another response $y_j$ is given by the sigmoid ($\sigma$) of the difference between their respective scalar rewards, $r_i$ and $r_j$:
$$P(y_i \succ y_j) = \sigma(r_i - r_j)$$
The sigmoid function, defined as $\sigma(x) = \frac{1}{1 + e^{-x}}$, smoothly maps any real-valued difference to a valid probability in the range $(0, 1)$, tending toward $0$ as $x \to -\infty$ and $1$ as $x \to +\infty$.
Training this reward model relies directly on collected pairwise preference data, which is the most practical format to gather from evaluators. Each data point consists of an input prompt $x$, a winning response $y_w$, and a losing response $y_l$. The reward model is trained via a pairwise loss function. Parallel to cross-entropy training—where model parameters $\theta$ are chosen to maximize the likelihood of observed training data—reward model training maximizes the probability that the model assigns a higher preference to the winning response over the losing response:
$$\max_\theta P(y_w \succ y_l \mid x) = \max_\theta \sigma\big(r_\theta(x, y_w) - r_\theta(x, y_l)\big)$$
Because probabilities can become vanishingly small and lead to numerical instability, and because machine learning workflows standardly minimize loss rather than maximize likelihood, the objective is converted by taking the negative logarithm. The final pairwise loss minimizes:
$$\mathcal{L}_\text{RM}(\theta) = -\mathbb{E}_{(x, y_w, y_l)}\left[\log \sigma\big(r_\theta(x, y_w) - r_\theta(x, y_l)\big)\right]$$
When a student inquires about the symbol $\mathbb{E}$, the instructor confirms that it simply represents the expectation over the dataset, functioning intuitively as a sum or average across all pairwise examples.
```mermaid flowchart LR accTitle: Reward Model Scoring and Bradley-Terry Formulation accDescr: Diagram showing how a prompt and two candidate responses are scored by a reward model and evaluated through a sigmoid difference. subgraph INPUTS["Input Data"] P["Prompt (x)"] YW["Winning Response (yw)"] YL["Losing Response (yl)"] end subgraph RM["Reward Model r_theta"] RW["Scalar Reward: r(x, yw)"] RL["Scalar Reward: r(x, yl)"] end DIFF["Difference: r(x, yw) - r(x, yl)"] SIG["Sigmoid: P(yw > yl)"]
P & YW --> RW P & YL --> RL RW & RL --> DIFF DIFF --> SIG ```
- **Reward model architectures**: - *LLM backbone with a classification head*: Takes the base autoregressive language model, extracts the final token's embedding representation, and projects it into a scalar reward value. This allows full reuse of the pretrained model weights. - *Encoder-only model*: Feeds the full prompt-response pair through bidirectional self-attention and projects the output directly to a scalar score. - **Supervision source**: Human preference comparisons provide the underlying ground-truth labels required for Reinforcement Learning from Human Feedback (RLHF).
---
[01:01:49](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=3709s) Reinforcement Learning from Human Feedback (RLHF)
Once the reward model has learned to evaluate response quality, training transitions to the reinforcement learning phase. The instructor notes that this is the “more mathematically involved stage,” where the goal shifts to modifying the weights of the primary language model so its generated text maximizes the scores predicted by the reward model.
In this workflow, the prompt is fed into the generative LLM, which outputs a response. That generated pair is routed to the reward model, which evaluates whether the behavior should be encouraged or discouraged. The resulting scalar reward signal is used to compute gradient updates for the LLM. The instructor emphasizes a critical architectural distinction: during this stage, the reward model trained in step one is completely frozen; only the generative LLM's weights are being updated.
The RL objective function balances two competing forces: 1. **Reward maximization**: Encouraging the policy to produce sequences that achieve higher reward model scores. 2. **KL divergence / reference penalty**: Constraining the updated policy from straying too far from the reference model (typically the supervised fine-tuned, or SFT, checkpoint).
Preventing excessive divergence is critical because the reward model is an imperfect surrogate. Without a reference anchor, models fall prey to "reward hacking"—a failure mode where the policy exploits flaws and blind spots in the reward model to generate outputs that achieve high scores despite being unnatural, incoherent, or unhelpful to human evaluators.
When asked specifically how policy gradients and weight updates are computed under the hood, the instructor defers the detailed derivations: “save your question for next week. We'll go into that in detail. But the one thing I want you to remember here is in this stage the reward model is fixed. We're not updating its weights. We're only updating the the weights of the LLM.”
- **Data scale**: RL training typically operates across prompt sets that are orders of magnitude larger than the preference datasets used to train the reward model. - **Initialization**: The policy model begins directly from the weights of the supervised fine-tuning (SFT) stage.
---
[01:05:38](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=3938s) Direct Preference Optimization (DPO)
While RLHF offers a powerful alignment mechanism, it is notoriously cumbersome in practice: it demands maintaining multiple models simultaneously (the active policy, the reference model, and the reward model), tuning sensitive reinforcement learning hyperparameters, and navigating optimization instabilities. As an alternative, Direct Preference Optimization (DPO) reframes preference alignment into a stable, supervised objective.
The instructor highlights that DPO eliminates the need for an explicit, standalone reward model entirely. By analytically expressing the optimal reward function in terms of the ratio between the policy model $\pi_\theta(y \mid x)$ and the frozen reference model $\pi_\text{ref}(y \mid x)$, DPO derives a closed-form loss that directly updates the LLM:
$$r(x, y) \propto \beta \log \frac{\pi_\theta(y \mid x)}{\pi_\text{ref}(y \mid x)}$$
When substituted into the Bradley-Terry formulation, the resulting loss structurally mirrors the reward model loss from earlier, but operates entirely over sequence probabilities:
$$\mathcal{L}_\text{DPO}(\theta) = -\mathbb{E}_{(x, y_w, y_l)}\left[\log \sigma\left(\beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_\text{ref}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_\text{ref}(y_l \mid x)}\right)\right]$$
Intuitively, this loss mechanism simultaneously pulls two optimization levers: - It actively increases the probability of generating the winning response $y_w$ relative to the reference policy. - It actively decreases the probability of generating the losing response $y_l$ relative to the reference policy.
By bypassing reinforcement learning loops and freezing a copy of the reference model, DPO provides preference alignment through standard supervised classification mechanics.
[01:07:24](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=4044s) The DPO Loss Function and Bradley-Terry Formulation
The Direct Preference Optimization (DPO) objective optimizes a loss function constructed to maximize the difference between the implicit reward of the winning response and that of the losing response ($R_w - R_l$). The mathematical formulation frames this as minimizing the negative expectation of the logarithm of the sigmoid applied to the reward difference:
$$\mathcal{L}_{\text{DPO}} = - \mathbb{E} \left[ \log \sigma (R_w - R_l) \right]$$
Here, the implicit reward $R$ is expressed in terms of a scaling factor multiplied by the log-ratio of the probability assigned by the model being trained ($\pi$) to the probability assigned by a frozen reference model ($\pi_{\text{ref}}$):
$$R(x, y) \propto \log \left( \frac{\pi(y \mid x)}{\pi_{\text{ref}}(y \mid x)} \right)$$
To drive the difference $R_w - R_l$ as large as possible, the optimization increases the probability of the winning output $y_w$ under the trained model relative to the reference model, while decreasing the probability of the losing output $y_l$. Answering a student's question about the notation $\pi$, the instructor explains that in reinforcement learning terminology, the language model is treated as a policy ($\pi$). Responding to a follow-up query about $\pi_{\text{ref}}$, the instructor confirms: “Yes, it is the model that you start from when you perform that training.” Reassuring the class about the mathematical complexity, the instructor remarks: “I just want to say that this formula can be scary but if you take the Bradley Terry formulation in minds and interprets the left and right term as a function of the ratio between what the model that you're trying to tweak over the reference model. If you think about that this way, then hopefully it makes a bit more sense.”
```mermaid flowchart TD accTitle: Direct Preference Optimization Probability Adjustment accDescr: Diagram showing how DPO increases winning token probabilities and decreases losing token probabilities relative to a reference model. subgraph Loss["DPO Loss: Maximize (Rw - Rl)"] direction TB RW["Winning Reward Rw = log( π(yw|x) / π_ref(yw|x))"] RL["Losing Reward Rl = log( π(yl|x) / π_ref(yl|x))"] end subgraph Update["Model Policy Adjustments"] UpWin["Increase π(yw | x)"] DownLose["Decrease π(yl | x)"] end RW --> UpWin RL --> DownLose ```
---
[01:10:15](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=4215s) Comparing RLHF and DPO
Comparing Reinforcement Learning from Human Feedback (RLHF) to DPO highlights key differences in training setup and data dynamics. RLHF requires two distinct stages: first, training a separate reward model on preference pairs; second, optimizing the language model policy using reinforcement learning algorithms. Consequently, RLHF requires maintaining and updating multiple models, making it computationally heavy. In contrast, DPO reformulates the problem into an elegant, closed-form supervised learning objective that bypasses explicit reward modeling altogether.
However, an important architectural distinction lies in whether the optimization is *on-policy* or *off-policy*. DPO evaluates the loss on static, pre-collected completion pairs rather than completions freshly generated by the active model checkpoint during training. The instructor emphasizes: “RLHF is an on policy method because it is actually leveraging the actual outputs from the LLM which contrasts with off policy methods which are actually training the model based on fixed outputs that are not necessarily generated by the model.”
Returning to the running example—a user asking, *"Can I put my teddy bear in the washer?"*—the instructor contrasts an instruction-finetuned output with a preference-tuned output. Instead of a blunt *"No,"* a preference-aligned model produces a gentler, more conversational response: *"No, it's better not to; your teddy could get hurt. A gentle hand wash is safer."*
| Feature | Reinforcement Learning from Human Feedback (RLHF) | Direct Preference Optimization (DPO) | |:--- |:--- |:--- | | **Stages** | 2 stages (Reward modeling + Reinforcement learning) | 1 stage (Direct supervised optimization) | | **Model Footprint** | Multi-model (Policy, Reference, Reward, Critic) | Dual-model (Trained policy + Reference model) | | **Compute Overhead** | High / Compute-heavy | Lower / Supervised finetuning overhead | | **Policy Nature** | On-policy (generates fresh outputs during RL) | Off-policy (evaluates fixed, pre-existing outputs) |
---
[01:12:08](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=4328s) The Shift Toward Reasoning Models
The lecture transitions to reasoning, defined simply as “the ability to solve a problem.” The instructor contrasts pure knowledge-retrieval prompts with reasoning-intensive prompts. Asking *“What is the course code for Stanford's transformers and LLMs class?”* is a factual lookup: “it's something that you know you know you don't know.” By contrast, asking *“Your bear was born in 2020. How old is the bear now?”* requires deduction: identifying the current year, computing the arithmetic difference, and arriving at the correct final number.
Earlier techniques relied on Chain-of-Thought (CoT) prompting, where few-shot demonstrations explicitly nudged the model to articulate its reasoning path step by step before generating the answer. However, the instructor notes: “The problem with that method is we don't want to always tell the LM to do that we want the LM to do that by itself and this is exactly what we will see here.”
Tracing the historical development: - **September 2024:** OpenAI becomes the first company to demonstrate marked jumps on mathematics and code benchmarks using automated internal reasoning mechanisms. - **Late 2024 / Early 2025:** Other frontier AI labs adopt similar reasoning strategies across their flagship architectures. - **January 2025:** DeepSeek-R1 is released as the first open-weights model to publicly document the exact training methodology behind reasoning models.
---
[01:15:09](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=4509s) Reasoning Chains: UI Evolution, Privacy, and Pricing
The user interface design of reasoning models has evolved significantly. In early 2025, applications explicitly highlighted model thinking—such as OpenAI's interfaces displaying a *“thinking”* label, a timer showing how many seconds the model deliberated, an expandable reasoning summary, and a manual option to *“think more.”* Over time, reasoning models became standard across all product tiers, and consumer interfaces reduced these indicators to a simple thinking effort parameter.
Hiding intermediate reasoning chains from end users is driven by two major concerns: 1. **Privacy and Safety:** As demonstrated in published research, querying certain third-party provider APIs allows attackers to reconstruct the underlying reasoning chains. These traces often ingest and reflect sensitive user context, previous chat history, and system instructions that providers cannot safely expose. 2. **Competitive Distillation:** Exposing complete reasoning traces allows competitor labs to collect those chains and use them directly as high-grade training datasets to distill equivalent capabilities into rival models.
The instructor also cautions students regarding inference costs: intermediate reasoning tokens count as generated output tokens. When utilizing reasoning models through an API, users are billed for both the visible response and the hidden reasoning tokens produced during the generation step. When asked if models choose when to reason, the instructor confirms that models are trained to allocate internal reasoning effort adaptively based on prompt difficulty, though users can also modulate this via UI toggles.
```mermaid flowchart LR accTitle: User Input to Reasoned Output Flow accDescr: Workflow showing user prompt ingestion, internal thinking token generation, billing capture, and the final response. Input["User Prompt"] --> Delib["Internal Reasoning Chain<br/>('Thinking Tokens')"] Delib --> Billed["Token Accounting<br/>(Charged as Output Tokens)"] Delib --> Response["Final Visible Answer"] Billed -.-> Hidden["Hidden from UI / Protected"] Delib -.-> Hidden ```
---
[01:19:07](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=4747s) Training with Verifiable Rewards
Training a model to self-generate reasoning chains relies on reinforcement learning with verifiable reward signals, differing fundamentally from subjective preference scoring. For domains such as mathematics and software engineering, solutions possess unambiguous, objective truth criteria: - **Coding benchmarks:** Code completions can be piped directly into sandbox environments and verified against predefined unit tests and edge cases. - **Mathematical tasks:** Symbolic derivations or numerical conclusions can be parsed and matched deterministically against exact ground-truth answers.
Because every generated response can be evaluated as strictly correct or incorrect without relying on human evaluators or noisy reward models, training environments can construct deterministic, rule-based reward functions based directly on the final output.
- Non-verifiable tasks require human raters or learned reward models to assess subjective qualities like tone, politeness, and formatting. - Verifiable tasks evaluate execution success (e.g., unit test pass rates) or ground-truth equality (e.g., target mathematical values). - Ground-truth evaluation allows scalable reinforcement learning updates without human annotators in the loop.
[01:20:36](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=4836s) Group Relative Policy Optimization (GRPO)
Afshine Amidi explains how models can be trained to produce reasoning chains using reinforcement learning. In this setup, the reward signal is composed of two primary components: whether the final answer is correct, and whether the response contains a reasoning chain (typically formatted using reasoning tokens). This training is driven by an RL algorithm that has surged in popularity: Group Relative Policy Optimization (GRPO). While promising that the mathematical formulations will be explored in depth in lecture four, Afshine gives the high-level intuition: given a prompt or query, the model (acting as the policy) outputs a group of multiple candidate responses.
```mermaid flowchart TD accTitle: GRPO Overview accDescr: A prompt generates multiple candidate responses, evaluated against verifiable ground truth to compute relative advantages. A["Query / Prompt"] --> B["Policy LLM"] B --> C1["Candidate Response 1"] B --> C2["Candidate Response 2"] B --> C3["Candidate Response N"] subgraph Eval ["Verifiable Evaluation"] C1 & C2 & C3 --> D["Check vs. Ground Truth"] D --> E["Compute Relative Advantages"] end E --> F["Update Policy with KL Penalty vs. Base Model"] ```
The algorithm evaluates whether these responses are correct and computes advantages based on how much better a specific candidate is relative to the rest of the group. If an answer performs much better than the group baseline, the model is updated to produce more of that behavior; if worse, it is discouraged. Throughout this process, updates are constrained by penalizing divergence relative to a reference model. Afshine highlights the primary departure from traditional RLHF: “So here it's the same mindset. The main difference here is you're actually relying on verifiable rewards. You don't need a reward model.” Instead of training a separate reward model, the pipeline checks whether the model's final answer strictly matches a known ground-truth solution.
- The dual-component reward enforces both answer correctness and the presence of intermediate reasoning tokens. - GRPO calculates group-relative advantages to reinforce high-performing responses within a sample batch. - Reference model regularization prevents the policy from deviating excessively from the base model. - As RL training steps progress, model accuracy steadily climbs, accompanied by an empirical increase in the length of the generated reasoning chain.
---
[01:23:31](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5011s) On-Policy Distillation (OPD)
Before handing the lecture over to Shervine Amidi, Afshine outlines the core limitations of existing alignment and reasoning techniques. GRPO provides a purely sequence-level, sparse reward: the entire output is evaluated as either correct or incorrect, with no granular feedback on intermediate reasoning steps. Conversely, token-level supervised methods provide dense signals, but they operate off-policy—evaluating sequences generated by external sources rather than by the model itself, causing train-test distribution shifts.
To bridge this gap, modern training pipelines employ On-Policy Distillation (OPD). In OPD, the student model generates its own response on-policy token by token. Instead of waiting for a sparse end-of-sequence reward, a teacher model evaluates each generated token dynamically, and deviations between the student's output distribution and the teacher's predictions are penalized. Afshine summarizes the benefits: “So the good thing here is it is on policy because you're actually using the generation of the students and it is also dense because you're getting a token level signal.”
```mermaid flowchart LR accTitle: On-Policy Distillation Flow accDescr: The student generates tokens on-policy while a teacher provides dense token-level supervisory feedback. Prompt["Prompt"] --> Student["Student Model"] Student -->|"Generates On-Policy Tokens"| Tokens["Output Sequence"] Tokens --> Teacher["Teacher Model"] Teacher -->|"Token-Level Supervision"| Loss["Penalize Deviations"] Loss -->|"Dense Gradient Update"| Student ```
Afshine notes key variations of this technique: - **On-Policy Self-Distillation:** When an external teacher model is unavailable, the student model itself acts as the teacher, but it is explicitly given the correct ground-truth answer in its prompt so it can provide optimal steering tokens. - **Specialized Teacher Ensembles:** Frontier open-weight models frequently leverage multiple specialized teacher models (such as dedicated models for mathematics and engineering) to provide dense supervision across diverse domains.
---
[01:27:50](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5270s) Real-World Training Pipeline: The GLM-4 Case Study
Shervine Amidi takes over to ground the theoretical training stages in a concrete, end-to-end industry example. He recommends consulting the Artificial Analysis Intelligence Index, an aggregator of public benchmarks that distills current model performance into comparative metrics. While closed-source frontier models often retain an edge, Shervine points out that open-weights releases provide invaluable transparency: “Usually these open source models they're slightly behind the true frontier from closed source models. But the great thing about them is that often times they tell all the secret recipe behind the preparation of these LLMs and their open weights.”
Focusing on the technical report of the GLM-4 model family (referred to in lecture as GLM-4 / GLM-5), Shervine breaks down the pre-training data composition and curriculum: - **Web Data & Filtering:** Bulk web text sourced from Common Crawl contains vast amounts of low-quality and synthetic noise. Strict filtering heuristics aggressively trim this down to approximately 1% of the raw ingested data. - **Authoritative Knowledge:** High-quality sources such as Wikipedia provide foundational general knowledge, though extensive manual curation is required for specialized domains omitted from top-tier sites. - **Coding Data:** Code from platforms like GitHub forms the bedrock of reasoning and agentic workflows, requiring deliberate data balancing for underrepresented targets such as mobile-specific languages. - **STEM & Scientific Literature:** Papers and mathematics datasets are incorporated directly into pre-training to establish early analytical and reasoning capacity.
Pre-training for GLM was partitioned into two distinct phases, initially running at a short context window of roughly 4,096 tokens (4K). The first stage is coarse and focuses on broad language structure using web text; the second stage reduces web data volume while ramping up coding and reasoning datasets. Addressing a student question about what the model actually learns, Shervine clarifies that this stage optimizes solely for next-token prediction without concern for chat formatting: documents are concatenated and chunked continuously into dense batches without conversational structure.
[01:32:58](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5578s) Document Concatenation, Data Curation, and Model Collapse
In the standard pretraining regime, documents are cut and concatenated together to fully populate the model's context window—meaning an individual training batch will not necessarily begin cleanly with a beginning-of-sequence token. For early pretraining, context lengths typically remain on the order of a few thousand tokens. Shervine shifts attention to the critical role of data curation, contrasting the current training environment with the initial wave of large language models released around 2022. Back then, the internet was almost entirely composed of organic, human-generated content, so practitioners rarely had to worry about the origin or synthetic corruption of the text.
```mermaid flowchart TD accTitle: Mechanism of Model Collapse accDescr: Diagram illustrating how finite sampling and model approximation cause distribution degradation across generations. subgraph DataGen["Data Distribution & Sampling"] A["True Human Distribution\n(Diverse, heavy long-tail)"] -->|"Finite sampling"| B["Sampled Training Corpus\n(Long-tail events omitted)"] end subgraph ModelStep["Model Training & Output"] B --> C["Model Approximator\n(Cannot capture full distribution)"] D["Vendor Preference Tuning\n(Heavily upweights specific phrases)"] -.-> E["Synthetic Output Distribution\n(Biased, degraded diversity)"] C --> E end ```
Today, models face the looming threat of **model collapse**. Shervine illustrates this through a thought experiment: even if you posited a theoretically "perfect" architecture learning from a human-generated corpus, the true natural distribution is vast, diverse, and filled with nonzero probabilities for extremely rare, long-tail events. Because training relies on a finite sample from this infinite corpus, those long-tail details inevitably slip away. As Shervine explains:
> “The thing is since your sampling is finite, you will not capture all these details into training your model which means that the output of your model is by nature doomed.”
Real-world models are not perfect estimators; they are lossy neural network approximators. Compounding the issue further, downstream vendors and data curators deliberately inject behavioral preferences and stylistic biases into post-trained models. Certain idiosyncratic, buzzwordy terms—such as describing code as “loadbearing” or “byte identical”—become heavily upweighted relative to their natural baseline frequency. When future models scrape the web and consume these synthetic artifacts, distribution shift rapidly compounds. Regarding training duration, Shervine addresses an earlier audience question: while pretraining generally runs for $\mathcal{O}(1)$ epochs across the general web, high-classifier-score data is frequently repeated for slightly more passes.
---
[01:36:00](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5760s) Midtraining and Context Extension Strategies
Midtraining introduces curated, higher-grade corpora to transition the base model to larger tasks. Looking specifically at the training recipe of models like GLM-5, the primary design objective of midtraining is scaling up the usable context length reliably. The data mixture deliberately shifts to long-form media: - **Code repositories:** pull requests bundled with issue discussions and accompanying multi-file diffs. - **Literature and technical works:** entire books and long manuscripts.
This phase is also designed to combat **context rot**—the degradation where a model loses track of facts buried deep in an extended prompt. Curators purposefully construct synthetic examples that inject a specific target fact into the middle of a massive context block and force the model to retrieve or reference it downstream (needle-in-a-haystack style).
Midtraining unfolds across distinct sequential stages—initially targeting long code, followed by generalized long-form text. Instead of indiscriminately slicing tokens across boundaries as in basic pretraining, midtraining uses **best-fit packing**: whole documents are packed neatly into the context buffer so they remain uncut, applying padding only when remaining space cannot accommodate an entire piece. The training objective remains next-token prediction, but with structurally cleaner document boundaries.
---
[01:38:11](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5891s) Supervised Finetuning (SFT) and Masked Losses
Supervised finetuning (SFT) transforms the raw base predictor into a responsive, task-oriented assistant. During SFT, data volume drops significantly compared to the trillions of tokens digested in pretraining, but the quality threshold rises dramatically. Emphasizing general helpfulness, modern recipes flood SFT datasets with structured reasoning chains and programming problems.
A central technique highlighted in the GLM-5 literature is interleaving internal reasoning directly prior to tool calls. By giving the model an explicit reasoning path before emitting a tool invocation payload, tool usage becomes substantially more reliable: - **Think Tokens:** Models generate their chain of thought inside special `<think>` tags, functioning as an internal scratchpad. While the user is billed for these tokens, the internal reasoning text can be suppressed from the final displayed response. - **Localized Loss Formulation:** SFT departs from naive autoregressive loss over the entire token string. Because the prompt is supplied by the user, the loss is masked out across the input prompt; the model is only evaluated and updated on next-token prediction over the assistant's target completion.
---
[01:39:59](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5999s) Reinforcement Learning Paradigms and On-Policy Distillation
The post-training reinforcement learning (RL) process in modern frontier models is heavily skewed toward eliciting and stabilizing reasoning capabilities.
```mermaid flowchart LR accTitle: GLM-5 Post-Training Reinforcement Learning Pipeline accDescr: Diagram illustrating three distinct RL branches feeding into on-policy cross-stage distillation against prior checkpoints. subgraph RLStages["Reinforcement Learning Stages"] R1["Reasoning RL\n(Verifiable math competitions)"] R2["Agentic RL\n(Test suite harnesses, bug fixes)"] R3["General RL\n(Helpfulness, EQ, instruction-following)"] end RLStages --> OPD["On-Policy Cross-Stage Distillation\n(Anchored against post-SFT & RL Checkpoints)"] OPD --> Final["Preserved, Un-degraded Final Policy"] ```
The GLM-5 methodology splits reinforcement learning into three distinct operational tracks: 1. **Reasoning RL:** Concentrates on verifiable domains such as mathematical competitions, where the model can spend tokens reasoning through a problem and the final answer can be verified against a ground-truth label. 2. **Agentic RL:** Places the model inside an interactive execution harness where it inspects its own work via deterministic environments—such as attempting to turn a failing software test into a passing test during automated bug fixing. 3. **General RL:** Targets qualitative, open-ended criteria along three explicit axes: *foundational correctness* (strictly following complex system instructions), *emotional intelligence* (aligning with curator definitions of helpful, polite, and constructive tone), and *task-specific quality*.
A pervasive hazard across multi-stage RL pipelines is **catastrophic forgetting**, where refining one behavioral axis erodes competencies gained in earlier phases. To prevent this regression, GLM-5 leverages **on-policy cross-stage distillation (OPD)**. The active policy generates trajectories and is distilled against older, stable teacher checkpoints—specifically, the model checkpoint saved immediately after SFT and the checkpoint from the initial RL reasoning stage—ensuring newly acquired behaviors do not destroy core foundational abilities.
---
[01:42:36](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=6156s) Open Weights, Distillation Controversies, and the Future of Reasoning
Shervine concludes the lecture with practical commentary on open-weight releases and agent design trends. While open-weight technical reports offer valuable glimpses into hyperparameter choices and training methodologies, they routinely omit their most proprietary recipes. Shervine advises the class to maintain a healthy skepticism:
> “Some of the secret sauce behind the data isn't always spelled out. And I just want to say that keep a critical eye on everything you see because you see often times popping up in the news some providers that complain about others distilling their data.”
He points to lightweight agent frameworks like `pi` as an example of where agent development is heading. Traditional agents relied on elaborate, fragile harness engineering—giant prompts, complex outer-loop state managers, and defensive scraping wrappers. Because newer RL-tuned models exhibit dramatically stronger native reasoning and test-driven self-correction, developers can streamline the external harness down to bare-bones tooling and let the model's internal policy manage execution. Shervine notes that this expansion of intrinsic reasoning power is already yielding real academic milestones, pointing to OpenAI's recent announcements solving previously open mathematical problems, before dismissing the class for the weekend to enthusiastic applause.
## Notable quotes > [01:27:50](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=5270s) Usually these open source models they're slightly behind the true frontier from closed source models. But the great thing about them is that often times they tell all the secret recipe behind the preparation of these LLMs and their open weights. — Shervine Amidi
> [46:37](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=2797s) So as a human it is much simpler for you to figure out that something is better than something else as opposed to stating that something is good in absolute scale.
> [10:33](https://www.youtube.com/watch?v=S3bCDcJhz4s&t=633s) The problem with maximizing the product of probabilities which are each in between zero and one is that the product tends to zero. So it can lead to numerical instabilities.
## Mentioned Afshine Amidi, Artificial Analysis Intelligence Index, Bradley-Terry model, Chinchilla, Common Crawl, DataComp-LM, DeepSeek-R1, GitHub, GLM-4, GLM-5, GPT-6 Astra, Low-Rank Adaptation (LoRA), OLMo 2, OpenAI, pi, RoPE (Rotary Position Embeddings), Shervine Amidi, Stanford University, Thinking Machines, Wikipedia, YaRN
## Video description For more information about Stanford’s graduate programs, visit: https://online.stanford.edu/graduate-education
To follow along with the course schedule and syllabus, visit: https://cme295.stanford.edu/syllabus/
Chapters: 00:00:00 Introduction 00:03:36 Pretraining 00:10:33 Cross-entropy loss 00:17:15 Data mixtures 00:22:18 Midtraining 00:23:41 Long context training 00:31:47 Supervised finetuning (SFT) 00:40:15 Low-Rank Adaptation (LoRA) 00:46:37 Preference tuning 00:54:44 Bradley-Terry formulation 01:01:49 Reinforcement Learning from Human Feedback (RLHF) 01:05:38 Direct Preference Preference Optimization (DPO) 01:12:08 Reasoning 01:20:56 Group Relative Policy Optimization (GRPO) 01:23:31 On-Policy Distillation (OPD) 01:27:47 End-to-end example
Afshine Amidi is an Adjunct Professor at Stanford University.
Shervine Amidi is an Adjunct Professor at Stanford University.
Follow the playlist: https://youtube.com/playlist?list=PLakGfbKCei80&si=HF2tNywj7nXIQq8X
[Source](https://www.youtube.com/watch?v=S3bCDcJhz4s)