How GPT Works: Modern Transformer Architecture Explained (2026)
Learn how GPT works end to end: tokenization, RoPE, GQA and MLA self-attention, Mixture-of-Experts FFNs, KV caching, and speculative decoding.
When an engineering assistant writes unit tests, refactors SQL queries, or reasons across a 100-page repository, no search index fetches canned answers from storage. Instead, a Generative Pre-trained Transformer (GPT) computes a probability distribution over its vocabulary and predicts one token at a time.
Understanding how GPT works under the hood turns black-box prompting into predictable systems engineering. Modern frontier systems combine decoder-only transformer blocks with Grouped-Query Attention (GQA), Multi-head Latent Attention (MLA), sparse Mixture of Experts (MoE) layers, and hardware-aware KV caching to serve billions of daily tokens at millisecond latency.
Key Takeaways
- Modern GPT systems convert prompts into dense vectors rotated by Rotary Position Embeddings (RoPE) and refine representations across dozens of decoder-only transformer blocks.
- Causal masked self-attention isolates future positions while GQA and MLA shrink KV cache footprints by 8x to 16x compared to dense Multi-Head Attention.
- Sparse Mixture-of-Experts (MoE) routers activate only 5% to 15% of total weights per token using SwiGLU feed-forward experts.
- Production inference separates compute-bound prefill from bandwidth-bound decode using FlashAttention SRAM tiling, PagedAttention, and speculative decoding.
What Does GPT Actually Mean?
Each word in GPT specifies an architectural decision that drives both capability and inference cost across modern large language model fundamentals.
- Generative: During generation, the network outputs probability logits over the entire vocabulary for the next missing piece rather than assigning a static label. Because each output appends back onto the running input sequence, small shifts early in generation compound downstream.
- Pre-trained: Before any chat tuning occurs, models ingest trillions of tokens across web text, books, and source repositories using self-supervised next-token prediction. That training teaches syntax, logic, and code idioms directly inside weight matrices.
- Transformer: Instead of scanning words sequentially like legacy Recurrent Neural Networks (RNNs), a transformer routes contextual signals between every token position in parallel matrix multiplications.
Unlike bidirectional encoders or dual encoder-decoder translators, frontier models such as GPT-6.1 Sol, Claude Opus 5.5, Gemini 4 Argon, and Llama 4 Maverick run as unified decoder-only stacks. Every transformer block refines hidden vectors in residual streams using the same causal sequence rule from prompt start to generation stop.
Evolution From Original Transformers to Modern GPT Architecture
The foundational 2017 Vaswani architecture documented in Attention Is All You Need on ArXiv introduced an encoder-decoder pipeline built around Multi-Head Attention and ReLU feed-forward networks. Production transformer architecture rapidly shed the encoder half because decoder-only pre-training scaled cleanly with raw compute and data volume.
Modern GPT blocks also replaced almost every internal sub-layer from the original 2017 blueprint to stabilize deep training runs and slash memory pressure. Pre-layer RMSNorm replaced post-layer normalization because omitting mean centering accelerates GPU kernels while keeping residual gradients bounded across 100+ layers.
Fixed sinusoidal offsets gave way to Rotary Position Embedding (RoPE), introduced in the RoFormer paper published in 2021 on ArXiv. Rather than adding static coordinate vectors to embeddings once at layer zero, RoPE rotates Query and Key matrices inside every layer so dot products depend strictly on relative distance between tokens.
Inside feed-forward layers, frontier systems swapped standard GELU projections for SwiGLU gates paired with sparse Mixture of Experts routing. Combined with supervised alignment in our LLM pre-training and alignment pipeline, these upgrades allow open-weight models like DeepSeek-V4.1-Flash to match massive dense checkpoints at a fraction of inference FLOPs.
Step-by-Step: How GPT Processes Input Text
Every single API call moves strings through four deterministic matrix stages before a single output character streams back to the client. Inspecting each stage explains latency, token pricing, and formatting behavior simultaneously.
Figure 1: End-to-end decoder-only GPT transformer forward pass from BPE tokenization and RoPE through causal GQA/MLA attention, SwiGLU MoE routing, KV caching, and next-token softmax sampling.
1. Subword Tokenization and Vocabulary Packing
Neural networks operate strictly on floating-point tensors, so text first passes through subword tokenization via Byte-Pair Encoding (BPE). Common English terms map to single integer IDs while rare identifiers fragment into predictable prefix, root, and suffix chunks.
Modern tokenizers expanded vocabularies dramatically to pack multilingual words and code indentation efficiently, as covered in how AI tokens compress text. GPT-6 family tokenizers built on 200,000-entry vocabularies shrink source code token counts by up to 25% compared to legacy 50,257-token schemes, cutting attention quadratic cost before layer one executes.
2. Vector Embeddings and Rotary Position Embedding (RoPE)
Each integer ID fetches one dense column vector of dimension $d_{model}$ (typically 4,096 to 16,384 floats) from a learned embedding table. Vectors sitting close together under cosine similarity share syntax roles or domain semantics learned during pre-training.
Because matrix attention compares all token pairs simultaneously without loops, models inject word ordering dynamically via Rotary Position Embedding inside each attention block. RoPE applies frequency-paired 2D rotation matrices to Query and Key sub-vectors proportional to token index $m$, preserving exact relative spacing $(m - n)$ even when sequences scale past 128K tokens.
3. Masked Self-Attention, Q/K/V Projections, and NumPy Implementation
Inside the attention block, the input tensor $X$ projects through learned weight matrices into Queries ($Q$), Keys ($K$), and Values ($V$). During training and prompt prefill, masked self-attention fills the upper triangle of the attention score grid with $-\infty$ before softmax normalization.
That triangular mask guarantees token $t$ reads only itself and prior positions $0 \dots t-1$, preventing future answer leakage during parallel prefill passes. The concise NumPy implementation below computes causal scaled dot-product attention directly on an embedding matrix:
import numpy as np
def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
shifted = x - np.max(x, axis=axis, keepdims=True)
exp_vals = np.exp(shifted)
return exp_vals / np.sum(exp_vals, axis=axis, keepdims=True)
def causal_self_attention(
X: np.ndarray, W_q: np.ndarray, W_k: np.ndarray, W_v: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
"""Compute single-head masked self-attention with lower-triangular causality."""
seq_len, _ = X.shape
d_k = W_k.shape[1]
Q = X @ W_q # (seq_len, d_k)
K = X @ W_k # (seq_len, d_k)
V = X @ W_v # (seq_len, d_k)
scores = (Q @ K.T) / np.sqrt(d_k)
# Upper triangle (j > i) becomes -inf so future tokens receive zero probability
future_mask = np.triu(np.full((seq_len, seq_len), -np.inf), k=1)
weights = softmax(scores + future_mask, axis=-1)
output = weights @ V
return output, weights
rng = np.random.default_rng(7)
X_sample = rng.normal(size=(4, 8))
W_q = rng.normal(scale=0.2, size=(8, 4))
W_k = rng.normal(scale=0.2, size=(8, 4))
W_v = rng.normal(scale=0.2, size=(8, 4))
attn_out, attn_weights = causal_self_attention(X_sample, W_q, W_k, W_v)
print("Output shape:", attn_out.shape)
print("Causal weights row 1 (future masked):", np.round(attn_weights[1], 3))
Notice row 1 prints exact zeros for positions 2 and 3 because causal masking forces probability mass onto tokens already observed.
4. RMSNorm, SwiGLU Feed-Forward Networks, and Mixture of Experts
After attention mixes contextual cues across tokens, residual vectors pass through RMSNorm and enter the Feed-Forward Network (FFN). Frontier models replace single linear GELU expansions with SwiGLU, multiplying a Swish-activated branch against a parallel linear gate to filter noisy features cleanly.
Rather than running every parameter in a dense FFN on every token, flagship architectures deploy Mixture of Experts (MoE) layers containing dozens or hundreds of specialized expert sub-networks. A lightweight softmax router scores each token hidden state and dispatches compute strictly to the top 2 or top 8 experts.
| Internal Component | Legacy GPT-2 Design | Frontier Design (2026) | Engineering Impact |
|---|---|---|---|
| Normalization | Post-layer LayerNorm | Pre-layer RMSNorm | Faster kernels and stable deep residual gradients |
| Position Signal | Learned absolute vectors | Rotary Position Embedding (RoPE) | Clean relative spacing and 1M+ context extrapolation |
| Attention Heads | Dense Multi-Head (MHA) | GQA or Multi-head Latent Attention | 8x to 16x smaller KV cache in GPU memory |
| FFN Activation | Standard GELU | SwiGLU gated projection | Higher knowledge accuracy per active parameter |
| FFN Topology | Dense all-active weights | Sparse Mixture of Experts (MoE) | High total capacity with low per-token FLOPs |
MoE decouples stored knowledge capacity from per-token runtime compute, letting a 400B-total-parameter model execute with under 20B active parameters per forward step.
Inside Self-Attention: From MHA to GQA and MLA
Standard Multi-Head Attention splits embedding vectors into 32 to 128 independent heads so distinct subspaces track syntax agreement, coreference pronouns, or code indentation simultaneously. While expressive, original MHA forces inference servers to retain a separate Key tensor and Value tensor for every single query head across every layer.
At 128K context lengths, that uncompressed KV footprint balloons into tens of gigabytes per concurrent user and stalls GPU memory capacity. To eliminate that overhead without losing accuracy, frontier systems deploy two attention compression architectures:
- Grouped-Query Attention (GQA): Introduced in the GQA paper published in 2023 on ArXiv, GQA partitions query heads into shared groups (such as 8 query heads reading 1 shared Key-Value pair). Models like Llama 4 Maverick shrink KV memory usage by 8x while preserving multi-head reasoning fidelity.
- Multi-head Latent Attention (MLA): Pioneered in DeepSeek-V2 on ArXiv, MLA projects Keys and Values down into a compact shared low-rank latent vector before caching. During decode, up-projection matrices absorb directly into Query matrices so servers read one tiny latent vector instead of full multi-head tensors.
Comparing storage profiles clarifies why architecture engineers prioritize attention compression before scaling concurrency. A 70B MHA checkpoint demands roughly 2.5 MB per token in FP16, whereas an equivalent MLA checkpoint compresses KV demand down toward 70 KB per token, unlocking massive server batch sizes.
Autoregressive Generation, KV Caching, and Speculative Decoding
Transformer inference executes across two radically different hardware regimes during every single request: prefill and decode. Treating both phases identically causes severe tail-latency spikes when user prompts scale up.
Figure 2: Five-layer production transformer optimization stack balancing prefill compute, HBM memory bandwidth, KV cache compression, and multi-token decoding.
During prefill, the GPU processes all prompt tokens concurrently in massive matrix-matrix multiplications, saturating Tensor Core FLOPs until the first token emits (measured as Time to First Token, or TTFT). During autoregressive generation (decode), the engine emits strictly one new token per step, loading multi-gigabyte model weights and accumulated history from High Bandwidth Memory (HBM) just to compute a single vector update.
Because standard attention would recompute Keys and Values for all previous tokens at every decode step, production runtimes enable KV caching to retain historical tensors in VRAM. Combined with IO-aware SRAM tiling in FlashAttention on ArXiv, kernels compute exact softmax weights chunk by chunk on fast on-chip SRAM without materializing massive $N \times N$ score matrices in slow HBM.
You can observe KV cache acceleration directly using PyTorch and the Hugging Face GPT-2 architecture documentation:
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "openai-community/gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id).eval()
inputs = tokenizer("Transformer KV caching accelerates inference because", return_tensors="pt")
def benchmark_decode(use_cache: bool, max_new_tokens: int = 40) -> float:
start = time.perf_counter()
with torch.no_grad():
_ = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
use_cache=use_cache,
do_sample=False,
)
return time.perf_counter() - start
cached_sec = benchmark_decode(use_cache=True)
uncached_sec = benchmark_decode(use_cache=False)
print(f"use_cache=True: {cached_sec:.3f}s")
print(f"use_cache=False: {uncached_sec:.3f}s ({uncached_sec / cached_sec:.2f}x slower)")
Once logits exit the final normalization head, the sampler applies softmax, filters probability tails using temperature and top-p decoding, and appends the chosen token. Because single-token decoding remains bounded by HBM memory bandwidth, frontier stacks accelerate output speeds 3x to 6x using speculative decoding, formalized in Leviathan et al. on ArXiv.
Under speculative decoding or native Multi-Token Prediction (MTP), a lightweight draft predictor guesses 3 to 8 candidate future tokens while the flagship model verifies all candidates concurrently in one parallel pass. Correct prefixes accept instantaneously without violating the exact target distribution, breaking the one-token-per-HBM-read wall.
Architectural Tradeoffs: Decoder-Only vs Encoder-Only vs Hybrid SSMs
While GPT models dominate open-ended next-token prediction, engineering teams choose between four distinct sequence topologies depending on recall accuracy, streaming throughput, and context economics.
| Dimension | Encoder-Only (BERT Style) | Decoder-Only (GPT Style) | Pure SSM (Mamba) | Hybrid (Transformer + SSM) |
|---|---|---|---|---|
| Attention Masking | Bidirectional full attention | Causal lower-triangular mask | Linear state recurrence | Interleaved SSM + sparse attention |
| Prefill Complexity | Quadratic $O(N^2)$ | Quadratic $O(N^2)$ | Linear $O(N)$ | Sub-quadratic proportional to ratio |
| Decode KV State | Non-generative | Linear $O(N)$ KV cache growth | Constant $O(1)$ hidden state | Compact partial KV cache |
| Exact Verbatim Recall | High for short spans | Very high via exact KV lookup | Lower due to lossy state compression | High via periodic attention anchors |
| Primary Workload | Semantic search and classifiers | Reasoning, coding, chat agents | Edge streaming and genomics | High-throughput 1M-token generation |
Pure State Space Models (SSMs) compress history into a fixed-size state vector, eliminating KV cache bloat at ultra-long contexts. However, fixed states suffer from lossy compression on verbatim copy-paste tasks and multi-hop extraction, which explains why production assistants retain decoder-only or hybrid attention layers whenever exact recall matters.
Production Failure Modes and Transformer Bottlenecks
Deploying transformer models under concurrent production traffic exposes memory and numerical failures that rarely surface in single-prompt notebooks. Diagnosing these bottlenecks prevents silent accuracy regressions and server outages.
- KV Cache HBM Fragmentation and Batch Collapse: Contiguous pre-allocation wastes up to 60% of GPU memory on unused sequence padding, causing sudden out-of-memory crashes under burst traffic. Production engines like vLLM adopt PagedAttention to slice KV tensors into fixed virtual pages, freeing VRAM immediately as individual requests complete; calculate exact request sizing in our context window VRAM economics guide.
- Attention Sink Collapse Under Naive Eviction: As demonstrated in StreamingLLM with Attention Sinks on ArXiv, causal transformers dump massive softmax mass onto the first two to four tokens regardless of semantic content. Building a naive sliding-window cache that evicts those opening tokens causes perplexity spikes and immediate text looping; retaining the initial 4 sink tokens alongside the rolling window restores stable streaming.
- KV Quantization Precision Drift: Compressing KV tensors from FP16 down to INT4 shrinks HBM bandwidth demand fourfold, yet aggressive low-bit quantization corrupts subtle dot-product rankings on needle-in-a-haystack queries and strict JSON tool calls. Always benchmark FP8 KV caches on strict schema extraction evals before shipping INT4 compression.
- RoPE Extrapolation Breakdown: Scaling context windows beyond pre-trained horizons using naive frequency multipliers smears relative attention scores across unseen distance intervals, causing models to miss middle-document constraints or invent tool parameters. Prefer models natively continued-pretrained with YaRN or NTK-aware RoPE schedules at full target sequence lengths.
Frequently Asked Questions
What is the primary difference between GPT and ChatGPT?
GPT refers to the underlying decoder-only neural architecture pre-trained for general next-token prediction across raw text and code. ChatGPT is a complete hosted software product combining instruction tuning, preference alignment, safety classifiers, tool runners, and conversation memory around GPT models.
Why does GPT use a decoder-only transformer instead of encoder-decoder?
Decoder-only architectures apply one uniform causal language modeling objective over every token, allowing massive scaling without separate cross-attention projections. Benchmarks consistently show that scaling dense and MoE decoder stacks matches or exceeds encoder-decoder translation quality while simplifying multi-turn caching.
Why do transformers require positional embeddings like RoPE?
Self-attention compares every pair of token vectors symmetrically via matrix dot products, making an unencoded block completely blind to word order. Rotary Position Embeddings rotate Query and Key projections by token index so dot products reflect relative spacing between words accurately.
How does Grouped-Query Attention (GQA) differ from Multi-head Latent Attention (MLA)?
GQA reduces KV cache size by making multiple Query heads read from a single shared group of Key and Value heads. MLA compresses Keys and Values into one low-rank latent vector cached in VRAM, cutting memory even further while reconstructing multi-head expressivity during compute.
How much does KV caching actually speed up text generation?
Without KV caching, generating token $N$ forces the GPU to recompute attention projections for all $N-1$ preceding tokens, causing quadratic latency growth. Caching past Keys and Values drops each decode step to linear work for the new token alone, preventing response time from stalling on long replies.
Can speculative decoding change model output quality?
No, lossless speculative decoding uses rejection sampling against the target model logits so final output distributions remain mathematically identical to unaccelerated decoding. It only accelerates inference speed by verifying multiple draft guesses in parallel per memory read.
Why do GPT models sometimes ignore rules placed in the middle of long prompts?
Causal masking combined with softmax attention normalization and positional decay creates a U-shaped recall bias favoring initial system instructions and the newest tokens. Placing critical output schemas at the start or end of your prompt improves instruction compliance measurably.
Will State Space Models (SSMs) replace GPT transformers completely?
Pure SSMs run in linear time with constant memory, yet their fixed recurrent state compresses long context imperfectly and underperforms on exact verbatim retrieval. Production systems increasingly pair SSM layers with periodic self-attention blocks rather than abandoning attention outright.