Concepts / Sampling in Language Models

Sampling in Language Models

A transformer language model has an embedding module at the entry, a stack of transformer blocks in the middle, and an output layer at the exit.

  • Programming
Interactive lab

Try it: Text Vectorization: Tokens to Vectors

The text-to-tensor pipeline: standardize, split into tokens, build a frequency-ranked vocabulary with padding and [UNK], map tokens to integer ids, pad or truncate, then one-hot or multi-hot encode and look the ids up in an embedding table.

How it works

  1. Standardize: lowercase and delete punctuation.
  2. Split on whitespace into tokens.
  3. Build the vocabulary: 0 = padding, 1 = [UNK], then words by frequency (ties: first appearance), capped at max tokens.
  4. Map each token to its id (1 if it did not make the vocabulary), then pad with 0 or truncate to the sequence length.
  5. Encode: one-hot rows per position or one multi-hot row per text; embed: id k selects row k of the embedding table.

Default run (18 steps): Raw text (59 characters): "The movie was great. The plot was great, the acting wasn't!". A model cannot read strings, so it is turned into numbers step by step. … Embedding lookup: id k selects row k of a fixed 8 x 3 table, giving a (8, 3) dense matrix instead of (8, 8) sparse one-hots. Row 0 (padding) is looked up too; a trained Embedding layer would learn these rows.

Simplified: Bounded ASCII text (up to 200 characters, 40 tokens), whitespace splitting only, and a small FIXED embedding table (a real Embedding layer learns its rows). The multi-hot vector keeps the padding slot (always 0) so its positions line up with the ids.

Educational simulation

Loading the simulation…

Following One Token Through the Model

Imagine you could freeze a language model at the moment it receives one token of input and then follow that token step by step until the model produces a prediction. Along the way the token passes through several distinct stages, and each stage has a specific job. Learning the components of a transformer is largely a matter of naming those stages, understanding what each one does to the data, and seeing how they are arranged.

This article takes that route. We begin with the path a token travels from input to output, then zoom into the parts that repeat. Sampling is the final step in the course's story: the probabilities the model produces at the exit are what it uses to choose its outputs. The focus here is the architecture that produces those probabilities.

The Three Stages of the Stack

A transformer-based language model has an embedding module at the entry, a stack of transformer blocks in the middle, and an output layer at the exit. Two of those three stages are used only once per prediction. The transformer blocks are the part that repeats, and most of the model's internal machinery lives there.

Token IDinteger from the input textEmbedding moduletoken and position vectorsTransformer block 1attention then MLPTransformer block Nrepeated in sequenceOutput layersingle matrixToken probabilitiesused for samplingconverted to vectoroutput vectorsrepeatsfinal vectorsmapped to tokens
What happens to a token's representation from the moment text enters the model until a next-token distribution comes out, and where does each module sit along that path?

Read the diagram from left to right. The token enters as an ID, is converted into a vector by the embedding module, is transformed repeatedly by the transformer blocks, and leaves the model through the output layer as a set of token probabilities. The vector changes in meaning at each stage, but the overall journey is one-directional, from input to output. The blocks in the middle are drawn as a repeated element because the same template is applied many times in sequence.

Entry: Turning Token IDs into Vectors

Before any transformer block sees the input, the model passes it through an embedding module. This module consists of two matrices: the embedding matrix and the positional embedding matrix. The embedding matrix converts tokens into embedding vectors, and the positional embedding matrix converts token positions into embedding vectors. Together they turn an ordered sequence of token IDs into vectors that carry both identity and location information.

Token ID 3row 3 of embedding matrixToken ID 0row 0 of embedding matrixToken ID 7row 7 of embedding matrix
How does a token ID become a vector, and which row of the embedding table is selected for each token in the input?

The diagram above uses illustrative token IDs. The principle is what matters: each token ID selects one row of the embedding matrix, so the same token always starts from the same vector at the entry of the model. The positional embedding matrix works the same way for positions, which is how the model knows where a token sits in the sequence, not just which token it is.

Inside a Transformer Block

The transformer blocks are where most of the model's internal machinery lives. A transformer architecture is built by stacking multiple transformer blocks. The exact contents of a block can vary from one model to another, but in general each block contains two sub-modules: an attention module and an MLP (multi-layer perceptron) module. Think of the block as a fixed template, and the model as many copies of that template placed one after another.

Transformer blockone copy of the templateAttention moduleruns firstQuery, key, value,output projectionsmatrices inside attentionMLP moduleruns secondLinear layersinside MLPNonlinear activationReLU or GELUcontainscontainsthenbuilt frombuilt fromseparated by
What does one transformer block contain, in what order do the attention and MLP sublayers process the data, and how does information pass through the block?

Read the concept map as a containment tree plus an order. The block contains the two sub-modules, and within the block the attention module processes the data before the MLP module does. The arrow between them marks that order. The map also shows what each sub-module is built from, which the next two subsections describe in more detail.

Why the MLP Needs Nonlinearity

The source establishes that the MLP's linear layers are separated by nonlinear activation functions, and it names ReLU and GELU as examples. A useful way to see why the separation matters is to ask what would happen without it. If you stacked two linear layers with no activation between them, the result would still be one linear transformation. Feeding the output of one linear layer into another simply produces a different linear map. Stacking many linear layers therefore gains nothing in expressive power over a single one.

A nonlinear activation breaks that collapse. Because the function applied between the linear layers is not a straight-line transformation, the MLP can represent patterns that no single linear map could. This is the general reason the MLP needs nonlinear activations, and it is the reason the MLP is described as a stack of linear layers with activations between them rather than as a plain chain of matrix multiplications.

Exit: The Output Layer

After the last transformer block has produced its output vectors, the output layer takes over. Its job is to map those vectors into token probabilities. The output layer is also called the unembedding layer or the model head. It typically consists of a single matrix, which projects each output vector onto the vocabulary so that every token receives a score. These probabilities are what the model uses to sample its outputs, a process covered elsewhere in the course.

The output layer is the mirror image of the embedding module. The embedding module turns token IDs into vectors at the entry, and the output layer turns vectors back into a distribution over tokens at the exit. Both are used once per prediction, while the blocks between them repeat.

Model Size from Three Dimensions

The size of a transformer model is set by the dimensions of its building blocks. Three values matter most. The first is the model dimension, written $d_{model}$ and described in the source as the model's hidden size. It determines the sizes of the key, query, value, and output projection matrices inside each transformer block. The second is the number of transformer blocks, which the source notes is often called the number of layers. The third is the feedforward dimension, which is the width of the linear layers in the MLP module.

Model sizeset by three dimensionsModel dimensionsizes attention projectionmatricesNumber of blockshow many times the templaterepeatsFeedforward dimensionwidth of MLP linear layersgoverned bygoverned bygoverned by
If I increase the model dimension, the number of blocks, or the feedforward dimension, which parts of the model grow and how do those changes combine to set total size?

The source states that larger values for these dimensions produce larger models. Each of the three values grows a different part of the model: the model dimension grows the projection matrices in every block, the feedforward dimension grows the linear layers in every MLP, and the number of blocks adds more copies of the whole template. Because the blocks are repeated, a change to the per-block sizes is multiplied across every block in the stack.

Tracing a Prediction from Entry to Exit

Worked example

Tracing one token through a small hypothetical model

Suppose a hypothetical model has an embedding module, a stack of 32 transformer blocks, and an output layer. A single token with ID 7 is the last token of the input. Trace what happens to it from entry to exit, and say which parts of the model run once and which run repeatedly.

  1. 1
    Entry

    The token enters as ID 7. The embedding module uses the embedding matrix to convert the token into a vector and the positional embedding matrix to convert its position into a vector. Together these carry identity and location.

  2. 2
    First block

    The vector enters transformer block 1. The attention module runs first, using its query, key, value, and output projection matrices, and then the MLP module runs, using linear layers separated by a nonlinear activation.

  3. 3
    Remaining blocks

    The output of block 1 becomes the input to block 2, and so on. Because the model has 32 blocks, the same template is applied 32 times in sequence. The source calls this count the number of layers.

  4. 4
    Exit

    After block 32 produces its output vector, the output layer's single matrix maps that vector to a score for every token in the vocabulary. These scores become token probabilities, which is the distribution the model later samples from.

  5. 5
    Run counts

    The embedding module and the output layer each run once for this prediction. The transformer blocks run 32 times. Most of the internal machinery therefore sits in the repeated part.

Result

Token ID 7 travels one directional path: embedding module, 32 transformer blocks each containing attention then MLP, output layer, and finally a probability distribution over the vocabulary.

Mistakes When Reading a Model's Stack

  • Common mistake

    Treating the embedding module and the output layer as repeated parts of the model

    What it looks like

    Counting the embedding module as one of the stacked layers when reporting a model's depth.

    Why it fails

    The source says the embedding module and the output layer are each used only once per prediction. Only the transformer blocks repeat.

    Do this instead

    Count the transformer blocks when you want the number of layers. The entry and exit stages are separate from that count.

  • Common mistake

    Thinking the MLP can be a plain chain of linear layers

    What it looks like

    Drawing two linear layers back to back inside the MLP with nothing between them.

    Why it fails

    The source describes the MLP as linear layers separated by nonlinear activation functions. Without the activation, stacked linear layers collapse into one linear map.

    Do this instead

    Place a nonlinear activation such as ReLU or GELU between the linear layers.

  • Common mistake

    Assuming the position indices fix the context length exactly

    What it looks like

    Reading a model with 2,048 position indices and concluding its context length can never be larger.

    Why it fails

    The source says the naive relationship is a starting point. Some techniques increase context length without increasing the number of position indices.

    Do this instead

    Use the position count as the naive maximum, and check the model's documentation for techniques that change this.

  • Common mistake

    Confusing the model dimension with the number of blocks, when they are separate dimensions that scale different parts of the model

Predicting Which Part Grows

What do you think happens?

A model's position indices cover 2,048 positions. Using the naive relationship from the source, what is its maximum context length?

Reveal answer
Answer:

2,048

The source states that, naively, the number of position indices determines the maximum context length, so 2,048 positions gives a naive maximum of 2,048. The source also notes that some techniques can increase context length without changing the number of position indices, so this is a starting point rather than a fixed law.

MEDIUM

Suppose you double the feedforward dimension of a model but leave the model dimension and the number of blocks unchanged. Which parts of the model grow, and which parts stay the same? Name each part you identify and say which of the three dimensions controls it.

Hints
  • Recall which of the three dimensions sets the width of the linear layers in the MLP module.
  • The model dimension controls the projection matrices in the attention module, so it is not the answer here.
  • Think about whether doubling a per-block width changes the number of blocks.

Key Takeaways

  • A transformer language model has five major components: the embedding module and the output layer, each used once per prediction, and the transformer blocks, which repeat and contain an attention module and an MLP module.
  • The embedding module converts token IDs and their positions into vectors using the embedding matrix and the positional embedding matrix. The output layer maps final vectors to token probabilities, and sampling draws from those probabilities.
  • The MLP module is built from linear layers separated by nonlinear activation functions such as ReLU or GELU, because stacked linear layers without activations collapse into a single linear map.
  • Model size is governed by three dimensions: the model dimension, which sizes the attention projection matrices; the number of transformer blocks; and the feedforward dimension, which sets the width of the MLP's linear layers. Larger values produce larger models.

Related concepts

More concepts starting with S