Transformers and Large Language Models
Foundations of Natural Language Processing and Transformers
Natural Language Processing and Its Main Task Types
Natural Language Processing (NLP) is the field concerned with computationally handling human language. Because machine-learning models operate on numerical representations rather than text directly, NLP systems must transform text into forms that models can process.
NLP tasks can be grouped into three broad categories:
Text classification
A model receives a text input and predicts a category or label.
Sentiment classification: predicts whether a review expresses a positive, negative, or neutral sentiment.
Intent detection: identifies what a person wants to do, such as creating an alarm.
Language detection: identifies the language of a text.
Topic classification or modeling: identifies the subject matter associated with a text.
Token or entity classification
A model receives a text and predicts labels for multiple parts of it, often individual tokens. Named Entity Recognition (NER) is a common example: it identifies text spans that refer to categories such as people, locations, or times.
Other token-level linguistic tasks include:
Part-of-speech tagging: identifying whether each word is a noun, verb, and so on.
Parsing: identifying grammatical structure, including relationships between words or the hierarchical structure of a sentence.
These tasks differ from sentence classification because predictions are attached to words, spans, or entities rather than to the whole sentence.
Text generation
A model receives text and produces text in response. The output can have a variable length, so its size is not necessarily known in advance.
Examples include:
Machine translation: converting text from a source language to a target language.
Question answering: producing an answer to a question.
Summarization: producing a shorter version of a document.
Open-ended generation: producing text such as a poem, explanation, or code.
Evaluating NLP Systems
The appropriate evaluation method depends on the task. Classification metrics measure agreement with labels, while generation metrics must account for the many valid ways of expressing the same idea.
Classification metrics
Accuracy is the proportion of examples for which the model predicts the correct label.
Precision asks: among the examples predicted to be positive, what proportion are truly positive?
Recall asks: among all truly positive examples, what proportion did the model correctly identify?
F1 score combines precision and recall using their harmonic mean:
Accuracy can be misleading when the classes are imbalanced. For example, if 99% of examples are positive and 1% are negative, a model that always predicts the positive class achieves 99% accuracy while never detecting a negative example. Precision and recall help reveal this kind of failure.
For token classification and NER, metrics can be computed at the token level or aggregated by entity type. For example, a system’s ability to identify locations can be evaluated separately from its ability to identify times.
Generation metrics
Translation and other generation tasks are harder to evaluate because multiple outputs may be correct even when they differ from a single reference.
BLEU compares a generated translation with one or more reference translations using text overlap.
ROUGE is a family of overlap-based metrics often used for generation and summarization.
Both require reference text, which means that human-produced labels or reference outputs are needed.
Perplexity measures how well a language model assigns probability to text. A lower perplexity generally indicates that the model finds the text less surprising.
Reference-based measures such as BLEU and ROUGE have limitations: they may penalize valid wording that differs from the reference. Model-based, reference-free evaluation is another approach to generation assessment.
How Language Modeling Developed
The central goal of many language models is to learn useful patterns in language and use them to represent or generate text.
Recurrent neural networks (RNNs) and related sequence models were explored well before modern large language models.
Word2vec helped popularize learned word embeddings: numerical representations that capture useful relationships between words.
The transformer, introduced in 2017, established the architecture underlying many modern language models.
Later models grew in the amount of training data and computation used, helping produce the large language models that became widely prominent in the 2020s.
The development of these systems depended not only on new architectures but also on access to large datasets and sufficient computing resources.
Tokenization: Turning Text into Units
Models need a way to divide text into pieces they can represent numerically. Tokenization is the process of splitting text into these units, called tokens. A token may be a word, part of a word, character, or another chosen unit.
Word-level tokenization
A word-level tokenizer treats each word as a distinct token.
It is straightforward and keeps sequences relatively short.
Related forms such as “bear” and “bears” become separate tokens, even though they share a root and meaning.
A word that was not encountered during training may be impossible to represent as a known token. This is an out-of-vocabulary (OOV) problem.
A system can reserve a special unknown-token representation for unseen words, but this does not capture the identity of the unfamiliar word.
Subword tokenization
A subword tokenizer splits some words into smaller, reusable pieces. Related words can share a common subword, such as a root or stem.
It can represent many word forms using a shared vocabulary of pieces.
It reduces the risk of encountering an entirely unknown word compared with word-level tokenization.
A word may require multiple tokens, making the sequence longer.
Subword tokenization is often a practical balance: it preserves some meaningful word structure while controlling vocabulary size and OOV risk.
Character-level tokenization
A character-level tokenizer represents text one character at a time.
It can handle unfamiliar spellings and many misspellings because its basic units are widely reusable.
It generally avoids the same kind of whole-word OOV problem.
It produces much longer sequences, increasing computation and inference time.
Individual characters often carry less semantic information than words or subwords, making it harder for the model to build meaningful representations.
Choosing a vocabulary size
The appropriate token vocabulary depends on the language and task. A single-language system may use a vocabulary on the order of tens of thousands of tokens, while multilingual systems or systems that also handle code may use vocabularies on the order of hundreds of thousands. Larger vocabularies can represent more text in fewer pieces, but require more vocabulary entries and associated model parameters.
Representing Tokens with Vectors
Once text has been tokenized, each token must be represented numerically.
One-hot encoding
A simple representation assigns each vocabulary item a vector with a 1 in its own position and 0 everywhere else. For a vocabulary of size V, each one-hot vector has dimension V.
For example, with a vocabulary containing “soft,” “teddy bear,” and “book,” each token receives a different vector with a single nonzero entry.
One-hot vectors are easy to construct, but they do not express semantic relationships:
Distinct one-hot vectors are orthogonal.
Their similarity does not reflect whether their tokens have related meanings.
The representation dimension grows with vocabulary size.
A model needs a representation in which related tokens can have similar vectors.
Vector similarity
Cosine similarity compares the angle between two vectors. It is based on the normalized dot product:
Vectors pointing in similar directions have high cosine similarity; orthogonal vectors have similarity near zero. Cosine similarity focuses on direction rather than vector magnitude.
A useful learned representation might place “teddy bear” closer to “soft” than to “book,” depending on the contexts in which the tokens occur.
Learning Word Representations with Word2vec
Word2vec is a family of methods for learning word embeddings from text. Instead of assigning unrelated one-hot vectors as the final representations, the model learns dense vectors that encode useful patterns.
Word2vec uses a proxy task: it trains a model to predict words from their context, then uses the learned internal representations as embeddings. The prediction task is useful because solving it encourages the model to capture regularities in language.
Continuous bag of words and skip-gram
Continuous bag of words (CBOW): uses surrounding words to predict a target word.
Skip-gram: uses a target word to predict surrounding words.
The two approaches reverse the direction of prediction but share the idea of learning from contextual relationships.
A simple prediction model
A vocabulary of size V can be represented with one-hot input vectors. A neural network maps an input vector to a smaller hidden representation of dimension d, then produces scores over the vocabulary. A softmax converts those scores into probabilities for possible next or neighboring tokens.
During training:
The model receives a token, often represented with a one-hot vector.
It computes a hidden representation through learned weights.
It predicts a target token or context word.
A loss, often cross-entropy, measures the difference between the prediction and the correct target.
Backpropagation updates the weights to improve future predictions.
The learned hidden representation can then serve as the token embedding. For a one-hot input, multiplying by the embedding weights selects the corresponding token’s vector.
The objective is not necessarily to use the trained model only for its prediction task. The prediction task is a way to learn representations that may be useful for other tasks.
Embedding dimensions and training
Embedding dimensions are chosen as a trade-off:
More dimensions can provide greater representational capacity for complex tasks.
More dimensions also increase computation, memory use, and potentially inference cost.
Simpler downstream tasks may need less representational capacity than more demanding ones.
Training can be monitored using the proxy-task loss. A common stopping approach is to monitor the loss over repeated passes through the training data, called epochs, and stop when it has converged sufficiently. The most suitable stopping point can depend on how well the representations perform on a downstream task.
Why contextual word representations are needed
A static embedding assigns a word the same representation regardless of where it appears. However, a word can have different meanings in different contexts. For instance, “bank” can refer to a financial institution or the side of a river. A representation that changes according to surrounding words is contextual; later sequence models and attention mechanisms are designed to capture this context.
Recurrent Neural Networks
A recurrent neural network (RNN) processes a sequence one token at a time while maintaining a hidden state. The hidden state is intended to summarize the sequence processed so far.
At each time step, an RNN combines the current token representation with the previous hidden state:
Here, xt is the representation of the token at time step t, and ht is the updated hidden state. The exact function f depends on the network’s learned operations.
Using RNNs for different NLP tasks
Sentence classification: the final hidden state can be used as a summary of the sentence and mapped to a label, such as positive or negative sentiment.
Token classification: hidden states at individual positions can be used to predict labels for the corresponding tokens.
Generation or translation: an encoder can process an input sequence into a final state, which a decoder then uses to produce an output sequence.
RNNs incorporate word order, unlike an unordered average of token embeddings. However, the final state must carry information about earlier tokens, which becomes difficult for long sequences.
Long-range dependencies and vanishing gradients
When an RNN is trained to predict a later token, the training signal must propagate backward through the earlier computations that produced its hidden states. This process is called backpropagation through time.
Repeated multiplication of gradient-related quantities can cause:
Vanishing gradients: values shrink toward zero, making it difficult to update parameters associated with earlier parts of the sequence.
Exploding gradients: values grow excessively large, producing unstable updates.
The vanishing-gradient problem makes it hard for an RNN to retain information over long distances. RNNs also process tokens sequentially, so later computations depend on earlier ones, limiting parallel processing and making long sequences slow to handle.
LSTMs: Extending Recurrent Networks
A Long Short-Term Memory (LSTM) network extends the recurrent approach to improve the handling of information over time. In addition to a hidden state, an LSTM maintains a cell state intended to carry information that should be preserved across sequence steps.
The cell state gives the model a mechanism for managing what it retains or discards. This helps address the difficulty that basic RNNs have with long-range dependencies, though it does not remove every limitation of recurrent architectures. LSTMs still process sequences sequentially.
Attention: Connecting Relevant Parts of a Sequence
Attention provides a direct way for a model to connect a prediction with relevant information from other positions in a sequence. Rather than relying only on a single hidden state to preserve the entire past, an attention mechanism can look back at multiple earlier representations.
For example, when translating a sentence, the model producing a target-language word can use attention to focus on the relevant parts of the source-language sentence. This is especially useful when the relevant source word is far from the current position in the output.
Queries, keys, and values
Attention represents the matching process using three learned quantities:
A query expresses what the current position is looking for.
A key represents what each candidate position offers for matching.
A value contains the information to retrieve from that position.
The model compares a query with keys to estimate relevance. It then uses those relevance weights to form a weighted combination of the corresponding values. The query, key, and value vectors are produced using learned projections of the input representations.
In self-attention, queries, keys, and values are derived from the same sequence. Each token can therefore build a representation using information from other tokens in that sequence. The resulting representation is contextual: the same word can have different vectors in different sentence contexts.
The Transformer Architecture
The transformer is built around attention and processes sequence relationships without the RNN’s token-by-token recurrent mechanism. Its self-attention layers let tokens connect directly with other positions in the sequence, while matrix operations allow much of the computation to be parallelized.
The original transformer architecture has an encoder and a decoder, particularly suited to sequence-to-sequence tasks such as translation:
The encoder builds contextual representations of the source text.
The decoder produces the target text one token at a time, using both the encoded source and the output tokens generated so far.
Transformer Inputs: Embeddings and Position
Each input token is first mapped to a learned embedding. Self-attention alone does not indicate the order in which tokens appeared, so the transformer adds positional information to the token representations.
The original transformer uses positional encodings based on sine and cosine functions. These are added element by element to the token embeddings, allowing the model to use information about token positions while processing the sequence.
For a sequence of length n and embedding dimension dmodel, the token representations can be arranged in a matrix with one dimension for sequence positions and one for embedding features.
Scaled Dot-Product Self-Attention
Given matrices of queries Q, keys K, and values V, scaled dot-product attention is:
Here, dk is the dimension of the key vectors. The computation proceeds as follows:
The product QK⊤ computes a query–key similarity score for each query and key pair.
Dividing by dk scales these scores. Without scaling, dot products can grow with vector dimension, which can make softmax distributions too concentrated.
Softmax turns each query’s scores into weights over the keys.
Multiplying those weights by V produces a weighted sum of value vectors for each query.
Each output is therefore a mixture of information from the sequence, weighted by how relevant other positions are to the query.
Multi-Head Attention
Multi-head attention performs attention several times in parallel using different learned query, key, and value projections. Each head can learn a different way of connecting positions or extracting information.
If there are h heads, their outputs are concatenated and passed through an additional learned projection. Conceptually:
The different heads are not forced to learn distinct patterns, but training can lead them to develop different useful representations. The concatenation and final projection combine those representations into the model’s required output dimension.
Encoder Layers
The encoder repeatedly applies attention and feedforward processing:
Self-attention: each input token can incorporate information from other tokens in the source sequence.
Feedforward network (FFN): a position-wise neural network further transforms each token’s representation.
The FFN provides additional representational capacity. In transformer layers, its internal hidden dimension is typically larger than the input and output dimensions, giving the model room to construct richer features.
The encoder is commonly stacked into multiple layers. Its final output is a sequence of contextualized representations: each vector represents an input token in light of the other tokens in the source sentence.
Decoder Layers and Cross-Attention
The decoder produces a target sequence autoregressively, meaning that each new token is predicted using the tokens generated so far.
Masked self-attention
The decoder uses causal, or masked, self-attention. At a given output position, it can attend to the current position and earlier output positions, but not to future positions. This prevents the model from using information that would not yet be available during generation.
Cross-attention
The decoder also uses cross-attention to connect the target-generation process with the encoder’s source representations:
Queries come from the decoder’s current representations.
Keys and values come from the encoder outputs.
This lets the decoder determine which parts of the input are most relevant to predicting the next output token.
Feedforward processing and prediction
After attention, the decoder uses a feedforward network to further transform its representations. At the end of the decoder stack, a linear projection produces scores over the vocabulary. Softmax converts these scores into a probability distribution for the next token.
The decoder begins with a beginning-of-sequence token, often called BOS. After it predicts a token, that token becomes part of the decoder input for the next prediction. Generation continues until the model produces an end-of-sequence token, often called EOS.
Translation with an Encoder–Decoder Transformer
A translation system using the transformer follows this overall process:
Tokenize the source-language text and add the required sequence boundary tokens.
Convert tokens into embeddings and add positional information.
Pass the source sequence through the encoder to obtain contextual representations.
Start the decoder with a BOS token.
Use masked self-attention to represent the target tokens generated so far.
Use cross-attention to select relevant information from the encoded source.
Predict a probability distribution over the vocabulary and choose the next token.
Continue until EOS is generated.
Because the encoder’s representations are available to decoder layers through cross-attention, the decoder need not rely on a single fixed-size vector to retain the whole input sentence.
Label Smoothing
In language generation, a given context may allow multiple reasonable next tokens. Label smoothing reflects this by replacing a completely certain one-hot target with a softer target distribution.
For a vocabulary of size V and a smoothing parameter ε, the correct class receives target probability 1−ε, while the remaining probability is distributed among the other classes:
This discourages the model from treating the observed target as the only possible continuation. It can improve generalization and has been used to improve translation metrics such as BLEU.
Key Conceptual Progression
The major ideas connect as follows:
Tokenization divides text into units a model can process.
Embeddings turn those units into numerical vectors.
Word2vec-style proxy tasks learn useful static token representations from context.
RNNs and LSTMs process ordered sequences and maintain hidden state, but can struggle with long-range information and sequential computation.
Attention directly connects a representation to relevant positions elsewhere in a sequence.
Transformers use self-attention, positional information, and feedforward layers to build contextual representations and generate sequences efficiently.
The transformer’s attention mechanism allows each token’s representation to depend directly on other relevant tokens, enabling contextual meaning to be computed across a sequence rather than stored only in a recurrent hidden state.

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