🌏 中文版
Video status: Videos included. This article is written from the English captions of the Spring 2026 Lecture 12 recording published by Stanford Online, with notation matched to the end of Chapter 14 and to Chapter 15 of the 2026 main notes. I did not see the board, so the formulas written on it are reconstructed from the notes.
This lecture has two topics that have nothing to do with each other; they just landed on the same day. The first 34 minutes finish the diffusion loss that the previous lecture left open, and the conclusion is that the whole training objective can be written as "make the network guess the noise that was added." The last 40 minutes open the next four or five lectures on large language models: the two-stage paradigm of foundation models, and how to adapt a pretrained model to a new task when you have labeled data, covering linear probe, finetune, LP-FT, and LoRA.
The YouTube title says Representation Learning. In practice, representation learning shows up in this lecture as a single definition (from 47:51), used to set up the linear probe; twice the lecturer says that how representations are trained is left to the next lecture. So the title reads more like the name of the unit than a summary of these 76 minutes.
Prerequisites: the forward process and ELBO from the previous lecture, conditional distributions of a multivariate Gaussian, and backpropagation. After reading, you should be able to derive the noise-prediction loss from the posterior mean yourself, work one training step and one sampling step by hand, and say how much LoRA saves on each of three things: compute, memory, and serving many users. For the whole course, see the Stanford CS229 Course Overview.
The lecturer is Tengyu Ma. In the first two minutes (00:05–02:11) he lays out the remaining seven or eight lectures: one on what people did before GPT became mainstream, then training autoregressive language models, post-training of language models and reinforcement learning, with reinforcement learning basics and robotics applications mixed in, plus one guest lecture on machine learning systems.
First half: the diffusion loss
Where the previous lecture stopped (recording 02:11–07:35)
Set up the notation first; all of it carries over from the previous lecture. The forward process is a fixed noising chain, is the clean image, and is close to a standard Gaussian. With and , the previous lecture gave the one-shot form:
The reverse process is the model to be learned. Every step is Gaussian, with the mean output by a neural network:
Taking the ELBO of leaves three kinds of terms:
The previous lecture only handled the last group, the terms. The true posterior is the Gaussian , and the model's variance is deliberately chosen to be the same . For two Gaussians with the same covariance, the KL reduces to the difference of the means:
The expectation is over : draw an from , compute the two means, subtract and square, then average over the randomness of .
The two remaining terms: one is zero, one looks like the rest (recording 07:35–14:58)
The terminal term . is defined to be a standard Gaussian. When is large enough, the noise washes out the signal and also approaches a standard Gaussian. The two distributions are the same, so the KL is zero (strictly, it tends to zero as grows), and it is simply treated as zero. The notes add another reason: this term does not contain at all, so even if it were not zero it would not affect training.
The last-step reconstruction. The notes call this term (in the captions it sounds like "L1"; this article follows the notes). The derivation takes four steps.
Step one: the reverse model is a Markov chain, so given , the variables carry no further information, and .
Step two: the model for the step was never specified, so make it Gaussian like the other steps: .
Step three: take the log of the Gaussian density. Everything outside the exponent becomes a constant, leaving the quadratic inside the exponent:
Step four is a notational arrangement: define . The expression above then becomes times a coefficient, the same shape as for .
This definition should not be just a way to force the shapes to match; it has to be checked against the formula for . Apply the one-shot formula at (where and ) and solve for :
The next section derives, for , . Plug in : , which is exactly the line above. So one formula holds all the way from to . The lecturer's comment is that there is a more fundamental reason behind it, but you can also treat it as a coincidence caused by different notation at the boundary.
At this point, the ELBO to maximize equals (equation (14.17) in the notes, with already dropped), which means minimizing the sum of squared errors over all time steps. The subscripts line up as follows: covers , and covers . The name is always one less than the it uses.
Drop the coefficients, then look again at what this loss compares (recording 14:58–19:09)
The lecturer then mentions a practical detail: the coefficient in front of each term (, ) is simply dropped in implementations, leaving
Then he restates what each of the two means stands for, and this part is worth pausing on:
- is the model's guess for the mean of when it sees only .
- is the true process's reconstruction of when it knows both and . The previous lecture showed it is a linear combination of and .
The loss asks the model's reconstruction to stay close to the latter. This is an algorithm you can implement directly: draw , run the forward process to get , compute from the formula, feed into the network to get , compute the squared error, and backpropagate.
Here is a point the lecture does not spell out and that often trips up self-learners (an addition in this article): the model cannot see , so how can it match a target that contains ? The answer is in the expectation. The minimizer of a squared error in expectation is the conditional mean, so the best is , an average over every that could have produced this . The model does not have to guess the of any single data point.
Where the posterior mean comes from, and switching to noise prediction (recording 19:09–26:34)
At this point the lecturer is not sure whether the previous lecture explained where comes from, so he goes back and gives the idea: conditioned on , and are jointly Gaussian, any conditional distribution of a joint Gaussian is still Gaussian, and the appendix of the notes has a ready-made formula to plug into. The lecture only gives the route; the calculation below is an addition in this article, following Lemma A.1.2 in the notes. The guide to the previous lecture took the Bayes-rule, complete-the-square route. Here we take the route in the notes, and both give the same and .
Given , the coordinates are independent, so look at one dimension:
- has mean and variance .
- has mean and variance .
- Their covariance is , because is independent of .
The conditional Gaussian formula is . Set and :
The coefficient of is . Use to factor out ; after putting the bracket over a common denominator, the numerator is . The variance uses the other half of the same lemma, :
Put together:
The coefficients look complicated, but they are just two scalars. Now comes the main line of the lecture. , , and are tied together linearly by the one-shot formula; knowing any two gives the third, so can be swapped out. Substitute :
- Coefficient of : .
- Coefficient of : .
So
Now the target contains only and . is the network's input, so it is already known. The lecturer's point is: why make the network learn the part you already know? Hard-code it into the formula and let the network handle only the unknown piece. So parameterize the model's mean in the same shape, with the network outputting only an estimate of the noise:
Subtract the two and the term cancels completely:
Square it and multiply back the original :
"So basically, you turn this reconstruction into a noise prediction problem." (25:31)
is the noise that was added to build in the first place, and the network's job is to look at and guess it back. Then the coefficient in front is dropped once more, leaving only .
The two "drop the coefficient" moves need to be kept apart (this paragraph is an addition in this article; both times the lecture only says to drop the coefficient). Dropping in the form and dropping the whole coefficient in the form give two different weightings, which differ by a factor that varies with , . What the lecture ends up using, and what (14.28) in the notes writes, is the unweighted version in the form.
Five steps to train, one loop to sample (recording 26:34–32:04)
Training (notes pp.187–188):
- Draw an from the training set.
- Draw a time step uniformly from to . The original objective is a sum of terms; here one term is picked at random each time, the same idea as stochastic gradient descent drawing one data point at a time.
- Draw noise .
- Build .
- Compute the gradient of and update .
Most texts write simply as . The lecturer's take is that it is a random variable anyway, so the name does not matter. The notes give the reason more fully: the for different are correlated with each other and not i.i.d., but each training step uses only one time step and only needs its marginal distribution to be a standard Gaussian, so the subscript serves no purpose. The loss in step 5 is named after equation (14.28) in the notes, with the subscript being the sampled time step; it corresponds to in the ELBO decomposition, and the off-by-one is only naming.
Sampling:
- Draw .
- For : compute , plug it into the formula above to get , then set with .
Each step of the reverse process carries its own noise, hence the ; we chose earlier, so . The notes have one detail the lecture does not mention: at the last step (), set and add no more noise.
Working one training step and one sampling step
The following is an example made up for this article, not from the lecture. The data is one-dimensional, with and , and we look at the step .
Schedule quantities first. , , , , and .
Build . Take and suppose the sampled noise is :
Compute the posterior mean two ways. In the form with : the coefficient of is and the coefficient of is , so . In the form with noise: , and . Both routes give the same number, so the substitution in the previous section was done correctly.
Compute the loss. Suppose the network currently outputs (the truth is ). The noise-prediction loss is . In terms of means, , , and the square is . The ratio of the two, , is exactly . The fully weighted ELBO term is , which equals .
Take one sampling step. If this were a step during generation and we drew , then .
These numbers show three things. Comparing means and comparing noise measure the same error, up to a multiple set by the schedule (here ). Dropping the coefficients amounts to changing every time step's multiple to . For a single on its own, the loss is multiplied by a positive constant, the minimum sits at the same , and the optimum does not change; what changes is the relative weight across time steps, and when one network has to serve every and cannot reach the optimum at each one, the weights decide which time steps it leaves the error on. Finally, guessing the noise too low makes the model's mean too high. The directions are opposite because the noise enters the formula with a minus sign.
Why diffusion models are easy to learn, and one student question (recording 32:04–36:40)
The lecturer first says there is no strong theory that proves everything; what follows is intuition. First, one direction is a fixed noising function, so you do not have to parameterize both the forward and the reverse process; people have tried using learnable functions on both sides, and the optimization was harder. Second, the price is a very long time axis (the original approach used of 1,000), but once it is stretched out, each step's reconstruction becomes locally simple: starting from pure white noise, outlines and rough shapes come first, then sharpening and detail step by step. A neural network can in principle represent anything, but how it represents it and how it learns it still matter, and diffusion models split one big generation task into many small steps that are easy to learn.
A student asks how the parameters actually get updated, and the lecturer's answer works as a way to read the second half of this course: once the loss function is defined, everything else can be computed. Write the network and the loss in PyTorch, compute the gradient, take a step. New applications or algorithms mostly innovate at the level of the loss; you can also innovate at the optimizer level, and a new optimizer then works for diffusion models, language models, and linear regression alike. The coming lectures are mainly about data, architecture, loss functions, and training procedures, and no longer about how to compute gradients.
Second half: the foundation-model paradigm and adaptation methods
Pretraining plus adaptation (recording 36:40–46:51)
The lecturer starts with where the term "foundation model" came from. After GPT-3 came out in the summer of 2020, Stanford professors gathered in a room to play with the OpenAI playground. There was no ChatGPT then, only a text box where what you wrote and what the model generated appeared in the same field; you could adjust hyperparameters such as temperature, and a dropdown on the right let you choose the model. Later Percy Liang led a group studying this new paradigm, wrote a survey, and coined the name. The lecturer says he looked it up the day before: the survey's abstract calls it an emergent paradigm, and his own lecture notes say the same:
"But I think after three years, we probably should just not call it emergent paradigm. It's the new paradigm." (38:26)
He also warns that five years ago this paradigm covered a broader set of techniques, some of which are now outdated; the next lecture or two will cover what was popular from 2019 to 2022, then the mainstream after 2022.
The paradigm has two stages.
Pretraining. Use a huge amount of unlabeled data, several orders of magnitude more than before, and very messy: scrape whatever can be scraped from the web, HTML files with their tags, Word files, documents in other formats. The training data of the early versions was quite messy and was only cleaned up gradually later. As a formula it is plain: is the parameters, each data point has a loss, and you take the average:
There are only two differences from supervised learning: no labels, and is very large. What actually is comes in later lectures. The parameters the optimization produces are written .
Adaptation. Start from a good foundation and adapt to all kinds of downstream tasks. The old approach was one model per task, and people doing multi-task learning trained at most three at once. Now the number of tasks has almost no upper limit; the lecturer says the GPT paper evaluated around a hundred tasks, and eventually the very notion of a "task" became hard to define.
Adaptation depends on two things: how much downstream data you have and of what kind, and which technique you use. On the data side, the downstream dataset is pairs :
- When is small, around 5 to 10 examples, it is called few-shot.
- When and you ask the model to solve the task from a text description alone, it is called zero-shot.
The lecturer says one of GPT-3's breakthroughs was that sometimes even few-shot was unnecessary, and today almost nobody collects downstream labels in order to adapt a model. But from 2019 to 2022, labeled downstream datasets were still the norm, for example collecting a small sentiment classification dataset and then adapting the model. On the technique side, this lecture and the next cover adaptation methods that update parameters; methods that rely only on prompts and leave the parameters alone come later.
Representations and the linear probe (recording 46:51–54:50)
To talk about adaptation with labeled data, you first need the concept of representation learning. It is one kind of pretraining: what gets trained is not a chat model but a model that turns data into a vector
This vector is called a representation, also a feature or an embedding. Training yields and therefore a fixed function ; put any data in and a vector comes out. The loss used to train it is the subject of the next lecture.
A linear probe adds a linear head on top of this fixed representation: an -dimensional vector , with the prediction being the inner product , followed by a softmax for classification. Taking regression as the example:
is fixed, so each data point's is a fixed vector and the only variable is . This is the same problem as the linear regression from the very start of the course, except that the input features have changed from the raw to the representation. It works far better than hand-designed features or a linear model on the raw , because is usually not a linear function of , while the representation turns the semantically important information into a form that can be read off linearly.
The lecturer mentions in passing that the linear probe is still a tool in mechanistic interpretability research on language models: even if you do not use it to solve a task, you can use it to probe what the model represents internally.
There are two student questions in this part.
One asks whether foundation models are built per domain or are general. The lecturer says that three or four years ago vision and language each had their own way of learning representations; now people want multimodal capability, with one model taking in images, text, and even video, so the methods have to be unified, and in 2026 many models are called omni or multimodal models. The representation-learning-plus-linear-classifier recipe from this lecture is more common in vision and is still used in medical imaging: extract the representation first, then for each kind of imaging task train a small linear head on a small dataset.
The other is sharper: on what grounds do we assume the downstream task is linear in the representation? The lecturer says this is not really an assumption. The pretraining loss itself pushes the representation toward being linearly usable, and it will be clear once you see the concrete loss in the next lecture.
Finetune, initialization, and LP-FT (recording 54:50–1:02:20)
Finetune differs from the linear probe in exactly one place: also becomes a variable.
Here the lecturer points out something worth thinking about. This loss function carries no trace of pretraining at all. You could use the identical loss and start from a random and a random , and that would be training a giant model from scratch. The only place pretraining enters the problem is the starting point of , and the result is much better.
"because it's the same loss function. Just initialization are different." (56:19)
His inference: this loss has a great many global minima, possibly millions, and they are not the same as each other. With little downstream data, the training loss can almost always be driven to zero, so "good or bad" refers to test performance. Starting from a random point lands on some solution with zero training loss but poor test performance; starting from the pretrained lands on another solution with the same zero training loss but much better test performance.
A student follows up on what exactly pretraining produces. The answer is , a concrete set of numbers under a given architecture. The architecture has to be fixed first, and pretraining and adaptation must use the same one, otherwise there is no way to interpret those numbers.
LP-FT is linear probe first, then finetune. Write the loss as :
- LP: fix and minimize over only, giving .
- FT: start from and minimize over both and .
The lecturer says that if you go down this road, LP-FT is probably the main approach today. As for why it is better:
"I think we don't know exactly either." (1:01:27)
He says there is some theory on this, and gives his own rough explanation: with direct finetuning, is random and is pretrained, and a random sometimes damages the representation a little. Fix first so that fits the representation, then train both together; the representation still changes, but by less than it would with a random head.
LoRA: change only along low-rank directions (recording 1:02:20–1:07:36)
LoRA (low-rank adaptation) does not depend on which loss you use for adaptation; as long as you are minimizing some loss and not doing zero-shot, it applies.
The motivation goes like this: finetuning changes every parameter in , and a pretrained model has billions of parameters while the downstream data is tiny. The word "adaptation" itself implies you should not need to change much. Changing everything invites overfitting and is overkill. So what about changing only some of the parameters? The difficulty is that you do not know which ones to pick. LoRA's answer is to let every parameter move but restrict the degrees of freedom of the change.
For a weight matrix, reparameterize the model as
where is the pretrained matrix, kept fixed, and only and are trained. Ordinary finetuning minimizes starting from ; LoRA minimizes , with and as the variables.
Degrees of freedom. A matrix has degrees of freedom, while and together have . The lecture's numbers are and : and , only 2% of the original.
Initialization. Set and random. Then , the starting is just , and before the first step the model behaves exactly like the pretrained model.
A tiny example confirms the mechanism (made up for this article). Take and ,
Initially is the zero matrix and the output is . Suppose that after a few training steps ; then and the output becomes . The two rows of the update are proportional, so its rank is 1, but itself is still full rank. What is low-rank is the change; the adapted matrix is not low-rank, a point the notes stress on p.195. Also, in this example equals , so not a single parameter is saved; has to be smaller than before any saving starts.
A student asks why not just add a matrix. Because that brings you back to degrees of freedom. Another asks whether a product like introduces some kind of symmetric bias. The lecturer says and are not equal, so there is no extra symmetry and the only restriction is low rank; and low rank is itself a bias.
The lecture's notation differs from the notes in three places, which matters when you look things up. The notes write the update as with and , so the two letters swap roles relative to the lecture. The factor initialized to zero is actually the same one on both sides, the left factor of the product with shape ; the lecture calls it and the notes call it (the example in the notes is ). The body of this article uses the lecture's throughout. The notes allow a non-square , with trainable parameters. The notes also have a scaling coefficient, , which the lecture does not mention.
Here are this lecture's four adaptation methods side by side (compiled for this article; means a weight matrix inside that LoRA rewrites):
| Method | Which parameters are trained | Starting point | Do the pretrained weights change? |
|---|---|---|---|
| Linear probe | Only | random | No, fixed at |
| Finetune | and | random, | All of them change |
| LP-FT | First only , then and | The second stage starts from | They change in the second stage, usually by less |
| LoRA | Only and for each rewritten matrix | , random | does not change; what is actually used is |
The first three differ in which parameters are variables and where they start. LoRA is a choice along a different axis: it prescribes what the change in the weights looks like, and it can be combined with any of the approaches above that update .
What LoRA saves (recording 1:07:36–1:15:45)
The last eight minutes are the most useful part of the second half. The lecturer does not hand out the answer; he checks one item at a time.
Compute: almost nothing saved. A student first answers "fewer parameters," and the lecturer says yes, but fewer parameters does not mean faster. In the forward pass every layer still computes ; the part cannot be skipped and it is the bottleneck, while is cheap. Backpropagation has to pass gradients backward and still multiplies by . There are two kinds of derivatives in backpropagation: with respect to activations and with respect to weights. The activation path saves nothing; the weight path saves a little because there are fewer trainable parameters.
"So largely speaking, your compute don't really change much." (1:08:37)
Memory: some savings, but not night and day. still has to sit in memory. During training, memory holds not only the parameters but also the gradients and the optimizer state (one student mentions that Adam tracks momentum). These are stored only for trainable parameters, so LoRA only needs them for and , and that is the saving. The lecturer says offhand that gradients plus optimizer state cost "12 times or 6 times" as much as the parameters themselves, and admits he does not remember exactly; do not cite this multiple as fact. He then adds a systems observation, saying he does not expect everyone to follow it: in large-scale multi-GPU training, gradients and momentum can be sharded across GPUs, so they are not necessarily the memory bottleneck to begin with. The notes put it this way: neither the base weights nor the activations that backpropagation has to keep get any smaller under a low-rank parameterization, and when these two dominate memory, LoRA's training-time memory saving is limited. Taken together, there is a memory saving, but in the lecturer's words it is not a night-and-day difference.
The two situations where it really matters. The first is when memory is right at the edge: saving 10% takes you from two GPUs to one. In that case any saving matters a lot, but it only happens when you have very few GPUs. The second is what the lecturer considers the main benefit, many users sharing the same :
"So in my opinion, that's probably the major benefit of LORA, which you can serve many, many users." (1:15:45)
Each user has their own , and only one copy of is stored. At inference time, whoever's request comes in gets their low-rank matrices swapped in. The adapters of a large share of users can be preloaded into GPU memory, so switching is fast; those not preloaded are loaded from CPU, and small matrices still load much faster than full ones. He cites the finetuning services of commercial models as an example (naming GPT and Gemini), says what these services give users is LoRA-style finetuning, and believes this is the reason. This is the lecturer's statement and conjecture in class; how each provider does it internally is not necessarily public, so do not cite it as confirmed fact.
The numbers he gives out loud are about 100 million parameters per user, 1,000 users, and a total of "about 10 billion." Multiplying it out gives , which is 100 billion, so the spoken numbers do not add up. The conclusion is unaffected: the comparison is against storing a full set of weights per user, and one set of low-rank matrices per user is far smaller.
The notes on p.195 have two more points the lecture does not get to: the same sharing idea also applies to multi-tenant training (several training jobs sharing the base weights); and LoRA is a trade-off in expressivity, so when the downstream distribution is far from pretraining or needs large changes, full-parameter training may still be better.
Self-check
-
Take , , , , and change the network output to . What are the noise-prediction loss, , and the weighted ? Answer: The loss is . , which is below ; guess the noise too high and the mean comes out too low. The weighted term is . Check: your divided by should be .
-
Why define ? Is this definition consistent with the formula for ? Answer: So that the last-step reconstruction term has the same shape as the other terms. The consistency check is to plug into and use to get , which is exactly the you get by solving .
-
During training, why can be written as with no subscript, when the for different are correlated? Answer: Each update samples only one time step, the loss uses only that one , and all it needs is for its marginal distribution to be . Correlation across time steps does not appear in a single step's loss.
-
Pretraining is nowhere to be seen in the finetuning loss function. How does pretraining have any effect? Answer: Only through the initial value of . With little downstream data, the loss has many minima with zero training error, and they differ in test performance; the starting point decides which one the optimization lands on. You have only answered correctly if you can say "the training losses are all near zero; the difference is in test performance."
-
One layer is a matrix and LoRA uses . What fraction of full finetuning's parameters are trainable? Roughly how much forward-pass compute is saved? Answer: and , about , which is . Forward compute is barely reduced, because still has to be computed, plus a little extra for . Answering "compute also drops to 1/256" confuses the number of trainable parameters with the amount of compute.
Corresponding reading
The main notes, main_notes.pdf (August 2026 edition):
- Section 14.3, Training diffusion models by maximizing the ELBO (pp.184–188): the ELBO decomposition (14.15)–(14.17), the posterior mean (14.18)–(14.19), the rewrite in terms of noise (14.22)–(14.24), the term (14.25)–(14.26), and the training and sampling algorithms (14.27)–(14.29). The conditional Gaussian formula is Lemma A.1.2 in the appendix.
- Section 14.4, Continuous-time view of reverse diffusion (pp.188–190): uses stochastic differential equations and the score to explain why the reverse process is Gaussian. The lecture does not cover this section at all.
- Chapter 15, Foundation models overview (pp.191–195): Section 15.1 covers linear probe, finetune, and LP-FT; Section 15.2 covers LoRA.
Where the lecture and the notes differ:
- For the terminal term, the lecture says it is zero as ; the notes additionally point out that it does not contain , so it can be removed from the objective outright.
- At the last sampling step, the notes set ; the lecture does not mention it.
- On why LP-FT works, the lecture says it is not fully understood; the notes cite Kumar et al. (2022), saying the method is meant to reduce the feature distortion caused by finetuning and can improve out-of-distribution performance in some settings.
- Section 15.1 of the notes mentions continued pretraining (keep training on new data with the pretraining loss); the lecture does not cover it.
- LoRA's notation, the scaling coefficient , and the expressivity trade-off, as listed in the previous section.
Series navigation: Previous: Lecture 11: diffusion models | Next: Lecture 13: contrastive learning and semantic search
Course video sources
Original video: Stanford CS229 Machine Learning | Spring 2026 | Lecture 12: Representation Learning
- Stanford CS229 Machine Learning | Spring 2026 playlist (Stanford Online, 17 videos)
- CS229 course website
- CS229 main notes, main_notes.pdf
Checked: 2026-10-12.
Content check: verified against the video transcript (2026-10-12): the whole article was compared section by section with the English captions of this recording, and the time ranges come from the caption timestamps. I did not see the board; formulas are reconstructed from Chapters 14 and 15 of the main notes, and places where the captions clearly misheard (for example "linear head" transcribed as "linear hat") have been corrected to follow the notes.
References
- Stanford CS229 Machine Learning | Spring 2026 | Lecture 12: Representation Learning (YouTube): the basis of this article; the lecture's statements and quotes all come from the English captions of this recording.
- CS229 main notes, main_notes.pdf: Section 14.3 (pp.184–188) was used to reconstruct the board formulas and equation numbers, and Chapter 15 (pp.191–195) to compare how linear probe, finetune, LP-FT, and LoRA are written.
- Stanford CS229 Machine Learning | Spring 2026 playlist: to confirm the lecture number and video title.
- CS229 course website: the course entry point.
- Stanford CS229 Course Overview: the overview and reading route for this series.
Loading...