Concepts / Building a Real Transformer Block

Building a Real Transformer Block

DummyGPTModel is a simplified GPT-style nn.Module. It builds token and positional embeddings, dropout, a stack of transformer blocks, a final layer normalization, and a linear output head.

  • Programming

Running the Model Before Explaining It

This lesson starts from running code rather than from a definition. The model you will meet is a class called DummyGPTModel. It is a stripped-down, GPT-style network built with PyTorch. Some of its internal parts are deliberately fake, so the code runs from start to finish even though those parts do no real work yet. Run the listing that accompanies this lesson and observe what comes out. Then use the trace in the following sections to explain every number you saw.

What do you think happens?

What do you think happens to the values after passing through the placeholder transformer block stack?

  • The values are changed by a learned transformation

  • The values come out exactly as they went in

  • The values are replaced with zeros

Reveal answer
Answer:

The values come out exactly as they went in

DummyTransformerBlock accepts its input and returns it without modification. A stack of copies, each passing its output to the next, is therefore also an identity operation, so nothing in that stack changes the data.

The Stages of DummyGPTModel

DummyGPTModel is a simplified GPT-style nn.Module. Its constructor builds token and positional embeddings, a dropout layer, a stack of transformer blocks, a final layer normalization, and a linear output head. The forward method is the single place where the order of operations is written down, so reading it from top to bottom gives you the data flow of the whole model.

The model receives a tensor of integer token indices, called in_idx. The stages then run in a fixed sequence. First, token indices are turned into vectors by the token embedding table and by the positional embedding table. Those two results are added together. Next comes the dropout layer, then the stack of transformer blocks, then the final normalization, and finally the linear output head, which produces the logits. Each box in the diagram below is a named component from the class, and each arrow is a value handed from one stage to the next.

in_idxinteger token indicestoken embeddingindex to vectorelement-wise sumone vector per positiondropouttransformer blocksn_layers placeholder copiesfinal layer normplaceholderlinear output headlogitsscore per vocabulary tokenpositional embeddingposition to vectorindex lookupposition lookupaddaddhand offhand offhand offhand offscores
After token indices enter DummyGPTModel, the embeddings are summed, then dropout, the transformer block stack, the final layer norm, and the output head run in that order.

Combining Token and Position Information

Integer token indices are not meaningful to the network as plain numbers, so the model first converts them into vectors in two separate ways. The token embedding table maps each token index to a vector, and this tells the model what each token is. The positional embedding table maps each position in the sequence to a vector, and this tells the model where that token sits. The two tables are indexed differently, one by token identity and one by position, so they answer different questions.

The forward method then adds the two tensors element by element. The result has the same shape as either input, so the next stage receives one combined vector per token position. This sum is taken before any dropout is applied. Nothing else runs between the lookups and the addition, which is why the summed embeddings are the input to every stage that follows.

token table row 2vector for token ID 2element-wise sumcombined vector for thispositionposition table row0vector for position 0addadd
A token ID selects one row from the token table, a position selects one row from the positional table, and the two selected vectors are added element by element.
Worked example

Following one token through the embedding step

A sequence contains the token ID 2 at position 0. Trace how this one token becomes a single vector before the transformer blocks. Use an embedding width of 4 for illustration.

  1. 1
    Look up the token vector

    The token ID 2 selects row 2 of the token embedding table. That row is a vector with 4 values, describing what the token is.

  2. 2
    Look up the position vector

    The position 0 selects row 0 of the positional embedding table. That row is also a vector with 4 values, describing where the token sits.

  3. 3
    Add element by element

    The first values of the two vectors are added together, then the second values, and so on. The result is still a vector with 4 values.

  4. 4
    Pass the result onward

    This combined vector, not either lookup on its own, is what the dropout layer and the transformer block stack receive for this position.

Result

One combined vector of width 4 represents the token at position 0, and it has the same shape as either lookup.

Why Placeholder Stages Leave Data Unchanged

DummyTransformerBlock and DummyLayerNorm are placeholders. Each one accepts whatever it is given and returns it without modification. Their constructors take the configuration or the normalized shape, so they have the same interface as the real components, which lets the rest of the model be written and run now. But they keep no logic, so no arithmetic happens inside them.

input tensorsummed embeddingsplaceholder stagereturns input as-isoutput tensorsame shape and valuespassed inreturned unchanged
The tensor entering a placeholder block or placeholder layer norm is the same tensor that leaves it, with the same shape and the same values.

Where the Logits Come From

The only stage that transforms the data at the end is the linear output head. It maps each position's embedding vector to a score for every token in the vocabulary, and those scores are called logits. The hidden-state tensor enters with one vector per position and leaves with one score per vocabulary token for each position. In shape terms, the last dimension changes from the embedding width to the vocabulary size, while the batch and sequence dimensions carry through unchanged.

Tracing Where an Unexpected Output Begins

Suppose the final logits look wrong. The method is to compare intermediate tensors stage by stage, in forward-pass order, and to find the first stage where the result diverges from what you expected. Because every stage passes its output to the next, an error introduced early will carry forward, so the earliest deviation is the one to investigate. The steps below follow the order of the forward method.

  1. 1
    Check the token embedding output for the first position. Confirm it is the row selected by the token index.
  2. 2
    Check the positional embedding output for the same position. Confirm it is the row selected by that position.
  3. 3
    Check the summed tensor. Confirm it equals the element-wise addition of the two lookups and keeps the same shape.
  4. 4
    Check the output of dropout. In evaluation mode it should match its input, so a difference here points to the dropout setting or mode.
  5. 5
    Check the output of the transformer block stack. Because it is a placeholder stack, it should match the dropout output exactly; any difference means something other than a placeholder is being used.
  6. 6
    Check the output of the final layer norm. Because it is a placeholder, it should also match its input exactly.
  7. 7
    Check the logits. Their values should follow directly from the output head applied to the tensor from the previous stage.
MEDIUM

Using the seven stages above, suppose the logits are wrong and the summed tensor already differs from the sum of the two lookups. Which stage is the first deviation, and which stages after it should you still inspect?

Hints
  • Stages are checked in forward-pass order, so the earliest mismatch is the one that matters.
  • A deviation at the summed tensor means the earlier lookups or the addition are the place to look, and later stages inherit the error.

Mistakes When Reading the Placeholder Model

  • Common mistake

    Assuming the transformer blocks are doing real work because they appear in the model

    Why it fails

    DummyTransformerBlock returns its input unchanged, so in this version the block stack has no effect on the values.

    Do this instead

    Treat the block stack as a placeholder with the right interface, and expect the output to depend only on the embeddings, dropout, and output head.

  • Common mistake

    Treating the token embedding and positional embedding as separate paths that are never combined

    Why it fails

    The forward method adds the two tensors element by element before any other stage runs.

    Do this instead

    Expect one combined vector per position as the input to dropout and every later stage.

  • Common mistake

    Looking at the final logits first when the output looks wrong

    Why it fails

    An early error propagates forward, so the final output hides where the problem began.

    Do this instead

    Compare intermediate tensors in forward-pass order and stop at the first stage that diverges.

Summary of the Forward Pass

Read the forward method top to bottom to see the order of stages. Token and positional embeddings are looked up separately and summed before anything else happens. The placeholder transformer blocks and placeholder layer norm return their input unchanged, so only the embeddings, dropout, and the output head shape the logits in this version. When an output is wrong, check the intermediate tensors in forward-pass order and find the first stage where they diverge.

At a glance

  • DummyGPTModel processes input in a fixed order: token and positional embeddings, their element-wise sum, dropout, the transformer block stack, the final layer norm, and the linear output head.
  • Token embeddings tell the model what each token is, positional embeddings tell it where the token sits, and the two are added before any other stage runs.
  • DummyTransformerBlock and DummyLayerNorm are placeholders that return their input unchanged, so in this version the logits come from the embeddings, dropout, and output head.
  • To locate an unexpected output, compare intermediate tensors stage by stage in forward-pass order and find the first stage where the result diverges.

Related concepts

More concepts starting with B