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:

  1. 01TextYour prompt
  2. 02TokensInteger ids
  3. 03EmbeddingsOne vector per token
  4. 04TransformerAttention + MLP, × N layers
  5. 05LogitsA score per vocab entry
  6. 06SamplingPick one token

↺ Sampling feeds back into Text

Autoregressive generation: each new token is appended to the input and the loop runs again until a stop token or length limit.

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

An illustrative split. Real tokenizers differ, but common words stay whole while rarer words fragment. The dot marks a leading space, which is usually part of the token.

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:

cos⁡(a,b)=a⋅b∥a∥ ∥b∥\cos(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a} \cdot \mathbf{b}}{\|\mathbf{a}\| \, \|\mathbf{b}\|}

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 tokenThecatsatonit
The1.00····
cat0.350.65···
sat0.100.600.30··
on0.050.150.500.30·
it0.050.700.100.050.10
Illustrative causal attention. Each row is a token attending to the tokens before it (and itself). 'it' puts most of its weight on 'cat' - that's how the model resolves the reference. The empty upper triangle is the causal mask: no peeking at future tokens.

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:

p(tokeni)=exp⁡(zi)∑jexp⁡(zj)p(\text{token}_i) = \frac{\exp(z_i)}{\sum_j \exp(z_j)}

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.

StrategyHow it worksUse it for
GreedyAlways take the most likely tokenDeterministic extraction; can get repetitive
TemperatureDivide logits by T before softmax. T below 1 sharpens, above 1 flattensT ≈ 0-0.3 for factual/code, 0.7-1.0 for creative
Top-kSample only from the k most likely tokensCutting off the long tail of nonsense
Top-p (nucleus)Sample from the smallest set whose probabilities sum to pAdapts 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:

KV bytes≈2×L×Hkv×dhead×bytes×tokens\text{KV bytes} \approx 2 \times L \times H_{\text{kv}} \times d_{\text{head}} \times \text{bytes} \times \text{tokens}

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.

1 · FoundationsPython, probability, linear algebra, neural-network basics
2 · NLP basicsTokenization, TF-IDF, embeddings, classical text pipelines
3 · TransformersAttention, positional encoding, encoder vs decoder
4 · LLMsPretraining, scaling, decoding, context windows
5 · PromptingInstructions, few-shot, chain-of-thought, structured output
6 · RAGChunking, embeddings, vector search, reranking, grounding
7 · Fine-tuningSFT, LoRA/QLoRA, preference alignment (RLHF, DPO)
8 · Agents & MCPTool use, planning, memory, multi-agent orchestration
9 · Eval & safetyBenchmarks, LLM-as-judge, guardrails, red-teaming
10 · Deploy & LLMOpsServing, gateways, observability, cost and latency control
Ten branches of GenAI engineering, from foundations (top) to operating systems in production (bottom).

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#

ConceptIn one line
ParametersThe learned weights. Open models commonly ship at ~1B, 7-8B, ~70B, and 400B+; frontier labs rarely publish counts.
TransformerThe attention-based architecture behind essentially all modern LLMs.
Decoder-onlyPredicts left-to-right with a causal mask - the GPT/Claude/Llama family.
Encoder-onlyReads 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 lawsLoss falls predictably as a power law in parameters, data, and compute.
Compute-optimalChinchilla's finding: scale data with parameters (~20 tokens per parameter).
Emergent abilitiesCapabilities that appear only past a certain scale, like in-context learning.

Tokens, embeddings, attention#

ConceptIn one line
TokenA chunk of text from the model's vocabulary - roughly ¾ of an English word.
BPEByte-Pair Encoding: build a vocabulary by merging frequent adjacent pairs.
EmbeddingA dense vector representing a token or a whole passage.
Cosine similarityThe angle-based similarity measure used for embeddings.
Self-attentionEach token weighs every (earlier) token to build context-aware representations.
Multi-head attentionSeveral attention computations in parallel, each learning different relationships.
Positional encodingHow order is injected - sinusoidal, learned, or rotary (RoPE).
Context windowMax tokens the model attends to at once - prompt plus output.
KV cacheStored keys/values of past tokens so decoding doesn't recompute them.
Logits / softmaxRaw next-token scores and the function that turns them into probabilities.

Training and adaptation#

ConceptIn one line
PretrainingNext-token prediction on web-scale text; produces a base model.
SFTSupervised fine-tuning on instruction → response pairs.
Fine-tuningAny further training on a narrower dataset.
PEFTParameter-efficient fine-tuning - train a small add-on, freeze the rest.
LoRATrain two small low-rank matrices per layer instead of the full weights.
QLoRALoRA on a 4-bit quantized base model - fits on a single consumer GPU.
Catastrophic forgettingFine-tuning that erodes previously learned abilities.
DistillationTrain a small student model to imitate a large teacher.
Synthetic dataTraining data generated by models, usually filtered for quality.

Alignment and safety#

ConceptIn one line
RLHFTrain a reward model on human preferences, then optimize the policy against it (often with PPO).
PPOThe reinforcement-learning algorithm classically used in RLHF.
DPODirect Preference Optimization - learn from preference pairs without a reward model or RL loop.
Constitutional AIUse written principles and AI feedback to steer behavior.
HallucinationFluent output that isn't grounded in facts or sources.
GuardrailsInput/output checks that block or rewrite unsafe or off-policy content.
Prompt injectionUntrusted text that smuggles in instructions the model then follows.
Red-teamingAdversarially probing a model to find failures before users do.

Efficiency and serving#

ConceptIn one line
QuantizationStore weights in fewer bits (8, 4) to cut memory and speed up inference.
FlashAttentionAn IO-aware exact attention kernel that avoids slow memory round trips.
PagedAttentionManage the KV cache in pages like virtual memory - the core of vLLM.
Speculative decodingA small draft model proposes tokens; the big model verifies several at once.
BatchingServe many requests together; continuous batching adds/removes them per step.
TTFT / TPSTime-to-first-token and tokens-per-second - the two latency numbers that matter.
Temperature / top-pDecoding knobs trading determinism for diversity.

Retrieval, agents, evaluation#

ConceptIn one line
RAGRetrieve relevant documents and put them in context before generating.
ChunkingSplitting documents into retrievable pieces - size and overlap matter a lot.
Vector databaseStores embeddings and finds nearest neighbors fast (HNSW, IVF indexes).
Hybrid searchCombine vector similarity with keyword search (BM25).
RerankingA slower, more accurate model reorders the top retrieved results.
In-context learningLearning a task from examples in the prompt, with no weight updates.
Chain-of-thoughtPrompting the model to reason step by step before answering.
Tool callingThe model emits structured calls to functions/APIs and uses the results.
AgentAn LLM in a loop that plans, calls tools, observes, and decides what's next.
LLM-as-a-judgeUsing 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

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.