What Is a Transformer? The Architecture Behind LLMs Explained

By LatestLLM Editorial · Published · Facts verified · 9 min read

Also called: transformer architecture, decoder-only transformer, transformer block, GPT architecture

Before this: Attention, Embedding, Positional encoding, Feed-forward network, Normalization and residual connections

In one line

A transformer is a neural network built from a stack of identical blocks, each mixing information between tokens with attention and then refining each token on its own.

Transformer, simply and technically

In plain English

Almost every modern chatbot, including ChatGPT, Claude and Gemini, is built on a design called the transformer, introduced by Google researchers in 2017. It reads your text as tokens, turns each token into a list of numbers, and passes those lists through dozens of identical processing stages called blocks. At the end it produces one thing: a probability for every possible next token.

Each block does two jobs in turn. First the tokens share information with each other through attention, so every word can take its context into account. Then each token is processed on its own by a small network that refines what it means. Repeating this many times builds up an increasingly detailed understanding, and the model writes its answer by predicting one token, adding it to the text, and running again.

Think of it like this: A transformer is like an assembly line of editors working on a document. At every station, the editors first gather round and compare notes about how the words relate to each other, then each editor goes back to their own word and improves its description. After dozens of stations, the last editor uses the polished descriptions to guess the next word. The analogy is imperfect in one way: every station has its own trained editors, but all stations follow exactly the same procedure.

Everyday example: Writing an answer one token at a time

You ask a chatbot to finish a sentence.

Input:

The capital of France is

Output:

 Paris

What it shows: The model ran your whole sentence through its stack of blocks, produced a probability for every token it knows, and picked " Paris" because it scored highest. To keep writing it appends " Paris" to the text and runs the stack again for the next token.

Technically

Current LLMs are decoder-only transformers. Token ids are embedded into d-dimensional vectors; L blocks each apply x = x + Attention(Norm(x)) and then x = x + FFN(Norm(x)); a final norm and the unembedding matrix map the last position to logits over the vocabulary, and softmax gives next-token probabilities. The additions form the residual stream that carries information through the depth of the network.

Since 2017 the recipe has converged on pre-norm RMSNorm, rotary position embeddings, gated feed-forward layers such as SwiGLU and grouped-query attention. Many large models replace the dense FFN with a mixture of experts. Published depths are 36 layers for gpt-oss-120b, 60 for Gemma 4 31B and 61 for DeepSeek-V3, against 12 for GPT-2 small in 2019.

Technical example: Counting GPT-2 small's parameters from its shape

Rebuild the parameter count of GPT-2 small (12 layers, width 768, 50,257 tokens, 1,024 positions) from its block structure.

Code (python):

d, vocab, positions, layers = 768, 50_257, 1_024, 12

attn_qkv = d * 3 * d + 3 * d      # fused query/key/value projection
attn_out = d * d + d              # output projection
mlp_up = d * 4 * d + 4 * d        # expand to 4x width
mlp_down = 4 * d * d + d          # project back
layer_norms = 2 * (2 * d)         # two LayerNorms (scale + bias)
per_block = attn_qkv + attn_out + mlp_up + mlp_down + layer_norms

embeddings = vocab * d + positions * d  # token + learned position tables
final_norm = 2 * d
total = embeddings + layers * per_block + final_norm

print(f"per block: {per_block:,}")  # 7,087,872
print(f"total: {total:,}")          # 124,439,808 (output head tied to embeddings)

Output:

per block: 7,087,872
total: 124,439,808

What it shows: The total matches the 124M-parameter checkpoint published as openai-community/gpt2. Each block's weight is dominated by about 12 x d squared parameters, two thirds of them in the feed-forward layers, a ratio that still roughly holds in dense models today.

Follow one token through a transformer. Step through the path a token takes in a decoder-only transformer: tokenizer, embedding lookup, a repeated block of normalisation, attention, residual add and feed-forward, then the final norm, unembedding and softmax. Each stage shows the real tensor shapes of GPT-2 small and links to the concept page that explains it. Shapes from GPT-2 small (12 layers, width 768, 12 heads, 50,257-token vocabulary).

The big picture

In plain English: Text goes in one end and a guess about the next token comes out the other. In between, there are three stages: turning tokens into numbers, passing those numbers through a tall stack of identical blocks, and turning the final numbers into a score for every possible next token.

Think of it like this: Think of a tall office building where every floor has the same layout: a meeting room where everyone talks, then individual desks. The document goes up floor by floor.

Technically:

Input: token ids t_1..t_n. Embedding: X_0 = E[t], shape n x d. Blocks: X_l = Block_l(X_{l-1}) for l = 1..L, each preserving shape n x d. Output: logits = Norm(X_L) W_U with W_U of shape d x V, followed by softmax. Training minimises cross-entropy between the predicted distribution at each position and the actual next token, computed for all n positions in one pass thanks to the causal mask.

The original transformer (Vaswani et al., 2017) had an encoder and a decoder for translation. GPT models kept only the decoder stack, BERT kept only the encoder, and decoder-only won for generative language models because one objective, next-token prediction, scales to any text.

Go deeper: details for practitioners
  • Encoder models such as BERT see the whole sentence in both directions and are still used for classification and for the embedding models behind search.
What is a logit?

A raw, unnormalised score for one vocabulary entry. Softmax turns the logits into probabilities.

What does decoder-only mean?

A transformer that has only the causally masked stack, so it reads left to right and predicts the next token.

Inside one block

In plain English: Every block has the same two steps. In the first step, attention, each token looks at the earlier tokens and borrows what it needs. In the second step, a small network works on each token separately, using what it has learned to enrich the token's meaning. Before each step the numbers are rescaled so they stay in a healthy range, and after each step the result is added on top of what was there before rather than replacing it.

Technically:

A pre-norm block computes h = x + Attn(RMSNorm(x)) and y = h + FFN(RMSNorm(h)). Attention is the only operation that moves information between positions; the feed-forward network is applied to each position independently. Modern FFNs are gated, for example SwiGLU: FFN(x) = W_2 (silu(W_1 x) * W_3 x), with an inner width several times d.

Researchers often describe the residual stream as a shared communication channel: attention heads read from it and write relevant context into it, and FFN layers read from it and write learned associations. Analysing what each component writes is the basis of much interpretability research.

Technical example: The block as two lines of code

Pseudocode for one pre-norm decoder block.

Code (python):

def block(x):
    x = x + attention(rms_norm(x))     # mix information across tokens
    x = x + feed_forward(rms_norm(x))  # refine each token on its own
    return x

What it shows: Everything else in a modern LLM is either the embedding before this loop, the output head after it, or a refinement of one of these two lines.

Go deeper: details for practitioners
  • Some designs add extra norms. Gemma uses sandwich normalisation, a norm both before and after each sub-layer, which helps stability at large scale. See the Gemma 4 architecture guide.
What is RMSNorm?

A normalisation that rescales a vector by its root mean square, keeping activations in a stable range. It is cheaper than LayerNorm because it skips mean subtraction.

What is a residual connection?

Adding a layer's input back onto its output, so each layer only has to learn a correction rather than a whole new representation.

Depth, width and scale

In plain English: Bigger models mostly have more blocks and wider blocks. GPT-2 small, from 2019, had 12 blocks. Today's open models have 36 to 61, and each block is several times wider. More blocks let the model build up more steps of reasoning about the text, while wider blocks let it keep track of more detail at each step.

Technically:

Dense parameters scale as roughly 12 L d^2. GPT-2 small (L = 12, d = 768) has 124 million parameters. gpt-oss-120b has 36 layers at width 2,880 but 117 billion total parameters, because its feed-forward layers are mixtures of 128 experts of which 4 run per token. DeepSeek-V3 has 61 layers at width 7,168 and 671 billion total parameters with about 37 billion active per token.

Mixture-of-experts layers replace one FFN with many and route each token to a few. This decouples total parameters, which set what the model can store, from active parameters, which set compute per token.

Go deeper: details for practitioners
  • Scaling laws (Kaplan et al., 2020; Hoffmann et al., 2022) relate loss to parameters, data and compute and guide how labs split a training budget between model size and tokens.
What is a mixture of experts?

A layer with many feed-forward networks, the experts, where a router sends each token to only a few of them.

How a transformer generates text

In plain English: The model never writes a whole answer at once. It predicts one token, adds it to the end of the text, and predicts again, over and over until it produces a special end marker or hits a length limit. Settings like temperature control whether it always picks the most likely token or sometimes takes a less likely one, which makes answers more varied.

Technically:

Autoregressive decoding samples y_t ~ p(. | y_<t) from the softmax over logits, often after temperature scaling and top-p or top-k truncation. The prompt is processed in one parallel prefill pass that fills the key-value cache; each subsequent token is a decode step attending to the cache, so decode cost is dominated by reading weights and cache from memory.

Because only the last position's logits are needed at each decode step, inference engines batch many users' decode steps together, use paged KV caches and apply speculative decoding to propose several tokens per pass. DeepSeek-V3's multi-token prediction heads are trained to make such speculation accurate.

What is temperature?

A number that divides the logits before softmax. Low values make the model pick the top token almost always; higher values spread probability to less likely tokens.

What is prefill?

The first phase of a request, where the whole prompt is processed in parallel to build the key-value cache before generation starts.

Common misconceptions

  • Myth: A transformer looks up answers in a database.

    Reality: It computes a probability for every next token from its learned weights. Facts are stored implicitly in those weights, not as retrievable records.

  • Myth: Each layer of a transformer does something completely different.

    Reality: Every block uses the same structure; only the learned weights differ, and different layers end up specialising through training.

  • Myth: The model plans and writes the full answer, then shows it to you.

    Reality: Generation is one token at a time, each conditioned on everything before it, including the tokens the model itself just produced.

Where you'll see this

Key takeaways

  • A transformer is a stack of identical blocks; each block mixes information across tokens with attention, then processes each token with a feed-forward network.
  • Residual connections add every block's output to a running vector per token, which makes very deep stacks trainable.
  • The model's only output is a probability for every possible next token; text is generated by sampling one token and repeating.
  • Modern LLMs are decoder-only transformers with refinements such as RMSNorm, RoPE, SwiGLU, grouped-query attention and mixtures of experts.

Frequently asked questions

What does a transformer do in simple terms?

It reads text as tokens, lets the tokens share context through attention over many layers, and predicts the most likely next token.

Who invented the transformer?

It was introduced in the 2017 paper "Attention Is All You Need" by Vaswani and colleagues at Google.

Is ChatGPT a transformer?

Yes. GPT stands for Generative Pre-trained Transformer, and all GPT models are decoder-only transformers.

What is the difference between a transformer and an LLM?

The transformer is the network design. An LLM is a specific transformer trained on very large amounts of text to predict tokens.

Why did transformers replace recurrent networks?

They process all positions in parallel during training and connect distant tokens directly, so they train faster and scale better on GPUs.

Sources

Facts last verified November 23, 2026.

Next concept: Next-token prediction

Learn next

  • Next-token prediction (Beginner): Next-token prediction is the task a language model performs: given the text so far, it scores every token in its vocabulary and one token is chosen as the next.
  • Mixture of experts (Intermediate): A mixture-of-experts model splits its feed-forward layers into many experts and uses a router to send each token to only a few, so most of its parameters stay idle per token.
  • Token (Beginner): A token is the small piece of text, often a word or part of a word, that a language model reads, counts and generates one at a time.
  • Dimension (Intermediate): A dimension is one slot in a vector, and a model's dimension or hidden size is how many numbers it uses to represent every token at each layer.