The Agentic AI Codex
Ch 06 · How LLMs Really Work
Chapter 06 · The engine room

How LLMs really work

Once you can answer six questions — what's a token, what's an embedding, what does attention compute, how is the model trained, how does it generate text, and what makes Claude differ from GPT — every other chapter clicks into place.

6.1 · An LLM in 60 seconds

An LLM is a giant neural network that, given a sequence of tokens, predicts a probability distribution over the next token. Sample one, append it, and repeat. That's it.

"The cat sat on the"→ tokenize→ embed + position→ N transformer blocks→ softmax over vocab→ "mat" (most likely)

The "intelligence" comes from scale: hundreds of billions of weights, trained on trillions of tokens, then aligned via human feedback.

6.2 · Tokens — the atomic unit

LLMs don't see characters or words. They see tokens: sub-word fragments learned by a tokenizer (e.g. BPE, SentencePiece, Tiktoken).

WordLikely tokens
"hello"[hello] · 1 token
"hello!"[hello][!] · 2 tokens
"unbelievable"[un][bel][iev][able] · 4 tokens
Urdu / Arabic / CJKoften 1–3 tokens per character — costs more!
Two rules of thumb
1 token ≈ 4 English characters ≈ ¾ of a word. Non-Latin scripts are denser — budget accordingly. A 200k-token context window is roughly 150,000 English words — a small novel — but only ~30,000 Urdu characters.

Why sub-word and not whole-word?

  • Fixed vocabulary (~50k–200k) — no out-of-vocab problem.
  • Handles typos, new slang, code, multiple languages.
  • Compresses common phrases into single tokens (e.g. the with leading space).

6.3 · Embeddings — turning tokens into vectors

Each token ID gets a learned vector of size $d_\text{model}$ (e.g. 4096). Semantically similar tokens end up near each other in this space.

$\mathbf{e}_t = \mathbf{E}[\text{id}_t] + \mathbf{p}_t$

Where $\mathbf{p}_t$ is a positional encoding so the model knows token order. Modern LLMs use RoPE (rotary embeddings) instead of fixed sinusoidal vectors.

Same idea, two places
Token embeddings live inside the model.
Sentence embeddings (from a smaller dedicated model) are what RAG uses to score similarity. Different layer, same mathematical idea — points in space.

6.4 · Self-attention — the deep dive

For each token, the model computes three vectors via learned projections:

  • Query $\mathbf{q}$ — "what am I looking for?"
  • Key $\mathbf{k}$ — "what do I expose?"
  • Value $\mathbf{v}$ — "what info do I carry?"

The attention weights for token $i$ over all tokens $j$ are:

$\alpha_{ij} = \dfrac{\exp\!\left(\mathbf{q}_i \cdot \mathbf{k}_j / \sqrt{d_k}\right)}{\sum_{j'} \exp\!\left(\mathbf{q}_i \cdot \mathbf{k}_{j'} / \sqrt{d_k}\right)}$

And the output is the weighted sum of values:

$\mathbf{o}_i = \sum_j \alpha_{ij}\,\mathbf{v}_j$

Multi-head attention runs many such queries in parallel — each "head" can learn a different relationship (syntax, coreference, topic).

Causal mask — why an LLM can't peek

During pre-training, the attention scores for future tokens are forced to $-\infty$ before softmax, so token $i$ can only attend to positions $\le i$. This is what makes next-token prediction well-defined.

6.5 · The full LLM stack

Embedding layer

Token ID → vector. Vocab size × $d_\text{model}$.

N transformer blocks

Each: multi-head self-attention → MLP, both wrapped in residual + LayerNorm.

Output projection

Final hidden state → logits over vocabulary (often weight-tied with embeddings).

Softmax + sampler

Logits → probabilities → sample the next token.

6.6 · How LLMs are trained — three stages

Stage 1
Pre-training
→ Stage 2
SFT
→ Stage 3
RLHF / DPO
→ Frontier model
StageWhat happensDataLoss
Pre-trainingSelf-supervised next-token prediction at massive scale.Trillions of tokens from the web, books, code.Cross-entropy
Supervised fine-tune (SFT)Teach the model to answer prompts in a desired format.Curated (prompt, ideal answer) pairs.Cross-entropy
RLHF / DPOMake outputs more helpful, harmless, and honest.Human preference rankings.PPO or DPO objective
RLHF, briefly
1) Train a reward model on human preference rankings of model outputs.
2) Use PPO to update the LLM so its outputs score higher on the reward model.
3) Add a KL penalty back to the SFT model so we don't drift into nonsense.

DPO (Direct Preference Optimization) is a newer, simpler method: optimize the policy directly from preference pairs without a separate reward model.

6.7 · Scaling laws — the cheat code

Kaplan (2020) and Chinchilla (2022) showed that loss decreases predictably with compute, data and parameters:

$\mathcal{L}(N, D) \approx \mathcal{L}_\infty + \dfrac{A}{N^{\alpha}} + \dfrac{B}{D^{\beta}}$

Practical takeaways:

  • Doubling model size and data together — predictable quality gains.
  • Chinchilla rule: for an optimal model, train tokens ≈ 20 × parameters.
  • Today’s frontier models are over-trained (much more data than Chinchilla optimal) because inference is more expensive than training over a model’s lifetime.

Loss vs training compute (illustrative)

6.8 · Decoding strategies — sampling matters

StrategyHowWhen
GreedyAlways pick argmax logit.Code, math; risks loops.
Beam searchTrack top-$k$ partial sequences.Translation; rarely used in LLMs today.
Temperature sampling$p_i \propto \exp(z_i / T)$, sample from $p$.Creative tasks.
Top-$k$ / Top-$p$ (nucleus)Truncate the tail, then sample.Default for chat.
Speculative decodingDraft with a small model, verify with the big one.Latency-sensitive APIs.

6.9 · Cost, latency & the inference economy

Two numbers run your bill:

  • Tokens in — your prompt + system message + RAG context + history.
  • Tokens out — the model's generation. Usually priced 3–5× the input rate.

Latency anatomy

  • TTFT (time-to-first-token): one heavy "prefill" pass over the entire prompt.
  • ITL (inter-token-latency): one forward pass per generated token thereafter.
The cheapest engineering trick
Prompt caching: providers cache the prefix of your prompt and skip the prefill cost. Put your stable system + RAG context at the top, your changing user message at the bottom. A 90% cache hit ratio is a 9× cost cut on long prompts.

6.10 · The model family map (2026)

FamilyStrengthsNotable models
Anthropic ClaudeReasoning, long context, safety, agentic useOpus, Sonnet, Haiku
OpenAI GPT / o-seriesStrong general purpose, "thinking" variantsGPT-5, o-series
Google GeminiMultimodal, very long contextGemini Pro / Ultra
Meta LlamaBest open-weight familyLlama 3 / 4
Mistral, Qwen, DeepSeekOpen-weight specialists (code, multilingual)Mixtral, Qwen, DeepSeek-V*
Phi / GemmaSmall but mighty for on-devicePhi-3, Gemma 2

6.11 · Mini notebook — a tokenizer in 20 lines

# Conceptual byte-pair-encoding sketch
def bpe_step(words):
    pairs = {}
    for w, freq in words.items():
        toks = w.split()
        for a, b in zip(toks, toks[1:]):
            pairs[(a, b)] = pairs.get((a, b), 0) + freq
    return max(pairs, key=pairs.get)

# Repeatedly merge the most frequent adjacent pair → grows a sub-word vocab.

6.12 · Self-check

Q1 · What does an LLM output at each step?
A single token
A probability distribution over the vocabulary
A string of characters
A plan in JSON
Q2 · Which sampling parameter most directly controls diversity?
Temperature
Vocabulary size
Hidden size
Layer count
Q3 · Where does Claude/GPT get its instruction-following behaviour?
Pre-training
SFT followed by RLHF/DPO
Tokenization
Sampling temperature