All articles

How does a Transformer work?

Avocado or lawyer? In French, “avocat” can mean either, and “mûr” (ripe) gives us a clue. Follow the translation to see how a Transformer, a type of neural network, uses context and produces text.

Our example, from French into English

Un avocat bien mûr.

A ripe avocado.

The attention mechanism

How “ripe” can change the representation of “avocat”.

The model works with pieces of text called tokens. To update a position, attention compares a list of numbers called the query (Q) with keys (K) from the positions it can see. A higher comparison score gets a larger weight. An operation called softmax turns the scores into weights that add up to 1.

The model uses those weights to take a weighted sum of the values (V), the lists of numbers that carry information. When the queries, keys and values come from the same sequence, this is called self-attention. Several computations can run in parallel, each producing a different mixture from the same sentence. These are called attention heads.

One self-attention calculation
Choose a step
Position we’re updating « avocat »
UnK
avocatK
mûrK

The query at “avocat” is compared with each key shown. To make the calculation easier to follow, the diagram shows three fragments and one attention head.

Position we’re updating « avocat »
Un10%
avocat25%
mûr65%

Each score becomes a weight. In this made-up example, “mûr” contributes more. The percentages were chosen to illustrate the calculation.

Representation with context
Un10%
avocat25%
mûr65%

Attention adds 10% of the value vector for “Un”, 25% of the one for “avocat” and 65% of the one for “mûr”. The resulting vector carries information about the context.

What gets mixed together

Compare « un avocat bien mûr » (a ripe avocado) and « un avocat au tribunal » (a lawyer in court). The token “avocat” can start with the same vector in both phrases. The surrounding positions change. Its query can therefore score the keys for “mûr” and “tribunal” differently. The available value vectors change too. The resulting vectors can carry different information about the same word.

Take a single entry from these lists of numbers. If the values for “Un”, “avocat” and “mûr” are 2, 4 and 8, the weights in the diagram give 0.10 × 2 + 0.25 × 4 + 0.65 × 8 = 6.4. The model repeats that operation for every entry in the vector. The 65% describes the weight of “mûr” in this one calculation. By itself, that number cannot tell you which translation the model will produce.

The encoder

From the source sentence to one representation per position.

Before the encoder, a tokenizer splits the sentence. A token can be a word, part of a word or a punctuation mark. Each token gets an initial vector, which is a list of numbers. The model also receives positional information so it can tell what order the pieces are in.

The encoder applies several layers. In the original encoder, self-attention can use positions before and after the token being examined. A small network then transforms each position’s vector independently. At the output, each position has its own representation enriched by context. The translation decoder can consult this set of representations.

From a sentence to vectors
Choose a step
Un
avocat
mûr

The sentence is split into tokens. The diagram shows a simplified split with three fragments.

Un
avocat
mûr

Each position starts with a list of numbers derived from the token and information about its place in the sentence. The bars stand for these numbers.

Un
avocat
mûr

The layers update the vectors. The bars change at every position, while the number of positions stays the same.

What changes from layer to layer

“Paul follows Lea” and “Lea follows Paul” contain the same words with different meanings. Positional information gives the network a way to account for their order. Once the numbers are in place, each position has its own list. In the diagram, “avocat” keeps its own box at each step, even as the bars inside change.

In an encoder layer, attention moves information between positions. The small network that follows can transform each result independently. The next layer takes these enriched lists and repeats the process. At the end, there is still a list for each position. This lets the decoder consult different parts of the input at different points in the translation. For example, the clues it uses to produce “ripe” can differ from the ones it uses to produce “avocado”.

The decoder

From the translation so far to the next token.

During generation, the decoder produces one token at a time. Its self-attention is called causal. At any position, it can use that position and those before it. In the translation Transformer, an additional operation called cross-attention uses a query from the decoder and keys and values derived from the encoder’s output.

An output layer uses the decoder’s representation to compute a score for each token in the vocabulary. These scores become probabilities. The system can pick the most probable token or sample one, depending on the method it uses. The chosen token joins the sequence and the process repeats until a stop signal or rule applies.

A translation that grows one token at a time
Choose a step
A

From the start signal, the model chooses “A” in this example. The rest of the translation is still to come.

Aripe

With “A” already written and information from the source sentence, the model chooses “ripe” here.

Aripeavocado

The calculation runs again with “A ripe” and adds “avocado”. The dashed box represents the rest, which will be generated in later passes.

Why the next token is still open

After “A”, several continuations would be grammatical. When translating, cross-attention gives the decoder access to clues such as “mûr” in the source. Once it chooses “ripe”, the next step starts from “A ripe”. Probabilities are recalculated using the new prefix and the same source. That is why a choice made early can change the rest of the translation even when the original sentence stays the same.

During training, the target translation is known. A causal mask lets the model calculate predictions for several positions in parallel while preventing each position from looking at the tokens that follow it. When the model is used to produce a new translation, each selected token becomes part of the input for the next pass. The diagram shows this second situation.

The Transformer

How the two parts work together, and when a model uses just one.

In the translation Transformer introduced in 2017, the encoder processes the source sentence. The decoder consults the representations of that sentence while working from the translation it has generated so far. The architecture stacks layers that combine attention with transformations applied to each position separately.

The family includes other designs. BERT uses an encoder alone, for example to classify text after fine-tuning. GPT-style models use a decoder alone with causal self-attention to continue the given text. T5 uses both an encoder and a decoder to turn one text into another.

The complete translation process
Choose a step

Source sentenceUn avocat bien mûr.

  1. Source sentence
  2. The encoder
  3. The decoder

The French sentence provides the tokens and their order.

Source sentenceUn avocat bien mûr.

  1. Source sentence
  2. The encoder
  3. The decoder

The encoder produces representations for all positions in the source sentence.

TranslationA ripe avocado.

  1. Source sentence
  2. The encoder
  3. The decoder

The decoder consults the source representations and adds output tokens one at a time. After several passes, the full translation is ready.

Following information through the model

The French phrase goes into the encoder once. Its representations remain available as the decoder moves forward. At each step, the decoder combines two kinds of information. Causal self-attention works over the translation generated so far. Cross-attention works over the representations of the French phrase. The output layer then turns the result into scores for the next token.

In a GPT-style model, the prompt and the generated text form one sequence. To continue “Translate into English: un avocat bien mûr”, the decoder can consult the prompt tokens through self-attention. The context comes from the start of the sequence. In both architectures, the next token depends on what the model learned. A plausible continuation can therefore contain a mistake even when the model has used the available context.

Two questions to check your understanding

Why can “avocat” have two different representations?

Attention combines information from the positions it can see. Replacing “mûr” with “au tribunal” changes that information, so the result of the calculation can change.

What happens once the decoder chooses “ripe”?

The token joins “A” in the translation so far. The next pass calculates new scores using “A ripe” and, for this translation model, the source representations.