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 "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).
| Word | Likely tokens |
|---|---|
"hello" | [hello] · 1 token |
"hello!" | [hello][!] · 2 tokens |
"unbelievable" | [un][bel][iev][able] · 4 tokens |
| Urdu / Arabic / CJK | often 1–3 tokens per character — costs more! |
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.
thewith 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.
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
Pre-training→ Stage 2
SFT→ Stage 3
RLHF / DPO→ Frontier model
| Stage | What happens | Data | Loss |
|---|---|---|---|
| Pre-training | Self-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 / DPO | Make outputs more helpful, harmless, and honest. | Human preference rankings. | PPO or DPO objective |
RLHF, briefly
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
| Strategy | How | When |
|---|---|---|
| Greedy | Always pick argmax logit. | Code, math; risks loops. |
| Beam search | Track 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 decoding | Draft 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.
6.10 · The model family map (2026)
| Family | Strengths | Notable models |
|---|---|---|
| Anthropic Claude | Reasoning, long context, safety, agentic use | Opus, Sonnet, Haiku |
| OpenAI GPT / o-series | Strong general purpose, "thinking" variants | GPT-5, o-series |
| Google Gemini | Multimodal, very long context | Gemini Pro / Ultra |
| Meta Llama | Best open-weight family | Llama 3 / 4 |
| Mistral, Qwen, DeepSeek | Open-weight specialists (code, multilingual) | Mixtral, Qwen, DeepSeek-V* |
| Phi / Gemma | Small but mighty for on-device | Phi-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.