A ai coolAId
Chapter 1 of 7

How LLMs Actually Work

From raw text to next-token probabilities: tokenization, embeddings, self-attention, pretraining as flashcards, logits, temperature, and KV caching.

Mental Model

A base Large Language Model is a next-token probability machine. It does not search a database of memorized answers, and it is not pretrained with reinforcement learning. It converts text into numbers, runs them through stacked attention layers, and outputs a probability distribution over what token comes next.

1. Text to Numbers: Tokenization & Embeddings

Neural networks only multiply matrices—they cannot read raw English or Python. Every prompt passes through two translation steps before the model "thinks":

  1. Tokenization (BPE): Raw UTF-8 text is split into common subword chunks (32k–200k vocabulary). Common words like function are 1 token; rare words or long numbers split into multiple tokens.
  2. Embeddings: Each token ID looks up a dense vector (e.g. 4,096 floats). Words and concepts used in similar contexts end up pointing in similar directions in this high-dimensional space.

Practical consequence: Whenever an LLM fails at counting letters ("how many r's in strawberry?"), reversing strings, or aligning fixed-width ASCII tables, the culprit is usually tokenization—the model never sees individual characters directly.

2. Inside the Transformer: Attention + MLP

A decoder-only Transformer repeats the same two-step block dozens of times (e.g. 32 to 128 layers):

  • Self-Attention (Communication): Every token creates a Query ("what am I looking for?"), a Key ("what do I contain?"), and a Value ("what information should I pass along?"). Comparing queries against all earlier keys computes attention weights: \[\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V\] The causal mask \(M\) ensures token \(t\) can only look backward at tokens \(1 \dots t\), never peek into the future.
  • Feed-Forward MLP (Computation): After gathering context via attention, each token passes independently through a small neural network that transforms and retrieves stored factual patterns.

3. Pretraining Is Flashcards, Not RL

A common misconception is that base LLMs are trained with reinforcement learning. In reality, Pretraining is pure self-supervised prediction:

  • Take trillions of tokens of books, web pages, and source code.
  • Hide the next token \(x_t\), ask the model to predict it from \(x_{<t}\), and penalize surprise using cross-entropy loss: \[\mathcal{L}_{\text{PT}} = -\sum_{t=1}^{T} \log P_\theta(x_t \mid x_{<t})\]
  • Because the true next token is already known, there is no game, no environment, and no delayed reward.

4. From Logits to Words: Softmax, Temperature & KV Cache

At the final layer, the model outputs a vector of raw scores called Logits—one score per token in the vocabulary. Softmax & Temperature turns those raw scores into probabilities:

\[P(i) = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}\]

Temperature \(T\) Behavior Best Used For
0.0 – 0.2 Sharp, near-deterministic (argmax) Code edits, SQL, JSON extraction, classification
0.6 – 0.8 Balanced fluency & variety General chat, summarization, brainstorming
0.9 – 1.2 High entropy, exploratory Creative writing, generating diverse RL / Best-of-N rollouts

Once a token is sampled, it gets appended to the prompt and the loop repeats. To avoid recomputing attention over the entire prompt from scratch on every single token, inference engines store past Keys and Values in a KV Cache. That turns decoding from compute-bound to memory-bandwidth bound—and is why prompt caching cuts API latency and cost dramatically when requests share a long prefix.