The Role of Transformers in Generative AI
How the Transformer works, why it sits under today's text, image and video models, and what it means for the cost of running them in the cloud.
Almost every generative model you can call from a cloud API today has a Transformer inside it. The chat model answering a support ticket is a stack of Transformer layers. So, increasingly, is the image model drawing a product shot and the video model animating it. One architecture from a 2017 translation paper ended up as the common engine of generative AI.
This article explains what that engine does, why it won, how it was adapted beyond text, and why its design shows up directly in your bill when you run a model. The earlier version of this article listed Bard and DALL-E 2 as current products. Both have long been replaced, so it has been rewritten. For the history of how text models got here, from n-grams through RNNs and LSTMs, read Text Generation Models: From RNNs to Transformers; this piece starts where that one ends.
What a Transformer does
A Transformer takes a sequence of vectors and returns a sequence of the same length, where each output vector has been updated with information from the rest of the sequence. That is the whole contract. What the vectors represent is up to you: word pieces, patches of an image, frames of audio, or chunks of a compressed video.
For text, the input is first split into tokens, small pieces of words, and each token is mapped to an embedding vector. The model then passes those vectors through a stack of identical blocks. Each block has two parts:
- Self-attention, where every position looks at the other positions and pulls in what is relevant to it.
- A feed-forward network, a small two-layer network applied to each position separately, which transforms what attention gathered.
Around each part sits a residual connection (the input is added back to the output) and a normalization layer, which keep deep stacks trainable. Large models repeat this block dozens of times. At the top, a final layer turns each vector into a score for every token in the vocabulary.
flowchart TB
T["Tokens"] --> E["Embeddings plus position"]
E --> B1["Block 1: attention, then feed-forward"]
B1 --> B2["Block 2"]
B2 --> BN["Block N"]
BN --> H["Output layer: score per vocabulary token"]
H --> S["Sample next token"]
S -->|"append and repeat"| T
The loop on the right side of the diagram is what makes it generative. A decoder-only model predicts one token, appends it to the input, and runs again. Every chat response you have read was produced this way, one token at a time.
Self-attention, step by step
Attention is the part that lets a token’s meaning depend on its context. Take the sentence “The bank raised its rates because it needed capital.” To represent “it”, the model needs to connect it to “bank”, not “rates”.
Each position computes three vectors from its embedding using learned weight matrices:
- A query: what this position is looking for.
- A key: what this position offers to others.
- A value: the information it hands over if selected.
The model compares one position’s query with every key using a dot product, scales the scores, and turns them into weights with a softmax so they sum to one. The output for that position is the weighted sum of all the values. If the query for “it” matches the key for “bank” strongly, most of the output comes from “bank”.
Written out, that is softmax(Q·Kᵀ / √d) · V, where d is the size of each key. Here it is in PyTorch, with the causal mask a text generator needs so that no position can look at tokens that come after it:
import math
import torch
def causal_attention(q, k, v):
# q, k, v: (batch, seq_len, d)
d = q.size(-1)
scores = q @ k.transpose(-2, -1) / math.sqrt(d) # (batch, seq, seq)
seq_len = q.size(1)
future = torch.triu(torch.ones(seq_len, seq_len, dtype=torch.bool,
device=q.device), diagonal=1)
scores = scores.masked_fill(future, float("-inf")) # hide later tokens
weights = torch.softmax(scores, dim=-1) # each row sums to 1
return weights @ v
x = torch.randn(1, 5, 16) # one sequence of 5 tokens, 16 dimensions
out = causal_attention(x, x, x) # real models project x into q, k, v first
print(out.shape) # torch.Size([1, 5, 16])
In practice you would call torch.nn.functional.scaled_dot_product_attention with is_causal=True, which computes the same thing using fused kernels. Writing it once by hand is still the fastest way to see that there is no magic: it is three matrix multiplications and a softmax.
Multiple heads and word order
Real models run attention several times in parallel, each with its own projections. These are attention heads. One head might track which noun a pronoun refers to, another the previous word, another matching brackets in code. Their outputs are concatenated and projected back to the model’s width.
Attention on its own ignores order: shuffle the inputs and each output is the same, only shuffled. The model needs position information added in. The 2017 paper added fixed sine and cosine patterns to the embeddings. Most current open models use rotary position embeddings (RoPE), which rotate the query and key vectors by an angle that depends on position, so attention scores depend on how far apart two tokens are. That relative form is part of why context windows could be stretched well beyond the lengths a model was first trained on.
In self-attention, what determines how much the token "it" draws from the token "bank"?
Correct! The query-key score sets the weight, and that weight decides how much of the value for "bank" flows into the new representation of "it".
Why the Transformer won
Before 2017, sequence models were mostly recurrent: they read one token at a time and carried a hidden state forward. The Transformer removed the recurrence, and three things followed.
Training became parallel. During training the whole target text is known, so the model can compute predictions for every position at once as large matrix multiplications. GPUs and TPUs are built for exactly that work. An RNN has to wait for step 499 before it computes step 500.
Distance stopped mattering. In a Transformer any two tokens are one attention step apart. Information from the first line of a document can reach the last line directly instead of surviving hundreds of state updates.
It scaled predictably. Research on scaling laws from OpenAI (2020) and DeepMind (2022) found that Transformer language model loss falls smoothly as you add parameters, data and compute, which made it possible to plan very large training runs with some confidence. That predictability, more than any single benchmark, is why investment concentrated on this architecture.
The price is that attention compares every token with every other token. Compute and memory for attention grow with the square of the sequence length, so doubling the context roughly quadruples that part of the work. Much of the engineering since 2017 has gone into managing that cost.
Three ways to arrange the stack
The original Transformer had an encoder, which read the source sentence, and a decoder, which wrote the translation while attending to the encoder’s output. Later models kept one half or both:
| Arrangement | Attention pattern | Trained to | Typical use today | Examples |
|---|---|---|---|---|
| Encoder-only | Every token sees every token | Fill in masked tokens | Classification, search embeddings, reranking | BERT and its descendants |
| Decoder-only | Each token sees only earlier tokens | Predict the next token | Chat, writing, code, agents | GPT, Gemini, Claude, Llama, Qwen |
| Encoder-decoder | Encoder sees all; decoder sees earlier tokens plus the encoder | Map an input to an output | Translation, speech recognition, some summarisation | T5, Whisper |
For generation, decoder-only won. It has one stack and one objective, any text is training data, and the same model handles a question, a translation or a code fix by treating each as a continuation of the prompt. Encoder-only models have not disappeared, though. They power much of retrieval: when a cloud RAG service turns your documents into embeddings, an encoder-style model is usually doing it. A later article in the Deep Dive series compares BERT and GPT in detail.
Why do chat models use a decoder-only design with a causal mask?
Correct! The causal mask makes training match generation: the model always predicts the next token from what came before.
Beyond text
Because a Transformer only needs a sequence of vectors, anything you can cut into pieces can go through it.
Images as patches. The Vision Transformer (ViT, 2020) split an image into 16 by 16 pixel patches, flattened each into a vector and fed the sequence to a standard encoder. Given enough training data, it matched or beat convolutional networks at image classification.
Text and images in one space. OpenAI’s CLIP (2021) trained a text encoder and an image encoder together so that a caption and its picture land close to each other as vectors. Encoders of this kind are how many image generators understand a prompt, and how multimodal search works.
Diffusion with a Transformer backbone. Image generators are mostly diffusion models: they start from noise and remove it step by step, guided by the prompt. Early diffusion models used a convolutional U-Net to predict the noise. Peebles and Xie’s Diffusion Transformer (DiT) paper in December 2022 replaced the U-Net with a Transformer working on patches of a compressed image, and found that quality kept improving as the Transformer grew. Stable Diffusion 3 (2024) uses a multimodal variant of that design, and OpenAI described its Sora video model the same year as a diffusion transformer working on patches of video. How diffusion produces images is covered in Generative AI in Image and Video Synthesis.
Many modalities in one model. Current frontier models such as Gemini accept text, images, audio, video and documents in a single prompt. Each input type has its own way of being turned into tokens, but after that, the same Transformer stack processes them together.
flowchart LR
TX["Text: word pieces"] --> TOK["Sequence of vectors"]
IM["Image: patches"] --> TOK
AU["Audio: short frames"] --> TOK
VI["Video: space-time patches"] --> TOK
TOK --> TF["Transformer blocks"]
TF --> OT["Next text token"]
TF --> OD["Denoised image or video latents"]
What the architecture means for serving cost
If you call a hosted model, you pay per token. If you host one yourself, you pay for GPU or TPU hours. Either way, the price reflects how the Transformer behaves at inference time, and a few mechanics explain most of it.
Prefill and decode
A request runs in two phases. In prefill, the model processes your whole prompt at once, in parallel, the same way it trains. In decode, it produces the answer one token at a time, and each step depends on the last. Prefill is limited mainly by raw compute; decode is limited mainly by how fast the hardware can read the model’s weights and cached state from memory. This is why providers usually charge more for output tokens than input tokens, and why a long answer takes longer than a long question.
sequenceDiagram
participant C as Client
participant S as Model server
C->>S: Prompt (2,000 tokens)
Note over S: Prefill: all prompt tokens in parallel, KV cache filled
S-->>C: First token
loop Decode, one step per token
Note over S: Attend over KV cache, append new keys and values
S-->>C: Next token
end
The key-value cache
During decode, each new token has to attend to every earlier one. Recomputing the keys and values for the whole conversation at every step would be wasteful, so servers store them: the KV cache. It grows by a fixed amount for every token in the context, in every layer.
You can estimate it. Per token, the cache holds a key and a value for each layer and each key-value head:
bytes per token = 2 × layers × kv_heads × head_dim × bytes per number
For a model shaped like Llama 3 8B (32 layers, 8 key-value heads of 128 dimensions, 16-bit numbers), that is 2 × 32 × 8 × 128 × 2 = 131,072 bytes, or 128 KiB per token. A single 32,000-token conversation needs about 4 GiB of cache on top of the roughly 16 GB of weights. Serve twenty such conversations at once and the cache, not the weights, fills the GPU.
You can read these numbers from any open model’s configuration with the Hugging Face Transformers library, which downloads only the small config file, not the weights:
from transformers import AutoConfig
cfg = AutoConfig.from_pretrained("Qwen/Qwen3-0.6B")
head_dim = getattr(cfg, "head_dim", None) or cfg.hidden_size // cfg.num_attention_heads
per_token = 2 * cfg.num_hidden_layers * cfg.num_key_value_heads * head_dim * 2 # 16-bit
print("layers:", cfg.num_hidden_layers)
print("query heads:", cfg.num_attention_heads, "key-value heads:", cfg.num_key_value_heads)
print(f"KV cache per token: {per_token / 1024:.0f} KiB")
print(f"for 32,000 tokens: {per_token * 32_000 / 2**30:.2f} GiB")
This arithmetic is the reason long-context requests cost more, why some providers charge a higher rate above a context threshold, and why cached prompt prefixes are discounted: a reused prefix means prefill work and cache memory the provider does not have to repeat.
You self-host a model and can serve far fewer concurrent long conversations than the model's weight size suggests. What is the most likely cause?
Correct! Weights are shared across requests, but every conversation needs its own key-value cache, and long contexts make it large.
How models keep the cost down
The basic block has barely changed since 2017. What has changed is a set of refinements, most of them aimed at the costs above.
| Technique | Problem it addresses | How it works |
|---|---|---|
| FlashAttention | Attention’s memory traffic | Computes attention in tiles kept in fast on-chip memory, without ever storing the full score matrix; exact, not an approximation |
| Grouped-query attention | KV cache size | Several query heads share one key-value head, shrinking the cache by that factor |
| Mixture of experts | Compute per token | Replaces the feed-forward network with many expert networks and a router that sends each token to only a few |
| Sliding-window and sparse attention | Quadratic attention cost | Some or all layers attend only to nearby tokens or a fixed pattern |
| Quantization | Weight and cache memory | Stores numbers in 8 or 4 bits instead of 16 |
| Hybrid layers | KV cache growth | Interleaves attention with state space or recurrent layers that keep a fixed-size state |
Grouped-query attention is the reason the Llama-shaped example above has 8 key-value heads rather than 32 to match its query heads; with full multi-head attention the cache would be four times larger. Mixture of experts explains model cards that quote two parameter counts: DeepSeek-V3, for example, has 671 billion parameters in total but activates about 37 billion for each token. You still need memory for all of them, but each token costs roughly what a much smaller model would.
None of these replaces the Transformer. Hybrid models come closest, and they still keep some attention layers, because attention is very good at recalling an exact detail from earlier in the context.
Working with Transformers in the cloud
Most teams never touch a Transformer’s internals. The practical choices are about who runs the model:
- Call a hosted model. Amazon Bedrock, Microsoft Foundry and Google Cloud’s Gemini Enterprise Agent Platform (formerly Vertex AI) serve Transformer-based models through an API, priced per token. Context limits, output limits and prices are per model, so read them from the model’s page rather than assuming. Some current models accept a million tokens or more of input; the KV cache arithmetic above is why those requests cost what they do. Comparing Cloud Platforms for Generative AI compares the three providers.
- Host an open-weight model. Download weights from a model hub and serve them on GPU or TPU instances with an inference server such as vLLM, which manages the KV cache in pages so more requests fit in memory. This pays off when you need a fine-tuned model, data that must stay in your environment, or steady volume high enough that dedicated hardware costs less than tokens.
- Fine-tune. Adapting a pretrained Transformer to your task with LoRA is covered step by step in Building Your First Generative AI Model.
When you size self-hosted hardware, budget for three things: the weights, the KV cache for your expected number of concurrent conversations at their expected length, and headroom for the server itself. Teams that budget only for the weights find their throughput limit the first time traffic arrives.
Limits worth knowing
The architecture explains some of what generative models get wrong, not just what they get right.
- They predict plausible continuations, not facts. A Transformer has no separate store of verified knowledge. When the training data or the prompt doesn’t settle a question, it still produces a fluent answer, which is where hallucinations come from. Grounding answers in retrieved documents is the standard mitigation.
- Long context is not perfect recall. A model can accept a very long prompt and still miss a detail in the middle of it. Test with your own documents before relying on a large window.
- Tokens are not words. Text is split into subword tokens, so models can stumble on spelling, character counts and arithmetic on long numbers, and the same text costs a different number of tokens in different languages.
- Cost scales with length. Every extra token of prompt and answer uses compute and cache memory. Concise prompts and capped output lengths are the cheapest optimization available.
Further reading
- Attention Is All You Need, Vaswani and colleagues, 2017
- An Image is Worth 16x16 Words, the Vision Transformer paper
- Scalable Diffusion Models with Transformers, Peebles and Xie
- FlashAttention and GQA: Training Generalized Multi-Query Transformer Models
- RoFormer: Enhanced Transformer with Rotary Position Embedding
- Hugging Face Transformers documentation and PyTorch scaled_dot_product_attention
- On this site: Understanding Neural Networks, Overview of Generative Models and Exploring OpenAI’s GPT Models
Key takeaways
- A Transformer turns a sequence of vectors into an updated sequence using self-attention, which mixes information between positions, and a feed-forward network, which processes each position.
- Attention works by matching each position’s query against every key and taking a weighted sum of the values; a causal mask turns the stack into a text generator.
- It won because training is parallel, any two tokens are one step apart, and quality improves predictably with scale; the cost is attention that grows with the square of the sequence length.
- Decoder-only models generate text; encoder-only models still power embeddings and search; the same blocks run on image patches, audio and video, including in diffusion image and video models.
- Serving cost follows the architecture: output tokens are produced one at a time, and the KV cache grows with every token of context and every concurrent conversation.
- Grouped-query attention, mixture of experts, FlashAttention, quantization and hybrid layers make Transformers cheaper to run without replacing them.
Part 11 of 30 · Introduction to Generative AI
- 01Introduction to Generative AI: What Is It?
- 02The History of Generative AI: From Concept to Reality
- 03Key Definitions and Concepts in Generative AI
- 04Pioneers of Generative AI: Meet the Inventors
- 05Understanding Neural Networks: The Backbone of AI
- 06Deep Learning Basics: Layers and Learning Rates
- 07Generative vs. Discriminative Models: What's the Difference?
- 08Overview of Generative Models: VAEs, GANs, and More
- 09Introduction to Variational Autoencoders (VAEs): From Basics to Advanced Applications
- 10Introduction to Generative Adversarial Networks (GANs)
- 11The Role of Transformers in Generative AI
- 12Applications of Generative AI in Everyday Life
- 13Ethical Considerations in Generative AI: Navigating the New Frontier
- 14Generative AI in Art and Music: The Creative Revolution
- 15Case Study: AI-Generated Artwork
- 16Generative AI in Text Generation
- 17Exploring OpenAI's GPT Models: Word Up! Bot
- 18Real-World Use Cases: Deepfakes and Their Impact
- 19Generative AI in Image and Video Synthesis
- 20Introduction to Reinforcement Learning in Generative AI
- 21The Future of Generative AI: Trends to Watch
- 22Generative AI in Healthcare: Opportunities and Challenges
- 23Generative AI in Finance: Risk Modeling and Beyond
- 24Generative AI in Marketing and Personalization
- 25Cloud Services for Generative AI: AWS Offerings
- 26Cloud Services for Generative AI: GCP Offerings
- 27Cloud Services for Generative AI: Azure Offerings
- 28Comparing Cloud Platforms for Generative AI
- 29Recap and Q&A: Introduction to Generative AI
- 30Building Your First Generative AI Model: A Practical Guide