Transformers and Large Language Models


Transformers and Large Language Models

Simon
Welcome to our introduction to transformers and large language models. Let’s begin with the course’s big picture: what is natural language processing, or NLP? It’s the field of building methods that work with text, and we can group many NLP tasks into three broad categories.

Anna
The first is classification: give a model some text and ask it to predict a label. For example, it might decide whether a movie review is positive, negative, or neutral. Intent detection is another example: if someone says, “I want to create an alarm for tomorrow,” the intent is to create an alarm.

Simon
Other classification examples include identifying a text’s language or topic. To evaluate a classifier, we might use accuracy: the fraction of examples it predicts correctly. But accuracy can hide problems when the classes are imbalanced.

Anna
Imagine that 99 percent of examples are positive and only 1 percent are negative. A model that always predicts positive gets 99 percent accuracy, yet it never finds a negative example. That’s why we also look at precision and recall.

Simon
Precision asks: of all the examples the model predicted as positive, what fraction really are positive? Recall asks: of all the truly positive examples, what fraction did the model find? The F1 score combines precision and recall using their harmonic mean.

Anna
The second category makes more than one prediction for an input. Named Entity Recognition, or NER, is a familiar example: given a sentence, label words or groups of words as things like locations or times. We can evaluate those predictions at the token level or aggregate performance by entity type.

Simon
There are also more linguistically oriented tasks, such as part-of-speech tagging—deciding whether a word is a noun or verb—and parsing tasks that analyze grammatical relationships. These are examples of making structured predictions across a text.

Anna
And the third category is generation: text goes in, and text comes out, with an output length that may vary. Machine translation, question answering, summarization, and generating code or a poem all fit this broad pattern.

Simon
Translation is a useful example because the model must produce a target-language sentence from a source-language sentence. Evaluation is trickier than ordinary classification: there can be several valid ways to translate the same idea.

Anna
One traditional approach is to compare the model’s translation with a reference translation. BLEU and ROUGE are examples of reference-based metrics, though ROUGE is a family of metrics. They provide useful comparisons, but they depend on having reference text.

Simon
And obtaining those references takes time and money. Another metric you may encounter is perplexity, which is based on the probabilities produced by the model and reflects how surprised the model is by the text. For BLEU and ROUGE, higher is generally better; for perplexity, lower is better.

Anna
The course will also look at newer ways to evaluate language models that can rely less on reference texts. The key point for now is that generation quality is harder to measure than simply checking whether a predicted label matches the answer.

Simon
Large language models may have become a major public topic with ChatGPT in 2022, but the underlying ideas have a longer history. Some model ideas go back to the 1980s, and LSTMs appeared in the 1990s.

Anna
Those earlier approaches were constrained by the available data and computing power. Later, Word2vec helped popularize meaningful word embeddings, and the 2017 transformer paper introduced the architecture that underpins many models used today. Scaling models with more data and compute helped lead to what we now call LLMs.

Simon
That history raises a basic challenge: computers work with numbers, while people communicate with text. So before a model can process a sentence, we need to split it into units and represent those units numerically. Splitting text into units is called tokenization, and each unit is a token.

Anna
There are several ways to choose tokens. At the word level, a sentence is split into whole words. That’s simple, but words that are closely related—like “bear” and “bears”—become separate tokens, even though they share a root.

Simon
Word-level tokenization can also create an out-of-vocabulary problem, or OOV. If a model encounters a word at prediction time that it did not see during training, it may have to mark that word as unknown. The more word forms we need to handle, the harder that can become.

Anna
Subword tokenization is a compromise. It breaks words into smaller pieces that can capture common roots, so “bear” and “bears” can share a piece. That can reduce the risk of an unknown word, but the resulting sequence has more tokens.

Simon
That longer sequence matters because processing cost depends in part on sequence length. Character-level tokenization goes further and splits text into individual characters. It can be robust to misspellings and casing errors, but sequences become much longer, and individual letters are difficult to interpret as meaningful units.

Anna
So each choice has a trade-off: words are simple but can have more OOV cases; subwords make use of roots and reduce that risk; characters handle some spelling variation but produce long sequences. The vocabulary size also depends on the language and on whether the tokenizer is multilingual.

Simon
As a rough scale discussed in class, a tokenizer for one language might have tens of thousands of tokens, while multilingual or code-focused systems may use vocabularies in the hundreds of thousands. Those are broad orders of magnitude, not a rule that every model must follow.

Anna
Once text has been split into tokens, we need a numerical representation for each one. A very simple option is one-hot encoding: give every token its own vector, with a one in its position and zeros everywhere else.

Simon
For a vocabulary with three tokens—say, “book,” “soft,” and “teddy bear”—each token gets a different vector, such as one-zero-zero, zero-one-zero, or zero-zero-one. It distinguishes tokens, but it doesn’t express that some tokens are more related than others.

Anna
Exactly. With one-hot vectors, different tokens point in orthogonal directions. But we might want “teddy bear” and “soft” to have more similar representations than “teddy bear” and “book.” Cosine similarity is one way to compare the angle between vectors; it focuses on whether they point in similar directions.

Simon
That motivates learning embeddings from data rather than assigning unrelated one-hot vectors as the final representations. Word2vec, a widely influential method from the 2010s, showed how to learn useful word representations through a prediction task.

Anna
Word2vec is associated with two approaches. Continuous bag of words uses the surrounding words to predict a target word. Skip-gram reverses that direction: start with a target word and predict the words around it.

Simon
Those prediction tasks are often called proxy tasks. The main goal is not necessarily to use the model’s prediction as the final product; it’s to make the model learn representations that capture useful patterns in language. If the representations support prediction, they may encode relationships between words.

Anna
A simple example uses a neural network. A one-hot vector for a word goes into the network, passes through a smaller hidden layer, and the model predicts a following or surrounding word. The hidden layer’s learned weights give that word a dense representation—its embedding.

Simon
During training, the model compares its probability predictions with the correct next word, often using cross-entropy loss. Backpropagation updates the weights to reduce the error, and the process repeats across examples. The learned hidden representation is the useful output for our purposes.

Anna
The vocabulary size is the number of possible tokens the model can represent. A toy example might use six tokens, but real vocabularies are much larger. Models can reserve an unknown-token representation for inputs they cannot identify, though subword tokenization can reduce how often that situation arises.

Simon
The embedding dimension is a design choice. A larger vector can provide more capacity for a complicated downstream task, but it also takes more computation and can affect inference cost. In practice, people often draw on dimensions used by existing systems, while balancing task complexity, latency, and cost.

Anna
There’s an important limitation, though: a word embedding learned this way is tied to the token, not to the particular sentence where it appears. A word with different meanings in different contexts can receive the same representation. And these basic embeddings don’t, by themselves, represent word order.

Simon
A tempting way to represent a whole sentence is to average its word embeddings. But averaging loses order and can lose meaning. To represent a sequence more directly, researchers developed recurrent neural networks, or RNNs.

Anna
An RNN processes tokens one at a time and keeps a hidden state that summarizes the sequence so far. At each step, it combines the current token with the previous hidden state. That gives the model a way to account for word order.

Simon
For a classification task such as sentiment analysis, we might use the final hidden state to predict a label. For token-level labeling, we can make predictions for particular tokens. For generation, a summary of the input sequence can help guide the output.

Anna
The challenge is that an RNN has to carry information forward through a sequence of steps. Its hidden state can struggle to preserve details from far back in a long text. That difficulty is often described as a long-range dependency problem.

Simon
LSTMs—Long Short-Term Memory networks—were designed to improve how recurrent models keep track of information. They include a cell state in addition to the hidden state. That gives the model another mechanism for carrying information considered important, although it doesn’t eliminate every difficulty.

Anna
One underlying training issue is the vanishing gradient. To update a prediction near the end of a sequence, training has to pass information backward through earlier steps. The resulting gradient can involve products of many quantities.

Simon
If those quantities are repeatedly below one, their product can become extremely small, so updates to earlier parts of the sequence become difficult. If they are repeatedly above one, the product can grow very large—an exploding gradient. These issues, and the need to process steps sequentially, made long sequences challenging for RNN-based approaches.

Anna
That brings us to attention. Instead of relying only on a summary carried through every step, attention creates a more direct link between what the model is working on now and relevant parts of the earlier text.

Simon
The transformer made this idea central. The 2017 paper “Attention Is All You Need” proposed moving away from processing a sentence strictly one token at a time. With self-attention, each token can directly draw on other tokens in the same sequence.

Anna
That makes a token’s representation depend on its context. For example, the representation of “bank” could differ depending on whether the sentence is about a riverbank or robbing a bank. The model can use its relationships with surrounding tokens to build that context-aware representation.

Simon
To describe attention, we use three terms: query, key, and value. The query represents what a token is looking for; keys help measure how relevant other tokens are to that query; and values are the representations that get combined according to those relevance scores.

Anna
For each query, the model compares it with keys, turns those comparisons into weights, and uses the weights to form a weighted sum of the corresponding values. The query, key, and value representations are learned through projections rather than being fixed by hand.

Simon
Here’s the standard self-attention calculation in words: project the input embeddings to get matrices Q, K, and V; multiply Q by the transpose of K; scale the result by the square root of the key dimension; apply softmax; and multiply by V. Softmax turns the scores into weights that sum to a distribution for each query.

Anna
The scaling matters because the dot products can grow as the query and key dimensions grow. Dividing by the square root of the key dimension helps normalize those scores before softmax. The result for each query is a weighted combination of values.

Simon
Transformers commonly use multi-head attention: they perform attention several times in parallel, with different learned query, key, and value projections. The heads can learn different relationships, and their outputs are concatenated and projected back to the model’s embedding dimension.

Anna
There’s no rule forcing each head to learn something different, but the training objective gives the model room to learn useful representations. The multi-head setup gives it multiple ways to relate tokens, somewhat like having multiple filters in a convolutional network.

Simon
The original transformer is an encoder-decoder architecture, introduced for translation. The encoder reads the source sentence and builds contextual representations. The decoder uses those representations to generate the target sentence one token at a time.

Anna
In the encoder, tokens use self-attention to relate to tokens across the input sentence. The attention output then passes through a feedforward network, or FFN, which gives the model another learned transformation. The original architecture stacks multiple encoder modules.

Simon
The decoder has two kinds of attention. Its masked self-attention looks at the tokens generated so far, not future output tokens. Its cross-attention uses the decoder’s current representation as the query and the encoder’s representations as keys and values.

Anna
That cross-attention lets the decoder ask which parts of the source sentence matter for the next translation step. The decoder also has a feedforward network, and the original architecture stacks decoder modules as well. Encoder outputs are available to the cross-attention layers.

Simon
There’s a catch: self-attention alone doesn’t tell the model which token came first or where a token sits in the sequence. Transformers therefore add positional information to token embeddings. In the original paper, this used sine and cosine functions added to the embeddings.

Anna
Let’s trace the full translation process. First, tokenize the input and add beginning-of-sequence and end-of-sequence markers. Then look up learned token embeddings and add positional information, creating a sequence of position-aware vectors.

Simon
Those vectors go through the encoder’s stacked attention and feedforward layers. The encoder produces contextual representations of the source tokens. The decoder starts with a beginning-of-sequence token, then uses masked self-attention and cross-attention to produce a representation for its next prediction.

Anna
A final linear projection produces scores over the vocabulary, and softmax turns those scores into probabilities. The model chooses or generates a next token, feeds it back into the decoder, and repeats the process until it generates an end-of-sequence token.

Simon
One training technique mentioned for translation is label smoothing. Instead of treating the correct next word as the only possible answer with probability one, it spreads a small amount of probability across other labels.

Anna
That reflects the fact that language often has more than one plausible continuation. Label smoothing makes the target less absolute, and the transformer paper reported that it could improve metrics such as BLEU for translation.

Simon
So we’ve moved from the basic challenge of turning text into numbers, through tokenization and embeddings, to sequence models and attention. The transformer combines contextual self-attention, positional information, and stacked encoder and decoder components to support tasks such as translation.

Anna
And that’s the foundation for the rest of the subject: how these models are trained, how they’re applied, and what their limitations are. The central idea to carry forward is that attention lets a model relate a token directly to other relevant tokens, rather than depending only on a single sequential summary.

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