Pretraining is the long, brutally expensive first phase where a model reads trillions of tokens of text and, by predicting the next one over and over, teaches itself language, facts, and reasoning — with no labels and no human in the loop.
01The answer, then the intuition
The model from the last chapter isn't born knowing anything — its parameters start as random noise. Pretraining is how those billions of numbers become a model of language. The recipe is almost absurdly simple: feed it a colossal pile of text, and at every position ask it to predict the next token. When it's wrong, nudge the weights to be a little less wrong. Do that for trillions of tokens.
Because the right answer is always just "the next word in the text," no human has to label anything — the data supervises itself. To predict text well, the model is quietly forced to learn grammar, facts, code, arithmetic, and reasoning, because all of those help it guess what comes next. Drag through a training run and watch capability emerge:
Illustrative. The loss falls and the model's writing sharpens as it sees more tokens.
02Mechanics
The output is a base model: fluent, knowledgeable, and completely unhelpful. It will happily continue your text, but it hasn't learned to follow instructions or be safe. Turning it into a usable assistant is the next chapter.
04The math
expand ▾For one position, with the model's predicted distribution $P$ and the true next token $t$, the loss is the negative log-probability it assigned to the truth:
Pretraining minimizes the average of this over the whole corpus of $D$ tokens — the cross-entropy loss:
by gradient descent on the parameters $\theta$: $\;\theta \leftarrow \theta - \eta\,\nabla_\theta \mathcal{L}$. Empirically the loss follows a scaling law — it falls as a power of the compute $C$:
This smooth, predictable curve is what makes "spend more, get a better model" a plannable investment rather than a gamble — the single fact underneath the entire build-out.
05The code
expand ▾The cross-entropy of a single prediction — the quantity, summed over trillions of tokens, that is pretraining.
loss.py
import numpy as np
def softmax(z):
e = np.exp(np.array(z, float) - max(z)); return e / e.sum()
def cross_entropy(logits, true_token):
p = softmax(logits)
return -np.log(p[true_token]) # surprise at the real next token
# model's logits over a tiny vocab; the true next token is index 0
logits = [6.0, 1.5, 1.8, 1.2]
print(round(cross_entropy(logits, 0), 3)) # 0.034 — confident and correct: tiny loss
print(round(cross_entropy(logits, 2), 3)) # 4.234 — it bet wrong: large loss
# training = average this over D tokens and take a gradient step, ~D/batch times
06The economics
The run → money
Pretraining is the most concentrated cost in all of AI — a single training run for a frontier model costs tens to hundreds of millions of dollars in compute, burned over weeks or months on a cluster of tens of thousands of GPUs that exists largely for this purpose. It is the sharpest spike of the build-out's capital expenditure, and it happens before the model has earned a cent.
The economics only work because the result is an asset: one expensive run produces a base model that is then served to hundreds of millions of users, amortizing the cost across billions of cheap-by-comparison inference calls. The scaling law is what makes the bet rational — spend predictably more on the run, get a predictably better asset.
So pretraining is the training half of the two clocks: the enormous, upfront, capitalized cost that the Circuit asks whether inference revenue will ever repay. Every new frontier run raises the stakes of that question.
07Going deeper
expand ▾
Brown et al. (2020) — GPT-3 · pretraining at scale and few-shot learning.
Hoffmann et al. (2022) — Chinchilla · how to spend a compute budget between parameters and data.
Wei et al. (2022) — Emergent Abilities of LLMs · capabilities that appear with scale.
Gao et al. (2020) — The Pile · what a pretraining corpus actually looks like.
"First Principles — how AI actually works", chapter "How models are pretrained", by The Catch. CC-BY 4.0. Hosted at TheCatch.AI / Tech Stack / AI Principles.
A parameter is a single learned number — one weight in one of the model's matrices. A large model is billions of them, and together those numbers are the model. "175 billion parameters" means 175 billion learned knobs.
01The answer, then the intuition
Every multiply you've met — the embedding lookup, the attention projections, the feed-forward layers — uses weights. A parameter is just one of those weights: a single number the model learned during training. There's nothing else in the model. The "knowledge" isn't stored anywhere special; it's distributed across all the weights, and the model file you download is literally a giant list of them.
That's why parameter count is the headline spec. It sets how much the model can learn, how much memory it takes to hold, and how much compute it takes to run. Build your own and watch those three numbers move — set the depth and width of a transformer:
02Mechanics
The parameters aren't spread evenly. In each transformer layer they sit in a handful of matrices:
So a layer holds roughly $12d^2$ parameters, and a model with $N$ layers holds about $12Nd^2$ plus the embeddings. They begin as random noise and are nudged, one tiny gradient step at a time, until the whole pile of numbers predicts text well. Training is the act of setting these parameters; everything else in AI is what you do with them once they're set.
04The math
expand ▾With $N$ layers, width $d$, and vocabulary $V$, the parameter count is dominated by the layers:
For a model of GPT-3's shape — $N = 96$, $d = 12288$, $V \approx 50{,}257$ — that comes to about $175$ billion, which is exactly the famous number. Notice the $d^2$: widening a model is quadratically expensive in parameters, while adding layers is only linear.
Two consequences set the cost. The memory to hold the weights is $N_{\text{params}}$ times the bytes per number — $2$ bytes in half-precision, $1$ in int8. And running the model takes about $2N_{\text{params}}$ floating-point operations per token. So the single number on the box determines both the storage and the compute.
05The code
expand ▾The exact function behind the slider above — runnable, and it reproduces GPT-3's 175B.
params.py
def transformer_params(n_layers, d_model, vocab, d_ff=None):
d_ff = d_ff or 4 * d_model
per_layer = 4 * d_model**2 + 2 * d_model * d_ff # attention (QKVO) + FFN
embedding = vocab * d_model # token embedding table
return n_layers * per_layer + embedding
# GPT-3 scale: 96 layers, width 12288, vocab 50257
N = transformer_params(96, 12288, 50257)
print(f"{N:,} parameters") # 174,563,733,504 parameters
print(f"{N/1e9:.0f}B params | {N*2/1e9:.0f} GB in fp16") # 175B params | 349 GB in fp16
06The economics
Count → money
Parameter count is the closest thing the AI economy has to a single price tag. It sets memory — a 175B model needs about 350 GB just to sit in half-precision, about five 80 GB GPUs before it has done any work. It sets compute — roughly $2N$ operations per token to run, and about $6N \cdot D$ to train. And by the scaling laws, it sets capability: bigger has reliably meant better, which is why the number keeps climbing.
That is the whole flywheel of the build-out. "Make it bigger" improves the product, but every extra parameter is more HBM to hold it, more GPUs to serve it, and more energy to train it. The race to larger $N$ is the race that fills the data centers — and the reason memory, not raw compute, is so often the binding constraint.
So when you read "405 billion parameters," translate it: that many learned numbers, that much memory, that much silicon. The parameter count you just dialed is the unit in which the entire Circuit is denominated.
07Going deeper
expand ▾
Brown et al. (2020) — Language Models are Few-Shot Learners (GPT-3) · the 175-billion-parameter model.
Kaplan et al. (2020) — Scaling Laws for Neural Language Models · why bigger reliably means better.
Hoffmann et al. (2022) — Training Compute-Optimal LLMs (Chinchilla) · how to balance parameters against training tokens.
Phuong & Hutter (2022) — Formal Algorithms for Transformers · the parameter tables, written out.
"First Principles — how AI actually works", chapter "Parameters & weights", by The Catch. CC-BY 4.0. Hosted at TheCatch.AI / Tech Stack / AI Principles.
The single most consequential fact in modern AI: model loss falls as a smooth power law as you add compute, data, and parameters. On a log-log plot it's a straight line — predictable enough to bet hundreds of billions on.
01The answer, then the intuition
You'd expect intelligence to be unpredictable. The surprise of the last five years is that, at least for next-token loss, it isn't. Plot a model's loss against the compute used to train it, on log-log axes, and the points fall on a straight line across many orders of magnitude. Double, then re-double the compute, and the loss keeps dropping by the same predictable fraction.
That line is a scaling law, and its flatness is why the industry looks the way it does: a lab can forecast, before spending a dollar, roughly how good the next model will be. Drag the compute budget and watch loss slide down the curve — the same ratio for every factor of ten:
Illustrative power law (Kaplan/Chinchilla form). Loss is on a relative scale; the straightness is the point.
02Mechanics
The catch is baked into the shape: a power law with a small exponent means diminishing returns. Each equal step down in loss costs another full factor of ten in compute. The line is friendly to forecasting and brutal to budgets.
04The math
expand ▾Empirically, loss follows a power law in compute (and similarly in $N$ and $D$):
Taking the log makes it a straight line — slope $-\alpha_C$ — which is why log-log plots are the field's native language. The full Chinchilla form separates the contributions and an irreducible floor $E$:
The small exponent is the whole economic story. With $\alpha_C \approx 0.05$, every $10\times$ in compute multiplies loss by $10^{-0.05} \approx 0.89$ — a fixed ~11% cut per decade. Constant progress therefore demands exponentially growing spend: to keep the loss falling in a straight line, the compute (and the bill) must rise geometrically. Predictable, and relentless.
05The code
expand ▾Loss across five orders of magnitude of compute — note the identical ratio at every step.
scaling.py
alpha = 0.050 # compute exponent (illustrative, Kaplan-ish)
Cc = 1e21
def loss(C): return (Cc / C) ** alpha
prev = None
for C in [1e21, 1e22, 1e23, 1e24, 1e25]:
L = loss(C)
ratio = "" if prev is None else f" (x{L/prev:.3f} per 10x)"
print(f"C={C:.0e} -> loss {L:.4f}{ratio}")
prev = L
# C=1e+21 -> loss 1.0000
# C=1e+22 -> loss 0.8913 (x0.891 per 10x)
# C=1e+23 -> loss 0.7943 (x0.891 per 10x)
# C=1e+24 -> loss 0.7079 (x0.891 per 10x)
# C=1e+25 -> loss 0.6310 (x0.891 per 10x) <- 10x the spend, same 11% gain
06The economics
The law → money
Scaling laws are the reason the build-out is rational rather than reckless. Because more compute reliably buys a better model, spending on clusters is a forecast, not a gamble — a lab can project the return on the next $10 billion and act on it. Remove that predictability and the whole capital cycle collapses; it's the closest thing AI has to a law of physics for investors.
But the same line contains the warning. The exponent is small, so returns diminish: each equal gain costs another factor of ten. Progress on the straight line requires spending that grows geometrically — which is exactly why capex is exploding, and exactly why the question of whether the payoff keeps pace is not academic. And a second limit looms: the data wall, since the world contains only so many quality tokens to train on.
This is the beating heart of the Circuit. The scaling law is the divergence in one equation: capability climbs smoothly while cost climbs exponentially, and the entire thesis rides on whether revenue can track the second curve as it chases the first. Everything the earlier chapters described — the chips, the memory, the tokens — is ultimately in service of buying another step down this line.
07Going deeper
expand ▾
Kaplan et al. (2020) — Scaling Laws for Neural Language Models · the original power laws.
Hoffmann et al. (2022) — Chinchilla · compute-optimal training, 20 tokens/parameter.
Wei et al. (2022) — Emergent Abilities of LLMs · when smooth loss hides sudden jumps.
Epoch AI — Trends in Machine Learning · measured compute, data, and cost trajectories.
"First Principles — how AI actually works", chapter "Scaling laws", by The Catch. CC-BY 4.0. Hosted at TheCatch.AI / Tech Stack / AI Principles.
A pretrained base model knows language but has no manners — it just continues text. Fine-tuning and RLHF are the two phases that turn that raw predictor into a model that follows instructions, stays helpful, and refuses harm.
01The answer, then the intuition
Out of pretraining you get a base model: brilliant at predicting text, useless as an assistant. Ask it "How do I reset my password?" and it might continue with a list of more questions — because that's what such text looks like on the web. It has the knowledge; it lacks the job description.
Two phases fix that. Supervised fine-tuning (SFT) shows it thousands of high-quality instruction→response examples, teaching it the shape of being helpful. Then RLHF — reinforcement learning from human feedback — has people rank competing answers, distills those preferences into a reward signal, and nudges the model toward replies humans actually prefer: clearer, more honest, and safe.
Pick a prompt and walk it through the three stages. The knowledge never changes — only the behaviour:
Illustrative responses showing what each alignment phase adds.
02Mechanics
instruction → ideal response pairs written by humans. The model learns the assistant format: when it sees a question, produce an answer, not more questions. Cheap relative to pretraining, but the data is hand-written and expensive per token.One subtlety worth holding onto: RLHF optimizes for what raters prefer, which is a proxy for what's actually good. Push too hard and you get models that are confidently agreeable rather than correct — the central open problem the field calls alignment.
04The math
expand ▾The reward model turns "humans prefer A over B" into numbers via the Bradley–Terry model. If the reward model scores responses $r(A)$ and $r(B)$, the modeled probability that $A$ is preferred is:
It's trained to maximize that probability on the human-labeled pairs — i.e. minimize $-\log \sigma(r(A)-r(B))$ whenever a human chose $A$. The policy $\pi$ is then optimized to earn reward while staying near the reference (SFT) model $\pi_{\text{ref}}$:
The first term pulls toward what humans like; the $\beta\,\mathrm{KL}$ term is the leash that stops it from degenerating into reward-hacking gibberish. Tuning $\beta$ is the whole art — too loose and the model games the reward, too tight and RLHF does nothing.
05The code
expand ▾How a single human comparison becomes a gradient on the reward model. Runnable.
reward.py
import numpy as np
def sigmoid(x): return 1.0 / (1.0 + np.exp(-x))
# reward model's current scores for two candidate responses
r_chosen, r_rejected = 2.3, 0.8 # a human preferred the first one
p_agree = sigmoid(r_chosen - r_rejected) # model's prob the human's pick is better
loss = -np.log(p_agree) # Bradley-Terry preference loss
print(round(p_agree, 3)) # 0.818 — model mostly agrees with the human
print(round(loss, 3)) # 0.201 — small loss; a confident wrong pick costs far more
# training nudges r_chosen up and r_rejected down until the model ranks like people do
06The economics
Alignment → money
Fine-tuning is a rounding error next to pretraining in compute — but it is where a model becomes sellable. Nobody subscribes to a base model; people pay for the aligned assistant. The hundred-million-dollar pretraining asset only earns revenue after this comparatively cheap polishing step gives it manners.
The cost here is a different shape: not GPUs but people. SFT demonstrations and preference labels are written and ranked by human annotators, and high-quality human feedback at scale is a real, recurring line item — increasingly the scarce input as raw compute becomes plentiful. "Data" stops meaning scraped web text and starts meaning curated human judgment.
So alignment is the conversion step in the Circuit: the move that turns a capitalized training asset into a product with paying users. It's also where the quality questions live — whether the helpful, confident answers people are paying for are actually right is the thing our research desk keeps testing.
07Going deeper
expand ▾
Ouyang et al. (2022) — InstructGPT · the SFT + RLHF recipe behind ChatGPT.
Bai et al. (2022) — Constitutional AI · using AI feedback to reduce the human-labeling burden.
Rafailov et al. (2023) — Direct Preference Optimization (DPO) · skipping the separate reward model.
Christiano et al. (2017) — Deep RL from Human Preferences · the original idea, before LLMs.
"First Principles — how AI actually works", chapter "Fine-tuning & RLHF", by The Catch. CC-BY 4.0. Hosted at TheCatch.AI / Tech Stack / AI Principles.
A large language model is a transformer trained to do one thing: predict the next token. Run that prediction over and over, feeding each guess back in, and the next-token machine becomes a writer.
01The answer, then the intuition
Everything in Part I builds to this. An LLM takes your text as tokens, runs it through the transformer stack, and produces a probability for every possible next token. It picks one, sticks it on the end, and runs again on the longer text. Repeat until done. That loop — predict, append, repeat — is all "generation" is.
The surprise of the last few years is that doing this one humble task well enough, at enough scale, produces translation, code, reasoning, and conversation as side effects. To answer a question, the most likely continuation of "the answer is" turns out to be the answer.
Below is that prediction step. The model gives a distribution over next tokens; a single knob, the temperature, controls how boldly it picks. Slide it:
Illustrative probabilities for one prediction step. Temperature reshapes the same distribution.
At low temperature the model is confident and repetitive; at high temperature it gets creative — and eventually incoherent.
02Mechanics
The mechanics are a short loop:
softmax turns those into probabilities.So an "LLM" is not a database of answers. It is a single learned function for "what token is likely next," wrapped in a loop. The next chapters open up where that function's knowledge comes from — pretraining — and how it's shaped to be helpful.
04The math
expand ▾Given the tokens so far, the model outputs a logit $z_i$ for each token $i$ in the vocabulary. With temperature $T$, the probability of the next token is:
As $T \to 0$ this collapses onto the single highest-logit token (greedy, deterministic); at $T = 1$ it is the model's raw distribution; as $T$ grows the probabilities flatten toward uniform — more random, eventually nonsense. Generating a whole sequence just multiplies these step by step:
Training maximizes exactly this probability on real text — equivalently, it minimizes the average cross-entropy (the negative log of the right token's probability). "Predict the next token" is the entire objective.
05The code
expand ▾Temperature sampling, then the autoregressive loop. Runnable — it's the whole idea.
generate.py
import numpy as np
def softmax(z, T=1.0):
z = np.array(z, dtype=float) / T
e = np.exp(z - z.max()); return e / e.sum()
# illustrative logits over a tiny vocabulary, after "The sky is"
vocab = ["blue", "clear", "grey", "dark", "falling", "the"]
logits = [4.2, 2.8, 2.3, 1.9, 0.8, 1.2]
for T in [0.5, 1.0, 1.7]:
p = softmax(logits, T)
print(f"T={T}:", ", ".join(f"{w} {pi:.2f}" for w, pi in zip(vocab, p)))
# T=0.5: blue 0.91, clear 0.06, grey 0.02, dark 0.01, falling 0.00, the 0.00
# T=1.0: blue 0.63, clear 0.16, grey 0.09, dark 0.06, falling 0.02, the 0.03
# T=1.7: blue 0.43, clear 0.19, grey 0.14, dark 0.11, falling 0.06, the 0.07
def generate(next_logits, prompt, n, T=1.0): # next_logits: context -> logit vector
toks = list(prompt)
for _ in range(n):
p = softmax(next_logits(toks), T)
toks.append(int(np.random.choice(len(p), p=p))) # sample the next token
return toks
06The economics
Prediction → money
Because generation is a loop, an LLM cannot produce its answer all at once — it must run a full forward pass for every single token it writes, each one conditioned on all the tokens before it. That sequential dependency is why responses stream in word by word, and why latency and cost scale with output length. Every token is one trip through ~$2N$ parameters.
This is the unit the whole industry is priced in. Providers bill per input and output token; the output tokens cost more precisely because each one is a fresh, un-parallelizable forward pass. Multiply by hundreds of millions of users generating billions of tokens a day, and "predict the next token" becomes the single largest recurring workload in computing — the inference demand that, even more than training, is what the data centers are being built to serve.
So the humble loop you just sped through is the business. The token is the product; the model is the factory; and the Circuit is the account of whether that factory's output ever justifies its cost.
07Going deeper
expand ▾
Radford et al. (2019) — GPT-2 · language modeling as a path to general capability.
Brown et al. (2020) — GPT-3 · scale turns next-token prediction into few-shot learning.
Holtzman et al. (2019) — The Curious Case of Neural Text Degeneration · why top-p / nucleus sampling beats greedy.
Jurafsky & Martin — Speech and Language Processing · the language-modeling objective, from the ground up.
"First Principles — how AI actually works", chapter "What is an LLM?", by The Catch. CC-BY 4.0. Hosted at TheCatch.AI / Tech Stack / AI Principles.