Step 1 of 5
How LLMs Actually Work
The full pipeline: tokens, embeddings, attention, next-token prediction, decoding, the KV cache, and context windows.
14 min read
Every large language model - Claude, GPT, Gemini, Llama - does the same thing at its core: it reads a sequence of tokens and predicts the next one. Then it appends that token and does it again. Everything impressive about these models emerges from running that loop billions of times during training and thousands of times per answer.
This guide walks through that loop end to end. It's the vocabulary every other guide on this site builds on, so it's worth getting solid.
The complete pipeline#
Here is what happens between you pressing Enter and the first word appearing:
- 01TextYour prompt
- 02TokensInteger ids
- 03EmbeddingsOne vector per token
- 04TransformerAttention + MLP, × N layers
- 05LogitsA score per vocab entry
- 06SamplingPick one token
↺ Sampling feeds back into Text
1. Tokenization#
Models don't see characters or words - they see tokens, chunks of text from a fixed vocabulary (typically 32k-200k entries). Most modern tokenizers use Byte-Pair Encoding (BPE): start from bytes, then repeatedly merge the most frequent adjacent pair into a new token. Common words become single tokens; rare words split into pieces.
Tokenization·is·surprisingly·unintuitive.
7 tokens
A useful rule of thumb for English: about 4 characters, or ¾ of a word, per token. That matters because context limits, pricing, and speed are all measured in tokens. Code, non-English text, and numbers usually cost more tokens per character.
2. Embeddings#
Each token id indexes a row in an embedding matrix, producing a vector of a few thousand numbers. Training arranges these vectors so that meaning becomes geometry: tokens used in similar contexts end up pointing in similar directions.
Similarity between two vectors is usually measured with cosine similarity - the cosine of the angle between them:
1 means same direction, 0 means unrelated (orthogonal), −1 means opposite.
The same idea powers semantic search and RAG: embed documents and queries into one space, then retrieve the nearest neighbors.
3. Attention#
A token's embedding alone doesn't know its context - "bank" is the same vector in "river bank" and "bank account." Attention fixes that. Each position looks back at earlier positions, decides how relevant each one is, and mixes in their information.
| Query token | The | cat | sat | on | it |
|---|---|---|---|---|---|
| The | 1.00 | · | · | · | · |
| cat | 0.35 | 0.65 | · | · | · |
| sat | 0.10 | 0.60 | 0.30 | · | · |
| on | 0.05 | 0.15 | 0.50 | 0.30 | · |
| it | 0.05 | 0.70 | 0.10 | 0.05 | 0.10 |
A transformer stacks dozens of these attention layers, each followed by a small feed-forward network (MLP). Early layers tend to capture syntax; later layers capture more abstract relationships. The Transformers deep dive covers the mechanics.
4. Next-token prediction#
After the last layer, the model projects the final position's vector onto the whole vocabulary, producing one raw score - a logit - per token. Softmax turns logits into probabilities:
Exponentiate each score, then normalize so everything sums to 1.
That's the whole training objective: maximize the probability of the actual next token across trillions of examples. Grammar, facts, reasoning patterns, and coding ability are all side effects of getting very good at this one prediction.
5. Decoding strategies#
Given a probability distribution, how do you pick the next token? The choice changes the character of the output dramatically.
| Strategy | How it works | Use it for |
|---|---|---|
| Greedy | Always take the most likely token | Deterministic extraction; can get repetitive |
| Temperature | Divide logits by T before softmax. T below 1 sharpens, above 1 flattens | T ≈ 0-0.3 for factual/code, 0.7-1.0 for creative |
| Top-k | Sample only from the k most likely tokens | Cutting off the long tail of nonsense |
| Top-p (nucleus) | Sample from the smallest set whose probabilities sum to p | Adapts to confidence - narrow when sure, wide when not |
6. The KV cache: prefill vs decode#
Generation happens in two very different phases:
Prefill - reading your prompt
- All input tokens are processed in parallel.
- Compute-bound: the GPU's math units are the bottleneck.
- Determines time-to-first-token (TTFT).
- Long prompts make prefill the dominant compute cost.
Decode - writing the answer
- One token at a time, each depending on the last.
- Memory-bandwidth-bound: reading weights and cache dominates.
- Determines tokens per second (latency per token).
- Long outputs make decode dominate wall-clock time.
During decode, each new token needs the attention keys and values of every previous token. Recomputing them each step would be quadratic waste, so they're stored in the KV cache. The cache is why decode is fast - and why long contexts eat GPU memory:
Per token: 2 (K and V) × layers × KV heads × head dim × bytes per value. For a Llama-2-7B-shaped model in fp16 that's 2 × 32 × 32 × 128 × 2 bytes ≈ 0.5 MB - so a 4,096-token context needs about 2 GB of cache per sequence.
This is why techniques like grouped-query attention (fewer KV heads), cache quantization, and PagedAttention exist - see Optimization & Serving.
- KV cache
- Stored keys and values from previous tokens so decoding doesn't recompute them each step - the main memory cost of long-context serving.
- Grouped-query attention (GQA)
- Shares key/value heads across multiple query heads to shrink the KV cache without losing much quality.
- PagedAttention
- Manages the KV cache in fixed-size blocks like virtual memory pages - eliminates fragmentation and is the core of vLLM.
7. Context windows and "lost in the middle"#
The context window is the maximum number of tokens the model can attend to at once - prompt plus output. Windows have grown from 2k tokens to hundreds of thousands, but a bigger window doesn't mean uniform attention across it.
Research on long contexts found a U-shaped pattern: models use information at the start and end of the context best and are measurably worse at facts buried in the middle. In practice:
- Put the most important instructions at the start and repeat critical constraints near the end.
- In RAG, rank the best chunks first rather than dumping everything in.
- Fewer, more relevant tokens usually beat more tokens.
The GenAI roadmap#
With the pipeline in hand, here is the map of everything else there is to learn - roughly in the order it builds up. Each branch links to where this site covers it.
Where to go next for each: branches 1-4 are this track (Classical ML & NLP, Transformers, Training); 5 is the Prompt Engineering Playbook; 6 and 9 are in AI System Architecture; 8 is the Agentic Systems track; 10 is the Production AI track.
50 must-know LLM concepts#
A glossary to skim now and come back to. Every term appears somewhere in the guides.
Scale and architecture#
| Concept | In one line |
|---|---|
| Parameters | The learned weights. Open models commonly ship at ~1B, 7-8B, ~70B, and 400B+; frontier labs rarely publish counts. |
| Transformer | The attention-based architecture behind essentially all modern LLMs. |
| Decoder-only | Predicts left-to-right with a causal mask - the GPT/Claude/Llama family. |
| Encoder-only | Reads the whole input bidirectionally - BERT; great for classification and embeddings. |
| Mixture of Experts (MoE) | Many expert MLPs per layer, a router activates a few per token - big capacity, lower compute. |
| Scaling laws | Loss falls predictably as a power law in parameters, data, and compute. |
| Compute-optimal | Chinchilla's finding: scale data with parameters (~20 tokens per parameter). |
| Emergent abilities | Capabilities that appear only past a certain scale, like in-context learning. |
Tokens, embeddings, attention#
| Concept | In one line |
|---|---|
| Token | A chunk of text from the model's vocabulary - roughly ¾ of an English word. |
| BPE | Byte-Pair Encoding: build a vocabulary by merging frequent adjacent pairs. |
| Embedding | A dense vector representing a token or a whole passage. |
| Cosine similarity | The angle-based similarity measure used for embeddings. |
| Self-attention | Each token weighs every (earlier) token to build context-aware representations. |
| Multi-head attention | Several attention computations in parallel, each learning different relationships. |
| Positional encoding | How order is injected - sinusoidal, learned, or rotary (RoPE). |
| Context window | Max tokens the model attends to at once - prompt plus output. |
| KV cache | Stored keys/values of past tokens so decoding doesn't recompute them. |
| Logits / softmax | Raw next-token scores and the function that turns them into probabilities. |
Training and adaptation#
| Concept | In one line |
|---|---|
| Pretraining | Next-token prediction on web-scale text; produces a base model. |
| SFT | Supervised fine-tuning on instruction → response pairs. |
| Fine-tuning | Any further training on a narrower dataset. |
| PEFT | Parameter-efficient fine-tuning - train a small add-on, freeze the rest. |
| LoRA | Train two small low-rank matrices per layer instead of the full weights. |
| QLoRA | LoRA on a 4-bit quantized base model - fits on a single consumer GPU. |
| Catastrophic forgetting | Fine-tuning that erodes previously learned abilities. |
| Distillation | Train a small student model to imitate a large teacher. |
| Synthetic data | Training data generated by models, usually filtered for quality. |
Alignment and safety#
| Concept | In one line |
|---|---|
| RLHF | Train a reward model on human preferences, then optimize the policy against it (often with PPO). |
| PPO | The reinforcement-learning algorithm classically used in RLHF. |
| DPO | Direct Preference Optimization - learn from preference pairs without a reward model or RL loop. |
| Constitutional AI | Use written principles and AI feedback to steer behavior. |
| Hallucination | Fluent output that isn't grounded in facts or sources. |
| Guardrails | Input/output checks that block or rewrite unsafe or off-policy content. |
| Prompt injection | Untrusted text that smuggles in instructions the model then follows. |
| Red-teaming | Adversarially probing a model to find failures before users do. |
Efficiency and serving#
| Concept | In one line |
|---|---|
| Quantization | Store weights in fewer bits (8, 4) to cut memory and speed up inference. |
| FlashAttention | An IO-aware exact attention kernel that avoids slow memory round trips. |
| PagedAttention | Manage the KV cache in pages like virtual memory - the core of vLLM. |
| Speculative decoding | A small draft model proposes tokens; the big model verifies several at once. |
| Batching | Serve many requests together; continuous batching adds/removes them per step. |
| TTFT / TPS | Time-to-first-token and tokens-per-second - the two latency numbers that matter. |
| Temperature / top-p | Decoding knobs trading determinism for diversity. |
Retrieval, agents, evaluation#
| Concept | In one line |
|---|---|
| RAG | Retrieve relevant documents and put them in context before generating. |
| Chunking | Splitting documents into retrievable pieces - size and overlap matter a lot. |
| Vector database | Stores embeddings and finds nearest neighbors fast (HNSW, IVF indexes). |
| Hybrid search | Combine vector similarity with keyword search (BM25). |
| Reranking | A slower, more accurate model reorders the top retrieved results. |
| In-context learning | Learning a task from examples in the prompt, with no weight updates. |
| Chain-of-thought | Prompting the model to reason step by step before answering. |
| Tool calling | The model emits structured calls to functions/APIs and uses the results. |
| Agent | An LLM in a loop that plans, calls tools, observes, and decides what's next. |
| LLM-as-a-judge | Using a strong model to grade outputs - scalable, but with known biases. |
That's 50. If a few still feel fuzzy, that's expected - the rest of this track makes them concrete.
Papers behind this guide
Attention Is All You Need
The transformer paper that started it all. If you read one paper, make it this one.
Google Brain, 2017
GPT-3: Language Models are Few-Shot Learners
Showed that scaling up language models creates emergent abilities - in-context learning from just a few examples.
OpenAI, 2020
Lost in the Middle
Models use information at the start and end of long contexts best - and miss the middle.
Stanford, 2023