← All notes

Neural Language Models

Contents

Language modelling is the task of predicting what word comes next.

For example: “My name is ____”.

More formally, given a sequence of words x1,x2,…,xtx_1, x_2, \ldots, x_t, compute the probability distribution of the next word xt+1x_{t+1}:

P(xt+1∣x1,…,xt).P(x_{t+1} \mid x_1, \ldots, x_t).

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 11 at that position and 00 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:

WordVector
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:

  1. vnotebook⋅vlaptop=1×0+0×1+0×0=0\mathbf{v}_{\text{notebook}}\cdot\mathbf{v}_{\text{laptop}} = 1\times0 + 0\times1 + 0\times0 = 0.
  2. vnotebook⋅vbanana=1×0+0×0+0×1=0\mathbf{v}_{\text{notebook}}\cdot\mathbf{v}_{\text{banana}} = 1\times0 + 0\times0 + 0\times1 = 0.

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:

vlaptop=[0.8, −0.3, 0.6, 0.1].\mathbf{v}_{\text{laptop}}=[0.8,\,-0.3,\,0.6,\,0.1].

Its second coordinate is −0.3-0.3, 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.

Word vectors in two latent dimensions: index, retrieval, and search point upward in similar directions; data, science, and computer point rightward; information lies between the two groups.
Related usage patterns can be represented by similar vector directions. Source: CS646, Word Representation lecture, slide 6 (UMass Amherst, Fall 2026).

In this illustrative diagram:

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]:

  1. Skip-gram: predicts context words given a center (target) word.
  2. Continuous Bag of Words (CBOW): predicts the target word from its surrounding context, treated as a bag of words.
CBOW combines surrounding context words to predict the center word. Skip-gram takes the center word and predicts surrounding context words.
CBOW and skip-gram. Source: CS646, Word Representation lecture, PDF page 31 (slide labeled 38), adapted from Mikolov et al. (2013).

Skip-Grams

We start with a large corpus of text and randomly initialized word vectors for a fixed vocabulary. At each position tt, we treat the word there as the center word cc and nearby words as context (outside) words oo.

Skip-gram uses a dot-product similarity between a center-word vector and an outside-word vector to compute p(o∣c)p(o\mid c), 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:

Center: code · context window: 2 words on each side compiled Java code can run on all Purple: center word · Blue: observed context words
p(compiled | code) p(Java | code) p(can | code) p(run | code)

Train on four center–context pairs with “code” as the center.

Center: can · context window: 2 words on each side compiled Java code can run on all Purple: center word · Blue: observed context words
p(Java | can) p(code | can) p(run | can) p(on | can)

Train on four center–context pairs with “can” as the center.

The center moves through the corpus, producing a new set of prediction pairs at each position. Adapted from CS646, Word Representation lecture, PDF pages 33–34 (slides labeled 41–42). This illustrates the training windows, not numerical changes to the vectors.

The training objective for skip-gram is to make the context words that actually occur in the text highly probable. One prediction,

P(wt+j∣wt;θ),P(w_{t+j}\mid w_t;\theta),

means: given the center word wtw_t, what probability does the model assign to its observed neighbor wt+jw_{t+j}?

SymbolMeaning
ttCurrent center position
jjOffset from the center, for example −2,−1,1,2-2,-1,1,2 when m=2m=2
mmContext window size on each side of the center
TTNumber of token positions in the training text
θ\thetaThe model’s learned parameters, including its word vectors

For each position t=1,…,Tt=1,\ldots,T, predict the context words within a fixed window of size mm, given the center word wtw_t. We skip j=0j=0 because the center word is not its own context target. Terms whose context positions fall outside the text are omitted. The data likelihood is:

L(θ)=∏t=1T∏−m≤j≤mj≠0P(wt+j∣wt;θ).L(\theta)= \prod_{t=1}^{T} \prod_{\substack{-m\le j\le m\\j\ne0}} P(w_{t+j}\mid w_t;\theta).

For the “code” window above, its contribution is:

P(compiled∣code;θ) P(Java∣code;θ)×P(can∣code;θ) P(run∣code;θ).\begin{aligned} & P(\text{compiled}\mid\text{code};\theta)\, P(\text{Java}\mid\text{code};\theta) \\ &\qquad{}\times P(\text{can}\mid\text{code};\theta)\, P(\text{run}\mid\text{code};\theta). \end{aligned}

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:

J(θ)=−1T∑t=1T∑−m≤j≤mj≠0log⁡P(wt+j∣wt;θ).J(\theta)= -\frac{1}{T} \sum_{t=1}^{T} \sum_{\substack{-m\le j\le m\\j\ne0}} \log P(w_{t+j}\mid w_t;\theta).

The transformation is:

J(θ)=−1Tlog⁡L(θ)\boxed{J(\theta)=-\frac{1}{T}\log L(\theta)}

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.

A feedforward network with input, hidden, and output layers beside an RNN unrolled over three time steps, with hidden states connected from left to right.
Read the right diagram from left to right as time passing. The three green boxes represent the same computation reused at three time steps, with the same learned weights. Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 3 (UMass Amherst, Fall 2026).

We can process the sequence of input vectors xtx_t (the red boxes) by applying a recurrence formula at every time step:

RNN recurrence: the new hidden state h_t is f_W applied to the previous hidden state h_{t-1} and the current input vector x_t. W denotes the function's parameters.
The hidden state is updated using the previous state and the current input. Source: CS646: Information Retrieval, Neural Language Models lecture slides (UMass Amherst, Fall 2026).

We can unroll this recurrence to follow the hidden state while reading “the cat sat”:

Unrolling an RNN for “the cat sat” Starting with h zero, process the word the to produce h one, then cat with h one to produce h two, then sat with h two to produce h three. Every step reuses the same function f W and the same parameters W. h₀ start fW h₁ step 1 the x₁ fW h₂ step 2 cat x₂ fW h₃ step 3 sat x₃
At each step:
  • 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.
Adapted from Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slides 5–7 (UMass Amherst, Fall 2026).

The same function fWf_W and set of parameters WW are used at every time step.

Kinds of RNNs

A many-to-one RNN: inputs x_1 through x_T update hidden states using shared weights W, and the final hidden state h_T produces a single output y.
The same weight matrix W is reused at every time step, and the final hidden state produces one output y. Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 9 (UMass Amherst, Fall 2026).

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 LtL_t measures error at one position:

Lt=−log⁡P(correct next word∣words read so far).\begin{aligned} L_t = -\log P(&\text{correct next word} \\ &\mid \text{words read so far}). \end{aligned}

The arrows leading to the large LL indicate that these errors are combined by summing or averaging. Here as well, the same weights WW are reused at every step, so errors from all positions help train that shared computation.

A many-to-many RNN with an output y_t and loss L_t at every step. Each position's loss feeds into the total loss L, and the recurrent computations share weights W.
Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 14 (UMass Amherst, Fall 2026).

A one-to-many RNN uses one input to generate a sequence of outputs. Here, xx could be a vector representing the image, and each yty_t predicts a word in the caption. An example is image captioning:

one image↓“a”→“cat”→“sleeping”\begin{gathered} \text{one image} \\ \downarrow \\ \text{“a”} \to \text{“cat”} \to \text{“sleeping”} \end{gathered}
A one-to-many RNN: one input x initializes a sequence of recurrent computations with shared weights W, producing outputs y_1, y_2, y_3, and onward to y_T.
Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 15 (UMass Amherst, Fall 2026).

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:

  1. Encoder RNN: Reads the input tokens (x1,…,x4x_1, \ldots, x_4), which are converted to embeddings. Its hidden state updates as it reads. The final encoder state contains a compressed summary of the input.
  2. 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 y1y_1, then uses its evolving hidden state and the previously generated token to produce each subsequent output yiy_i.

An example is translation:

“I am a student”⏟encoder reads↓“Je”→“suis”→“eˊtudiant”⏟decoder generates\begin{gathered} \underbrace{\text{“I am a student”}}_{\text{encoder reads}} \\ \downarrow \\ \underbrace{\text{“Je”} \to \text{“suis”} \to \text{“étudiant”}}_{\text{decoder generates}} \end{gathered}
An encoder RNN reads four embedded input tokens in the red box. A thick arrow transfers its final hidden state to the decoder RNN in the blue box, which generates three outputs y_1, y_2, and y_3. Decoder RNN
The encoder (red) passes its final state to the decoder (blue). The encoder RNN is many-to-one as it encodes the input sequence into a single vector, whereas the decoder RNN is one-to-many as it produces an output sequence from a single input vector. Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 17 (UMass Amherst, Fall 2026).

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 x2x_2, layer 3 combines layer 2’s new hidden state at t=2t=2 with its own previous hidden state from t=1t=1. 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.

Three stacked recurrent layers and a blue output layer over six time steps. Crosses mark layer 3 at time 1 and layer 2 at time 2, the two states used to update layer 3 at time 2.
Layers are counted from bottom to top. The crosses mark layer 3's previous state and layer 2's current state. Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 19 (UMass Amherst, Fall 2026).

A bidirectional RNN processes the same sequence in both directions, so each prediction can use context from before and after a word. Each input xtx_t goes into both RNNs. Their hidden states at that position are then combined (often by concatenating the two vectors) to compute yty_t. 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.

A bidirectional RNN: each input x_t feeds a forward recurrent chain with arrows to the right and a backward recurrent chain with arrows to the left. Both hidden states feed the output y_t at that position.
Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 20 (UMass Amherst, Fall 2026).

RNN Language Model

In an RNN language model, the embedding matrix EE 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:

P("retrieval"∣"the center for information").P(\text{"retrieval"} \mid \text{"the center for information"}).

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:

P(x1,…,xT)=∏t=1TP(xt∣x1,…,xt−1).P(x_1, \ldots, x_T) = \prod_{t=1}^{T} P(x_t \mid x_1, \ldots, x_{t-1}).

Each conditional distribution is computed from the RNN hidden state summarizing the preceding words. For t=1t=1, the prefix is empty.

The words ‘the center for information’ pass through embedding matrix E and recurrent hidden states. The final state produces a next-word distribution over the vocabulary, including ‘retrieval’ and ‘processing’.
Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 10 (UMass Amherst, Fall 2026).

From Hidden States to Probabilities

The hidden state is not itself a probability distribution over words. Unembedding and softmax turn it into one:

  1. A learned transformation maps the hidden vector to a score for every vocabulary word:

    zt=Uht+b.z_t = Uh_t + b.

    These scores are called logits. They can be positive or negative and do not need to sum to one.

  2. Softmax converts the scores into probabilities:

    pt(v)=ezt(v)∑u∈Vezt(u).p_t(v) = \frac{e^{z_t(v)}}{\sum_{u \in V} e^{z_t(u)}}.

    Here, VV is the vocabulary, and pt(v)p_t(v) is the probability that word vv comes next. Each probability is between zero and one, and the probabilities over the whole vocabulary sum to one.

An RNN hidden vector is unembedded into one score per vocabulary word, then softmax converts those scores into a probability distribution over the next word.
Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 11 (UMass Amherst, Fall 2026).

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”.

Training with teacher forcing: the decoder predicts ‘This was the sentence’, while its inputs use the correct sequence ‘This is an output’, regardless of those predictions.
Training: teacher forcing. Correct tokens are fed into the decoder. Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 24 (UMass Amherst, Fall 2026).
Test-time generation: arrows feed each predicted token back into the decoder to generate ‘This is a sentence’, ending with the EOS token.
Testing: generation. Predicted tokens are fed back into the decoder. Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 23 (UMass Amherst, Fall 2026).

There are three main approaches to choosing the decoder’s next token at test time:

  1. Greedy decoding: Select the highest-probability token at each step.
  2. Random sampling: Randomly select a token according to the predicted probability distribution.
  3. Beam search: Instead of keeping only one output sequence at each time step, keep the top KK most probable candidate sequences. Extend those candidates and retain the top KK 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.
Greedy decoding: red circles mark the highest-probability token chosen at each step, generating ‘This is a sentence’.
1. Greedy decoding. Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 26 (UMass Amherst, Fall 2026).
Random sampling: blue circles mark tokens sampled from each next-token distribution, generating ‘This was a word’.
2. Random sampling. Source: Negin Rahimi, CS646: Information Retrieval, Neural Language Models, slide 27 (UMass Amherst, Fall 2026).
Beam search with beam size two: retain A and C, then AB and CE, then ABD and CED as candidate sequences over three steps.
3. Beam search. Two candidate sequences are retained at each step. Source: Dive into Deep Learning, Fig. 10.8.3.

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:

h1→h2→h3→h4→h5.h_1 \rightarrow h_2 \rightarrow h_3 \rightarrow h_4 \rightarrow h_5.

There is no direct connection from h1h_1 to h3h_3 in a standard RNN. Nearby words have shorter paths between them, so the architecture naturally favours local relationships. For a sentence of nn words, the first and last words are separated by n−1n-1 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:

ht=fW(ht−1,xt).h_t = f_W(h_{t-1}, x_t).

To compute the current hidden state hth_t, we need the previous hidden state ht−1h_{t-1}. 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]

Bahdanau attention: the encoder produces a hidden state for each input word. All encoder hidden states feed context vectors that are recomputed for successive decoder outputs.
Each decoder step receives a context vector built from all encoder hidden states. Source: Bahdanau Attention Overview diagram.

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:

Columns: words being attended to

Updating ↓the₁catsatonthe₂mat
the₁0.100.450.100.050.100.20
cat0.100.150.450.050.050.20
sat0.050.550.100.100.050.15
on0.050.100.200.100.100.45
the₂0.050.100.050.100.150.55
mat0.050.100.100.150.550.05
Illustrative self-attention weights, not measured model outputs. Read each row across: larger numbers and more intense blue cells mean stronger attention. Each row sums to 1. The subscripts distinguish the two occurrences of “the.” This unmasked example represents encoder self-attention.
Self-attention visualization for ‘The animal did not cross the street because it was too tired’: lines from ‘it’ to other tokens show particularly strong attention to ‘animal’.
The token “it” attends to other parts of the sentence, including “animal.” Source: Jay Alammar, The Illustrated Transformer.

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: x1x_1 for “Cats,” x2x_2 for “drink,” and x3x_3 for “milk.” The layer performs three independent jobs:

JobReadsProduces
Update “Cats”x1,x2,x3x_1, x_2, x_3y1y_1
Update “drink”x1,x2,x3x_1, x_2, x_3y2y_2
Update “milk”x1,x2,x3x_1, x_2, x_3y3y_3

Updating “Cats” means computing a new vector for that word using information from the sentence. The word itself stays “Cats.” Before attention, x1x_1 represents “Cats.” After attention, y1y_1 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 yy 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:

A self-attention layer takes four available input vectors x_1 through x_4 and produces four output vectors y_1 through y_4 without a chain between output positions.
Self-attention: y1, y2, y3, y4 can be computed parallely.
A recurrent layer with four connected hidden states between input vectors x_1 through x_4 and output vectors y_1 through y_4. Connections between positions create sequential dependencies within each recurrent direction.
Recurrence: y2 is computed after y1, y3 is computed after y2, y4 is computed after y3.

Architecture

The original Transformer architecture: an encoder stack on the left and a decoder stack on the right, with embeddings, positional encodings, attention, feed-forward layers, residual connections and normalization, followed by a linear layer and softmax.
Figure 1: The Transformer - model architecture. Source: Vaswani et al., Attention Is All You Need (2017).

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:

xi=Embedding⁡(tokeni)+Position⁡(i)x_i = \operatorname{Embedding}(\text{token}_i) + \operatorname{Position}(i)
The prompt ‘Data visualization empowers users to’ is split into tokens, including ‘em’ and ‘powers’. Each token ID selects an embedding vector, which is added to its positional encoding to form the final embedding.
Expanding the Embedding layer view, showing how the input prompt is converted to a vector representation. The process involves (1) Tokenization, (2) Token Embedding, (3) Positional Encoding, and (4) Final Embedding. Source: Transformer Explainer, Polo Club.

Transformer Encoder

Transformer encoder: input embeddings and positional encoding feed a stack of N layers, each containing multi-head self-attention, a feed-forward network, and two Add & Norm operations with residual connections.

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 N×N\times labels mean “repeat this entire block NN 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 x1,x2,x3,x4x_1, x_2, x_3, x_4 become y1,y2,y3,y4y_1, y_2, y_3, y_4, 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 XiX_i as a row and multiply by the learned weights on the right [3]:

Qi=XiWQ,Ki=XiWK,Vi=XiWVQ_i = X_i W^Q, \qquad K_i = X_i W^K, \qquad V_i = X_i W^V
Six token embeddings form a 6 by 768 matrix. Multiplication by learned Q, K, and V weights of shape 768 by 2304, plus a learned bias, produces a 6 by 2304 matrix containing the query, key, and value vectors.
Computing Query, Key, and Value matrices from the input embeddings. This GPT-2 example combines all three projections into one matrix multiplication and adds a learned bias. Source: Transformer Explainer, Polo Club.

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

  1. Query (Q) is the search text you type in the search engine bar.
  2. Key (K) is the title of each web page in the search results.
  3. 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:

si=similarity⁡(q,ki)s_i = \operatorname{similarity}(q, k_i)

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.

Attention as a soft lookup over keys and values A blue query d is compared with five red keys a through e. Their similarity scores pass through softmax to produce weights. Each weight multiplies its green value vector, and the results are summed into the output. Queryd KeysValuesScores Softmax WeightsWeightedvalues a v₁ s₁ w₁ w₁ × v₁ b v₂ s₂ w₂ w₂ × v₂ c v₃ s₃ w₃ w₃ × v₃ d v₄ s₄ w₄ w₄ × v₄ e v₅ s₅ w₅ w₅ × v₅ ΣOutput A key-value store
Attention as a soft lookup. Adapted from Negin Rahimi, CS646: Information Retrieval, Transformer lecture, slide 15 (UMass Amherst, Fall 2026).

Scaled dot-product attention

Self-attention for one head is computed using:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤d)V\operatorname{Attention}(Q,K,V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt d}\right)V

Here, QQ, KK, and VV stack the token vectors as rows, dd 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 x1x_1, we take its query Q1Q_1 and compare it with every key:

E1,j=Q1⋅KjdE_{1,j}=\frac{Q_1\cdot K_j}{\sqrt d}

This produces four scalar scores:

[E1,1,E1,2,E1,3,E1,4][E_{1,1},E_{1,2},E_{1,3},E_{1,4}]

Notice that token 1 attends to itself too. Read the indices as:

E1,3E_{1,3}: how well the query from token 1 matches the key from token 3.

The dot product measures compatibility, and dividing by d\sqrt d controls the scores’ size.

Then we apply softmax across the four scores:

A1,j=exp⁡(E1,j)∑m=14exp⁡(E1,m)A_{1,j}=\frac{\exp(E_{1,j})}{\sum_{m=1}^{4}\exp(E_{1,m})}

The resulting weights are nonnegative and sum to 1. For example:

[A1,1,A1,2,A1,3,A1,4]=[0.1,  0.1,  0.3,  0.5][A_{1,1},A_{1,2},A_{1,3},A_{1,4}]=[0.1,\;0.1,\;0.3,\;0.5]

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:

Y1=∑j=14A1,jVjY_1=\sum_{j=1}^{4}A_{1,j}V_j

With the example weights:

Y1=0.1V1+0.1V2+0.3V3+0.5V4Y_1=0.1V_1+0.1V_2+0.3V_3+0.5V_4

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.

A four-token self-attention walkthrough Each input produces a blue query, a red key, and a green value. Query 1 is compared with every key, including its own. Softmax converts the scores into weights 0.1, 0.1, 0.3, and 0.5. Their weighted values sum to output Y1. Other queries reuse the same keys and values. Centerx₁ Q₁ K₁ V₁ forx₂ Q₂ K₂ V₂ intelligentx₃ Q₃ K₃ V₃ informationx₄ Q₄ K₄ V₄ E₁,1 E₁,2 E₁,3 E₁,4 Softmax across this row A₁,1 = 0.1 A₁,2 = 0.1 A₁,3 = 0.3 A₁,4 = 0.5 0.1 × V₁ 0.1 × V₂ 0.3 × V₃ 0.5 × V₄ Sum → Y₁
One query, four keys, and four values. Compare the selected query with every key, then scale the scores by √d. The weights are illustrative, not measured model outputs. Adapted from Negin Rahimi, CS646: Information Retrieval, Transformer lecture, slides 16–20 (UMass Amherst, Fall 2026).

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 nn be the number of tokens and DD the dimension of each input vector. Stacking the inputs as rows gives X∈Rn×DX\in\mathbb{R}^{n\times D}. Here, nn is the sequence length, separate from the NN used earlier for the number of stacked Transformer layers.

QuantityComputationDimensions2
Input representationsXXn×Dn\times D
Query and key weightsWQ, WKW^Q,\ W^KD×dD\times d each
Value weightsWVW^VD×dvD\times d_v
QueriesQ=XWQQ=XW^Qn×dn\times d
KeysK=XWKK=XW^Kn×dn\times d
ValuesV=XWVV=XW^Vn×dvn\times d_v
Scaled similarity scoresE=QK⊤/dE=QK^\top/\sqrt dn×nn\times n
Attention weightsA=softmax⁡row(E)A=\operatorname{softmax}_{\text{row}}(E)n×nn\times n
Output representationsY=AVY=AVn×dvn\times d_v

The first matrix multiplication compares every query with every key:

Q⏟n×d  K⊤⏟d×n  ⟶  QK⊤⏟n×n\underbrace{Q}_{n\times d}\; \underbrace{K^\top}_{d\times n} \;\longrightarrow\; \underbrace{QK^\top}_{n\times n}

After scaling, entry Ei,jE_{i,j} is the score for query ii and key jj. 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:

A⏟n×n  V⏟n×dv  =  Y⏟n×dv\underbrace{A}_{n\times n}\; \underbrace{V}_{n\times d_v} \;=\; \underbrace{Y}_{n\times d_v}

Row ii of YY is Yi=∑j=1nAi,jVjY_i=\sum_{j=1}^{n}A_{i,j}V_j, exactly the value-weighting step in the walkthrough. We get one output vector for every input token, with all token lookups computed in parallel.

Multi-head attention: h separate learned linear projections of queries, keys, and values feed parallel scaled dot-product attention heads. Their outputs are concatenated and passed through a final linear projection.
Source: Vaswani et al., Attention Is All You Need (2017), Figure 2.

In practice, we take hh different sets of linear transformations of each input, one set of query, key, and value projections per attention head (h=8h=8 in the original paper) [3]. Multiple attention heads allow the model to consider relationships between tokens from different perspectives. These hh 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 ziz_i denoting the MLP input at token position ii:

mi=MLP⁡(zi)=ReLU⁡(ziW1+b1)W2+b2.\begin{aligned} m_i &= \operatorname{MLP}(z_i) \\ &= \operatorname{ReLU}(z_iW_1+b_1)W_2+b_2. \end{aligned}

W1W_1 and b1b_1 expand the feature dimension, and W2W_2 and b2b_2 project it back.3

Add & Norm

Inputs x ell minus one feed self-attention F and a residual path. The attention output F of x ell minus one is added to the inputs to form x ell, then passed through layer normalization.
Residual connection and layer normalization around self-attention, labeled to match the equation below. Adapted from: Matthew Barnett, Walkthrough: The Transformer Architecture, Part 2/2.

Residual connections and layer normalization help Transformers train effectively. Both also remain active during inference.

  1. Residual connections add a sublayer’s input to its output:

    xℓ=xℓ−1+F(xℓ−1)\boxed{x_{\ell}=x_{\ell-1}+F(x_{\ell-1})}

    Here, FF 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.

  2. 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 dd numbers, x=[x1,…,xd]x=[x_1,\ldots,x_d], compute its mean and variance:

    μ=1d∑ixi,σ2=1d∑i(xi−μ)2\mu=\frac{1}{d}\sum_i x_i, \qquad \sigma^2=\frac{1}{d}\sum_i(x_i-\mu)^2

    Then normalize:

    LayerNorm⁡(x)i=γixi−μσ2+ϵ+βi\boxed{\operatorname{LayerNorm}(x)_i =\gamma_i\frac{x_i-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta_i}

    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

Decoder stack. Source: Vaswani et al., Figure 1.

Like the encoder, the decoder consists of a stack of NN layers (N=6N=6 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:

Position i may attend only to positions j≤i\boxed{\text{Position }i\text{ may attend only to positions }j\le i}

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 −∞-\infty before applying softmax. Their attention weights then become zero, since e−∞=0e^{-\infty}=0. Each position can still attend to itself and all earlier positions.

1. Unnormalized scores
Q ↓ K →Thecatsat
The123
cat120
sat012

Scaled query–key scores, before masking.

2. Mask future positions
Q ↓ K →Thecatsat
The1−∞−∞
cat12−∞
sat012

Replace scores above the diagonal with −∞.

3. Row-wise softmax
Q ↓ K →Thecatsat
The1.00000
cat0.2690.7310
sat0.0900.2450.665

Each row sums to 1; future tokens get 0.

Illustrative attention scores for “The cat sat.” Rows are query positions; columns are key positions. The diagonal stays visible, so each token can attend to itself. The final numbers are attention weights over input positions, not next-token probabilities.

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

Annotated Transformer architecture showing Q, K, and V paths. Encoder self-attention and decoder masked self-attention each use their own sequence for all three; decoder cross-attention receives Q from the decoder and K and V from the encoder output.
Q, K, and V sources in the Transformer. Annotated architecture diagram adapted from Vaswani et al., Figure 1.

In self-attention, queries (QQ), keys (KK), and values (VV) 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:

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
French decoder input J’aime selected query position French decoder input ⟨start⟩ · J’aime same sequence as Q Q K, V Score Q against K → softmax → mix V Updated representation at J’aime
Cross-attention
French decoder state J’aime after masked self-attention English encoder output I · love · machine · learning different sequence Q K, V Score Q against K → softmax → mix V Updated representation at J’aime
The same query position, two sources of context: the French prefix in masked self-attention, and the English input in cross-attention. Words are shown as single tokens for illustration; actual tokenizers may split them into smaller pieces. ⟨start⟩ marks the beginning of the decoder input.

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 dd-dimensional hidden state into ∣V∣|V| logits, one score per vocabulary token. Softmax then converts these scores into next-token probabilities [3].

The top of the Transformer decoder: a linear layer and softmax produce output probabilities from the final decoder representation.
The final Transformer hidden state, shaped one by d, passes through an unembedding matrix shaped d by vocabulary size to produce logits. Softmax converts the logits into a probability for each vocabulary token. The slide shows tied weights, with the unembedding matrix equal to the transpose of the embedding matrix.
Left: the linear layer and softmax in Vaswani et al., Figure 1. Right: CS646, Transformer lecture, slide 33 (UMass Amherst, Fall 2026).

Here, hNLh_N^L is the hidden vector for just one token position, represented as one row containing dd numbers.6

  1. LL: the final Transformer layer.
  2. NN: the last input token’s position (in this slide, rather than the number of stacked layers).
  3. dd: 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, E⊤E^\top, so the two operations share learned weights. The language model head computes the vocabulary logits:

hNL⏟1×dE⊤⏟d×∣V∣=u⏟1×∣V∣\underbrace{h_N^L}_{1\times d} \underbrace{E^\top}_{d\times |V|} = \underbrace{u}_{1\times |V|}

Softmax converts uu 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

  1. If N=3N = 3, the encoder side of the architecture is:

    Input tokens
        ↓
    Embeddings + positional encoding
        ↓
    Encoder layer 1
        ↓
    Encoder layer 2
        ↓
    Encoder layer 3
        ↓
    Final input representations → decoder

    Each encoder layer updates the full sequence of token vectors. The final representations are supplied to the decoder’s cross-attention sublayers. ↩

  2. For one attention head, let dd be the query and key dimension, as above, and let dvd_v be the value dimension. Queries and keys need the same dimension so we can take their dot product. Values can have a different dimension. ↩

  3. For GPT-2, replace ReLU with GELU. ↩

  4. 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 (2,4,6,8)(2, 4, 6, 8); afterward, it produces (20,40,60,80)(20, 40, 60, 80). 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 μ\mu and divide by the standard deviation σ\sigma:

    Input to Layer BMean μ\muStandard deviation σ\sigmaNormalized features (x−μ)/σ(x-\mu)/\sigma
    (2,4,6,8)(2, 4, 6, 8)(2+4+6+8)/4=5(2+4+6+8)/4 = 5(9+1+1+9)/4=5\sqrt{(9+1+1+9)/4} = \sqrt{5}(−3,−1,1,3)/5≈(−1.34,−0.45,0.45,1.34)(-3,-1,1,3)/\sqrt{5} \approx (-1.34,-0.45,0.45,1.34)
    (20,40,60,80)(20, 40, 60, 80)(20+40+60+80)/4=50(20+40+60+80)/4 = 50(900+100+100+900)/4=500\sqrt{(900+100+100+900)/4} = \sqrt{500}(−30,−10,10,30)/500≈(−1.34,−0.45,0.45,1.34)(-30,-10,10,30)/\sqrt{500} \approx (-1.34,-0.45,0.45,1.34)

    The two vectors have different scales but produce the same normalized features in this simplified example. Actual layer normalization uses σ2+ϵ\sqrt{\sigma^2+\epsilon} 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. ↩

  5. 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. ↩

  6. For example, with input “I love pizza”, treating each word as one token, N=3N=3. If d=4d=4, all final hidden states together form:

    HL=[h1Lh2Lh3L]shape 3×4.H^L= \begin{bmatrix} \rule{1em}{0.4pt} & h_1^L & \rule{1em}{0.4pt} \\ \rule{1em}{0.4pt} & h_2^L & \rule{1em}{0.4pt} \\ \rule{1em}{0.4pt} & h_3^L & \rule{1em}{0.4pt} \end{bmatrix} \quad\text{shape }3\times4.

    Each hiLh_i^L in this schematic matrix stands for an entire row of four features. The last row is:

    hNL=h3L=[0.2, −0.5, 1.3, 0.7]shape 1×4.h_N^L=h_3^L=[0.2,\,-0.5,\,1.3,\,0.7] \quad\text{shape }1\times4. ↩

Bibliography

  1. Tomas Mikolov, Kai Chen, Greg Corrado, and Jeffrey Dean, “Efficient Estimation of Word Representations in Vector Space,” arXiv preprint arXiv:1301.3781, 2013.
  2. Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio, “Neural Machine Translation by Jointly Learning to Align and Translate,” arXiv preprint arXiv:1409.0473, 2014.
  3. Ashish Vaswani et al., “Attention Is All You Need,” in NeurIPS, 2017.