Transformer Architecture Explained: A Step-by-Step Guide

Transformer architecture explained step by step: embeddings, self-attention, multi-head attention and decoder-only LLMs, with code tests and a learning path.

R&D, Futurense
December 4, 2026
•
8
min read
AI and Machine Learning
UI/UX Design
Education & Academic Guidance
transformer-architecture-explained
Box grid patternform bg-gradient blur

What Is a Transformer?

A transformer is a type of neural network built for sequences such as sentences, code or audio. It comes from the 2017 paper "Attention Is All You Need" by Vaswani and colleagues. The authors proposed a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely.

That sentence carries the whole idea. Earlier sequence models, such as recurrent networks, read text one word at a time. A transformer reads all positions together and decides, for each one, which other positions matter. If you are new to the basics, our guides on deep learning and artificial neural networks cover the foundations first.

Today the idea sits behind large language models, image generators and speech systems. Stack Overflow's engineering blog notes the decoder-only transformer is used almost universally by all large language models.

Why Transformers Replaced Recurrent Networks

Recurrent networks have two problems. They process tokens in order, so training cannot be spread easily across many chips. And information from early tokens must survive many steps to reach later ones, so long-range links fade.

The paper's complexity table summarises the trade. Self-attention costs O(n²·d) per layer, but needs O(1) sequential operations and gives O(1) maximum path length between any two positions. Put plainly: every token can reach every other token in one step, and the whole layer computes at once. The price is the n² term, which we return to in the cost section.

The paper reported 28.4 BLEU on English-to-German translation and 41.8 on English-to-French in its latest arXiv version, after training for 3.5 days on eight GPUs. Training speed mattered as much as accuracy, because it made much bigger models practical.

Transformer Architecture Explained Step by Step: Tokens, Embeddings and Positions

Every transformer starts with three steps before attention appears.

  1. Tokenization. Text is split into tokens, which are pieces of words. "Unhappiness" might become three tokens.
  2. Embeddings. Each token ID maps to a vector of numbers, learned during training. In the original paper every layer works with vectors of size 512.
  3. Positional encoding. Attention by itself ignores order, so position information is added to each embedding. The paper used sinusoids of different frequencies, saying it hypothesised this would allow the model to easily learn to attend by relative positions.

Newer models use other position schemes, but the purpose is the same.

Self-Attention: Queries, Keys and Values

Self-attention is the heart of the architecture. For each token, the model creates three vectors by multiplying the embedding with learned matrices:

  • A query: what this token is looking for.
  • A key: what this token offers to others.
  • A value: the information it passes on if chosen.

The model compares each query with every key, turns the scores into weights with softmax, and returns a weighted sum of the values. The paper's formula is:

Attention(Q, K, V) = softmax(Q Kᵀ / √d_k) V

Think of a library search: the query is your question, each key is a catalogue entry, and the value is the book's content. Softmax makes the weights positive and sum to one, so the output leans toward the best matches.

The √d_k divisor is easy to skip past and worth understanding. The authors write that for large d_k, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients, so they scale by 1/√d_k. We test this below.

Multi-Head Attention

One attention pattern is limiting. A token might need to link to its subject, its verb and a nearby number at once. Multi-head attention runs several attention operations in parallel, each with its own learned projections, then joins the results.

The base model in the paper used h=8 heads, with each head working in 64 dimensions (512 divided by 8). The authors note that with a single head, averaging inhibits attending to different representation subspaces at different positions, which motivates splitting the work.

A caution: some heads show interpretable patterns, but many do not, so "head 3 handles grammar" is an oversimplification.

The Rest of the Block: Feed-Forward Layers, Residuals and Layer Norm

Attention is only half of each transformer layer. The other pieces matter just as much for training.

  • Feed-forward network. After attention, each position passes through a small two-layer network applied identically at every position. In the paper its inner size was 2,048.
  • Residual connections. Each sub-layer's input is added back to its output, so gradients flow easily through deep stacks.
  • Layer normalization. Keeps values in a stable range. The paper's output of each sub-layer is LayerNorm(x + Sublayer(x)).

The original encoder stacks N=6 identical layers, and each layer has two sub-layers: multi-head self-attention, then a position-wise feed-forward network. The paper's base model had roughly 65 million parameters. Frontier models are far larger but still stack this same block.

Encoder, Decoder and Decoder-Only Models

The original transformer had two halves, built for translation.

Three families grew from this:

Transformer Model Architectures: Encoder-only vs. Encoder-decoder vs. Decoder-only
Family Uses Example job
Encoder-only Understanding text Classification, search embeddings
Encoder-decoder Input-to-output mapping Translation, summarisation
Decoder-only Generating text Chatbots, code assistants

Chat models belong to the third family. A Towards AI explainer notes that the first GPT paper used a Transformer decoder for generative pretraining in 2018, and that the cross-attention block which read the encoder's output disappears in decoder-only models. Our guide to generative AI models shows where each type is used.

We Tested the Transformer Math in Code

We checked four claims with a small NumPy script. These are our own tests on random numbers, not benchmarks of a real model.

Test 1: why scale by √d_k. For random queries and 64 keys, we measured the dot-product variance and how peaked the softmax became, with and without the scaling.

Attention Scaling and Variance Analysis by Key Dimension (d_k)
d_k Variance of q·k Avg. top weight, scaled Avg. top weight, unscaled Rows with top weight above 0.99, unscaled
16 16.1 0.109 0.584 2.6%
64 64.1 0.107 0.792 20.4%
512 511.9 0.109 0.928 59.7%

The variance matches d_k almost exactly, as the paper argues. Scaled attention stays at about the same sharpness whatever the size, while unscaled attention collapses toward one-hot choices, and at d_k=512 six in ten rows put over 99% of their weight on one token. Those saturated rows are where gradients vanish.

Test 2: attention ignores order by itself. We shuffled the input tokens of a self-attention layer with no positions added. Outputs were the same, only shuffled in the same way. After adding sinusoidal positions to the shuffled sequence, the outputs changed, with a maximum difference of 5.4. So position encoding is what lets the model tell "dog bites man" from "man bites dog".

Test 3: the causal mask works. With a lower-triangular mask, every row of weights summed to 1 and the maximum weight on future tokens was exactly 0.

Test 4: the n² cost, by arithmetic. A fully materialised attention score matrix in 16-bit precision needs about 0.002 GB at 1,000 tokens, 0.128 GB at 8,000 and 32.8 GB at 128,000, per head per layer. This is arithmetic, not a measurement, and practical systems avoid storing the full matrix.

Limits. Random data, one layer, no training. The tests confirm the mechanics, not model quality.

What Changed Since 2017: KV Cache, GQA and FlashAttention

Production LLMs differ from the paper in practical ways, mostly to make generation cheaper.

  • Decoder-only layout. The encoder and cross-attention are dropped.
  • KV cache. The Towards AI article explains that during generation, the system can keep keys and values in a KV cache, saving it from recomputing them for every new token.
  • Grouped-query attention (GQA). Several query heads share one key and value head, shrinking the cache. A study guide notes that Llama-3 70B uses 64 query heads and 8 KV heads, reducing KV cache size 8x. Treat that as a secondary source.
  • FlashAttention. An exact, IO-aware method that avoids storing the full n×n matrix, enabling longer context lengths.
  • Mixture of experts. Some models activate only part of their parameters per token, trading memory for compute.

To see the scale, we calculated a hypothetical model with 32 layers, 32 query heads, head size 128 and 16-bit values. With 32 KV heads it needs 512 KiB per token, or 16 GiB at 32,768 tokens. With 8 KV heads it needs 128 KiB per token, or 4 GiB. These numbers are illustrative, not from a model card, but they show why KV cache design shapes inference cost and affordable context length.

Costs and Limits of Transformers

Transformers are powerful, not free.

  • Quadratic attention. Doubling the sequence length roughly quadruples attention compute and, without tricks, memory.
  • Hardware appetite. Training and serving depend on accelerators. Our explainer on GPUs, TPUs and NPUs covers the options.
  • Hallucination. The architecture predicts plausible tokens, not verified facts. Grounding with a RAG pipeline reduces this.
  • Size trade-offs. Bigger is not always better for a given job, as our comparison of small language models vs large language models shows.

Where Transformers Are Used Today

Natural language processing came first, but transformers now also power code assistants, image and audio models and multimodal AI that handles several data types at once. The core pattern of attention plus feed-forward layers repeats.

How to Learn the Transformer Architecture

A practical order for a learner:

  1. Refresh matrix multiplication and softmax.
  2. Read the original paper's sections 3.1 to 3.5 slowly.
  3. Implement scaled dot-product attention in NumPy, as we did above.
  4. Build a small decoder-only model on a tiny dataset.
  5. Read how a real open model differs.

If you want a career route, our guide on how to become an AI engineer maps skills to roles. Futurense also offers a GenAI and Agentic AI programme with IIT Roorkee. Check eligibility and the current curriculum on the programme page before applying.

Common Transformer Misconceptions

  • "Attention means the model understands." It computes weighted sums; understanding needs separate evidence.
  • "A bigger context window fixes everything." Quadratic cost and accuracy limits still apply.
  • "Transformers are only for text." They are used across modalities.

‍

What is the transformer architecture in simple terms?

A transformer reads all tokens of a sequence at once and uses self-attention to decide which tokens matter to each other. Stacked layers refine those relationships into predictions such as the next word.

What is self-attention in a transformer?

Self-attention lets every token compare itself with every other token using queries and keys, then take a weighted mix of their values. The weights come from a softmax over scaled dot products.

Why does attention divide by the square root of d_k?

Dot products grow with the key dimension, which pushes softmax into saturated regions with tiny gradients. Dividing by the square root of d_k keeps their spread stable. Our test showed variance equal to d_k without scaling.

What is the difference between encoder and decoder?

The encoder builds a representation of the input. The decoder generates output one token at a time, using masked self-attention and, in the original design, cross-attention over the encoder's output.

Why are most LLMs decoder-only?

Decoder-only models suit next-token generation, use one KV cache and scale simply. They are used almost universally by LLMs, though encoder-only models still suit classification and search embeddings.

Is the transformer still the best architecture?

It remains the dominant design for LLMs, and researchers continue to modify it. Whether a new architecture will replace it is unsettled, so treat any claim of a clear successor with caution.

Logo Futurense white

Advanced Engineering Program in Applied AI, ML with Context Engineering

IITM Pravartak

Become the Context Engineer every AI & ML team needs to design scalable, business-driven workflows.

Learn More

Share this post

Similar Posts