Apr 23, 2026

LLM From the Inside - From Predicting Tokens to Reasoning

Primer · Engineering · LLM · Transformer · RLHF · 2020–2026
LLM · from the inside · for mid-level SWEs

A model that predicts the next word, three layers of training, and a handful of clever runtime tricks - that's the entire LLM story.

ChatGPT launched in late 2022 on top of GPT-3.5. Four years later, in 2026, frontier LLMs carry over a trillion parameters, context windows spanning millions of tokens, and can "think before answering." The core is still something very simple: predicting the next token. This piece peels back the layers visually, enough for a mid-level software engineer to grasp the whole stack - from the tokenizer, the transformer, pretraining, RLHF, Claude's Constitutional AI, all the way to KV cache, speculative decoding, MoE, and reasoning.

Nov 2022
ChatGPT launches · GPT-3.5
~15T
pretraining tokens (LLaMA 3+)
1M
max context window, 2026
0
memory between requests (default)

Who is this for? Mid-level software engineers who've heard terms like "transformer," "RLHF," "inference," "MoE" but haven't yet pieced them together into one picture. No deep math background needed - just basic matrix and probability knowledge, and some coding experience.

What this isn't. Not a textbook. No derivatives, no gradient descent from scratch. The goal: build a mental model accurate enough to read papers, write prompts, choose models, and debug LLM apps without getting the technical details wrong.

1 · The whole LLM story in one sentence

An LLM is a function that takes in a sequence of tokens and returns a probability distribution over its entire vocabulary for the next token. That's the whole API at its core. Everything flashy - writing code, solving math, reasoning, writing prose - is just the surface of calling that function over and over, each time grabbing one new token and appending it to the end of the sequence.

The cat sat on the mat
Next-token prediction. The model scores the probability of every token in its vocabulary (~50k–200k entries). mat wins. Append it to the end, run again. Repeat until a stop token appears or the budget runs out.
Why "tokens" and not words? The tokenizer (usually BPE - Byte Pair Encoding) chops text into common chunks. "ChatGPT" might become ["Chat", "G", "PT"]; "playing" becomes ["play", "ing"]. This lets a finite vocabulary cover proper nouns, rare words, and unfamiliar languages - and explains why character counts in an LLM never match your estimate.

An annoying consequence: an LLM doesn't know individual characters. It sees "strawberry" as roughly 2–3 merged tokens. Asking "how many r's?" is asking it to count something it has never actually seen. Most of an LLM's "dumb" mistakes live in this tokenizer layer, not in the reasoning layer.

2 · The Transformer - the heart of every LLM

Every modern LLM - GPT, Claude, LLaMA, Gemini, Mistral, DeepSeek, Qwen - uses the Transformer architecture (Vaswani et al., Google, 2017, "Attention Is All You Need"). The version used for text-generating LLMs is called a decoder-only transformer. The structure is remarkably repetitive: the same block stacked 30–120 times.

Token Embeddings + Positional
[B, T, d_model]
RMSNorm / LayerNorm
pre-norm
Multi-Head Self-Attention
Q · Kᵀ / √d → softmax → V
Feed-Forward / MLP (SwiGLU)
up → gate → down
↑ repeated 30–120 times (n_layers) ↑
Final RMSNorm
[B, T, d_model]
LM Head (logits)
[B, T, vocab] → softmax
Decoder-only transformer. One block = attention + FFN + two norms + residual. Stacking is everything. GPT-3 has 96 blocks, LLaMA 3 70B has 80, Claude doesn't publish its count.

Self-attention in 60 seconds

For every token, three vectors are produced: Q (query - "what am I looking for?"), K (key - "what am I?"), V (value - "what information do I carry?"). The current token compares its query against the keys of every preceding token, producing match scores, then blends the values weighted by those scores. The result: every token gets "rewritten" with its surrounding context.

Multi-head attention. Each head learns a different kind of relationship: Head 1 (purple) catches the subject (cat), Head 2 (blue) catches the verb (saw), Head 3 (green) catches nearby words. Many heads run in parallel and get concatenated - that's the "multi-head" part.
Vocab
50k–200k
Tokenizer size. Bigger = better coverage of rare languages, but costs more RAM.
d_model
4k–16k
Vector dimension per token. Bigger means "richer" but compute explodes quadratically.
n_layers
32–120
Number of stacked blocks. Deeper means learning multi-level abstractions.
n_heads
32–128
Parallelizes attention. Since 2024+, GQA/MQA are used to share key-value across heads.
Why "attention is all you need"? Older architectures (RNN, LSTM) processed sequences one step at a time - token 100 had to wait for token 99. Attention looks at the entire sequence in parallel, letting GPU matrix multiplication be fully exploited. That's the single reason the Transformer could scale to trillions of parameters while RNNs couldn't.

3 · Timeline - from GPT-3 to the 2026 generation

Before ChatGPT, LLMs were an academic toy. After ChatGPT, they became a product. Below are the milestones that shaped the industry, compressed into less than four and a half years.

GPT-3
2020-06
ChatGPT (3.5)
2022-11
LLaMA 1
2023-02
GPT-4
2023-03
Claude + Mistral
2023-03 / 09
o1 - reasoning era
2024-09
DeepSeek R1
2025-01
Claude 4.x · LLaMA 4
2025-26
Breakthrough · 2022-11
ChatGPT (GPT-3.5)
Not OpenAI's strongest model, but the first one thoroughly RLHF'd for the public. 100M users in 2 months - the fastest in software history. The moment LLMs left the lab.
Scale + multimodal · 2023-03
GPT-4
A leap in capability: passing bar exams, medical exams, coding beyond expert level. The first with integrated vision. OpenAI stopped disclosing size - estimated at ~1.8T (MoE).
Open weights · 2023-02
LLaMA 1 → 4
Meta released weights. LLaMA 1 leaked onto 4chan → sparked the local-LLM community boom. LLaMA 3 (2024) and LLaMA 4 (2025) are frontier open models - competitive with GPT-4.
Safety-first · 2023-03
Claude
Anthropic, spun off from OpenAI in 2021. Took a different path: Constitutional AI - using AI to self-correct AI against a "constitution" of principles, rather than relying solely on human raters.
Efficient open · 2023-09
Mistral 7B / Mixtral
A French startup proved a small (7B), well-trained model can beat bigger ones. Mixtral 8×7B (MoE) kicked off the MoE trend in open weights.
Reasoning · 2024-09
OpenAI o1 → o3
The first time a model was rewarded for thinking longer. It generates long chains of thought before answering. Marked a new scaling axis: test-time compute, not just pretraining.
Open reasoning · 2025-01
DeepSeek V3 / R1
China released reasoning weights competitive with o1, at a reported training cost of ~$6M USD. It shook the market, wiping ~$600B USD off Nvidia's market cap in a single day (Jan 2025).
Present · 2026
Claude 4.7 · GPT-5 · Gemini 3
The frontier converges around: extended thinking (toggle reasoning on/off), 1M context, tool use/agents, multimodal by default. The closed-open gap has narrowed to 3–6 months.

4 · How training works - three stages

A model like Claude or GPT-4 isn't trained just once. It passes through three stages that differ enormously in data, objective, and cost. Understanding these three stages is the key to understanding why LLMs "behave" the way they do.

Stage 1 · 99% compute
Pretraining
Ingests nearly the entire clean internet. The only objective: predict the next token. Produces a base model - knows everything but rambles, doesn't follow instructions.
Data: ~15T tokens
Compute: months, $10–100M
Loss: cross-entropy next-token
Stage 2 · ~0.5% compute
SFT - Supervised Fine-Tuning
Humans write tens of thousands of prompt → ideal answer pairs. The model learns chat format, instruction-following, tool use. Produces a chat model.
Data: 10k–1M pairs
Compute: days
Loss: next-token, assistant turns only
Stage 3 · ~0.5% compute
RLHF / DPO / RLAIF
Trained by comparison: the model writes 2 answers, someone (human or AI) says which is better. The model learns to shift its distribution toward "better." Produces an aligned model.
Data: 100k–10M preferences
Compute: days-weeks
Loss: reward-weighted / preference

Pretraining - where all the "knowledge" comes from

Pretraining is the data-ingestion stage. Everything an LLM "knows" about the world - Python syntax, Roman history, a pho recipe - enters here. The dataset is a blend: Common Crawl (heavily filtered), Wikipedia, books, GitHub code, arXiv, Stack Exchange, blog posts. Quality filtering is the most closely guarded part - bad data makes a bad model.

GPT-3 175B params · 2020
0.3T tokens
Chinchilla 70B · 2022
1.4T tokens
LLaMA 2 70B · 2023
2.0T tokens
LLaMA 3 70B · 2024
15T tokens
LLaMA 4 / frontier 2025-26
20T+ estimated
The Chinchilla scaling law (DeepMind, 2022) showed GPT-3 was undertrained - for the same compute, a smaller model with more data does better. Rule of thumb: each parameter should see ~20 tokens. The 2024+ generation goes further: LLaMA 3 sees ~200 tokens/param because "over-training" makes inference cheaper - a smaller model runs faster, even though training costs more.

After pretraining, you have a base model. It knows how to write Python code, knows Vietnamese grammar, knows who Trần Hưng Đạo was - but if you ask it "Hi, what are you up to?" it will answer something like: "I'm writing a post. What about you? - I'm just relaxing. - Nice, me too..." It's just continuing text, it doesn't know what "answering" means. That's the job of the next two stages.

SFT - teaching the model to "answer"

SFT = Supervised Fine-Tuning. Fundamentally the same as pretraining (next-token prediction), but the data is tens to hundreds of thousands of user question → assistant answer pairs, hand-written or curated. The model learns the chat format, an assistant's demeanor, and where to stop.

SFT data shapes the model's initial "personality." If every answer is long, polite, and bulleted - the model learns to match it. This is why every chatbot sounds a bit alike: the same pool of contractor raters, the same style guide.

RLHF - teaching the model to "answer better"

SFT teaches "one correct answer." RLHF (Reinforcement Learning from Human Feedback) teaches degree of quality. The classic recipe was popularized by OpenAI in 2022 (InstructGPT, the foundation of ChatGPT):

  1. Generate: the model answers the same prompt 2-4 times.
  2. Rate: human annotators rank the answers.
  3. Reward model: train a small model to predict the rater's score.
  4. RL: use the reward model as a "teacher"; PPO optimizes the policy (the LLM) to raise expected reward, with a KL penalty to keep it from drifting too far from the base model.

RLHF is what turned GPT-3 into ChatGPT. With the same base model, before RLHF it was useful roughly 30% of the time; after RLHF, 80%+. Alternative techniques have since emerged:

DPO · 2023
Direct Preference
Drops the separate reward model, optimizing directly from preference pairs. Simplifies the pipeline, more stable than PPO. Most open-source models since 2024+ use DPO/variants.
RLAIF · 2022+
AI Feedback
Replaces human raters with another LLM. Cheaper, faster, scalable. Anthropic pioneered this with Constitutional AI.
RLVR · 2024+
Verifiable Rewards
For math/code - automatically checks whether the answer is right or wrong. No rating needed. Core to DeepSeek R1 and other reasoning models.

5 · Constitutional AI - Claude's path

Anthropic was founded in 2021 by a group of ex-OpenAI researchers, including Dario & Daniela Amodei and key authors of the GPT-3 paper, with the thesis: RLHF's bottleneck is humans - it doesn't scale, isn't consistent, and isn't transparent about values. The proposed solution: Constitutional AI (CAI), a 2022 paper.

OpenAI / industry default · 2022
RLHF
1
The model generates a pair of answers for the same prompt.
2
A human annotator picks the better one.
3
Train a reward model to mimic human preference.
4
PPO pushes the LLM toward higher reward.
Weakness: values are hidden inside raters' heads, hard to audit. Hard to scale (labor-intensive). Inconsistent across raters.
Anthropic / Claude · 2022+
Constitutional AI (CAI)
1
Write a "constitution" - a list of principles in English (e.g., "Choose the least harmful response").
2
The model answers the prompt, then critiques itself and rewrites the answer according to the constitution.
3
A second AI compares the pair of responses and picks the one that follows the constitution more closely.
4
Use that preference to train via RLAIF - like RLHF but with AI-generated feedback.
Advantage: values are made explicit in the constitution (auditable, debatable). Scalable. Consistent. Reduces dependency on rating labor.

Claude's constitution is partially public - drawing from the UN Universal Declaration of Human Rights, Apple's terms of service, and AI research principles. This doesn't mean Claude "reads the constitution" every time it answers - the principles are baked into the weights through the RL stage.

Character training - another layer of Claude

Anthropic has publicly disclosed an additional step called character training (starting around Claude 3, 2024): using CAI-like techniques to shape personality (as opposed to just "safety"). Claude is taught traits like curiosity, candor when warranted, humility about its own limits, and not feigning agreement. This is why Claude is often noted to have a distinct "voice" compared to GPT or Gemini.

Engineer's angle: When you use the API, your system prompt sits on top of the character already baked into the model. You can't "un-bake" the character with a prompt - you can only emphasize or adjust it at the margins. That's why, given the same prompt, Claude and GPT-4 answer with a different "rhythm."

6 · Inference - runtime optimization

Train once, run billions of times. Inference is where your cloud bill comes from, and where ML engineers have poured the most effort in 2023-2026. The techniques below stack together - a single Claude API request typically benefits from nearly all of them.

KV cache - the simplest trick, the biggest impact

When generating the 100th token, attention needs the K and V of the preceding 99 tokens. Recomputing from scratch for every token costs O(n²). The KV cache simply stores the K, V once computed. From the second token onward, only the new K, V gets computed. O(n²) → O(n).

Token 1
k₁v₁
-
-
-
-
-
-
-
Token 2
k₁v₁
k₂v₂
-
-
-
-
-
-
Token 5
k₁v₁
k₂v₂
k₃v₃
k₄v₄
k₅v₅
-
-
-
Token 8
k₁v₁
k₂v₂
k₃v₃
k₄v₄
k₅v₅
k₆v₆
k₇v₇
k₈v₈
Prompt caching, which Anthropic and OpenAI have recently started selling, is exactly this - keeping the KV cache across requests that share the same prefix. Long system prompt? Pay ~10% of the price the first time, ~1% on subsequent calls. Strategy: put the invariant part at the top of the prompt.

Speculative decoding - one draft + one verify

Large models run slowly (each token is a full pass through all the weights). The idea: use a small, fast draft model to guess k tokens ahead. Then the large model checks all k tokens in one pass. Tokens the draft guessed correctly are accepted. The first wrong token gets corrected. Result: if the draft guesses right 70% of the time, speed increases ~2-3x with no quality loss (mathematically, the output distribution is identical).

Draft (small)
The
quick
brown
fox
jumps
Target (large)
The
quick
brown
fox
dog
Output
The
quick
brown
dog

Four tokens produced in one forward pass of the target model instead of four separate passes.

MoE - splitting into experts

Mixture of Experts: instead of activating all 70B parameters for every token, say 400B parameters are split into N "experts" (typically N=8, 32, or 256). For each token, a small router selects the top-k experts (usually k=1-2). Only k/N of the weights get computed. Result: large capacity (more parameters = more knowledge), small compute (only a fraction is active).

Token
"Python"
ROUTER - selects top-2/8
E1
E2
E3
E4
E5
E6
E7
E8
Output
h(t)
Mixtral 8×7B: ~47B total, only ~13B active. DeepSeek V3: 671B total, 37B active. The capacity of 671B at the inference cost of 37B - the reason MoE dominates 2024-2026.

Quantization - fewer bits, kept quality

Weights are usually trained in FP16/BF16 (16-bit). After training, they can be compressed to INT8, INT4, even FP4 with very little loss. LLaMA 3 70B needs 140GB in FP16; only 40GB in INT4 - runnable on a single consumer GPU. This is why you can run LLaMA on a MacBook M-series.

Test-time compute - answering slower to answer correctly

A second scaling axis appeared in late 2024 with OpenAI o1: instead of making the model bigger, let it generate more tokens before the final answer. Reasoning tokens (thinking/reasoning tokens) get rewarded when they lead to the correct answer (via RLVR on math/code). More compute at runtime → better answers. AI economics flipped: now you can pay more per answer to get a smarter one.

User prompt
If 8 people shake hands with each other exactly once, how many handshakes occur?
Hidden reasoning (model thinks - usually not returned to the user)
Each handshake involves 2 people. Total pairs = C(8,2) = 8!/(2!·6!) = 28. Let me double-check: person 1 shakes with 7 others, person 2 with 6 remaining... 7+6+5+4+3+2+1 = 28. Matches.
Final answer (user sees)
28 handshakes.

Claude has had "extended thinking" since Claude 3.7 (2025): you flip a flag, the model generates up to tens of thousands of hidden reasoning tokens, then returns a concise final answer. For hard bugs in code, the gap between "thinking off" vs "thinking on" is sometimes several dozen percentage points of accuracy.

7 · Open source - the new playing field

By 2026, open weights are no longer a toy. DeepSeek R1, LLaMA 4, Qwen 3, Mistral Large - all compete neck-and-neck with the closed frontier on many benchmarks. "Open weights" doesn't mean true open source (code + data + pipeline). Most only publish weights; the data and training process stay closed. But it's enough for you to: run locally, fine-tune, and audit behavior at the input-output level.

Model Params (total / active) Context Type Notes
Claude Opus 4.7 Anthropic · 2026 - / - 1M Closed Frontier reasoning + character. Architecture undisclosed.
GPT-5 OpenAI · 2025 - / - 400k+ Closed Reasoning Unifies GPT + o-series. Router auto-selects the thinking level.
Gemini 3 Pro Google · 2025 - / - 2M Closed MoE Longest context. Native multimodal.
LLaMA 4 Behemoth Meta · 2025 ~2T / ~288B 10M (subset) Open MoE The largest open model. Teacher for the smaller LLaMA 4 variants.
DeepSeek V3 / R1 DeepSeek · 2024-25 671B / 37B 128k Open MoE Reasoning Low reported training cost (~$6M). The first open-source reasoning model competitive with o1.
Qwen 3 / QwQ Alibaba · 2025 235B / 22B 256k Open MoE Reasoning Strong in Chinese, multilingual across Asian languages. Many sizes from 0.5B to 235B.
Mistral Large 2 Mistral · 2024 123B / 123B 128k Open-ish Dense (not MoE). Restricted commercial license.
Gemma 3 Google · 2025 27B / 27B 128k Open Runs well on a single consumer GPU. Multimodal.
The closed-open gap in 2026: 3-6 months on general benchmarks; 6-12 months on hard reasoning. Where open wins: cost, privacy, customization (fine-tune, LoRA). Where closed wins: tool use/agent polish, reasoning depth, stable latency under heavy load. For prototyping apps, use a closed API; for apps that need to scale/comply, gradually migrate to open hosted (Fireworks, Together, Groq) or self-host.

Are "Open Source" LLMs really open source?

Most of what the media calls "open-source LLM" is actually open weights - weights published for download, running, and fine-tuning. But the data, training code, hyperparameters, logs - the things you'd need to rebuild the model from scratch - are almost always kept closed. In 2024, the OSI (Open Source Initiative) published an official Open Source AI definition requiring all four: weights, code, data (or details sufficient to reproduce it), and a license permitting modification + redistribution.

By that standard, most "open" LLMs today fail to qualify. Below is a spectrum of four levels, from fully closed to OSI-compliant open source:

Level 1 · Closed
API-only
GPT-5, Claude 4.7, Gemini 3
  • Weights
  • ~ Architecture (hints)
  • Training data
  • Training code
  • ~ Model card / safety report
  • Open license
Level 2 · Open weights, restricted license
"Community"
LLaMA 3/4, Gemma 3
  • Weights (downloadable)
  • Architecture + paper
  • Training data
  • Training code
  • ~ High-level recipe
  • ~ License: blocks >700M MAU, blocks training other models on the output, acceptable-use policy
Level 3 · Open weights, commercial license
"Permissive weights"
Mistral (Apache 2.0), Qwen 3 (Apache 2.0), DeepSeek (MIT-ish)
  • Weights
  • Architecture + paper
  • Training data
  • ~ Inference code (ref impl)
  • ~ Partial training recipe
  • License: Apache 2.0 / MIT - free commercial use
Level 4 · True open source (OSI)
Fully reproducible
OLMo 2 (AI2), Pythia (EleutherAI), Amber/LLM360
  • Weights + checkpoints
  • Architecture + paper
  • Public training data (Dolma, Pile)
  • Training code + configs
  • Log, loss curve, seeds
  • License Apache 2.0
Two suspicious things about "open": (1) The Meta LLaMA license bans using LLaMA's output to train other models - contrary to the spirit of open source. (2) Almost no one publishes training data, partly out of fear of copyright lawsuits (NYT suing OpenAI, Getty suing Stability), partly because data is a competitive advantage. Without the data, you can't audit for bias, can't detect test-set leakage, and can't reproduce the model.
Who's actually doing true open source? Mostly nonprofits or academic groups: Allen Institute (AI2) with OLMo 2 - 13B/32B params, public Dolma data, full configs + logs; EleutherAI with Pythia - infrastructure for interpretability research; LLM360 with Amber/Crystal. These three groups hold a small slice of market share but set the standard for everyone else.

For engineers: don't let "open source" marketing fool you when assessing legal standing or reproducibility. Ask directly: are there weights? what license? where's the training data? can it be retrained? Those four questions separate an LLM you can truly own from one you're merely "borrowing."

8 · A mental model for engineers

If you had to keep only five things to build an LLM app correctly, here they are:

1
An LLM has no state
Every request, you send the entire history. "Memory" is an illusion recreated by the client. The prompt is the only state machine.
2
Tokens, not words
Pricing is per token. Context is per token. When an LLM "misspells" something, 90% of the time it's the tokenizer splitting oddly. Don't make it count characters.
3
Temperature is randomness, not "creativity"
temperature=0 is not deterministic (it depends on batching, hardware). For tight reproducibility, use a seed + be careful with prompt caching.
4
Hidden reasoning ≠ the answer
Reasoning models have hidden tokens that cost more than normal input/output. Budget carefully. Turn off thinking for easy tasks.
5
Evals > benchmark > vibe check
Before switching models or prompts, have an eval that measures real outcomes. One pretty demo says nothing about a 0.1% failure rate.
6
Prompt caching is free performance
Put the invariant part (system prompt, few-shot examples, stable RAG context) at the top. Put the variable part (user input) at the bottom. Bill drops 90%.
In short. An LLM is a stack of Transformer decoder blocks, trained in three stages (pretrain → SFT → RL), served via KV cache + (depending on the vendor) speculative decoding + MoE + quantization + optional reasoning. ChatGPT didn't invent the LLM; it invented an LLM easy enough for ordinary people to use. Four years later, frontier models have improved 100x in capability, but the formula is still four pieces: architecture, data, RL, inference engineering. Everything else - agents, tool use, multimodal, MCP, 1M context - is a variation on these four pieces. Master them, and you can read any paper and any changelog from 2026.

Read next

More from the shelf

Apr 26, 2026Knowledge Barriers Fall Twice: Internet 1995, AI 2023 - Who Caught The Wave, Who Got Left BehindApr 23, 2026GPU, HBM, and the Memory Wall - AI's Real BottleneckJul 23, 2026The Attention Economy: A Trillion-Dollar Auction for Every Second of AttentionJun 5, 2026Prediction Market: When The Future Is Priced By Capital

Pass it on

If it found you, share it kindly

XEmail

03 Discussion

Leave a note

A considered space for questions, counterpoints, and useful additions. Civil, on-topic, signed.

Reader notes

...

Loading notes...