Transformers and Large Language Models


Transformers and Large Language Models

Corey
Welcome to the course. Before we get into transformers, let’s set the scene: this is a class about how large language models work, especially the mechanisms behind their architecture, how they’re trained and used, and what they’re good or not so good at.

Anna
And it’s meant for a pretty wide audience. If you’re interested in research, you’ll encounter techniques and applications in the field. If you want to build a personal project with a coding agent, you’ll get a better sense of what those tools can and can’t do. And whatever your role, understanding AI is becoming an increasingly important kind of literacy.

Corey
The instructors bring both academic and industry backgrounds to it. They’re twin brothers with similar paths: they studied in France, came to the United States for graduate school at MIT and Stanford, and then worked at Uber, Google, and Netflix. They’ve been working with language models since the early 2020s and have taught versions of this class since 2021.

Anna
The course asks for some foundations, not necessarily deep expertise: familiarity with linear algebra, especially matrices and multiplication, plus basic machine-learning concepts like neural networks, loss functions, and embeddings. Embeddings will be covered in the class, but knowing the basics beforehand helps.

Corey
It’s also worth using this year’s material rather than relying only on last year’s recordings. The field moves quickly, and the instructors are updating the class to include developments such as policy distillation, AI and coding agents, and approaches that don’t generate strictly one token at a time, including diffusion-based ideas.

Anna
For logistics, it’s a two-unit course meeting Fridays from 3:30 to 5:20. You can take it for a letter grade or credit/no credit. Lectures are recorded and posted within two days, though the instructors encourage attending in person when possible.

Corey
There are no homeworks, but there are two exams. The midterm covers the first four lectures, and the final covers the last five of the nine total lectures. Each counts for half the course grade. The exams include multiple-choice and free-response questions, and examples of the 2025 exams are available on the website, though this year’s questions will differ.

Anna
For studying, the advice is to keep up regularly and pay attention to what is actually covered in lecture. The textbook may contain material that the instructors don’t teach, and that extra material isn’t expected on the exams. In broad terms, anything covered in class could be fair game.

Corey
There aren’t official office hours, but the instructors stay after class to answer questions. There’s also an Ed discussion platform, accessible through Canvas, and private questions can go through the mailing list or the instructors’ Stanford email addresses. Canvas is where announcements appear.

Anna
The website also has the syllabus, recordings, and past exams. Slides are posted a day before each lecture so students can annotate them. There’s a textbook called the Super Study Guide: Transformers and LLMs, and a concise, recently updated cheat sheet for reviewing before exams. The guide is available through the library and online, and the cheat sheet is translated into multiple languages; students can contact the instructors if they’d like to help add another.

Corey
Because each class meeting is under two hours, lectures can’t cover every detail. Slides point to sources for further reading, so those are useful if a topic gets only a brief treatment in class but you want to explore it further. The instructors also aim to connect the material to industry practice, especially in the second half, and update content when relevant developments emerge.

Anna
That’s the course setup. Now let’s look at the bigger story: how did we get from earlier language models to today’s LLMs and coding agents?

Corey
In the 2010s, the field generally didn’t have one model that could do everything. It was common to have a separate model for each use case: one for sentiment classification, another for translation, and another for identifying names or places in text. Recurrent neural networks, or RNNs, were among the dominant approaches.

Anna
A major turning point came in 2017 with the paper “Attention Is All You Need.” It introduced the transformer, an architecture that proved highly scalable. In this context, scaling means that adding data, compute, and model parameters could produce strong improvements in performance compared with earlier approaches.

Corey
Researchers scaled transformers both by increasing model size and by training on more tokens. That progression helped bring about modern large language models, which can generate text and code effectively. Then ChatGPT’s release in November 2022 was a turning point from the product side: it brought chatbot-style interaction to a much broader public.

Anna
And the story continues from conversational assistants to agentic systems, including coding agents. The course plans to explore how that happened, particularly in its second part. But first, it starts with a more basic question: how do you get text into a form a model can work with?

Corey
That’s tokenization. A model works with numbers, not raw text, so tokenization divides text into units called tokens. Each token can then be represented mathematically, usually as a vector of numbers. For example, the sentence “a cute teddy bear is reading” might be split into six tokens, though a different tokenizer could split it differently.

Anna
The set of tokens a tokenizer is allowed to use is called its vocabulary. The vocabulary and the way it divides text determine the sequence length—the number of tokens in the input. That matters because the length of the sequence affects how much work the model has to do.

Corey
One simple option is word-level tokenization: treat spaces as boundaries, so each word is a token. It’s easy to understand and interpret, but it has drawbacks. English words have many forms, such as singular and plural, which can make the vocabulary large. And if a word wasn’t in the training vocabulary, it may be out of vocabulary when the model encounters it later.

Anna
Word-level tokens also don’t automatically share information about related forms. “Bear” and “bears” refer to the same animal, but if they’re separate tokens, there’s no guarantee their learned representations will be similar. The model may have trouble benefiting from the shared root.

Corey
At the other extreme, character-level tokenization uses individual characters. It can keep the vocabulary small and handle unfamiliar spellings or misspellings by reusing known characters. But it creates much longer sequences, and longer sequences take more computation to process. Individual-character representations can also be less interpretable than representations of whole words.

Anna
So a common compromise is subword tokenization. It breaks words into pieces that are smaller than words but can capture frequent letter combinations and word roots. For example, “reading” might be split into “read” and “ing.” Related forms such as “bear” and “bears” can then share a token.

Corey
A popular subword method is BPE, or byte-pair encoding. In broad terms, it starts with an initial set of tokens and repeatedly finds frequent pairs in the training data, merging them into new tokens until it reaches a chosen vocabulary size. Frequent combinations become single tokens, which can shorten sequences and make processing more efficient.

Anna
But the learned vocabulary depends on the data used to train the tokenizer. If you care about multiple languages, the tokenizer should be trained on a corpus that represents those languages. A shared vocabulary may use some of its space for each language, potentially leading to longer sequences for a particular language. On the other hand, languages can share useful patterns too, so the trade-off isn’t simply negative.

Corey
Modern language-model vocabularies are often on the order of hundreds of thousands of tokens, and the common subword approach is BPE. Tokenization also includes special tokens that communicate things beyond ordinary text.

Anna
For instance, an unknown token can stand in for a piece of text the vocabulary doesn’t contain. Beginning-of-sequence and end-of-sequence tokens, often shortened to BOS and EOS, mark where a generated sequence starts and finishes. A padding token can make sequences the same length, which can help when computations are arranged in batches.

Corey
There are also special tokens used to mark roles such as user and assistant. The exact spellings and conventions aren’t universal, so the important idea is that these tokens encode information about how to interpret parts of the sequence.

Anna
Once text is tokenized, the next question is how to represent each token in a useful way. The most basic representation is a one-hot vector: one position is one, and every other position is zero. But different tokens are all orthogonal under a dot product, so this representation says nothing about which tokens are similar.

Corey
What we want instead are meaningful representations: vectors that can reflect relationships between tokens. For instance, we might want “teddy bear” and “soft” to be related, while “book” might be less related. That matters because a model uses its input representations to do things such as predict a token or classify a text.

Anna
An early approach to learning such representations was Word2Vec. It learns from a proxy task—a task that helps produce useful representations but isn’t necessarily the final goal. In its continuous-bag-of-words version, the model predicts a word from its surrounding context; in skip-gram, it predicts surrounding words from a given word.

Corey
The basic setup is a small neural network. A one-hot input of vocabulary size V is transformed into a hidden representation of size D, and then another transformation produces scores for the vocabulary. A softmax can turn those scores into probabilities. The model compares its predictions with the correct target, uses a loss such as cross-entropy, and updates its weights.

Anna
For a simple example, suppose the model sees “a” and must predict “cute.” It gets probabilities for possible next words, and training pushes the probability for “cute” toward the correct target. Repeating this over many examples can produce hidden representations in the network that capture useful relationships, such as associations between words or patterns like Paris to France and Berlin to Germany.

Corey
Word2Vec has an important limitation: each word has one learned representation regardless of context. The word “bank” has different meanings in “river bank” and “go to the bank,” but this approach gives it the same representation in both cases. It also doesn’t account for word order: “the child hugs the teddy bear” and “the teddy bear hugs the child” contain the same words but express different relationships.

Anna
RNNs address the word-order issue by processing a sequence one token at a time and carrying a hidden state forward. That state is meant to summarize the sequence seen so far. The model can use the current token together with the state from earlier tokens, so its representation reflects order and prior context.

Corey
That made RNNs useful for tasks such as sentiment classification, predicting whether a word is a noun or a verb, and generating text. But a single state that keeps being updated can have trouble preserving information from far back in a sequence. That’s the long-range dependency problem.

Anna
For example, if a sentence uses “it” to refer to something mentioned much earlier, the model needs to retain the relevant information. RNNs can struggle to do that, in part because of the vanishing-gradient problem during backpropagation. LSTMs—long short-term memory networks—added a cell state intended to carry information for longer, but they still had limitations.

Corey
There’s another practical drawback: RNNs process tokens sequentially. To make a later prediction, the model needs the state produced by processing earlier tokens, so it has to work through the sequence step by step. That makes training slow, and the approach didn’t always produce the results researchers wanted.

Anna
Attention offered a different idea. Rather than relying only on one hidden state to summarize everything in the past, give a token direct connections to other tokens and let the model learn which ones matter. In translation, for instance, when producing a target-language word, it can be helpful to directly consult the source-language word that word is translating.

Corey
Self-attention takes that idea further. To build a representation of a token, the model can consider all the tokens in the sequence, rather than just the current token and a summary of what came before. This basic idea is central to the transformer.

Anna
The standard terms are queries, keys, and values—Q, K, and V. A query represents what a token is looking for; keys describe the tokens it might connect to; and values carry the information that will be combined. The query is compared with each key, and the resulting similarities determine how much weight to give each value.

Corey
Imagine the token is “teddy bear” and its query is effectively asking, “What helps describe me?” If the key for “cute” matches that query strongly, the value associated with “cute” contributes more to the teddy-bear representation. The result is a weighted combination of values, where the weights come from query–key similarity.

Anna
Queries, keys, and values are learned using projection matrices applied to the token representations. In matrix form, the core computation is commonly written as softmax of Q times K-transpose, scaled by the square root of the key dimension, and then multiplied by V. The softmax turns similarities into weights that sum to one.

Corey
Why does that matrix expression work? Q times K-transpose produces a table of query–key dot products: each row corresponds to a query and each column to a key. After softmax, those scores are weights. Multiplying by V takes a weighted sum of the value vectors for each query, giving the context-aware representations.

Anna
The 2017 transformer paper applied attention in an encoder–decoder architecture for machine translation. The encoder reads the source text and produces meaningful representations. The decoder uses those representations, along with the target sequence generated so far, to produce the translation.

Corey
At the input, each token gets an embedding from a learned lookup table. That embedding represents the token itself, but by itself it doesn’t tell the model where the token appeared. So the transformer adds a positional embedding to convey sequence position.

Anna
The original transformer used positional encodings built from sine and cosine functions at different frequencies. The intuition is that different frequencies can represent different positional patterns, somewhat like the hands of a clock turning at different rates. Learned position embeddings are another option, but if a model only learned positions up to a certain length, it may not have representations for longer positions.

Corey
The encoder then processes the input through layers that include self-attention and a feed-forward neural network. Self-attention lets each token’s representation incorporate information from other tokens in the source sequence. The feed-forward network projects representations through a higher-dimensional space and an activation function, helping the model learn nonlinear relationships.

Anna
At the end of the encoder, each source token has a context-aware representation. The decoder begins with a BOS token, adds its positional information, and applies masked self-attention. Masking means a token can attend to itself and earlier generated tokens, but not to future tokens that haven’t been generated yet.

Corey
The decoder also has cross-attention. Here, its queries come from the target-side representations, while keys and values come from the encoder’s source representations. That lets the decoder use the source sentence to decide what target-language token to produce.

Anna
Finally, the decoder’s output is projected to the vocabulary and passed through a softmax to produce probabilities for the next token. The model selects a token, feeds it back into the decoder, and repeats the process autoregressively until it produces EOS. The softmax inside attention and the final softmax have different jobs: one weighs connections between tokens, while the other gives probabilities over possible next tokens.

Corey
A few other design choices help the transformer train effectively. Residual connections add a layer’s input back to its output, so a layer can modify a representation rather than having to replace it entirely. They also help with backpropagation in deep networks.

Anna
Layer normalization normalizes activations and can help convergence. Dropout randomly removes some units during training so the model doesn’t rely too heavily on particular features, which can help it generalize. These ideas aren’t unique to transformers, but they’re useful parts of the architecture.

Corey
The transformer also uses multi-head attention. Instead of learning just one set of query, key, and value projections, it learns several attention heads in parallel. Each head can capture a different way for tokens to interact; their results are combined and projected back into the model’s representation space.

Anna
In the original setup, if the model dimension is D-model and a sequence has length N, the input can be represented as an N-by-D-model matrix. Projection matrices turn it into queries, keys, and values. Queries and keys need compatible dimensions to be compared, and the attention calculation produces an N-by-N table of token-to-token scores before those scores are applied to the values.

Corey
With multiple heads, each head works in its own projected space. The results are concatenated and passed through another projection so the representation returns to the model dimension. Then the feed-forward network typically expands the model dimension to a larger hidden dimension and maps it back. The original paper stacked six encoder blocks and six decoder blocks.

Anna
Label smoothing is another training technique mentioned in the original transformer work. Instead of asking the model to assign all the target probability to one token, it softens the target distribution—for example, assigning most of the probability to the correct word and a small amount to alternatives. That reflects the fact that language can often be completed in more than one valid way.

Corey
Putting the whole translation example together: tokenize the English sentence, add token and position embeddings, run the source through the encoder, then start the decoder with BOS. The decoder repeatedly uses masked self-attention and cross-attention to predict target-language tokens, and generation ends when EOS appears.

Anna
So what is the essential idea behind the transformer? The paper title gives the headline: attention is central. The feed-forward networks also contain a large share of the model’s parameters and learning capacity, while residual connections, normalization, dropout, and related choices help the system train more effectively.

Corey
And that original 2017 translation architecture is a starting point, not the end of the story. Later lectures will look at how language models are trained and how they can power agents and other systems. The key foundation from today is the path from text, to tokens, to representations, and then to attention-based computation.

Anna
That path also explains why the course begins with tokenization and embeddings before the full transformer. Once those pieces are clear, it becomes easier to understand how a model can connect words across a sequence, generate one token after another, and ultimately support the language tools and agents we use today.

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