So today we're going to talk about
architecture, which at least to me has
always been pretty inscrutable.
Um and so I'm going to take the approach
of just telling you kind of everything,
right? I'm going to go through all of
the modern papers.
Um and we're going to just look through
what has everyone done? Um and so I've
titled this everything you didn't want
to know about architectures and
hyperparameters because I think we all
wished we lived in a world where the
only things you had to know were like VC
dimension or something, right? Like very
simple, you know, theoretical tools, but
that's not really where we are.
So okay. What we are going to do is we
are going to try to understand
architecture from kind of like a survey
lens, right? The best thing to do, you
know, better than listening to this
lecture even is for you to go out and
like train your own models and try
different architectures, right? That's
by far the best thing to do. That's part
of the philosophy of the course. But
we're not going to be able to cover the
whole design space of all the different
architectures that are out there, right?
Like that's not something that we have
the compute or the time to do.
So my opinion is the second best thing
that we could do is to try to learn from
the experience of others, right? What
has What has everyone else done? What
are the choices that they are making,
right? And by looking at kind of a
broader, somewhat zoomed out picture,
maybe we can start to understand, oh,
these are the kinds of parameters and
choices that are sort of fixed across
all effective architectures and these
other ones can be sort of varied without
impacting
how the model performs, right? So I'm
going to talk about, you know, basically
transformer variants. Like what is the,
you know, modern transformer starting
with, you know, the Vaswani paper and
then, you know, as we go to more modern,
more recent architectures, what do they
have in common? And then what are we
allowed to vary? Or not allowed, but
what do people vary as they go through
this, right?
So
I think many of you have taken an NLP
course of some kind or at least seen a
transformer, so you've probably seen,
you know, the very vanilla transformer
from Vaswani et al. Um you know, there
there are some fairly standard choices
that you make. You say, oh, transformers
don't have positional dependence, so
we're going to add a position embedding.
And what do we do? We're going to add
some sines and cosines.
Um we're going to have information
processing through a ReLU. Um and then
we're going to have a a post norm. I'll
talk about what exactly that is later.
Um and when you look at your assignment,
your A1, you're going to notice some
differences between the standard or the
vanilla transformer and what we've asked
you to implement. Well, we're going to
ask you to move the layer norm to the
front of each transformer block or the
non-residual layers. We're going to ask
you to implement something called rope.
Um
and we're going to ask you to implement
something called SwiGLU and not ReLU.
Right? Why do we pick these? Um one
reason is we've, you know, copied a lot
of this over from LLaMA, but so did
everyone else. Really, I think if you
were to train on your own language
model, I think you'll quickly run into
this question of, oh, there's so many
choices, right? Like what do I choose
for all these things?
And so let's now sort of walk through
all these different models.
The way I kind of think about
architectures is to think about to look
at all the different things people have
done and say, what are the things that
people have done? Can we pick and choose
from those?
Um Percy always makes fun of me for this
a little bit, but you know, I try to
look at all the the different models
that come out each year to try to make
this lecture.
Um and last year I thought, oh, there's
just a couple papers. It's going to be
fine. It's going to be fine. And then I
look through all the things and there's
a lot of papers. There's Qwen 2 and
Gemma 3
and InternLM2.
and then there were even more. There's
like NeMo Tron 4 and Qwen 2 and oh oh my
goodness, there were 19 new dense
models. And so last year I had my work
cut out for me.
And then this year, you know, I thought,
well, there can't be that many new LM
releases. Like it's got to be slowing
down, right? Like people can't keep
training 20 dense LMs per year. Um and
that's technically right. There aren't
that as many dense LMs. Initially, you
know, I was like, oh, there's Qwen 3,
Gemma 4 just came out last Thursday, so
I put that in there. And almost 3. You
know, there's only a couple. And of
course I have to give a shout-out to
Percy's own 8B model trained with
Marine. And I was like, oh, we'll just
have a few things to cover. Um but it
turns out if you start looking, there's
a lot of different models. Um and so the
fact that we have so many different
models, most of these actually are MoEs,
mixtures of experts, and I'll be talking
about that tomorrow rather than today.
Um because we have such a big diversity
of models, we actually get a pretty good
picture of all the different choices
that we can make. Um
so I I made this like little table.
We'll come back to this little table at
the end of the lecture.
Um but basically at this point, you
know, starting with, you know, the
original transformer, there's been
actually quite a few autoregressive
language models kind of trained on the
same class of things.
Um and you can ask questions like, what
are the different vocabulary sizes? Or
what kind of layer norms do we use? Or,
you know, what kind of position
embeddings do people use? And we see
some fairly clear trends. I'll be
talking about this as we go.
Okay.
Um so
the goal here is that we're going to
cover couple different things. We're
going to cover common architecture
variations. So these are different
building blocks of the transformer.
Um and after we've established what the
standard building blocks are, like, you
know, what do we use for the the
nonlinearities or what do we use for
position embeddings, then we're going to
talk about hyperparameters. We're going
to go down even lower detail and say
like, you know, what is FF dim? Um
should we make that a multiple of four
or like multiply the the hidden by four
to get FF dim? How many vocab elements
should I have? Um
and then after that, we're going to talk
about very low-level tricks of how to
get models to train stably. And the
reason why I'm going to talk about that
in this lecture is because these
stability tricks have a pretty close
connection with the architecture
variation, right? Um one of the things
that, you know, higher level I want to
sort of impress upon you is that
architectures are actually a a very
complex set of tradeoffs, right? Like
what does a architecture have to do?
Well, it has to learn from data, so it
has to generalize. It has to train
efficiently on GPUs. And it has to not
blow up, right? Like halfway through
training, if your, you know, training
losses just go like down like this and
then suddenly blow up, that's no good at
all, right? So all these different
requirements end up getting baked
straight into the architecture. And
that's why these things are a little bit
messy and a little bit complex.
Um but you should keep that in mind and
that's why, you know, things aren't in
many ways not so elegant.
So we're going to start with the core
architecture piece. And as a high-level
view, you know, I think the the way that
I see a lot of the architecture stuff,
you know, looking basically
historically, is kind of in the early
days of, you know, starting with the
transformer until, you know, GPT-3 or
so, there's a lot of experimentation
that happens. People try lots of
different things. There's no like gold
standard that everyone has unified on.
And then, you know, LLaMA 2 comes out
and everyone's like, wow, LLaMA 2 is
great. I want my own LLaMA 2. And so
everyone starts training LLaMA 2-alikes
with, you know, minor variation
that people have. And then finally, you
know, last year we saw really big
differences or or sort of a trend
towards architecture modifications that
make training more stable. And this year
we see lots of trends towards
architecture variations that enable
longer context dependence. So there are
these big themes that are happening, but
really I think, you know, you see this
like big point when LLaMA 2 comes out
and everyone's like, wow, I want to
train something with that. And then
suddenly, or not suddenly, but after
that, people are starting to explore
once again. So it's kind of cool to see
all these different changes.
Um I think people can disagree about a
lot of things on architectures, but
there is one thing that everyone agrees
on, you know, like if you take the
transformer paper, I think a lot of
people will say like the transformer
people got like most of the things
got like most of the things
right, except this. And the thing that
they really did not get right or like I
think most people agree they did not get
right is where you put the layer norm,
right? So in the original um
? So in the original um
uh transformer paper, you know, the
layer norm goes in what you would call
the residual path, right? So in the
transformer, you know, you have the
residual stream, this X that kind of
runs through the whole network. And
sort of a delta back into this residual
stream.
And then in order to make sure that
these gradients are sort of stable
across layers, you know, a layer norm is
placed at the end of each of these
components.
Now, um
instead of putting the layer norms in
the residual stream, there's an
alternative. Um I'll refer to this as
pre-norm,
um in which you can put the layer norm
outside of the residual stream, but
before each of the computations. So you
can put it before the multi-head
attention, you can put it before the
FFN, right? Um we'll call this pre-norm.
the nomenclature will get a little bit
confusing. Um You can call this uh
post-norm for now, but let's call this
sort of residual norm, right? Cuz you're
putting the norm in the residual layer.
Um basically all modern language models
uh push the layer norm outside of the
residual stream. This is just like a
thing that basically everybody does.
Um there is one funny exception, but it
is OPT-350M.
And if you all are familiar with sort of
language models, we kind of know OPT in
general was, you know, kind of a mess of
a language model, right? And OPT-350M
um is even more so because I don't know
why only that model uh has a post layer
norm in the residual stream.
Okay. So this is one of the things that
like everyone agrees on. And so you
might wonder like why is this like such
a, you know,
uh like a uni- unified thing across all
the different models?
Um and if you look at some of the early
works studying like where do you place
the layer norm style research, um what
you really see is that, you know, the
early motivation for a lot of this was
when you train a transformer, you need
to do a warm-up. Actually, you know,
modern transformer training still does
warm-ups as well. But you definitely
need to do warm-up when you train.
Now, wouldn't it be nice if we could
remove the warm-up, right? So, that was
kind of the initial motivation for a lot
of this research.
But people quickly realized that
removing the warm-up had very serious
issues in terms of the stability and
convergence
of these things, right? So, if you did
post norm plus layer norm, which is, you
know, basically the original transformer
thing, you got this purple dash line.
Oh, you just don't converge as well
compared to doing something like pre
norm. You can ignore the other terms.
You would get much nicer convergence
even without warm-up, right? So, this
was the original motivation.
But really what people kind of quickly
realized is that, you know, moving the
layer norms outside the residual stream
has some pretty important implications
as you make your network deeper and as
you start to grapple with stability
issues.
To me, I think the gradient attenuation
issues are kind of the most clear.
When you sort of talk to people who do
architecture design, I'm not really one
of the the people that deeply engages in
this. But one of the things that people
often say is keep your residual stream
clean, right? So, in this case, you have
your X's coming in from the bottom on
the pre norm side, and this X propagates
all the way up to the top, right? All
the way up to your your final output.
And that allows gradients to propagate
if you in the backward pass straight
through this, right?
Um that makes gradient propagation very
simple,
which improves both stability and signal
propagation. And that's sort of what
people realized very, very quickly, that
if you do something like pre norm in
blue
initialization, sort of the gradient
size is kind of remains the same, right?
Because you have this nice straight
through propagation in the backward
pass. On the other hand, if you have
post layer norm, you have these kind of
complicated effects that happen because
you're layer norming each time you're
going through a transformer block. And
that's going to change the norm of your
gradients as you go backwards through.
So, you can kind of see,
you know, from the principle of keep
your residual stream clean, that pre
norm makes a lot of sense.
People also realized through
experimentation that this also improves
stability in general, that the sizes and
frequencies of gradient spikes
were improved under pre norm compared to
post norm. And, you know, this is a
figure from Salazar and UN, who were one
of the first ones, I think, to to study
this phenomena carefully.
I think this is the reason why it stuck
around, right? Stability and the ability
to go deep are both very, very important
for modern large language models. And
so, this idea of moving your layer norm
outside of the residual stream is one
that basically everyone has adopted.
Um so now, you know, if putting layer
norms in residual streams is bad,
why does layer norm have to be at the
start? Of course, we have pre norm,
which is, you know, before our
computation, but we could have it after
computation as well, right? That's
as well, right? That's
equally good at least under that
knowledge logic.
Um and that's exactly right. Many recent
models like Grok or Gemma 2 or Olmo 2
have the structure where they moved the
layer norm after the computation. So,
it's a post norm of a kind, but it's
outside the residual stream.
Other models still actually just put
layer norms everywhere. They put a layer
norm here, they put a layer norm after.
I'll get to this later as we talk about
stability, but one of the other lessons
that it seems to have held up very well
is if you have stability issues, you can
kind of sprinkle in layer norms
everywhere, and that will generally
improve stability.
It's almost very strange to be saying
this cuz it's so ridiculous. And yet,
that statement has actually been proven
right. Every time, you know, people have
encountered stability issues, they say,
"Oh, but what if we just throw a layer
norm into attention?" Turns out that
works, too. We'll get to that later. So,
okay, that's post norm
or double norm in this case where you
have two layer norms here.
Okay. The other thing that you can do is
in the original transformer, you have
the layer norm, which is this operation
right here. So, you have your
activations X.
You're going to mean subtract, divide
the variance, and then scale it back up,
right? And this works just fine, right?
It's not like this is wrong. And many
models have successfully trained on this
scheme.
But basically, most or all modern
models, I think,
use RMS norm, which doesn't subtract the
mean or add a bias term, right? So, it's
just a scaling down and scaling back up,
right? So, you can see this in the
equation here.
Um and really, layer norm is more
expressive than RMS norm. So, there's
really representationally no reason why
you have to use RMS norm.
But RMS norm is nice because in
practice,
there's really no expressiveness loss.
RMS norm models just as well as layer
norm. But more importantly, it is, you
know, faster, right? This is the part
where kind of the systems and sort of
architecture co-design starts to come
in.
Percy mentioned, you know, in the
previous lecture, this idea of
arithmetic intensity, right? We want to
keep our GPUs hot by doing, you know,
matrix multiplies and other very intense
computations. We do not want to be
wasting our GPUs by having them move
little tiny bits of memory back and
forth, right? That's a very inefficient
use of our, you know, very powerful GPU.
And so, what we want is to remove
operations that are small and involve
memory movement, but don't give us much
expressive power, right? So, by that
view, what we really want to be doing
here is, you know, if the mean
subtraction and addition isn't really
doing much for us, just get rid of it,
right? Um
you might think, "Okay, why does this
matter? We're just optimizing this
teeny, tiny operation that accounts for,
you know, in this case, something like
0.17%
of the total floating point operations
of our system."
But, you know, as Percy mentioned, it's
not really about the flops, right? The
flops are the the floating point
operations we do, that's sort of
multiplying matrices, but that's not
runtime, right? Runtime is a much more
complicated object. And, you know,
statistical normalizations, things like
layer norms, even though they're only
0.17% of the flops, depending on your
workload and depending on the setup, can
be up to 25% of the runtime, right?
That's kind of crazy. On tiny models,
this can be really, really big because
you're still having to move all these
parameters back and forth from fast to
slow memory and vice versa
when you're doing these operations. So,
data movement is really, really
important, and RMS norm can still matter
a lot because of this, right? So,
um
you can see kind of the difference here.
The arithmetic intensity is in white,
and then you can kind of see the flops
involved in black. And you see that
layer norm has a very low arithmetic
intensity, which is the operation we try
to want to remove as much as possible.
Yeah, question over there.
Data movement for normalization is so
disproportionate compared to arithmetic
contraction
So, for a ten- Something like tensor
contraction, which is, in this case,
matrix multiplies,
the majority of the workload is, you
know, multiplying. Whereas for stat
normalization, the majority of the
workload is memory movement. And memory
movement is quite slow. So, imagine the
case where like moving something is like
almost all of the compute, then you're
still paying quite a bit here, right?
Cuz activations can be quite large.
Yeah, I think the percent runtime in
this case is quite extreme. This is like
in the, you know, tiny models with like
matrices that don't really generally
make sense in modern workloads, but this
is, you know, giving you a sense of why
this is a free optimization.
Um and you do see this, right? This is
another paper in which people were
evaluating different architecture
interventions. They're on Get All in
2020.
I think this was a Google paper, and
they show, you know, for teeny, tiny
transformer of a 200 million parameters,
you got more steps per second. That's
the third column over here when you
switch to RMS norm. And in fact, you
actually get better performance, which I
don't think is something that you're
guaranteed, but it's a nice bonus
regardless, right? So, you got a free
systems win by just moving to RMS norm.
And so, basically, everyone has has
decided to move over to this now.
And in general,
there's a more general version of this.
There's no guarantee to any of the
things I'm saying, but bias terms in
transformers and neural networks
are generally not that useful. So, in
the original transformer, the linear
terms all have biases,
but most implementations actually just
drop the biases entirely, right? Once
again, this is another example of
something that's not very arithmetically
intense, but fairly memory
intensive, relatively speaking. And so,
ive, relatively speaking. And so,
you might as well just drop these,
right? And get the free systems win.
There's also some cases, I'll just
mention this offhand, where the bias
terms can also induce stability issues.
So, they're useful in other ways, but
really, I think the primary reason these
are dropped is just to simplify things
from the systems perspective.
Cool.
Okay. So, I think layer norms, the story
is pretty easy.
Um it's easy in the sense that what
people do is fairly standardized. Our
our understanding, not at like a deep
theoretical level, but our understanding
of like what layer norm does is fairly
good, right? Everyone moves the layer
norm outside the residual stream,
often pre norm, but I think this might
partially be be because Llama 2 did
that. Um and we roughly have a sense of
how to use layer norm to control things
like
gradient spikes
and keep signal propagation nice.
Related to that, we also now, you know,
basically always use RMS norm, and you
hopefully understand the general
principles here
of basically just dropping bias terms.
And that allows us to to keep our system
more arithmetically intense
while keeping the expressive power the
same.
Um I think the unsatisfying thing about
a lot of architectures is that, you
know, you can't really reason about this
beforehand, right? Like we don't know
beforehand that dropping the bias terms
that dropping the bias terms
is okay, but from a lot of
experimentation and now collectively
acquired knowledge, we roughly know that
dropping the bias terms on both the
linear and RMS norm is okay for typical
language modeling workloads, right? Um
this is the kind of statement that we
can make on the basis of of what we do
when we look at a variety of different
models.
Okay, any questions uh for layer norm
stuff?
Good. Okay. So, now I'm going to talk
about activations. Um
and there's a whole zoo of activations.
There's just a lot, right? Like ReLU,
GELU, Swish ELU, GeGLU,
SeLU, SwiGLU, LiGLU.
Um and what are these things?
Um I think at what point one point of
my, you know, more stats ML training, I
thought to myself I will never learn
these things. I will make it a point of
pride to never know what a SwiGLU is. Um
but now it's actually very important for
us to to actually like have a general
sense of what these objects are um and
which parts of these names actually kind
of matter for performance, right?
Um So, you can build and train a
language model on just a fairly vanilla
activation. Um
even, you know, I guess Chinchilla is
probably the best model out of that
group, but even if you just want a ReLU,
you know, you can train a reasonably
performant language model using just
that activation. There's nothing wrong
with that, right? And if we move to
GELU, which is a Gaussian error unit,
and really the only difference is this
tiny divot at the bottom here, which
really, you know, for the most of the
activation doesn't change anything, but
changes the gradients right near zero,
um then you can train models like GPT-3,
right? That's a perfectly good large
language model, not, you know, modern by
modern standards, but perfectly fine.
Um but then, you know, we get to the
gated linear units like SwiGLU and
GeGLU, and these are really where most
of the action is. You know, this is very
similar to layer norm in that I think
almost all credible modern language
models use a gated linear unit of some
kind.
Okay, so what is a gated linear unit?
So, these are gated activations. So, if
we want to look at something like a feed
forward layer, um we can just look at
this first part. This is, you know, a
very standard ReLU feed forward, right?
I have my X, I hit it with a W1, you
know, I I entry-wise threshold at zero,
and then I hit it with another W2, I get
my output, right? Very straightforward
ReLU network.
Another thing, um I don't say this as my
personal experience, but another thing
that is often said in architecture
design is that gating is often very
helpful. So, if you apply that very
general heuristic, what you might get is
to say, "Okay, well, instead of just
having, you know, this entry-wise ReLU,
why don't we also have a gate? And the
second gate, the second term here, this
is just going to multiply the output of
my ReLU entry-wise, and I have a second
matrix V, okay?"
Now, this is just going to modulate the
output of my ReLU.
Um and then I'm going to do everything
else the same, right? So, instead of,
you know, just having XW1W2, I have XW1,
and I'm going to gate that with XV. This
is another
uh activation the same size as this, and
then I'm going to, you know, down
project it back with W2.
Okay, so what is this? Now, this is a
RegLU. This is a you you make these
names by adding the first activation, in
this case ReLU, and GLU, right? So, the
ReLU gated linear unit.
Um and gating has been a, you know, very
effective other primitive in
architecture design, and it turns out
that this is very effective in language
modeling as well.
So,
um if you take something like a GELU,
we've already talked about that, right?
That's like the ReLU, but with a little
divot at the bottom here, um you will
get a GeGLU. Um and if you take a
SwiGLU, which is X times a sigmoid, then
you will get a SwiGLU. So, this is a
Swish times, you know, the rest of it.
Um and this really covers a lot of the
modern models, right? Um generally the
Google folks have used GeGLU, so like
the Gemma models, the T5 models are
those. Um and everything that's kind of
like a LLaMA descendant uses a SwiGLU.
Um so, PaLM and the LLaMA descendants
are all kind of SwiGLU models. Um
I would say that SwiGLU is probably the
more dominant one, but honestly amongst
the gated units, doesn't really matter.
Now, here's a side note that will uh be
a semi-important piece of trivia later.
Um if you look up here, right? Um you
will notice that there are more
parameters for the gated uh model,
right? Cuz I have this parameter of V.
And so, if you do a little bit of math,
right? I now have three matrices instead
of two matrices,
right? What you should do is you should
maybe use a smaller feed forward
dimension by a factor of 2/3 in order to
keep the total parameter count the same,
right? So, this is roughly the idea of,
"Well, I want to keep the same number of
total parameters as my original MLP, but
I now want to make it gated, so I'm
going to make the feed forward
dimension, which is the output dimension
of this W, a little bit smaller by 2/3,
right?" So, this is a general rule of
thumb that people have followed, but
it's not really an iron rule.
You know, the original Noam Shazeer
paper that, you know, proposed this,
had some, you know, very small deltas
originally, but they're consistent
deltas, and I think to his credit, um
I think a lot of his papers have these
like error bar assessments of like
training multiple replicates and
checking to see if they're better. Um
and if you look, the GLU variants are
almost always consistently better than
the non-GLU variants. And this is a
parameter matched comparison because um
Noam Shazeer is always doing this 2/3
adjustment to make sure that all of the
models have the total same total number
um of parameters.
So, this is quite nice. It's in some
ways a free win. Um almost everyone uses
a GLU. There have been other sort of
more controlled systematic comparisons.
This is uh the same paper I was talking
about before, Noam et al. in 2020.
Um Google actually in the 2020s did
quite a few nice large-scale
architecture comparison papers, um
although with a T5 architecture and not
uh autoregressive uh language model. Um
and they, you know, basically
comprehensively compare things like
GLUs, and you see once again, um if we
look at the SwiGLU or the GeGLU or the
GLUs in general, they do significantly
better at loss or the other downstream
metrics, right?
Fairly compelling on paper uh on these
papers, also clear from now a lot of
model training runs that SwiGLU and GLU
are good, right?
So, there's a lot of variations in
gating, but really the important single
axis to know is that gating uh for these
nonlinearities is actually quite
important, gives you
uh nice boost without much of a
computational cost. Um you know, that's
not to say that gated linear units are
necessary. I mean, GPT-3 was that. Um I
think the NeMo Tron 340B model used a
squared ReLU, which is a kind of a crazy
choice, but that works, too. Um both of
these models are perfectly performant,
but it's actually quite rare to see
anything that's not trained on a gated
linear unit, right? So, evidence is
pointing towards consistent gains on
using these gating tricks.
So, those are I think the the more
consensus choices for things that we can
do in architecture. Um now, this one I
think is a really fun idea, but one that
I think now the test of time has shown
maybe is not quite as good or maybe not
as popular of an idea.
Um normally, we do our transformer
blocks serially, right? We compute our
attention, then we compute the MLP,
right? One after the other.
Um if you're very systems-minded, you
might say, "Well, this introduces a
bottleneck, right? I have to wait for
the computation of one to do the other.
If they were instead in parallel, I
could bring to bear some new and cool
systems optimizations, potentially,
right?" So, you might ask, "Could we
parallelize the transformer block?"
And um this was originally an idea that
was in GPT-J, which is the open-source
attempted replication of GPT-3.
Um and kind of very interestingly, I
think GPT-J has been surprisingly
influential in sort of propagating a lot
of ideas. I mean, PaLM as well. Google
um is actually surprisingly bold with
the architectures that they do. Um but
the description in uh PaLM, uh which you
can see in their report, is kind of the
following. Instead of nesting this,
which is the sequential format at the
top, you know, you're just going to add
together the output of the MLP and
attention layer, and just add both of
those back into the residual stream.
Um if you implement this right, you can
actually share a lot of the components.
Like, you can share the layer norms, you
can fuse the matrix multiplies. This
allows you to potentially get additional
systems optimizations. Um
And I think a lot of the people that
have been influenced by Google, so
Cohere, you know, was founded from one
of the former
uh transformer authors, they do a lot of
Google-inspired optimizations. They
followed kind of this architecture. Um
but not very many others. Um this has
been a approach that has really fallen
out of popularity over the past, I
think, 2 years. Um I think mainly
because optimization of the serial form
has gotten sufficiently good that the
systems gains from the second one just
isn't worth the small hits to uh
representation power that you end up
getting going from uh parallel to
serial.
Effectively, you can think about it as
you've lost half of your depth, right?
And that can be
uh a deleterious
uh thing to do to your model.
So, in terms of the architecture things,
actually, you know, the fact that this
is so short should kind of suggest to
you how much the original transformer
formulation has somewhat stood the test
of time, right? Cuz the only thing I'm
really talking about changing here
um is, you know, where the norms go, or
you know, whether we have bias terms, or
whether we gate the MLPs, but those are
actually pretty minor changes compared
to all the things that you can do.
Now, uh, those of you that are, you
know, sort of carefully paying attention
might say, but wait, you know, there's a
lot of transformer alternatives that
change the attention. Um, yes, you'll
have to wait until next lecture because
today I'm just only going to cover sort
of core attention based methods. Um, and
next lecture I'll throw in a little bit
of a state space model stuff, but as
long as you're in this like dense
attention land, actually the
architecture from the original
transformer paper is pretty close to
what we do.
So, you see, uh, quite a bit of this,
right? So, uh, just now going back to
this, blue here is RMS norm block as
layer norm. You see most of the modern
models are sort of RMS norm models.
Serial versus parallel layers, the blue
one's parallel, the rest is serial. You
see mostly serial layers. Um, pre-norm
versus post-norm. Some of these, uh,
ones that I marked as post-norm are
actually pre and post-norm.
Um, and then these ones on the right,
these are GLUs, uh, almost always with
the exception of things like, uh,
Falcon, which use a gated linear unit,
but almost all of these are really, uh,
gated linear units for modern models.
So, you can see the trends quite
visually, um,
from what I'm telling you.
Okay. So, really the thing that is very
different across implementations, and I
think a place where a lot of the
architecture stuff is still in flux, is
how you do kind of position dependence
and incorporate information from other
positions, right? So, the core attention
component in some sense.
Um, so there are lots of different ways
that you can encode position into a
transformer.
And just so you know, to to remind you,
right? This is very, very important
because attention is positionally
independent, right? They're just inner
products, so you can just shuffle them
and attention would be the same if you
don't have a position embedding.
The original transformer had sine and
cosine embeddings, kind of like a
Fourier transform intuition that if you
have sines and cosines, then you can
kind of recover position from that no
matter what.
Um, a number of other sort of large
models that, you know, followed soon
after that used absolute embeddings,
where each position had its own
different embedding.
Um, and then, uh, several other sort of
Google models like to use relative
embedding. So, in here you're not
adding, um, embeddings into the into the
embedding, uh, like word vector
embeddings, but instead you're adding a
s, but instead you're adding a
vector to the attention computation
itself, right? So, if you're three
positions off, sort of the attention
matrix gets a different offset added to
it. And and, you know, models like T5
and Chinchilla use kind of this scheme.
Um,
the thing that has really become pretty
dominant in terms of position embedding
is this class of embeddings called rope,
which some of you may be familiar with.
Um, most models past 2024 use this type
of embedding. And it's kind of
remarkable given that rope, you know, in
some ways came out of nowhere.
Um, originally I think this was also a
GPT-J innovation, um,
from I think, uh, sort of not very well
known sort of blog post and, uh, paper
combination, uh, from an author in
China. Um, but really it has some really
interesting ideas for for why you would
do something like rope.
So, rope, you know, is a relative
position embedding. And a relative
position embedding, let's make an
, let's make an
opinionated stance that I should not
care about the absolute position of any
words. So, if, you know, A uh, an apple
appear together, even if it appears at
the start or at the end, right? In rope
embeddings, they should kind of get the
same, uh, sort of result. Um, and we do
know that, you know, or and we want to
sort of represent it in this way, right?
So, I have an embedding F, and I have
another embedding F, and these are going
to take in the identity of the words X
and Y and the positions absolute of I
and J.
And I want this to be equal if I take
the inner product of these embeddings to
be equal to a function that only depends
on the relative difference.
Right? Um, and every existing embedding
before it didn't really fulfill this
equality. Like sine is not relative
because it has these absolute cross
terms that are not relative. Absolute
position embeddings, just by the the
name of it, is obviously not relative.
And then relative embeddings,
technically these are relative, but
they're not kind of embeddings because
they're just adding to the attention
just adding to the attention
matrix, right? So, there's no inner
product structure that, you know, you
can extract out of the
So, given this, you might ask, is there
a nice way that we can truly have this
relative embedding?
And the idea is very cool. Um, it's
really just looking at kind of uh,
properties about angles and cosines. So,
we want our embeddings to be invariant
to absolute positions, and we know that
inner products of any kind are invariant
to arbitrary rotation, right? So, the
idea is to say, I'm going to take my
semantic word vectors, the ones that are
are independent of any position. So,
this is my starting point. And then I'm
going to rotate each of these vectors,
in this case in 2D, um, based on the
position that the words appear. So, you
know, just as a
uh, simple example, we, let's say we
have the uh, sentence, we know that,
right? We appear at position zero, so
I'm not going to touch that at all,
right? I'm just going to keep that where
it is.
The word know is at position one, so I'm
going to rotate it by some angle, right?
And that's my my one position rotation.
Now, what happens if I apply the same
idea to, uh, the following sequence, of
course we know, right? In this case, we
and know are still adjacent, they're
right next to each other, but their
absolute position is shifted, right? Of
course, you know, comes before we know
now. In this case, I'm going to rotate
the word we by two positions because
it's two index, right? 0 1 2. So, the
word we is in the second, uh, position
number two, so I rotate by two. I rotate
know by three positions cuz it's in
position number three, and what do you
know, the relative angle between these
two is still separated by one, right?
So, this is a very, very simple idea of
just using rotations, uh, to represent,
um,
position. And if we do that, then
anytime we take an inner product, those
inner products are going to be invariant
of absolute positions.
Now, you might say, well, in two
dimensions that's pretty easy cuz you've
only really got one choice, you got
clockwise and counterclockwise, but in
high dimensions, there's an infinite
space of ways that you can rotate
vectors. So, what do you do in D
dimensions? Um, well, you do the
simplest possible thing and it works.
The simplest possible thing is to reduce
it to the 2D case repeatedly. So, you
have a D-dimensional vector, just cut it
up into chunks of two, and each pair of
two dimensions gets rotated. And the
theta at which these things rotate vary,
right? Some of them are very low
frequency, so they rotate very slowly,
so they uh, they can capture long-range
dependence. Some of them rotate very
quickly, so they capture things like,
are they neighbors to each other, right?
Um, and then at the end, you know, after
I've rotated every pair of vectors, I
get sort of my final embeddings. So,
this is the, you know, rope approach.
the paper, if you read it, has a very
complex motivation about complex
numbers, but really I think the
intuitive way, at least to me, to think
about it, is to just you want to rotate
by reducing to the two-dimensional case,
and you're just rotating every pair of
coordinates.
Gemma 4 just came out on Thursday, and
they have like another different kind of
fun thing that they do, which they call,
um, I think proportional rope or P-rope,
um, which is a really strange way to
just say that the only thing they rotate
is the first two coordinates, but that's
another valid thing that you can do as
well. So, there's a lot of different
things that you can do in this space
that end up working.
Okay. In practice, what you're going to
end up doing is, you know, you can take
your vector and you can make a sparse
multiply with sines and cosines, and
this is going to be giving you some way
of rotating your input vectors X's,
right? So, X times, uh, W times R, this
is going to be your final embedding that
you get.
Um, and finally, you know, this is a
sine and cosine, which looks a little
like sine embeddings, but it's really
important that I'm multiplying with
these sines and cosines rather than
using them as embeddings cuz that means
that there are no cross terms. Um, and
this is purely relative, right? There's
no absolute position information that
you'll get out of inner products.
Um, if we really, really wanted to get
into low-level details and you ask like,
how do I actually implement this thing,
you know, you're going to have to do
that. Um, you have your usual attention
stuff, and then what you do is you
generate cosine and sine angles, um,
based on the position IDs of sort of
where your sequence is, and then you're
going to apply those cosines and sines
onto both your queries and keys for your
sort of attention computation, um, and
you can either apply them as a matrix
multiply or you can go through and apply
them manually, uh, just as a rotation,
right? Fairly straightforward, and you
would do this at the attention level
rather than at the very bottom to sort
of enforce position invariance every
time you're doing attention
computations.
Okay. So, that was rope. Um, it is a
little bit confusing, but once you
understand the geometry of just rotating
things, it's actually fairly, uh,
straightforward.
Okay. I'm going to pause here for one
moment, um, in case anyone has any
questions about the various like
architecture bits. Um, we're going to
then talk about even lower-level details
about hyper parameters. So, yes.
Do you know about any papers that do a
higher-dimensional rotation?
Higher-dimensional rotation never
worked?
It's a good question.
I don't think so. By a
higher-dimensional rotation, like any,
you know, 2D rotation in the space would
just be kind of a variant of this. You
could certainly do like any one manifold
that like is a closed loop. I have not
seen that.
Yes. What do you recommend for this?
What do you think is the best way to
distill this kind of knowledge problem.
People who are back to work boards.
It's a good question. Um
I don't know if there's a way beyond
some combination of like looking broadly
enough to get a to get to get a pattern,
which is what I the procedure I'm trying
to do in this lecture here. And then the
other one is to try it yourself even a
much smaller scale to form an intuition
and like a theory for how these things
come together. I think those two are
really the right ways. I think reading
any single paper in isolation is very
very difficult especially now because no
single paper seems to give any full
detail for a lot of language models
these days.
Oh, lots of questions now. Okay, good.
We'll go in Yeah. Um so I have a
question about the question on the
parallel layers and the the serial
layers. Yeah, I understand the modern
models are
thinking of the resource efficiency. So
they will use the parallel layers. They
have the
idea but there's there's a difference
there's a there's a big difference
between the accuracy um for these two
patterns, right? I want to know like
what's the What's the
What's the difference of of the
accuracy? Is it big enough to Is it
small enough to allow the current model
trainers to ignore that or is there any
problem? Yeah, I think you know, the
that's actually really mixed. So if you
read the original Palm paper, I think
they're like very confident about the
use of parallel layers like no
performance drop 15% systems utilization
improvement. So if you read just that
you'll kind of say like oh, it's just as
good. Um but I think a lot of the the
later Google models have stopped using
this, which you can take on as an
implicit signal that actually there
might be some losses. And once again,
this one is a little bit hard to um to
get precise numbers on because no one's
done the ablations as far as I know on
parallel versus serial um controlled
nice ablations at least.
Yeah.
So yeah, so
what's the difference between like Eagle
and RoPE?
Yeah, yeah. I mean this difference is
really just like which of the
coordinates you're rotating.
Like you don't rotate most of them
because a lot of the I mean the argument
originally I think is that the low
frequency parts just aren't rotating
very much. And so you can drop them if
you're really strapped for you know,
sort of extra space. And these this is
really a optimization for teeny tiny
models where like you don't have very
much like hidden dimensions to to have
activations for.
For the relative embeddings not having
an inner product,
um is that cuz it only applies to keys
specifically? I'm trying to understand
the logic. Yeah, so they applied both
the the keys and values, which is kind
of why you know, you get this like
relative effect from where you are. Um
you want to not have cross terms, right?
So so if you look at the sine and cosine
embeddings, then you'll not only get
sort of the you know, the original
vectors, you'll kind of get these weird
cross terms between the position
embeddings and the word embedding
themselves and so on and so forth. And
then you can kind of back out what the
absolute position is. So even sine and
cosine embeddings are not like pure
relative position embeddings. Um
you know, you have to accept the premise
that you know, the relative embedding is
what you want. But once you do kind of
you end up at the RoPE solution somewhat
naturally.
So what's the issue with So the issue
with this is that it just can't be
factorized as an inner product. That's
more of an aesthetic problem, right?
Like if if your constraints are I need
it to be uh relative and I need it to
factorize as f of xi and f of yj, then
this is not a solution in that class. Um
to be fair, there's a lot of um
embeddings that work this way that do
work like Alibi and other kinds of like
approaches like do do this kind of
inject into the attention matrix and
they do reasonably well. Um it's not
necessarily the one that's become the
dominant approach is what I can say.
Cool. Okay.
Great.
Now we'll talk about hyperparameters um
and I think hyperparameters are really
something that you start to engage with
once you like actually have to train a
model, right? When your knowledge about
language models are abstract, you don't
have to care about any of these. But
once you have to instantiate it, you
start to ask questions like well, how
big should the feed forward size be?
Um how many heads should I have?
Um what should my vocab size be, right?
and you might also have questions of
like what should my weight decay or
dropout be? Like do I even need to
regularize? I I have a lot of tokens,
right? So do I need regularization?
Um and do I need very deep models or
very wide models? Like what are the the
right kinds of things to do here, right?
Um and all of these if you start out
with no knowledge, it's actually very
daunting because you have to search this
like very big high dimensional space.
Um but the space of things that people
try is actually pretty small. And from
that maybe you can start to think about
you know, smarter search processes of
like where you want to vary things.
One of the things that's a really
consensus hyperparameter
um is this idea of the uh
ratio between the feed forward size,
which is kind of the output of your
first matrix multiply in an MLP, and the
model dimension, right? So this is
really the the uh ratio of the two
dimensions of your W1 and your as well
your W2 matrix.
Um this seems like a thing that's very
important and controls kind of the
richness of your MLPs. So what should it
be? Well, for whatever reason, it should
maybe be four times your hidden
dimension, right? Um and this is a rule
of thumb that works remarkably well and
I will show you some data on like why
maybe this is a fine number to choose.
There's a few exceptions um and funnily
enough, the really extreme exceptions
kind of backtrack on that.
Um exception number one is variants of
the gated linear unit. I already told
you about this. So if you were thinking
about it, this is probably cached in
your head, right? GLUs have more
parameters, right? If you keep the same
dimensions. So if you want to keep the
parameter size of your MLPs the same,
well, you need to scale down by 2/3,
right? So most GLU variants, this means
that you're going to end up with
something like 2.67-ish,
right? So everyone that's uh down here
2.67 to 2.5, this is roughly applying
this like 2/3 correction.
Um and then for whatever reason, um the
Llama 2 folks decided, well, we actually
have very efficient um attention heads
with like um
uh
uh MQ A, which I'll talk about later. Um
and because of that, we can multiply
this ratio by an arbitrary 1.33 and
we'll get roughly 3.5. And so the Llama
people kind of like arbitrarily chose a
slightly different ratio, which
essentially emphasizes the MLPs a little
bit more. Um but really if you actually
look through all of the the papers,
you'll find you know, either 2.6-ish or
3.5 for GLUs um or four if you're doing
uh non-GLU models.
Okay. There's another exception, which I
find to be very funny but also very very
cool, which is um
you know, throughout as you read these
like technical reports, you'll find that
most people are just very boring in
their choice of architectures. They're
like we did Llama but we changed one
thing. Um but you know, folks at Google
are very bold sometimes um and T5 is one
of my favorite ones because they have
some really bold settings. Uh they
decided that um instead of following
this like 4x rule of thumb, they decided
that they want to have a 64x
multiplier, which is like way bigger
than four. Um and they have a reasonable
argument for this as well. This is
another like systems-based argument,
right? They said, well, you know, if the
bigger my matrix multiplies, the more
efficient I can keep my hardware. So if
I make this, you know, multiplier really
big, then you know, my matrix multiplies
can potentially be sort of more
efficiently utilized, right?
Um and some others like Gemma 2 have
also tried to really push a little bit
higher on this. But really uh T5 is an
kind of astounding exception at 64. I
don't think any other model has really
gone that high in the feed forward
multiplier.
and empirically, if you look at other
sort of works that try to do more
controlled comparisons of this ratio, um
I've taken this one from Kaplan in 2020.
This is the classic uh neural scaling
laws paper um where they they do sort of
various controlled uh studies on
language models. You'll see, you know,
this wasn't the point of the study,
right? It was a scaling laws study. But
you'll see in one of the panels that
they actually have a sort of ablation or
sweep where they change the feed forward
ratio and they look at the loss, right?
Um for a very small model here, right?
But what they what they find in this
paper is there's a basin where you start
at about one and you end up about maybe
10 where this hyperparameter is like
pretty good and very very flat. You lose
very little relative to the optimal loss
down here, right? Um and then if you get
it really wrong, like you get, you know,
above 10 to 100 or something like that,
you know, then your loss starts really
shooting up quadratically.
Um and so a lot of these choices that
range between like 2.6 to four, they're
all kind of falling into this relatively
nice basin. So you're fine choosing
those numbers, right?
Okay. So what can we learn about this
hyperparameter? Well, the default
choices have worked very well for nearly
all modern language models. So you can
safely choose that. Um T5 was a fine
model or the Virgin 1 T5 was a fine
model, right? Like it wasn't a bad
, right? Like it wasn't a bad
model. Um and so even radical choices
. Um and so even radical choices
can technically work, but it's probably
going to be compute inefficient. And I
think the funniest part of the saga of
this kind of the punchline of the T5
saga to me is that they have a follow-up
model T5 1.v v1.1 um that's like
supposed to be the improved version of
T5 and they kind of go back to the
standard 2.5 multiplier, you know? So
there's nothing explicitly stated here,
but clearly, you know, when they tried
to to update T5, they decided that they
wanted to go back to a more standard
multiplier, which I find to be a little
bit funny.
Okay. So, that's the, you know,
feed-forward ratio,
um which now you have like a rough sense
of like what the right order of
magnitude is.
Now, let's talk about a different
consensus hyperparameter. Um I always
found this to be very strange when sort
of teaching uh 224N and, you know, just
sort of teaching students about this,
which is, if you have a multi-head
attention, where you have multiple heads
for your attention in your transformer,
um the canonical thing to do, the thing
that almost everyone does, is if you
have multiple heads, you make sure that
the size of those heads, the head
dimension, is such that you sort of have
the same dimension as a single-head
transformer, right? So, you always make
sure that you sort of divide the hidden
dimension to basically multiply with H.
So, in this case, right, you have H, the
number of heads, and the dimension of
each head is D over H, so you multiply
the two and you get D, right? For some
reason, this is kind of the rule of
thumb.
Um of course, this doesn't have to be
true. We can arbitrarily change the the
ratios between head dimensions and model
dimensions, but most models do follow
this guideline, and it turns out to work
pretty well. Um
You know, we can look at a variety of
different models, classic and new. I,
you know, have the latest and greatest
quad as well, and you kind of find,
yeah, the ratios are roughly around one
a model head. Um you know, notable
exception of T5, um and even Lambda,
which is another Google model, um but
really everyone sticks around one. And I
think this is
kind of an interesting one.
Um I think the thing about head
dimensions uh that I'll that I'll end
with here is I think this is yet another
kind of forgiving hyperparameter. Um
there's a couple of ablations that
people have done. There's once again a
pretty wide basin around one that you
can sort of get away with.
Okay, but that one's maybe not the most
critical uh hyperparameter.
I think maybe one of the most critical
and interesting ones, I think
conceptually, is this idea of an aspect
ratio, right? Um and then sort of to add
an extra point here,
um when you scale models up or down, the
way you usually do that is you fix an
aspect ratio, like how wide your model
is versus how deep it is, and then you
make the whole model bigger, right? So,
the aspect ratio in some sense controls
the entire depth-to-width tradeoff as
you make models bigger, right?
Now, you might wonder how deep should my
model be. Like, if you've been following
all this stuff on like reasoning and so
on, you might think I need a really deep
model or really shallow model if I want
systems utilization. You might think
that there's a lot of sort of variation.
And there is a lot of variation, um much
more so than other hyperparameters, but
there's actually like a fairly clear
sweet spot that most modern models fall
into.
Um you don't really see models go like
too uh too deep, um and you also don't
see models go too wide uh in either
direction, right? You see most models
have a ratio about a hundred um D model
over N layers. Um so, about hundred sort
of width for every layer that you have.
I mean, this is true for like GPT-3 or
LLaMA or any one of these models.
and really, I think the considerations
are partly a tradeoff between
expressiveness and hardware, right? If
you have an extremely extremely deep
model, um they get very very annoying to
deal with systems-wise. The deeper your
model, like, what is the ways that you
have for parallelizing them? Well, you
might have to cut up your layers. If you
cut up your layers,
we'll talk about this in the systems
lecture. Once you start cutting up your
layers um depth-wise, you have very
serious issues in parallelization.
Pipeline parallel, which is what this is
called, is something that like most
people really really do not want to deal
with. Whereas width is much easier to
parallelize. If you have a really wide
model, you know, you can cut that up
very easily in your GPUs. Uh tensor
parallel is what it's called is much
much simpler to deal with.
and so, in some sense, you know, there's
systems reasons to go wide, and maybe
there's expressiveness reasons to go
deep, and you end up at roughly a
hundred. Um and I think one of the
really interesting things about um
transformer hyperparameters is there are
a lot of hyperparameters that seem quite
important, but they're also fairly
forgiving, and people have converged
roughly on the minimum. This is yet
another plot from Kaplan et al., um
which shows another sweep over
hyperparameters for differently sized
Um and once again, you see, regardless
of kind of the size of your model,
roughly speaking, the optimum aspect
ratio is fairly similar, and they live
at about a hundred, maybe a little bit
less depending on how you want to do the
accounting, but really, you know,
anywhere near a hundred is a pretty safe
bet for aspect ratios.
Um ETA and others uh did a number of
really interesting sort of like
architecture um
architecture variation experiments, in
which their general conclusion on this
was that let's look at the top panel
here. You have a lot of different kinds
of
uh models that you can have in terms of
depth-to-width tradeoffs, um but as you
sort of sweep the depth-to-width
tradeoffs, you find that really, um the
only thing that matters in some sense is
FLOPs. As you increase the FLOPs, the
models get better, and that's really
controlling the majority of the effects,
not necessarily uh the aspect ratio. And
so, I think what has really emerged from
this is the sense that there's a general
forgiving band of hyperparameters that
people tend to choose, and then you
really worry about primarily your
systems utilization rather than sort of
expressiveness concerns, which are hard
to reason about.
Um okay. And then maybe the last
hyperparameter thing uh that I want to
mention is vocabulary sizes. Um
and this one's kind of interesting to me
because there's a really clear
difference between two classes of
models. Um I think in the early days of
a lot of, you know, um
uh early days of open-source model
training, um
there were a lot of monolingual models
whose only goal was to be good on
English. And for those models, you had
these like much smaller vocab size, in
the 30,000 range. Um and then,
post-LLaMA, a lot of people were really
interested in multilingual or like
production systems. So, these include
closed-source models like GPT-4. Um all
these have much much larger vocab sizes,
and these are roughly in the hundred to
200,000
um vocab range.
And you see generally that, you know,
Google models have a ton more vocab. Um
LLaMA derivatives roughly range at about
a hundred uh thousand tokens, and then
the the sort of monolingual models are
about 30,000.
Um this is somewhat clear. The
multilingual models really do need much
larger vocab to cover the whole space.
Generally, the models on the right are
also bigger. There have been scaling law
studies showing that the bigger your
model, the larger the vocab it can
handle, and so this is also partially
driven by uh modern scaling trends,
where the models on the right are
generally bigger. No one's training
small uh sorry, large monolingual models
uh anymore.
Okay. So, um yeah.
Sorry, uh the question was like, if you
have Sorry, multilingual models or
sorry? Multimodal. Multimodal. Yeah, so
I guess it depends on the way that your
tokens are encoded, but, you know, if
you're tokenizing your images and things
like that, then you need to, you know,
have many more tokens to account for
those. Um if you look at like various
open-source releases, they'll have like
a different image tokenizer with its own
vocab, which is quite large.
Uh how valid is it to
compare
bits uh bits per byte for different for
different tokenizers?
how valid is it to compare bits Oh, that
is a great question. Okay, yeah. Uh
that's not a hyperparameter question,
but that is a good question. Um so,
what is the right way? Okay, so so, let
me let me like
step back a moment and like put us in
the right mindset. So, if we think about
language modeling, language modeling is
is a generative modeling task, right? We
are modeling the probability of a
sequence.
Now, as long as your sequence is fixed,
right? It's the same. You have you know,
adulterated it anyway, and you provide a
probability over all strings, that's
always valid to compare, right? At that
level of things, it's always valid.
Now, when you ask the question, is it
valid to compare the bits per byte of uh
arbitrary token or or two arbitrary
tokenizers?
Really, there's two things at play. The
one thing is, you know, did you touch
the sequence at all? Like, if you look
at some tokenizers in the past, before
subword tokenizers, they would drop some
tokens or drop some words. That changes
that makes the comparisons invalid. But
modern tokenizers are complete. They can
model any sequence, so that's not a
concern. Um the other thing that you
have to worry about is, are we like
length normalizing it in any way, right?
But for bits per byte, you're always
normalizing with the same number, which
is the number of bytes, and so this is
always a valid comparison, right? So,
that's kind of how to think about, you
know, tokenizer comparisons. So, for
example,
uh I think they had the results showing
that
comparing perplexity for fixed
tokenizers
is is is is um
always leads to to better actual
performance.
On on downstream network tasks.
Is the same thing they were looking for?
Um perplexity and BPD are kind of dual
to each other, so yes, if that's what
you're asking.
It's only yes and only no, cuz if you're
comparing
you could two frame compare the
perplexity as compared
but you're changing it different splits.
Changing it different [snorts]
Okay, we'll have to we'll have to talk
later cuz I'm not sure I understand the
question, but I think that that's an
interesting set of questions. Okay,
good.
All right.
So, um you know, we're we're going
through really the the the low-level
lowest levels of details of language
modeling, which I think has really
exposed a lot of interesting ideas while
we sort of talk through this. And I
think dropout is one of the end
regularization, I think is another very
interesting class of ideas. Also one
that I think is very counterintuitive
from your machine learning 101
intuition.
So, let's uh
go through what I think is like the the
standard argument for, you know,
regularization. Um well, if I'm doing
language modeling, I have a lot of data,
right? I have more data than I can
process most of the time, right? Unless
you're at, you know, Google, maybe even
then, there is more internet data than
there is flops. So, you know, I'm
probably not even going to see the same
data twice, right? Um so, I'm only going
to do a single pass on a corpus, and
there's very good reasons and arguments
to believe that a single pass of SGD or
other optimizers is never really going
to memorize my data very much, right?
So, this means overfitting is not really
a problem uh almost ever during compute
constrained language modeling.
Now, you know, some people even actually
only look at training loss because they
believe so strongly that overfitting
doesn't happen in single pass SGD.
Now, given this, you know, you can sort
of sit and think about this. Should I
use dropout or weight decay in language
model training, right?
Okay, you can think about it a bit.
you know, one unfortunate thing is that
a lot of recent models don't talk about
this stuff at all. Um it's really
lower-level details than like tech
reports are willing to expose.
Um but if you look, actually you find a
lot of models um do both. Especially
weight decay actually is a fairly
popular intervention even for modern
high-performance language models. Um
this is very, very surprising, you know?
I mean, some of the dropout things um
you know, maybe
uh have gone out of favor, but weight
decay actually remains fairly popular.
And this is very mystifying. Like, why
is this?
Um and this is, you know, one of the
reasons why I think deep learning is
hard and this architecture lecture is
very strange and hard. Um it's because
these things interact in very strange
ways. So, there have been papers that
have argued um and shown nice evidence
that weight decay is actually not a
regularizer sometimes. It actually
interacts with the optimizer to
essentially um
make optimization better. Um so, if you
look at the training versus validation
loss across different weight decay
settings on, you know, language model
training for single pass SGD, you don't
really see any difference. Like, weight
decay isn't shifting things so the
validation loss is better. There's
already no overfitting. We're on the x
equals y line here, right? So, doesn't
control overfitting,
but if we kind of look at different
levels of weight decay, and not only
just different levels of weight decay,
we look at weight decay combined with
learning rate decay, um what we find is
that the stronger weight decay runs,
these blue dash lines on the bottom, you
know, do significantly better because
they start out slow, but they
essentially end up um converging to a
much better minimum later. And this is,
you know, generally true when we decay
learning rate, not necessarily true when
we're in constant learning rate, which
is maybe somewhat more of where your
intuition is coming from.
So, you know, this is part of why it's
very difficult to reason sort of a
priori or like from scratch, you know,
the behavior of all these different
choices and why, you know, I think Percy
and I have designed this class so that
you interact with stuff because, you
know, you might come upon this thing
that where basically weight decay is
actually an optimization intervention
and not necessarily a regularization
intervention, which is, you know, what
you would expect here, right? So, always
keep that in mind that these kinds of
unexpected effects can really start to
kick in
uh for these kinds of uh settings.
All right. So, to put everything
together for hyperparameters, there's
actually for, you know, a lot of the the
maybe more hairy-looking
hyperparameters, actually just fairly
standard choices that have worked well
for everybody, right? You know, factor
of four rule of thumb, keep your head
dim and your number of heads uh equal to
the model dimension, um pick an aspect
ratio roughly around 100, um
and, you know, if you ask about
regularization, right? You want to maybe
try a couple things cuz regularization
actually does interact with optimizers
in ways that are quite counterintuitive,
right? So, this is the thing that some
people uh still do even though you you
don't need the regularization at all.
Actually, maybe I'll stop here in case
yeah.
Are there any significant differences
maybe for like um
the future models?
Ooh, diffusions.
That I have not looked into enough, to
be honest. Um there aren't that many
people training big diffusions is one
issue. Um and many of the models that
have been trained are retrofitted cuz I
think the architectures are actually the
same as the, you know, like a Lama-like
model. Um but if you're asking the
question of like, what's the optimal
architecture if you were to train from
scratch, I don't know what that is
actually off the top of my head.
Yeah. Do you have any explanation for
why regularization works in some cases?
Well, I guess it's not that
regularization in general affects
optimization. I don't think people do
dropout anymore because, you know, it
doesn't really uh interact well with
optimization. But for example, weight
decay, you know, which is shrinkage to
zero, um that might allow you to use a
higher learning rate or it might allow
you to decay faster. There are lots of
ways in which all these terms are
interrelated.
Now, I've talked a lot about how to
design um expressive models by sort of
looking at all these other models that
have been trained.
Um one of the things that I'll I'll
highlight now is over the last few years
um a really big emphasis has not been on
performance alone. It has actually been
on stability. And this becomes an
increasingly important concern as your
models get more and more expensive to
train, right? Um we've kind of seen that
a lot of these choices are forgiving,
right? Everyone's kind of doing similar
stuff. And so, you know, you can mess
with these, but you're not going to get
a big performance difference. That's
fine. But if your model, you know,
suddenly blows up some part into
training, like you get these like
horrible-looking spikes all over the
place, um you know, you might end up
with a model that is, you know, actually
not very good quality, right? Or it
might be unrecoverable. You might have
spent, you know, millions of dollars in
training, and, you know, you get to a
point where the model is no longer able
to be trained any further, right? That
would be a horrible thing to happen if
you have a lot of compute that you want
to spend.
So, you don't want to train models that
look kind of like this blue curve with
like spikes everywhere and these, you
know, big gradient norms happening. Um
so, what do we do to fix these stability
issues? I mean, this is really, I would
say, like a core core issue.
And, you know, if you have stability
issues in language models or in general
neural networks, there's a few, you
know, usual suspects that you've got to
start looking at.
Um one of them is the soft maxes, and
the soft max has two things that are
both really bad for stability. One of
them is an exponential, right? We can
see how that blows up very quickly. Um
you also divide two numbers, and that's
also a potentially very dangerous
operation, right? So, a soft max is one
place where you got to be extra, extra
careful.
And where are the soft maxes in a
language model? Well, there's two of
them. There's one on the output side
when we output our probability
distribution, and then in attention when
we normalize the attention, there's
going to be another soft max, right? So,
we can think of both of those as really
kind of danger zones for our model, um
especially the attention.
But okay.
Let's start with thinking about the
output soft max. The output soft max can
blow up on us. Um
and one of the things that we can do is
we can try to control
um sort of the the normalizer problem.
So, you know, let's sort of think about
the soft max calculation. We want to
compute a log probability to compute the
loss. Now, what is a log probability?
Well, it's, you know, the output of your
model U, and then you've got this log
normalizer, right? This U is
well-behaved because in some sense this
is the output of your model, right? This
is just the output of your residual
stream with all the things that are
added in. So, if U is well-behaved, then
log P, the first term, is well-behaved,
right? If the model is being okay.
Now, the second term, this log Z, this
might not be so okay, right? If Z is
really big or really small, even if the
output of your model is somewhat
well-behaved, it could blow up. And what
is Z? Well, it's an exponential, right?
So, it could potentially blow up very
quickly on you.
Or if this is zero, it could also blow
up on you, right? So, both of those
directions are very, very bad.
Now, we would ideally like our Z to be
somewhere near one, right?
Um or log Z to be somewhere near zero.
Um what can we do? Well, one of the
things that you notice, right? If you
sort of thought about the action of the
soft max, is this whole thing is
overparameterized, right? Um I could
sort of push things in and out. So, if I
add a constant to U, I can manipulate
the Zs without really affecting the
output of the soft max, right? You can
cancel out between the normalizer and
sort of the output of my model.
So, because of that property, one thing
that I could do is I could add a
regularizer. Um this is from from Jacob
Devlin's paper 2024, uh sorry, 2014, um
in which he adds sort of this squared
log Z term. Um
and what this is doing is it's just
penalizing how far away your log Z is
from zero. And if log Z is near zero,
that's nice because this whole
expression is kind of numerically
stable.
This is called the Z loss trick. Um it's
been used by a number of papers. Um
Jacob Devlin and others uh sort of
popular or initially pioneered this back
in 2014, and then it's become popular
again through a number of open-source
models. Like, Baichuan I think was the
first open-source model to do it, but
then DCLM and Almo and others have been
using this trick to stabilize their
output soft maxes.
So, this is this is a surprisingly
effective thing.
Now, okay. So, let's say we've handled
the instability issues on the output
soft max.
Now, we have to sort of turn our
attention towards the other potential
problem, which is attention, right? And
this is a a place where lots of
degeneracies happen. Lots of techniques
have been developed to control the
instability that attention operations
generate.
Um and really the, you know, the
high-level thing that I'll say
is
if you have instability, if you can
throw a layer norm in there somehow, it
might control it. And that's really in
some sense the the design philosophy
behind this idea called the QK norm. Um
so, what you do is remember that we
have, you know, our Qs and Ks um that
are going to be multiplied together, and
then they're going to go into the soft
max, right? So, in the standard
attention operation, I'm going to layer
norm as a pre-layer norm, multiply with
a QKV, and then I'm going to get my Qs
and Ks. Those will get multiplied by a
matrix multiply, I'll soft max them, and
I'll multiply that with V to get the
weighted average, and then I'll output
whatever comes after, right? So, this is
our usual attention. Now, what happens
if we just throw in a layer norm before
we multiply the Qs and Ks? If we do
that, then we know that the inputs to
this matrix multiply, and therefore the
inputs to the soft max, roughly have the
same scale. They're always going to have
a scale of roughly one because we've,
you know, used RMS norm to divide the
size of those Qs and Ks.
Okay. If we do that, then, you know,
we're kind of going to keep this soft
max operation stable. Tons of different
models do this. It's originally from
the multimodal world.
You know, some folks who were doing
making multimodal models sort of
initially discovered QK norm.
E to fix and chameleon really, you know,
used this and like proved it out. And
then a number of other open-source
language models, you know, realized that
the same tricks are entirely applicable
to
stabilizing attention for language
models, and I think this is now very,
very standard. Like QK norm is actually
a very standard intervention that most
of the large models now introduce. Um it
doesn't seem to affect performance um
from lots of different training runs,
but it does definitely prevent the kinds
of um attention degeneracies. Um and,
you know, I I'm really
&gt;&gt; [laughter]
&gt;&gt; the the way that I've seen this is, you
the the way that I've seen this is, you
know, we have layer norms initially in
the pre-norm. Now, we add them after the
the
nonlinearities in each block, and now
we're throwing them in both the Qs and
the Ks. And really, I think this is is
is kind of getting at
the stabilization tricks that people
apply to this world. Okay.
Now,
um the final set of things that I'll
talk about as a stability intervention.
And frankly, this one is not as popular
and more of a of a Google-specific trick
that I've seen. Um but uh logit soft
capping is a much harder intervention
that some people apply. So, this one, um
you know, in QK norm, what we're doing
is we are controlling the inputs to the
soft max and sort of hoping that the
outputs are well-behaved. If we really,
really want to enforce
um well-behaved outputs, what we can do
is we can kind of take the logits, the
things that go straight into the soft
max, and we can just cap them off so
they can never be too large or too
small, right? This is a hard almost a
hard constraint. Um it's called a soft
cap, of course, but a tan H, you know,
is bounded at some value.
Um and so uh this is in the Gemma
models. Um I think both Gemma or like
Gemma's two, three, and four all use the
logit soft cap trick. Um and what they
do is they take all of their logits from
the attention layers, and then they soft
cap them at some value.
Um some Nvidia folks have done actually
quite nice work doing systematic
comparisons of these stability
interventions. Um and what they find is
um if you start with a baseline model,
you can do all sorts of different
interventions, and QK norm is here, and
it does slightly better due to the fact
that you can crank up the learning rate
a little bit. Um but if you do soft
capping alone, you actually end up
losing performance. So, there is a a
quality degradation that happens. This
is a very strong intervention. You can
never express very confident uh signals
in your soft max beyond a certain point.
Um so, it does have some negative
consequences, but this is a very safe
way of stabilizing the outputs of your
attention. Or sorry, the the inputs to
your attention, the logits that go into
the soft max.
So, that's kind of the end of the
stability components. Um I can pause for
a moment here. Um and I'll talk about
sort of various attention things um
after that.
All right. So,
the last thing I want to talk about
today is various interventions that you
can make to your attention head.
Um and as I was saying at the beginning
of this lecture,
um I'm only going to talk about all the
things that you can do to sort of dense
all by all attention today. So, if you
if you were interested in hearing about
state space models or linear time
attention, um sadly today is not the day
for you.
Um the things that I do want to talk
about, which are really commonly
implemented um attention interventions
today, are uh group query attention,
which really saves inference cost by
reducing the number of heads, um and
sparse or sliding window attention, um
which really originally came from the
GPT-3-ish
family, but have now really been adopted
widely by most models that are looking
to do uh long context unless they're
doing exotic uh SSM stuff.
So, I'll start with um group query
attention or GQA or MQA. Um
this I'm going to first set up the need
for these kinds of things, and then
you'll kind of hopefully see what the
what the trick is um and why it's fairly
natural.
So, for the moment, we've been talking
about, you know, training and modeling
and all these things, but like let's
take a pause, and now let's think about
deployment, right? You train this very
big model, and now you need to serve it
to lots of users, and you're going to
pay a cost for serving.
And you're going to have to, in abstract
sense, pay for two different resources,
right? You're going to have to pay for
your flops, right? The computation that
you're performing, but you also have to
pay for another thing. You have to pay
for your memory accesses, right? Because
the memory accesses are also going to
impact, you know, your system's
characteristics, your latency, your
utilization, right? So, you want both of
these things to be small.
Now, let's think about what happens
during training or alternatively prefill
when you're looking at your prompt where
someone gives you the stuff. In this
case, you know, the total arithmetic
operations you have is, you know, order
of magnitude batch size sequence length
hidden dim squared, right? That's
roughly the size of things that you get.
And of course, you know, we're doing
quadratic attention, so we've got D
squared.
we've got uh
total memory accesses. Like what is our
memory access that we have here? Um we
have batch times sequence length times
uh hidden dim plus um
the sort of cost of the soft max, which
has a N squared component, and then
we've got a D squared component um for
the for the projections. So, the
arithmetic intensity here is pretty
good. Um
it's going to be one over K. This is the
number of heads, so you need to have um
uh sorry, head dims. So, your head dims
need to be big enough that you're
multiplying some reasonably sized
matrices. And you've got a one over BN,
so your sequences need to be long enough
or your batch sizes need to be big
enough. As long as both of these are
true, your GPUs are going to be fully
utilized. Great, right? You're You're
using all of your resources.
Now, you know, we have done we have
finished training, and now we're serving
our users. How do we serve our users?
We're going to generate tokens and send
it to them, right? Now, for doing that,
um I can't parallelize the generation
process. What I'm going to do is I'm
going to generate a token, I'm going to
condition on it, I'm going to generate
the next token, and I'm going to repeat
this process one by one, right? This is
just sort of the the curse of
autoregressive language modeling. We
have to do this.
Um in order to do this, the efficient
way to do it is to maintain all of the
sort of past keys and queries that I've
had in what's called a KV
over the past, and then whenever I need
to compute something new, I can reuse
sort of the the submatrices that I've
already had from the past. And I only
really need to compute sort of the new
um query key interactions that I need to
fill out the rest of this matrix, right?
So, every submatrix I've computed
before, I can keep. I only need to
compute my new ones. So, this saves a
lot on compute, right? That's great.
But,
the issue here is now our arithmetic
intensity is not so good, right? As you
might sort of intuit, this KV cache
approach is going to be reading and and
reading um parameters all the time,
right? Each time I have a new step,
right? I'm going to have to read in my
I'm going to have to read in my
parameters. I'm going to have to take
these dot products, and I'm going to do
this once every step.
And so, now what do I have? Well, you
know, my total memory Oh, sorry. My
total arithmetic operations are the
same. I'm multiplying the same matrices
still, right? Just incrementally rather
than all at once. But because I'm doing
this incrementally, you know, now I have
um a a memory access pattern of batch by
sequence squared by hidden dim plus um
sequence by hidden dim squared. And the
by hidden dim squared. And the
second term is not so pleasant, right?
It used to be that it was just D
squared, but now we've got N times D
squared. And if we compute the
. And if we compute the
arithmetic intensity, which is the ratio
of these two guys, um now we have N over
D plus one over B. So, now what we need
is large batches plus short sequence
length, or we need really big model
dimensions. So, if we want to serve a
small model efficiently, this is not so
Right? Um this is really difficult to
deal with, right? This N over D term,
this first term over here, which is
sequence length over hidden dim, is very
difficult to reduce if we're doing this
incremental computation. This is just a
hard thing to deal with.
So, this leads to this idea of MQA or
multi-query attention. Normally, you
have multiple heads in your attention
operation, and you're going to have
different keys, different values, and
different queries. That's normally how
queries. That's normally how
you do things.
But, one thing that we could do is maybe
we can keep the keys and the Vs the same
across all the heads, and the only thing
that's different across the heads are
the queries. If we do this, then this
drastically removes the amount of items
that need to be moved in and out of
memory, right? Because the KV cache,
right? Are now significantly smaller.
These are all shared across all the
heads. Um this significantly reduces the
total memory access as well as the
arithmetic intensity, and we're kind of
the key term that we were talking about
here, we had the N over D term. Now, we
have uh H multiplying this, right? And
so, this H term allows us to
significantly reduce the the I sorry,
increase the arithmetic intensity if we
have a lot of heads, right? This is a
significant gain over what we had
before.
So, this gets us significant efficiency
improvements,
but the issue with MQA is
this is on the right here, you have one
value and one key for all these queries.
You do in fact lose significant
expressive power if you do this.
And so, there's this trade-off between
system's efficiency and expressiveness,
and you might wonder, is there sort of a
sweet spot in which we can avoid trading
off, you know, quite a significantly
expressive power and computation. And
that's where GQA or grouped query
attention comes in. You know, the
original transformer is multi-head. We
have queries and keys for each head. In
multi-query, we have one key and value
for each for all the heads. In grouped
query, we reduce the amount of keys and
values, but we keep the number of
queries the same. So, we now have this
ratio that we can play with, which is
kind of the number of key heads or the
number of value heads
while keeping the total number of heads
much larger than that. So, this allows
us to very simply control the
the trade-off between expressiveness and
inference efficiency.
Um there are other sort of tricks from
DeepSeek-V2, multi-head latent
attention, that I'll sort of mention
briefly next time,
which sort of have a different kind of
factorization structure and a different
set of trade-offs. But really,
the nice thing about GQA is that in
practice the trade-off is quite
favorable. So, if you have multi-head,
your performance, this was you know, in
the I think T5 days if I remember right.
This is your downstream model
performance. This is your time per
sample. You want to reduce this as much
as possible.
With multi-head attention, you have best
performance but very high cost.
With MQA, you know, you have
lower cost but much lower performance.
Similarly, if you make your model
smaller to try to hit your performance
targets, you get much worse performance.
GQA really does get the best of both
worlds, you know, very low inference
cost, nearly the same performance as
your full multi-head.
Um and you see sort of this like GQA
group structure where if you have
a small reduction in the number of
heads,
you basically have most of the gains in
your performance, which allows you to
sort of keep most of the expressive
power
while getting significant inference
improvements. And Percy will talk a
bunch more about sort of the inference
mechanics later,
but sort of this should give you a
flavor of like why models today almost
all adopt this GQA structure because it
gives you a lot of this inference cost,
which is really critical, without very
much of a
expressiveness hit.
Cool. Any questions for for GQA or KV
cache? Yeah.
Given
that you have so many
like rules of thumb for what
hyper-parameters are good, like to what
extent are you still searching over
hyper-parameters versus exploiting these
rules of thumb that you
I think it's a mix of both. I think
every sort of model training run has
some theses about what can be varied.
And so, you see this in a lot of the
reports where I think the
hyper-parameters are often not where
people are touching too much.
But you see like architecture changes
like one at a time in a lot of these
reports. But it's very rare to like go
and change everything up. I think Google
is one of the only orgs that seems to
like really spice things up in a
significant way.
The Gemma series has done some pretty
interesting things.
The most recent Gemma 4 release, for
example, now has like individual
embedding for every layer
in a way to control the trade-offs
between like memory use and flops.
They're very interesting set of things
that they've done.
Oh, yeah, back there.
Do you experiment with like data all
things of these parameters
during training?
During training,
let me think.
Weight decay, yes. Weight decay, people
change in concert with like learning
rate.
That is actually a heuristic that people
do that works very well.
Um other than that, I don't know if
there's a lot of different hypers that
people change during training,
especially because the architecture ones
just make training incompatible. So, you
can't really, you know, change them
while you're you're training.
Yeah, so I think I think weight decay is
probably the one that I can think of.
The others are usually fixed.
Yeah, MQA is uh
it's not just inference time fixed. It's
a pleasure to train. That's right, yeah.
You you you train with a certain number
of keys.
Okay. The last thing I'll talk about is
sliding window attention, which is a
really old idea. Like, you know, GPT-3
used actually this you know, if you read
the paper, they'll say we alternate
between full attention, which where
every position can attend to everyone in
the past, and a banded matrix style
attention where you can attend to
everyone within a fixed window.
And you know, OpenAI has some early work
on these kinds of like different kinds
of attention patterns that you can use.
But actually, this has become really
really popular over the past year.
This idea of alternating, you know, the
big full attention and a more local
attention actually hits a sweet spot for
how to manage like long context
performance while not paying too much
for inference.
Um I think, you know, the more recent
revival in open models, I would maybe
say Cohere Command A was the first one I
saw do it, where they, you know, had
this like structure where every four
layers they would have a full attention
that attended to everything. The three
layers in between would use a sliding
window attention that would only be able
to look at local structure. And of
course, you know, as you go up sorry, in
this case down cuz they ordered the the
diagram the other way. As you go down
sort of these blocks, you know, you're
aggregating local information into
global ones. The local attentions at the
end can of course access more global
information, but this, you know, allows
you to manage the
the the cost of having a really long
context without having to go for
something like a state-space model or
more exotic intervention. And that's
worked quite well.
Um there's also some innovation where
people change the embedding format for
the long range information where they
get rid of things like rope, so you have
no position embeddings at all. So,
you're really looking almost at bags
where the short range information still
gets position information. So, people do
all sorts of you know,
kinds of interventions involving these
these
both the embeddings and alternating
local and global structure.
Um I'll say that this is a
you know, attention and in general how
to manage the trade-off between long
context and sort of long context cost
and performance is a still an active
area of investigation. It's a place
where the most architecture work and
changes are still being done. Um we see
essentially a bunch of other models
adopt this idea. Llama 4, most recently
Gemma 4, Omo 3, they all do this
combination of sliding window attention
and full attention, in their case using
full rope instead of nope as the
embedding.
So, as I said, this is becoming really
really popular.
Qwen 3.5, which I put on the right,
they're actually a little bit different
because they alternate a state-space
model
called a gated DeltaNet and a full
attention every sort of, you know, one
one full attention every four layer
every four layers.
So, it's the same alternating structure,
but they're using a different sort of
cheap layer. In their case, they're
using a state-space model. I'll explain
what that is next lecture instead of a
sliding window sort of local attention.
But you see this is like I think a new
theme over the past year where, you
know, open models are really trying to
grapple with long context performance,
and the way to do that, at least so far,
is to have these hybrid models that
aren't just global attention, aren't
just cheap attention. They're some sort
of mix in between. And that's that seems
to have worked very well so far in a lot
of these models.
Okay, cool. So, as I was sort of trying
to emphasize, when you look across all
of these models, you start to see a lot
of patterns and hopefully a sense of
general understanding about what things
you can do and what things are good to
folks. Um we also see a lot of
differences in how we handle context and
how we handle position embeddings.
Even tokenization, there's some
differences, right? So, there are
differences across these models, but
across these models, but
there's also commonalities that
hopefully now give you some intuition as
you go out and do your assignments and
and sort of mess with the leaderboard
and so on.
on.
Thanks.