LLM Fundamentals · Module 01 · 9 topics

Architecture

How raw text becomes a vector, flows through stacked attention, and comes out the other side as a prediction. Every box below is something you can poke.

01

Introduction

A large language model is a function that maps a sequence of tokens to a probability distribution over the next token. Everything else is detail in service of that one job. Here is the whole pipeline — click any stage to jump to it.

That one-sentence definition hides something remarkable. "Predict the next token" sounds almost trivial, yet to do it well across all of human text, a model is forced to absorb grammar, facts, reasoning patterns, translation, code, and a rough model of the world — because all of those are needed to guess what comes next. Capability is a side-effect of compression: the better you compress text, the more you must have understood it.

The architecture that does this is the Transformer (Vaswani et al., 2017). Modern LLMs use the decoder-only variant: text flows left-to-right, each token can only see the tokens before it, and the same stack of operations repeats at every position in parallel. The genius of the design is that it's almost entirely matrix multiplications — which is exactly what GPUs do fastest — so it scales to thousands of chips and trillions of words. As you walk through the seven stages below, keep one thing in mind: there is no separate "knowledge database" inside. Everything the model knows lives in the numbers (the weights) that these operations multiply against.

The forward pass, end to end

Text"the cat"
Tokenizeids
Embedvectors
+ Positionorder
Blocks ×Nattn + FFN
Predictnext token
Hover a stage to see what it does. The model repeats the Blocks ×N step dozens of times — that depth is where "understanding" accumulates.
02

Tokenization

Models don't see characters or words — they see tokens, chunks of text from a fixed vocabulary. Common words are one token; rare words split into pieces. Type below and watch the split happen.

Why not just feed the model words, or letters? Words fail because language has an unbounded vocabulary — every typo, name, hashtag and foreign word would be an unknown. Single characters work but waste the model's effort spelling out common words letter by letter. Subword tokenization is the compromise that won: keep frequent words whole, and break rare ones into reusable fragments, so a fixed vocabulary of ~50k–130k tokens can express any string.

The dominant method is Byte-Pair Encoding (BPE). It starts from individual bytes and repeatedly merges the most frequent adjacent pair into a new token, learning a vocabulary bottom-up from the training corpus. The result is that "the" is one token, but "tokenization" might be token + ization. This has real consequences you can feel as a user: tokens are why models charge per-token, why they're weak at character-level tasks like counting letters or rhyming, and why a leading space changes a token's identity. Try a rare or made-up word below and watch it shatter into pieces.

Live subword tokenizer (BPE-style demo)

This is an illustrative splitter, not a real GPT tokenizer — but the behaviour (frequent → whole, rare → fragments, leading space matters) is the same idea.

03

The Embedding Layer

Each token id is looked up in a big table and becomes a vector of numbers. Training arranges these vectors so that meaning becomes geometry — similar words sit close together. Pick two words and compare them.

A token id like 50143 is just an arbitrary index — it carries no meaning on its own. The embedding layer is a giant lookup table (in GPT-2, 50,257 × 768 numbers) that turns each id into a dense vector of, say, 768 real numbers. These vectors are learned during training: nothing tells the model that "king" and "queen" are related, but because they appear in similar contexts, gradient descent nudges their vectors close together. Meaning is never stored as a definition — it's stored as a position in space.

This is what makes the famous "word arithmetic" possible: in a well-trained space, king − man + woman ≈ queen, because directions in the space encode consistent relationships (gender, tense, plurality). We measure closeness with cosine similarity — the angle between two vectors — rather than raw distance, because what matters is direction, not magnitude. The scatter below is a flattened 2-D shadow of a high-dimensional space; pick any two words and watch their similarity score, and notice how words from the same category cluster.

Embedding space (2-D projection)

vector A (first 8 dims)
04

Positional Encoding

Attention is order-blind on its own — "dog bites man" and "man bites dog" would look identical. Positional encodings inject where each token sits, using sine/cosine waves of different frequencies. Each row below is one position's signature.

Here's a subtle problem. The attention mechanism (next topic) treats its input as a set, not a sequence — it has no built-in notion of first, second, third. Shuffle the words and the raw math gives the same answer. Yet order is everything in language. So we have to add position information explicitly.

The original Transformer used sinusoidal encodings: each position gets a unique fingerprint made of sine and cosine waves at many frequencies, added to its embedding. Low-frequency dimensions change slowly across the sequence (coarse position), high-frequency ones change fast (fine position) — together they give every position a distinct, smoothly varying signature the model can do arithmetic on, even for sequences longer than it saw in training. Modern models like Llama use a refinement called RoPE (rotary position embeddings) that rotates the query and key vectors by an angle proportional to position, which encodes relative distance directly inside attention and extrapolates better to long contexts. The heatmap below shows the classic sinusoidal pattern — each row is a position, each column a dimension.

Sinusoidal position encoding

Each row = a position, each column = a dimension. Low dims (left) wave slowly, high dims wave fast — together they give every position a unique fingerprint the model can do arithmetic on.
05

Attention

The core mechanism. Every token builds a query and asks every other token (via their keys) "how relevant are you to me?". The answer becomes a weighted blend of their values. Click a token to see what it looks at.

Attention is the idea that made the Transformer — the "T" in GPT — and it's worth slowing down on. Think of it as a soft, learned database lookup happening at every position simultaneously. Each token projects its vector three ways: a query (what am I looking for?), a key (what do I offer?), and a value (what will I contribute if chosen?). To update a token, the model takes the dot product of its query with every key, turns those scores into weights with softmax, and blends the corresponding values. A pronoun like "it" can thus reach back and pull in the noun it refers to; a verb can gather its subject and object.

Two details matter. First, this is causal (masked) attention: a token may only attend to tokens at or before its own position — you can't peek at the future you're trying to predict. Second, models run many attention "heads" in parallel, each free to specialize — one might track syntax, another long-range coreference, another simple position. The grid below is one head's weights; click any query token to see exactly what it chose to look at, and watch how it can only see backwards.

Self-attention weights — click a query token

Selected token . Brighter cell = more attention paid to that token. Notice attention is causal here: a token can only look backwards.
06

Layers of Understanding

One transformer block = attention (mix across tokens) + a feed-forward network (think per token), each wrapped in a residual connection and normalization. Stack many of them and abstractions build up layer by layer. Drag the depth slider.

Attention alone only moves information between tokens; it doesn't do much computation on each one. That's the job of the second half of every block: a feed-forward network (FFN), a little two-layer MLP applied independently to each position, usually expanding to 4× the width and back. If attention is "gather what's relevant," the FFN is "now think about it." Much of a model's factual knowledge is believed to live in these FFN weights.

Two unglamorous pieces make deep stacks trainable. Residual connections add each sub-layer's output back to its input, giving gradients a clean highway down through dozens of layers so they don't vanish. Normalization (LayerNorm, or RMSNorm in newer models) keeps the numbers in a stable range at every step. Stack this block 12, 80, even 126 times and a rough hierarchy emerges — early layers handle surface form, middle layers handle syntax and reference, late layers handle meaning, task structure and reasoning. Drag the slider and watch the kinds of features that tend to appear as depth grows.

Stacking transformer blocks

what tends to emerge with depth
07

Learning to Predict

The final layer turns the last token's vector into a score for every word in the vocabulary; softmax makes those scores a probability distribution. Temperature controls how bold the sampling is. Pick a prompt, then sample.

After the last block, each position holds a richly-processed vector. To predict, the model multiplies that vector by an output matrix (often the embedding table reused, "tied weights") to produce one logit — a raw score — for every token in the vocabulary. Softmax exponentiates and normalizes those scores into probabilities that sum to 1. That distribution is the model's answer; everything else is how we pick from it.

Temperature reshapes the distribution before sampling: divide the logits by a small number (<1) and the peaks sharpen — the model plays it safe and nearly always takes the top token; divide by a larger number (>1) and the distribution flattens — lower-probability, more surprising tokens get a real chance. This is the single knob behind "make it more creative" vs. "make it more focused." Real systems add tricks like top-k and top-p (nucleus) sampling to clip the long tail of nonsense. Generation is autoregressive: sample one token, append it, feed the whole thing back in, repeat. Adjust the temperature below, then hit sample a few times to feel the randomness.

Next-token distribution

Low temperature → the model plays it safe (picks the top bar). High temperature → flatter distribution, more surprising choices.
08

Instruction Tuning & RLHF

A raw pretrained model just continues text — it doesn't follow instructions. Instruction tuning teaches the format; RLHF (reinforcement learning from human feedback) then nudges it toward answers humans prefer. Compare the same prompt before and after.

Here's a counterintuitive fact: the base model that comes out of pretraining is not the helpful assistant you talk to. It's a pure text-continuation engine. Ask it "What is the capital of France?" and it might continue with "What is the capital of Germany? What is the capital of Spain?" — because that's a plausible continuation of a quiz, not because it's unhelpful. The knowledge is all there; the behaviour isn't.

Two steps fix this. Instruction tuning (supervised fine-tuning) shows the model thousands of example (instruction → good answer) pairs so it learns the assistant format and to actually respond. Then RLHF aligns it with human preference: the model generates several answers, humans (or a reward model trained on human rankings) say which is better, and the model is updated to produce more of what people prefer — more helpful, honest and harmless. This is a quick preview; Module 03 is entirely about this post-training stage. Toggle base vs. aligned below to see the difference one short fine-tuning phase makes.

Base vs. aligned — same prompt

the RLHF loop
Prompt
Model writesseveral answers
Humans rankbest → worst
Reward modellearns taste
Policy update↑ preferred
09

Case Study — GPT-2 from Scratch

Everything in this module — tokenize, embed, add position, stack attention blocks, predict — is exactly what GPT-2 does. It was the model that turned "scale a language model and capabilities fall out" from a hunch into a headline. Here is its full story, then a calculator that rebuilds its sizing from first principles.

Where it sits in history

GPT-2 was announced by OpenAI on 14 February 2019, in a blog post pointedly titled "Better Language Models and Their Implications." It was the middle child of the GPT line: GPT-1 (2018) had introduced the "pre-train then fine-tune" recipe at 117M parameters; GPT-2 kept the recipe almost unchanged but scaled it more than tenfold and re-framed the whole project around zero-shot task transfer; GPT-3 (2020) would scale the same idea again to 175B and discover in-context few-shot learning. The GPT-2 paper itself notes that its smallest model "is equivalent to the original GPT," and its second-smallest "is equivalent to the largest model from BERT."

The paper's title is "Language Models are Unsupervised Multitask Learners" (Radford, Wu, Child, Luan, Amodei & Sutskever). Its thesis is the heart of why GPT-2 mattered: if a high-capacity model is trained on enough diverse text, then in order to predict that text well it must implicitly learn to perform the tasks that naturally appear in it — translation, question answering, summarization. So those tasks can be invoked zero-shot, with no fine-tuning, just a natural-language prompt like TL;DR:. That reframing — from "fine-tune a model per task" to "prompt one general model" — is the conceptual ancestor of everything we now call prompting.

The model "too dangerous to release"

GPT-2 is as famous for how it was released as for what it did. On announcement day, OpenAI published the paper and released only the smallest model, withholding the weights of the full 1.5-billion-parameter version — citing fears it could mass-produce misleading news, impersonate people, and automate spam and phishing. A research lab declining to ship its own flagship on safety grounds was unprecedented, and the press ran with "the AI too dangerous to release."

What followed was a deliberate staged release, meant to let society watch for misuse at each rung of the ladder:

Feb 14, 2019

124M (small) released + paper published. The 1.5B model withheld; "staged release" and partner-sharing announced.

May 2019

355M (medium) released as the watch-for-misuse experiment continued.

Aug 20, 2019

774M (large) released alongside a report on release strategies and social impact.

Nov 5, 2019

Full 1.5B (XL) released — ~9 months later — after OpenAI found no strong evidence of misuse and judged the research benefits to outweigh the risks.

Why this still matters

GPT-2's staged rollout was the first high-profile case of a lab withholding a model over dual-use risk. Whether you read it as responsible disclosure or as overcaution-plus-hype, it set the template for every "should we release this?" debate that followed.

How it was built

Architecturally GPT-2 is a decoder-only Transformer with causal (masked) self-attention — the same family of blocks you stacked in topic 6. It changed only a few things from GPT-1, but they're the changes that made deep training stable, and most are still standard today:

  • Pre-norm: layer normalization moved to the input of each sub-block, with an extra final norm after the last block — far more stable gradients at depth.
  • Residual init scaling by 1/√N (N = number of residual layers), so signal doesn't blow up as you stack blocks.
  • Vocabulary expanded to 50,257, context doubled from 512 to 1024 tokens, batch size raised to 512.

Tokenizer: byte-level BPE

GPT-2 introduced the tokenizer template still copied everywhere. The goal was a model that can assign probability to any string with no <UNK> token. Pure byte-level models are universal but underperform; word-level BPE over Unicode would need a 130,000-symbol base vocabulary. The fix: byte-level BPE — start from just the 256 possible bytes, then learn 50,000 merges on top, plus one <|endoftext|> token = 50,257. Universal coverage, manageable vocabulary.

Training data: WebText

Rather than wrestle with Common Crawl's noise, OpenAI built WebText from a human-quality signal: every outbound link from Reddit that had earned at least 3 karma. That heuristic scraped 45 million links; after extraction (Dragnet + Newspaper), de-duplication and cleaning, it yielded ~8 million documents / ~40 GB of text. Wikipedia was deliberately removed — not for quality, but to avoid contaminating the zero-shot benchmark evaluations the paper relied on. The objective was the plainest possible one, in OpenAI's own words: "trained simply to predict the next word in 40GB of Internet text."

What it could do — all zero-shot

Without any task-specific fine-tuning, the 1.5B model set a new state of the art on 7 of 8 language-modeling benchmarks. On LAMBADA it slashed perplexity from 99.8 to 8.6 and raised accuracy from 19% to 52.7%; on the Children's Book Test it hit 93.3% / 89.1%. Summarization (via a TL;DR: hint) and translation (~5 BLEU) were weak but present in a model never trained for them — proof of the multitask thesis. And the cherry-picked unicorn sample — a coherent fake news article about English-speaking unicorns in the Andes — became the cultural moment generative text first "felt" real to a general audience.

Critically, the paper reported that all models still underfit WebText: even 1.5B parameters hadn't saturated the data, and performance kept improving log-linearly with size. That single observation was the argument for GPT-3, and for the entire scaling era that followed.

Build a GPT-2 configuration

The whole model's size is determined by a handful of numbers. Drag the sliders to rebuild any of the four real GPT-2 sizes — and watch the parameter count update live. Note: the paper's Table 2 labels these 117M/345M/762M/1542M; later releases count embedding params too and call them 124M/355M/774M/1558M — same four models.

Parameter calculator

Total parameters
Per-block params
Embedding params
Closest to
Vocabulary fixed at 50257, FFN width = 4 × d_model (the GPT-2 convention). Notice how layers and d_model dominate the count — that's why scaling is mostly "make it deeper and wider".

The four real sizes (paper Table 2)

124M · small
12 layers · d_model 768 · 12 heads · 1024 context — "equivalent to the original GPT."
355M · medium
24 layers · d_model 1024 · 16 heads — "equivalent to the largest BERT model."
774M · large
36 layers · d_model 1280 · 20 heads.
1.5B · XL
48 layers · d_model 1600 · 25 heads — the "too dangerous to release" flagship.

Head dimension is 64 throughout (heads = d_model ÷ 64). FFN width = 4 × d_model. These two conventions, plus byte-level BPE and the 50,257 vocab, were copied directly into GPT-3 and countless later models.