🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

GPT Architecture — Decoder-Only Transformers Complete Guide

Advanced TopicsLLM Architecture🟢 Free Lesson

Deep Learning

GPT Architecture - How Large Language Models Generate Text

Explore the GPT architecture and understand how large language models generate coherent text.

  • Autoregressive generation - predict next token sequentially
  • Decoder-only architecture - simple but powerful design
  • Scaling laws - performance improves with more parameters

Language is the house of being.

GPT Architecture — Complete Guide

GPT (Generative Pre-trained Transformer) is a decoder-only transformer trained to predict the next token. It powers ChatGPT, GPT-4, and modern LLMs.


Decoder-Only Architecture

GPT Decoder Block Architecture

GPT Decoder Block (×N)Input Embeddings + PositionAdd and LayerNormMasked Multi-Head Self-AttentionQ, K, V projections → Attention → Mask → OutputEach token attends only to previous tokens (causal mask)ResidualAdd and LayerNormFeed-Forward NetworkLinear(d_model → 4×d_model) → GELU → Linear(4×d_model → d_model)Position-wise (applied independently to each position)Add and LayerNorm→ Next Block or Output Layer

How the GPT decoder block works: This is the fundamental unit repeated N times in every GPT model. Input embeddings (token + positional) enter from the top and flow through two sub-layers. First, Masked Multi-Head Self-Attention (blue) computes context-aware representations — the "masked" part means each token can only attend to previous tokens, preventing information leakage from future tokens. The golden dashed line on the left is a residual connection that adds the original input to the attention output, then Layer Normalization stabilizes training. Second, the Feed-Forward Network (purple) processes each position independently through two linear layers with GELU activation, expanding to 4× d_model dimensions then projecting back. This FFN acts as a "knowledge store" — the attention layer gathers context, and the FFN makes decisions based on that context. The pattern (Attention → Add+Norm → FFN → Add+Norm) repeats for every block, with each layer learning increasingly abstract language patterns.


Autoregressive Generation

Autoregressive Text Generation Process

Autoregressive Generation: P(x_t | x_1, ..., x_{t-1})Step 1: Input[The]GPT ModelP(next|The)Output: "cat"P = 0.82Step 2: Input[The, cat]GPT ModelP(next|The,cat)Output: "sat"P = 0.91Step 3: Input[The, cat, sat]GPT ModelP(next|...)Output: "on"P = 0.76Final: "The cat sat on the mat"Each step conditions on all previous tokens

How autoregressive generation works: This diagram shows the step-by-step process of text generation. At each step, the model receives ALL previously generated tokens as input and predicts the next token. Step 1: given "The", the model predicts "cat" with P=0.82. Step 2: given "The, cat", it predicts "sat" with P=0.91 — notice the probability increased because the model now has more context. Step 3: given "The, cat, sat", it predicts "on" with P=0.76. The key insight: each prediction conditions on the ENTIRE history, not just the previous token. The model builds up the sentence one token at a time, with each new token becoming part of the input for the next prediction. This sequential process continues until an end-of-sequence token is generated or a maximum length is reached. The probabilities reflect the model's confidence — higher probability means the model is more certain about that token choice.

Choosing the Next Token

The probabilities in the diagram are only the raw material. Turning them into the token that actually gets appended is a separate decision, and the two knobs you will meet everywhere are temperature and top-k. Temperature divides the logits before the softmax: below one it sharpens the distribution toward the most likely continuations, above one it flattens the distribution so that unlikely words get a share of the probability mass. Top-k discards everything outside the k most likely candidates first, which stops a long tail of near-impossible tokens from collecting the mass the softmax still assigns them.

python
import torch

@torch.no_grad()
def generate(model, idx, max_new_tokens, temperature=1.0, top_k=None):
    model.eval()
    for _ in range(max_new_tokens):
        logits = model(idx)[:, -1, :] / max(temperature, 1e-6)

        if top_k is not None:
            cutoff = torch.topk(logits, top_k).values[:, -1, None]
            logits = logits.masked_fill(logits < cutoff, float("-inf"))

        probs = torch.softmax(logits, dim=-1)
        next_id = torch.multinomial(probs, num_samples=1)
        idx = torch.cat([idx, next_id], dim=1)      # feed it straight back in
    return idx

Greedy decoding is the special case where temperature is driven to zero and only the argmax survives: it is deterministic and often repetitive, which is why sampling with a modest temperature is preferred for open-ended writing while greedy or beam search remains common for tasks where a single correct string exists.


Causal Attention Mask

The causal mask ensures autoregressive behavior by preventing tokens from attending to future positions:

Where the mask matrix is:

Building the mask is a single call to an upper-triangular helper, and it is worth doing explicitly once so the arithmetic in the formula stops being abstract. The mask is added to the scaled scores rather than multiplied, because the masked entries hold negative infinity and an addition sends them to zero after the softmax — a multiplication would leave them as NaN.

python
import torch

def causal_mask(n, device="cpu"):
    return torch.triu(torch.full((n, n), float("-inf")), diagonal=1)

print(causal_mask(4))
# tensor([[ 0., -inf, -inf, -inf],
#         [ 0.,  0., -inf, -inf],
#         [ 0.,  0.,  0., -inf],
#         [ 0.,  0.,  0.,  0.]])

q, k = torch.randn(2, 4, 8), torch.randn(2, 4, 8)     # (batch, seq, d_k)
scores = q @ k.transpose(-2, -1) / q.size(-1) ** 0.5
scores = scores + causal_mask(4)
weights = torch.softmax(scores, dim=-1)

print(weights[0].round(2))
# each row sums to 1.0 and everything right of the diagonal is 0.0

Causal Attention Mask Visualization

Causal Attention Mask (4 tokens)x₁x₂x₃x₄QK✓≤≤≤✓✓≤≤✓✓✓≤✓✓✓✓Key (attended positions)QueryCan attend (mask = 0)Blocked (mask = -≡)Lower-triangular mask ensures causal/autoregressive property

How the causal mask enforces autoregression: This lower-triangular matrix visualizes which tokens can attend to which other tokens. Green cells (✓) mean the token CAN attend to that position; red cells (✗) mean attention is BLOCKED. Row 1 (x₁) can only attend to itself — it has no previous context. Row 2 (x₂) can attend to x₁ and itself, but not x₃ or x₄. Row 3 attends to x₁, x₂, x₃. Row 4 attends to all four. This creates the autoregressive property: when predicting token 4, the model can only use information from tokens 1, 2, 3 — never from token 5 or later. The mask is implemented by adding -∞ to blocked positions before softmax, making their attention weights effectively zero. This is what makes GPT a "decoder-only" model — it can only look left, never right.


Scaling Laws

GPT Model Evolution and Scaling

GPT Evolution: Parameters, Training Data, and Compute1GPT-1 (2018)117M parameters5GB BookCorpus8 GPUs × 5 days2GPT-2 (2019)1.5B parameters40GB WebText~256 TPU pods3GPT-3 (2020)175B parameters300B tokens~3.14×10²³ FLOPs4GPT-4 (2023)~1.8T parameters (MoE)~13T tokensMultimodal (text+image)Power-Law ScalingLog(Compute / FLOPs)Log(Loss)GPT-1GPT-2GPT-3GPT-4

How GPT models scale with resources: The timeline shows the explosive growth of GPT models. GPT-1 (2018) had 117M parameters trained on 5GB of book text using 8 GPUs for 5 days. GPT-2 (2019) jumped to 1.5B parameters on 40GB of web text. GPT-3 (2020) reached 175B parameters trained on 300B tokens — requiring ~3.14×10²³ FLOPs (equivalent to running a supercomputer for months). GPT-4 (2023) is estimated at ~1.8T parameters using a Mixture of Experts architecture. The scaling curve at the bottom shows the key insight: loss decreases as a power law with compute (Loss ∝ C^(-γ)). This means performance improves predictably with more parameters, data, and compute — you can forecast how much resources you need for a target performance level. The formula at the top (Loss ∝ N^(-α) + D^(-β) + C^(-γ)) shows that scaling any one factor alone has diminishing returns — you need to scale all three together.


Training Pipeline

GPT Training Pipeline

GPT Training Pipeline1. Data Collection• Web crawl (Common Crawl)• Books, Wikipedia• Code (GitHub)• 13T+ tokens2. Pre-training• Next-token prediction• Cross-entropy loss• AdamW optimizer• ~3-6 months on GPUs3. SFT• Human-written instruction-response pairs• ~100K examples4. RLHF• Reward model• PPO optimization• Human feedback• AlignmentTraining ObjectivePre-training: L(θ) = -Σ log P(x_t | x_{<t}; θ)RLHF: max E[r_φ(y|x)] - β·KL(π_θ || π_ref)

How GPT is trained end-to-end: This four-stage pipeline shows how a raw language model becomes ChatGPT. Stage 1 (Data Collection): Gather massive text corpora — Common Crawl (web pages), Wikipedia, books, and code from GitHub — totaling 13+ trillion tokens. Stage 2 (Pre-training): Train the model to predict the next token using cross-entropy loss with the AdamW optimizer. This takes 3-6 months on thousands of GPUs and teaches the model language structure, facts, and reasoning. Stage 3 (Supervised Fine-tuning): Train on ~100K human-written instruction-response pairs to teach the model to follow instructions. Stage 4 (RLHF): Use human feedback to train a reward model, then optimize the policy using PPO (Proximal Policy Optimization) with a KL-divergence penalty to stay close to the pre-trained model. The formulas at the bottom show the mathematical objectives: pre-training minimizes negative log-likelihood, while RLHF maximizes reward minus a penalty for deviating too far from the original model.


Common Mistakes & How to Avoid Them

Common Mistakes

Running generation with the model still in training mode, so dropout noise is sampled at inference and identical prompts give different answers

Fix: Call model.eval and wrap generation in no_grad, then check that repeating the same prompt twice produces the same first token

Applying temperature after the softmax instead of to the logits, which distorts rather than sharpens the distribution

Fix: Divide the logits by temperature first and only then run softmax; verify that a temperature below one makes the top token more likely

Forgetting the causal mask during training so the model learns to copy the next token and appears brilliant until the first real generation

Fix: Add the upper-triangular mask to the scores in every layer and unit-test that all attention weight above the diagonal is exactly zero


Key Takeaways


What to Learn Next

-> BERT Compare with bidirectional models.

-> Transformers Master the underlying architecture.

-> What are LLMs Learn the basics of large language models.

-> LLM Architecture Deep Dive Explore LLM internals in detail.

-> Pre-training Language Models Understand how models learn from text.

-> RLHF and Alignment Learn how to align models with human values.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement