Embedding Models: Architecture, Pooling & Selection › Worked Example: Mean Pooling Step by Step
Language AI HandbookAll chapters Embedding Models: Architecture, Pooling & Selection › Worked Example: Mean Pooling Step by StepOne section · Sections in this chapter5 / 12 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
To make mean pooling concrete, let's walk through a numerical example with a toy model. Suppose we have a toy transformer with hidden dimension , and we encode the three-token sequence ["The", "cat", "meows"] with one padding token added to match a batch length of 4.
After the final transformer layer, suppose the hidden states are as follows (each row is one token's hidden state, each column is one of the four dimensions):
where the first row is the hidden state for "The", the second for "cat", the third for "meows", and the fourth for the padding token. The attention mask is , showing that the first three tokens are real and the fourth is padding.
Step 1: Apply the mask. Multiply each hidden state row by its mask value:
Step 2: Sum the masked hidden states across all token positions, dimension by dimension:
Step 3: Divide by the number of real tokens. The sum of the mask values is , so we divide each dimension by 3:
Step 4: L2-normalize. Compute the Euclidean norm of this vector:
Then normalize:
The key insight from this example is that mean pooling is a simple weighted average where the weights come from the attention mask, and the normalization step ensures that the output vector lies on the unit sphere. The entire computation is differentiable with respect to the hidden states , which means gradients can flow back through the pooling operation during training, teaching the transformer to produce hidden states that aggregate well when averaged.