Neural Language Models
November 8, 2026 · Updated November 14, 2026
Contents
Language modelling is the task of predicting what word comes next.
For example: “My name is ____”.
More formally, given a sequence of words , compute the probability distribution of the next word :
A system that does this is called a language model.
Word Representation
Vectors
Words can be represented by one-hot vectors, where each word has its own position in the vocabulary. Its vector contains a at that position and everywhere else. The vector dimension equals the number of words in the vocabulary.
Suppose our vocabulary is [notebook, laptop, banana]. Each vector has three dimensions:
| Word | Vector |
|---|---|
| notebook | [1, 0, 0] |
| laptop | [0, 1, 0] |
| banana | [0, 0, 1] |
One-hot vectors identify words, but do not capture how their meanings relate. The vectors for distinct words are orthogonal, so their dot products are zero:
- .
- .
Their cosine similarities are also zero. So “notebook” is just as dissimilar to “laptop” as it is to “banana” according to these vectors, even though “notebook” (meaning a notebook computer) and “laptop” have similar meanings in this context.
We can approach this by learning a word’s vector through training it to predict nearby words. When the target word is “laptop,” nearby words might include “charged,” “my,” and “battery.” Training adjusts the word vectors so that these observed neighbors become easier to predict. Repeating this across many sentences builds the representation.
This uses dense word vectors: lists of learned numbers, generally with many nonzero entries, unlike one-hot vectors. A dense vector is a distributed representation, meaning that information about a word is spread across multiple coordinates. No single coordinate has to mean “laptop.”
For example, an illustrative four-dimensional vector for “laptop” might be:
Its second coordinate is , but that number alone does not identify “laptop” or necessarily correspond to a named feature such as “portability.” The useful relationships come from the learned coordinates together. These numbers are only an example, not values from a trained model.
With 10,000 words, a one-hot vector has 10,000 dimensions. Because words share usage patterns, we can represent them using fewer dimensions in a dense vector (here, 2 dimensions) while preserving useful relationships.
In this illustrative diagram:
- “index,” “retrieval,” and “search” point in similar directions, indicating related usage.
- “data,” “science,” and “computer” form another group.
- “information” lies between the groups, suggesting a connection to both.
Small angles between vectors mean high cosine similarity. This gives us the similarity that one-hot vectors lacked.
Word2Vec
Word2Vec introduces two ways to learn word vectors [1]:
- Skip-gram: predicts context words given a center (target) word.
- Continuous Bag of Words (CBOW): predicts the target word from its surrounding context, treated as a bag of words.
Skip-Grams
We start with a large corpus of text and randomly initialized word vectors for a fixed vocabulary. At each position , we treat the word there as the center word and nearby words as context (outside) words .
Skip-gram uses a dot-product similarity between a center-word vector and an outside-word vector to compute , the probability of an outside word given the center. The model learns separate center and outside vectors for each vocabulary word. We keep adjusting these vectors to increase the probabilities of the observed center–context pairs. CBOW reverses the prediction direction, using the surrounding words together to predict the center word.
For “compiled Java code can run on all,” a context window of size 2 takes up to two words on either side. First, “code” predicts “compiled,” “Java,” “can,” and “run.” Moving one position forward makes “can” the center, with “Java,” “code,” “run,” and “on” as its context:
p(compiled | code)
p(Java | code)
p(can | code)
p(run | code)
Train on four center–context pairs with “code” as the center.
p(Java | can)
p(code | can)
p(run | can)
p(on | can)
Train on four center–context pairs with “can” as the center.
The training objective for skip-gram is to make the context words that actually occur in the text highly probable. One prediction,
means: given the center word , what probability does the model assign to its observed neighbor ?
| Symbol | Meaning |
|---|---|
| Current center position | |
| Offset from the center, for example when | |
| Context window size on each side of the center | |
| Number of token positions in the training text | |
| The model’s learned parameters, including its word vectors |
For each position , predict the context words within a fixed window of size , given the center word . We skip because the center word is not its own context target. Terms whose context positions fall outside the text are omitted. The data likelihood is:
For the “code” window above, its contribution is:
Then multiply these contributions across all center positions. Training aims to maximize this product.
To use gradient descent, we turn this into a loss to minimize:
The transformation is:
- Log: turns a product into a sum, making computation easier and avoiding products of many tiny probabilities.
- Minus sign: turns maximization into minimization.
- Divide by : averages the summed context loss over center positions.
Recurrent Neural Networks
In a feedforward network (FFN), information moves from the input (pink) through hidden layers (green) to the output (blue). It has no carried state, so processing a new input does not automatically use information from previous inputs. For example, it can predict the next word from a fixed window of words supplied as input, but it cannot remember earlier words outside that window unless they are explicitly included in its input.
A recurrent neural network (RNN) processes a sequence one item at a time. Each step uses both the current input and a hidden state from the previous step. The hidden state is a vector of numbers that represents the RNN’s internal memory at a particular step. It’s called hidden because it is an internal representation rather than the input or the final prediction.
We can process the sequence of input vectors (the red boxes) by applying a recurrence formula at every time step:
We can unroll this recurrence to follow the hidden state while reading “the cat sat”:
- After “the”, the hidden state contains information from “the”.
- After “cat”, it is updated using “cat” and the previous state.
- After “sat”, it contains a compressed representation of the sequence so far.
The same function and set of parameters are used at every time step.
Kinds of RNNs
This is an example of a many-to-one RNN because it reads several inputs and produces one output for the whole sequence.
The diagram on the right is a many-to-many RNN. It receives an input and makes a prediction at every step. It also shows how we combine the prediction errors to train it. Each measures error at one position:
The arrows leading to the large indicate that these errors are combined by summing or averaging. Here as well, the same weights are reused at every step, so errors from all positions help train that shared computation.
A one-to-many RNN uses one input to generate a sequence of outputs. Here, could be a vector representing the image, and each predicts a word in the caption. An example is image captioning:
A sequence-to-sequence RNN reads an input sequence and then generates an output sequence. The two sentences can have different lengths. It has two stages:
- Encoder RNN: Reads the input tokens (), which are converted to embeddings. Its hidden state updates as it reads. The final encoder state contains a compressed summary of the input.
- Decoder RNN: The thick arrow passes the summary to the decoder, giving it information about what to generate. The decoder uses its first hidden state to produce , then uses its evolving hidden state and the previously generated token to produce each subsequent output .
An example is translation:
In a multi-layer RNN, several RNN layers stack on top of one another. Each layer has its own hidden state and memory. This diagram has three recurrent layers (green) and an output layer (blue). A higher layer receives the current hidden state from the layer below, plus its own memory from the previous time step. For example, for input , layer 3 combines layer 2’s new hidden state at with its own previous hidden state from . The two source states are marked with crosses in the diagram.
Stacking lets the model learn more complex representations through successive transformations. For example, layer 1 might learn to recognize words and local patterns, layer 2 might combine those patterns into information about what is being described, and so on. Weights are shared across time within a layer, but different layers have their own weights.
A bidirectional RNN processes the same sequence in both directions, so each prediction can use context from before and after a word. Each input goes into both RNNs. Their hidden states at that position are then combined (often by concatenating the two vectors) to compute . For example, consider:
“She sat by the bank of the river.”
At “bank”:
- The forward state has read “She sat by the bank.”
- The backward state has read “river the of bank.”
- Combining them helps the model recognize that “bank” refers to a riverbank.
The two directions usually have different learned weights. Within each direction, those weights are reused across all positions.
RNN Language Model
In an RNN language model, the embedding matrix maps each input word to a vector. The RNN uses that vector to update its hidden state. After reading the prefix, the final hidden state summarizes the words seen so far. The model uses this summary to predict the next word through a probability distribution over the vocabulary. For example, the “retrieval” bar in the diagram represents:
Repeating this prediction at each position and multiplying the probabilities assigned to the actual next words gives the model’s probability for the whole sequence:
Each conditional distribution is computed from the RNN hidden state summarizing the preceding words. For , the prefix is empty.
From Hidden States to Probabilities
The hidden state is not itself a probability distribution over words. Unembedding and softmax turn it into one:
-
A learned transformation maps the hidden vector to a score for every vocabulary word:
These scores are called logits. They can be positive or negative and do not need to sum to one.
-
Softmax converts the scores into probabilities:
Here, is the vocabulary, and is the probability that word comes next. Each probability is between zero and one, and the probabilities over the whole vocabulary sum to one.
Decoding
In an RNN encoder-decoder setup, the encoder’s final hidden state summarizes the input sentence. This vector gives the decoder its starting context for generation. Generation stops when the decoder produces <EOS> (the end-of-sequence token).
During training, we feed the decoder the correct previous token, even if its previous prediction was wrong. This is called teacher forcing. For example, suppose the correct output is:
“This is an output”.
In the left diagram, the model’s predictions read “This was the sentence”, but the inputs still follow the correct output. After predicting “was” instead of “is”, the decoder receives “is” as its next input.
During testing, the correct output is unknown. We feed each predicted token back as the next input, as shown in the right diagram. There, the decoder generates “This is a sentence”.
There are three main approaches to choosing the decoder’s next token at test time:
- Greedy decoding: Select the highest-probability token at each step.
- Random sampling: Randomly select a token according to the predicted probability distribution.
- Beam search: Instead of keeping only one output sequence at each time step, keep the top most probable candidate sequences. Extend those candidates and retain the top overall at the next step. The intuition is that ruling out the second-most-probable choice too early can lead to a much worse final result: decisions at earlier time steps affect the probabilities of all later tokens and therefore the probability of the whole sequence.
Issues with Recurrent models
1. Linear Interaction Distance
In an RNN, information travels word by word. At each word, the model updates its hidden state, a running summary of what it has read. Connecting distant words therefore requires many steps. For information from word 1 to reach word 5, it follows this chain:
There is no direct connection from to in a standard RNN. Nearby words have shorter paths between them, so the architecture naturally favours local relationships. For a sentence of words, the first and last words are separated by recurrent transitions. The longest communication path therefore grows linearly with sentence length.
Example: remembering a distant word
“The course, despite the many changes to the assignments and the schedule, was useful. I enjoyed it.”
To interpret “it,” the model needs to retain information about “course.” That information must pass through every intervening hidden-state update, even while the model incorporates details about the assignments and schedule.
Every recurrent update incorporates another word into a fixed-size summary, so earlier information can be weakened or overwritten. During training, gradients also pass backwards through the chain of recurrent updates. Repeated multiplication by small derivatives can shrink those gradients, making it difficult to learn dependencies between distant words. This is the vanishing gradient problem.
Word order is built into the RNN’s computation. Changing the order changes the chain of hidden states, so the same word can receive a different contextual representation.
Example: same words, different order
“The dog bites the man.”The dog does the biting.
“The man bites the dog.”The man does the biting.
When the RNN reaches “bites,” its previous hidden state summarizes either “the dog” or “the man.” Even though the embedding of “bites” is the same, its updated hidden state can differ because the preceding context differs. The final sentence representations can therefore distinguish who bit whom. This sensitivity to order is useful; the difficulty is carrying the relevant context through a long chain.
2. Lack of Parallelizability
RNNs must process word positions sequentially:
To compute the current hidden state , we need the previous hidden state . GPUs are good at performing many independent calculations at once, but these dependencies prevent an RNN from computing all hidden states across a sequence in parallel. It must finish each step before starting the next.
Calculations within each step and across different sequences in a batch can still run in parallel. However, the sequential chain across word positions limits how much a GPU can speed up the model, especially for long sequences.
Bahdanau Attention
Early sequence-to-sequence models typically used an encoder-decoder architecture with RNNs or LSTMs. In the basic setup, the encoder compressed the input into a single fixed-length context vector, creating a bottleneck.
For example, consider translating:
“The cat that was sitting on the mat near the window is sleeping.”
The encoder had to compress the entire sentence into one fixed-size vector. The decoder could access the input only through this final encoder state, so important details could be lost. In particular, it could struggle to connect “cat” with “is sleeping” across the intervening words.
In 2014, Bahdanau et al. proposed an attention mechanism for neural machine translation. Instead of forcing the decoder to rely on one fixed context vector, attention lets it focus on different parts of the input for each output word. The decoder can look back at all encoder hidden states and combine them into a context vector that changes at each generation step. [2]
Transformers
Self-Attention
In 2017, Vaswani et al. introduced the Transformer in Attention Is All You Need. It replaced recurrence with attention, using self-attention to let tokens exchange information directly within the same sequence. In an unmasked self-attention layer, each word can attend to every other word without passing information through a chain of recurrent hidden states. Self-attention itself has no built-in locality bias. Long-distance context has “equal opportunity” to be attended to. [3]
For the sentence “the cat sat on the mat”, an illustrative attention pattern might be:
- “sat” attends strongly to “cat” to gather information about who performed the action.
- “mat” attends strongly to the preceding “the” to capture their grammatical relationship.
- “cat” attends strongly to “sat” to gather information about what the cat is doing.
Columns: words being attended to
| Updating ↓ | the₁ | cat | sat | on | the₂ | mat |
|---|---|---|---|---|---|---|
| the₁ | 0.10 | 0.45 | 0.10 | 0.05 | 0.10 | 0.20 |
| cat | 0.10 | 0.15 | 0.45 | 0.05 | 0.05 | 0.20 |
| sat | 0.05 | 0.55 | 0.10 | 0.10 | 0.05 | 0.15 |
| on | 0.05 | 0.10 | 0.20 | 0.10 | 0.10 | 0.45 |
| the₂ | 0.05 | 0.10 | 0.05 | 0.10 | 0.15 | 0.55 |
| mat | 0.05 | 0.10 | 0.10 | 0.15 | 0.55 | 0.05 |
All word positions can be updated at the same time because they read input vectors that are already available. One position does not need to wait for another position’s updated representation. In an RNN, by contrast, each hidden state must wait for the previous hidden state.
Suppose the sentence is “Cats drink milk.” Before self-attention starts, we already have three input vectors: for “Cats,” for “drink,” and for “milk.” The layer performs three independent jobs:
| Job | Reads | Produces |
|---|---|---|
| Update “Cats” | ||
| Update “drink” | ||
| Update “milk” |
Updating “Cats” means computing a new vector for that word using information from the sentence. The word itself stays “Cats.” Before attention, represents “Cats.” After attention, also contains information gathered from “drink” and “milk,” helping represent what the cats are doing.
A GPU can run these independent jobs in parallel: each output reads the same set of input vectors, rather than waiting for another output. If there is another self-attention layer afterward, it uses the completed vectors as its inputs. Autoregressive generation still produces new tokens one at a time; the parallelism here is across positions whose inputs are already available.
The diagrams below show the same contrast for four positions:
Architecture
In the Transformer shown above, the encoder and decoder each contain a stack of Transformer layers.
Input Embeddings + positional information
A Transformer usually processes tokens, which need not be whole words. The exact split depends on the tokenizer’s vocabulary. Common words may stay whole, and less common words may become several pieces. After tokenization, each token has an integer ID that selects a row from a learned embedding table. This extensive matrix allows the model to assign semantic meaning to each token, in the sense that tokens with similar usage or meaning in language are placed close together in this high-dimensional space, while dissimilar tokens are farther apart.
The input to the first encoder layer is the token’s embedding plus a positional encoding, which adds information about where that token occurs:
Transformer Encoder
Each encoder layer contains self-attention, a feed-forward network, and the residual additions and layer normalization shown as “Add & Norm.” Its job is to turn each input token into a vector that captures both the token’s meaning and its context in the sentence. The labels mean “repeat this entire block times.” Each repetition is a separate layer with its own learned parameters.1 The token representations evolve through layers from the first block to the last one, allowing the model to build up an intricate understanding of each token.
Every encoder layer receives one vector for each input token and produces an updated vector for each token. This is the same pattern as the self-attention illustration above, where become , except that a complete encoder layer also includes the feed-forward network and Add & Norm operations. Token positions can be processed in parallel within a layer, but the next layer uses the previous layer’s outputs, so the layers run in sequence.
Multi-Head Self Attention
The self-attention mechanism enables the model to capture relationships among tokens in a sequence, so that each token’s representation is influenced by the others. It is called self-attention because the queries, keys, and values all come from the same input sequence.
Step 1: Query, Key, and Value Matrices
Each token’s embedding vector is transformed into three vectors: Query (Q), Key (K), and Value (V). These vectors are derived by multiplying the input embedding matrix with learned weight matrices for Q, K, and V.
Following the paper’s convention, we write each input vector as a row and multiply by the learned weights on the right [3]:
Q is what we’re trying to learn context for, K is the key to be matched, and V is the information to be extracted.
An analogy to understand Q, K, and V
- Query (Q) is the search text you type in the search engine bar.
- Key (K) is the title of each web page in the search results.
- Value (V) is the actual content of the web pages shown.
Once we match the search term (Query) with the relevant results (Key), we want to get the content (Value) of the most relevant pages.
Once we have the Q, K, and V matrices, we retrieve information for a query by first comparing it with every key. This gives a similarity score:
A higher score means that entry is more relevant to the query. In Transformer attention, softmax turns the scores into nonnegative weights that sum to 1. We multiply each value by its weight, then sum the weighted values. This is the general attention process.
Scaled dot-product attention
Self-attention for one head is computed using:
Here, , , and stack the token vectors as rows, is the dimension of each query and key, and softmax is applied separately to each row. The walkthrough below uses four tokens and unmasked encoder self-attention.
To update the representation of , we take its query and compare it with every key:
This produces four scalar scores:
Notice that token 1 attends to itself too. Read the indices as:
: how well the query from token 1 matches the key from token 3.
The dot product measures compatibility, and dividing by controls the scores’ size.
Then we apply softmax across the four scores:
The resulting weights are nonnegative and sum to 1. For example:
When updating token 1, the attention mechanism gives the largest weight to information from token 4.
Then we use those weights on the value vectors:
With the example weights:
We repeat the lookup for token 2 and the other tokens. These lookups can happen in parallel. The same keys and values are available, but a different query generally produces different weights.
The animation follows one query at a time so we can see how its output is built. In practice, we stack all token representations into a matrix and compute every query’s lookup together. Each row performs the same calculation we just did for token 1.
Let be the number of tokens and the dimension of each input vector. Stacking the inputs as rows gives . Here, is the sequence length, separate from the used earlier for the number of stacked Transformer layers.
| Quantity | Computation | Dimensions2 |
|---|---|---|
| Input representations | ||
| Query and key weights | each | |
| Value weights | ||
| Queries | ||
| Keys | ||
| Values | ||
| Scaled similarity scores | ||
| Attention weights | ||
| Output representations |
The first matrix multiplication compares every query with every key:
After scaling, entry is the score for query and key . Softmax is applied across each row, so every query gets its own set of weights summing to 1.
The second matrix multiplication performs all the weighted sums:
Row of is , exactly the value-weighting step in the walkthrough. We get one output vector for every input token, with all token lookups computed in parallel.
In practice, we take different sets of linear transformations of each input, one set of query, key, and value projections per attention head ( in the original paper) [3]. Multiple attention heads allow the model to consider relationships between tokens from different perspectives. These copies of self-attention are independent and can run in parallel, each with its own learned projection weights.
The head outputs are then concatenated and passed through a final learned linear projection, as shown in the diagram.
Multi-Layer Perceptron
Self-attention forms weighted sums of the value vectors. The attention weights depend nonlinearly on the inputs through softmax, but the value-mixing step does not apply an element-wise nonlinear activation. After multi-head attention combines information across tokens and projects the concatenated outputs, the Multilayer Perceptron (MLP) refines each token’s representation using two linear transformations with an element-wise nonlinear activation in between.
In GPT-2 (small), the first linear transformation expands the dimensionality four-fold from 768 to 3072. This gives the model a larger feature space in which to represent patterns. A GELU activation is then applied element-wise, allowing the MLP to learn nonlinear transformations.
The second linear transformation reduces the dimensionality back to 768. It maps the expanded features back to the model’s representation size, so the output can continue through the next parts of the Transformer block. These dimensions depend on the model; the original Transformer used a ReLU activation.
Unlike self-attention, which integrates information across tokens, the MLP processes each token independently. The same MLP weights are used at every token position. It transforms the features within each token’s vector, enriching the model’s representational capacity.
The ReLU version can be written as follows, with denoting the MLP input at token position :
and expand the feature dimension, and and project it back.3
Add & Norm
Residual connections and layer normalization help Transformers train effectively. Both also remain active during inference.
-
Residual connections add a sublayer’s input to its output:
Here, could be an attention sublayer or a feed-forward sublayer. This gives gradients a direct path through the addition and helps mitigate vanishing gradients in deep networks.
-
Layer normalization stabilizes training and can help the model converge faster. For each token, it computes the mean and variance across that token’s features, then centers and rescales them. Learned scale and bias parameters let the model adjust the normalized representation.
For one token represented by numbers, , compute its mean and variance:
Then normalize:
This helps control activation scales and reduces sensitivity to weight initialization. Changing inputs to later layers are often described using the intuition of internal covariate shift, though reducing this shift is not a complete explanation of why normalization helps.4
In the original Transformer architecture, layer normalization is applied after each residual addition: once around the self-attention sublayer and once around the MLP sublayer in each encoder block. These are the “Add & Norm” operations shown in the architecture diagram [3].
Transformer Decoder
Like the encoder, the decoder consists of a stack of layers ( in the original Transformer). Each layer has its own learned parameters.
Each decoder layer in the original Transformer contains three sublayers, applied in order: masked self-attention, cross-attention, and a feed-forward neural network. Each sublayer has a residual connection followed by layer normalization [3].
The encoder builds contextual representations of the input sequence, with each token able to attend to every input position. The decoder uses those representations to generate an output sequence one token at a time. Masked self-attention lets it attend only to the output tokens available so far, preventing it from looking at future tokens. Cross-attention lets it attend to the encoder’s output, and the feed-forward network refines each token’s representation.
Masked Self-Attention
When predicting the next token, the decoder must not look at future tokens in the output sequence. Otherwise, it could see the answer during training. The rule is:
Attending to yourself is allowed: the token at the current input position is already known. The target is the next token.
To enforce this rule, we set the attention scores for future tokens to before applying softmax. Their attention weights then become zero, since . Each position can still attend to itself and all earlier positions.
1. Unnormalized scores
| Q ↓ K → | The | cat | sat |
|---|---|---|---|
| The | 1 | 2 | 3 |
| cat | 1 | 2 | 0 |
| sat | 0 | 1 | 2 |
Scaled query–key scores, before masking.
2. Mask future positions
| Q ↓ K → | The | cat | sat |
|---|---|---|---|
| The | 1 | −∞ | −∞ |
| cat | 1 | 2 | −∞ |
| sat | 0 | 1 | 2 |
Replace scores above the diagonal with −∞.
3. Row-wise softmax
| Q ↓ K → | The | cat | sat |
|---|---|---|---|
| The | 1.000 | 0 | 0 |
| cat | 0.269 | 0.731 | 0 |
| sat | 0.090 | 0.245 | 0.665 |
Each row sums to 1; future tokens get 0.
Masking lets us train on all positions simultaneously while preserving the same information restriction used when generating one token at a time.5
Cross-Attention
In self-attention, queries (), keys (), and values () come from the same sequence. Each token attends to positions in that sequence, subject to any mask.
In cross-attention, queries come from one sequence, while keys and values come from another. This lets one sequence selectively retrieve information from another. In the original Transformer decoder, queries come from the decoder states after masked self-attention; keys and values come from the encoder’s final output [3]. Each is formed through its own learned projection.
Suppose we are translating:
- English input: “I love machine learning”
- French output: “J’aime l’apprentissage automatique”
Focus on the decoder position containing “J’aime.” Its masked self-attention can use the French prefix available so far. Its cross-attention query instead attends to the English encoder representations for “I,” “love,” “machine,” and “learning.” The resulting weighted combination of English value vectors helps the decoder predict the next French token.
Masked self-attention
Cross-attention
Cross-attention can attend to all English input positions because the entire source sentence is already available. The causal mask applies to the decoder’s self-attention over the French sequence.
Language Modelling Head
The language modelling head maps the decoder’s final hidden state at each position to a probability distribution over the vocabulary. A learned linear layer projects the -dimensional hidden state into logits, one score per vocabulary token. Softmax then converts these scores into next-token probabilities [3].
Here, is the hidden vector for just one token position, represented as one row containing numbers.
- : the final Transformer layer.
- : the last input token’s position (in this slide, rather than the number of stacked layers).
- : the number of features in each hidden vector.
The linear projection is also called unembedding. The slide shows weight tying: its matrix is the transpose of the input embedding matrix, , so the two operations share learned weights. The language model head computes the vocabulary logits:
Softmax converts into next-token probabilities. During generation, the head’s output at the last available position supplies the distribution used to select the next token.
Further reading
Footnotes
-
If , the encoder side of the architecture is:
Input tokens ↓ Embeddings + positional encoding ↓ Encoder layer 1 ↓ Encoder layer 2 ↓ Encoder layer 3 ↓ Final input representations → decoderEach encoder layer updates the full sequence of token vectors. The final representations are supplied to the decoder’s cross-attention sublayers. ↩
-
For one attention head, let be the query and key dimension, as above, and let be the value dimension. Queries and keys need the same dimension so we can take their dot product. Values can have a different dimension. ↩
-
For GPT-2, replace ReLU with GELU. ↩
-
What is internal covariate shift? Each layer receives representations produced by earlier layers. As the earlier weights change during training, the distribution of inputs received by later layers can change too. This is traditionally called internal covariate shift.
For a simple illustration, suppose Layer A feeds Layer B. Before a weight update, A produces ; afterward, it produces . Layer B now receives values at a different scale.
How does layer normalization help? Treat each row below as the feature vector of one token. Subtract the mean and divide by the standard deviation :
Input to Layer B Mean Standard deviation Normalized features The two vectors have different scales but produce the same normalized features in this simplified example. Actual layer normalization uses in the denominator for numerical stability, then applies learned scale and bias parameters. The example omits these adjustments. Controlling feature scale can make optimization more stable, but normalization does not freeze the full input distribution or prevent learned representations from changing. ↩
-
Training does not have to wait for an earlier prediction. Instead, we supply the ground-truth tokens as the decoder input, shifted by one position relative to the targets. This is called teacher forcing. ↩
Bibliography
- Tomas Mikolov, Kai Chen, Greg Corrado, and Jeffrey Dean, “Efficient Estimation of Word Representations in Vector Space,” arXiv preprint arXiv:1301.3781, 2013.
- Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio, “Neural Machine Translation by Jointly Learning to Align and Translate,” arXiv preprint arXiv:1409.0473, 2014.
- Ashish Vaswani et al., “Attention Is All You Need,” in NeurIPS, 2017.