What happens when you press 'submit' on ChatGPT?
contents
You press Enter. Between that and the first token in your browser sit trillions of tokens of training data, a deep stack of transformer layers (GPT-3 has 96), a reward model trained on human rankings, a KV cache that grows by one token per step in GPU memory, and a continuous batching scheduler that keeps the GPUs busy.
the data
OpenAI never published how many tokens GPT-4 saw. A 2023 SemiAnalysis leak put it at about 13 trillion. Most web-scale text starts as raw HTML from Common Crawl, which publishes a new crawl about once a month. The October 2026 crawl has 2.16 billion web pages, 371 TiB uncompressed. Raw Common Crawl is mostly garbage: boilerplate, navigation menus, duplicate content, spam.
The GPT-2 authors chose not to train on raw Common Crawl. They cite an earlier study that found a large amount of its documents "mostly unintelligible." So they switched to a different signal: Reddit karma. They scraped outbound links from Reddit posts with at least 3 karma. If humans upvoted it, it clears a basic quality bar.

Figure: how OpenAI built WebText. Source: Radford et al. 2019, "Language Models are Unsupervised Multitask Learners", section 2.1.
The cleaning pipeline every serious dataset now runs:
- Parse the HTML, remove the tags, and keep the main text.
- Remove duplicates. The same article has copies on hundreds of sites.
- Filter by language. Common Crawl covers 100+ languages.
- Filter for quality. Remove spam, adult content and low-quality text.
- Remove personally identifiable information (PII): email addresses, IP addresses, API keys.
FineWeb is the best public example of this pipeline. Hugging Face starts from Common Crawl and ends up with cleaned English text: 15 trillion tokens (GPT-2 tokenizer) in the first release, more than 18.5 trillion now. A URL blocklist from the University of Toulouse removes adult sites. A fastText classifier keeps English pages. Hand-written heuristic filters (from Gopher, C4, and their own) remove low-quality text, and MinHash removes near-duplicates. They chose not to use a learned quality classifier for FineWeb; the FineWeb-Edu subset adds one.

Figure: the FineWeb pipeline. Source: Hugging Face, "FineWeb: decanting the web for the finest text data at scale".
Each row has text, id, dump (which crawl it came from), url, and a few more columns. Streaming the first row:
from datasets import load_dataset
ds = load_dataset("HuggingFaceFW/fineweb", split="train", streaming=True)
row = next(iter(ds))
print(list(row))
# ['text', 'id', 'dump', 'url', 'date', 'file_path', 'language', 'language_score', 'token_count']
print(row["dump"], row["token_count"], row["text"][:60])
# CC-MAIN-2013-20 717 How AP reported in all formats from tornado-stricken regionsThe model learns only what's in the training data. Two models at identical parameter count but different data quality will perform very differently. No architecture change fixes a bad corpus.
tokenization
The model reads integers, not text.
A token is roughly a word or subword. In GPT-4o's tokenizer (o200k_base), " unbelievable" with a leading space is one token, but "Unbelievable" at the start of a line splits into "Un" + "bel" + "ievable". Characters are too granular (4096 characters = 4096 steps). Full words break on anything outside the training vocabulary. You can't handle novel words or code identifiers.
The standard is BPE (Byte Pair Encoding). Start with individual bytes, then merge the most frequent adjacent pair again and again.

Two phases. Training runs once on the corpus and learns the merge rules:
def get_stats(ids):
counts = {}
for pair in zip(ids, ids[1:]):
counts[pair] = counts.get(pair, 0) + 1
return counts
def merge(ids, pair, idx):
newids = []
i = 0
while i < len(ids):
if i < len(ids) - 1 and ids[i] == pair[0] and ids[i+1] == pair[1]:
newids.append(idx)
i += 2
else:
newids.append(ids[i])
i += 1
return newids
# GPT-2 runs this 50,000 times on a large corpus
# "t","h" -> "th" -> "the" (if "th"+"e" is frequent enough)Inference applies the learned merges to new text:
def encode(text, merges):
tokens = list(text.encode("utf-8")) # start as raw bytes
while len(tokens) >= 2:
stats = get_stats(tokens)
pair = min(stats, key=lambda p: merges.get(p, float("inf")))
if pair not in merges:
break
tokens = merge(tokens, pair, merges[pair])
return tokens
Figure: at inference the tokenizer maps text to IDs and back. tiktoken's o200k_base gives [60751, 668, 261, 41751] for "Tell me a joke"; the first ID in the figure does not match.
In practice you'd use tiktoken:
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o") # o200k_base
tokens = enc.encode("How does ChatGPT work?")
print(tokens) # [5299, 2226, 17554, 162016, 1101, 30]
print(len(tokens)) # 6GPT-4's older cl100k_base tokenizer needs 7 tokens for the same sentence: it splits "ChatGPT" into " Chat" + "G" + "PT". Bigger vocabularies give shorter sequences. I counted these with tiktoken:
| Text | GPT-2 (gpt2) | GPT-4 (cl100k_base) | GPT-4o (o200k_base) |
|---|---|---|---|
| "How does ChatGPT work?" | 7 | 7 | 6 |
| "Explain transformers." | 5 | 4 | 3 |
| "Unbelievable" | 4 | 3 | 3 |
| Vocabulary size | 50,257 | 100,277 | 200,019 |
Explore token splits interactively at tiktokenizer.vercel.app.
Fewer tokens per sentence = less compute per request. Token efficiency is a real cost lever at scale.
Tokenizing with o200k_base (GPT-4o): "How does ChatGPT work?"
6 tokens
the transformer
Modern LLMs use a decoder-only transformer. Token integers go in, a probability distribution over the next token comes out.

Figure: the decoder half of the original Transformer. Source: Vaswani et al. 2017, "Attention Is All You Need", Figure 1. A decoder-only model such as GPT drops the middle attention sublayer, which reads from the encoder.
Three parts:
- The embedding layer turns token IDs into dense vectors: 4,096 numbers per token in Llama 2 7B, 12,288 in GPT-3 175B.
- N identical transformer blocks refine those vectors: 32 blocks in Llama 2 7B, 96 in GPT-3 175B.
- The output layer turns the final vector into a logit vector, one float per vocabulary token: 50,257 for GPT-2, about 200,000 for GPT-4o.


Each block has two sublayers:
- In attention, tokens exchange information with each other.
- In the MLP (multilayer perceptron, also called the feed-forward network or FFN), each token processes its own vector alone.
Attention moves information between tokens. The MLP changes each token's vector based on what it collected. Residual connections accumulate: each block adds to the previous vector instead of replacing it.
| Part | Job |
|---|---|
| Attention | Routing: moves information between tokens |
| MLP / FFN | Computation: processes each token |
| Residual | Memory: accumulates what each block adds |
how attention works
Every token computes three vectors at every layer:
- Q (query): what am I looking for?
- K (key): what do I advertise about myself?
- V (value): what information do I carry?
The attention score between positions i and j is dot(Q_i, K_j) / sqrt(d_k). Without the sqrt(d_k) scale, large dot products push softmax into regions with very small gradients. A softmax turns the scores into weights. The weighted sum of the V vectors gives the output.
Like a search engine: Query is your search string, Keys are document titles, Values are the document contents. Dot product is the relevance score.
For "bank" in "river bank":
Q_bank · K_river= high score, borrows "river" meaningQ_bank · K_finance= low score, ignores finance context
import numpy as np
def attention(Q, K, V, mask=None):
d_k = Q.shape[-1]
scores = Q @ K.T / np.sqrt(d_k)
if mask is not None:
scores = scores + mask # -inf for future positions
scores -= scores.max(axis=-1, keepdims=True)
weights = np.exp(scores)
weights /= weights.sum(axis=-1, keepdims=True)
return weights @ VThe causal mask fills future positions with -inf before softmax. Each token only attends to itself and earlier tokens. This constraint lets the model generate one token at a time without peeking ahead.
Multi-head attention runs several attention operations in parallel, each with its own weight matrices: 8 heads in the original Transformer, 96 in GPT-3 175B. Different heads learn different relationships, such as subject-verb agreement, coreference and syntactic structure. The model concatenates the head outputs and projects them back to the model width.
For a deeper look at how residual connections and attention interact across layers, see from residual connections to attention residuals.

Figure: the full encoder-decoder Transformer. Source: Vaswani et al. 2017, Figure 1. The red box marks the encoder, which decoder-only models such as GPT do not have.
Self-attention: "The cat sat on the mat"
"sat" attends most to "cat" (subject of the verb). Different heads learn different dependency types.
context window
The context window is the model's working memory: every token it can attend to at once. When a chat gets too long, the app must drop or summarize old messages, and the model has no access to what it drops.
GPT-2: 1,024 tokens. GPT-4o: 128,000 tokens. Larger context = more GPU memory and more compute per token, but it allows longer documents and conversations.
Context window filling: tokens accumulate, the oldest get dropped when it is full
Tokens accumulate left to right. When the window fills, the app drops the oldest tokens. The model has no access to them after that.
the modern decoder stack
The transformer above is 2017. Llama, Qwen, DeepSeek, Gemma keep the skeleton and swap almost every component:
- RMSNorm, pre-norm. RMSNorm (root mean square norm) is cheaper than LayerNorm. Putting it before each sublayer (pre-norm) lets gradients survive deeper stacks.
- RoPE. Rotary position embedding replaces the original positional encoding. It rotates Q and K by an angle that scales with position, so the dot product depends on the distance between tokens. YaRN stretches it past the trained length.
- GQA. In grouped-query attention, groups of query heads share one key/value head: Llama 3 70B has 64 query heads but only 8 KV heads, so its KV cache (explained below) is 8x smaller than with one KV head per query head. It is the same lever the inference post leans on, decided at architecture time.
- SwiGLU MLP.
W2 @ (silu(W1 @ x) * (W3 @ x)). It is gated and has two up-projections instead of one. It gives lower loss than a plain ReLU MLP of the same size. - Hybrid attention. Most layers attend only to a local window, a few stay global. You get long context without paying quadratic cost in every layer.
life of a token walks one vector through all of this if you want the longer read.
when does generation stop?
Three stopping conditions:
- The model generates a special end-of-sequence (EOS) token.
- The output hits the configured
max_tokenslimit. - The output matches a stop sequence that the caller set, such as
"\n\n".
A repetition penalty does not stop generation. It lowers the logits of tokens that already appeared, so the model repeats itself less.
pretraining
Take 15 trillion tokens of cleaned text. Feed sequences into the transformer. At each position, predict the next token. Compute the cross-entropy loss against the actual token. Backprop. Repeat. (If you want to understand how backprop and the tensor operations underneath this work, building pytorch from scratch walks through it.)
The supervision signal is the text itself.
The model learns whatever is predictable in human-written text: grammar, facts, reasoning patterns, code structure, mathematical notation. No one programs this in. It falls out of the loss.
GPT-2 as a concrete example:
- Dataset: WebText, 40GB of text in slightly over 8 million documents, from Reddit links with at least 3 karma.
- Sizes in the paper: 117M, 345M, 762M and 1,542M parameters.
- Architecture: decoder-only, 1,024-token context window, byte-level BPE tokenizer with 50,257 tokens.
- Cost: OpenAI did not publish it.
- Today: Karpathy's llm.c reproduced the 1.5B model in 2024 in about 24 hours on one 8xH100 node, for about $672.
GPT-4 scale: trillions of tokens, thousands of GPUs, months. Sam Altman said GPT-4 cost more than $100M to train. OpenAI has not published GPT-4's architecture. Leaked reports from 2023 say it is a Mixture of Experts (MoE): each block has several expert FFNs, and a router sends each token to only 2 of them. The same reports (SemiAnalysis, July 2023) put the total at about 1.8 trillion parameters in 16 experts, with about 280 billion active per token. Treat these numbers as rumors. MoE gives you the capacity of a very large model at the per-token compute of a much smaller one. The DeepSeek-V3 post shows the routing code.
MoE: router picks 2 of 8 FFN experts per token per layer
The top-2 experts by router score run. 2 of 8 = 25% of the expert FFN weights per token.
What comes out: a very good autocomplete. Feed it "The capital of France is" and it outputs "Paris" with high probability. Feed it a half-written function and it completes it. Ask it a question and it continues your text instead of answering. The base model has no concept of question vs answer. It learned text continuation.
pretraining is compression
Shannon showed that prediction and compression are the same problem. If a model gives the next token probability p, an arithmetic coder can store that token in about -log2(p) bits. Better prediction = smaller file.
Marcus Hutter took this seriously. The Hutter Prize offers €500,000 to whoever compresses 1GB of English Wikipedia below a target size. The prize bets that compression = intelligence. To compress English text well, you need to model it: grammar, syntax, world facts, coreference, causal structure. A lookup table won't do it. You need a predictor that generalizes.
This is what pretraining produces. DeepMind's "Language Modeling Is Compression" (2023) used Chinchilla 70B as the predictor for an arithmetic coder. It compressed enwik9 (the 1GB Wikipedia file) to 8.3% of its raw size, about 0.66 bits per byte, if you don't count the model's own size. gzip gets 32.3%. Shannon's 1951 experiments put the entropy of English between 0.6 and 1.3 bits per letter.
The weights don't store the internet. They store what predicts the internet. That's why the model knows "The Eiffel Tower is in Paris" without having memorized that specific string. It learned the statistical structure that makes "Paris" the right continuation. It's also why the model hallucinates: it generates the most probable continuation and does not look up stored facts. When training data is sparse on a topic, plausible-sounding text and true text are indistinguishable to the predictor.
Pretraining is where the money goes. Alignment costs a fraction of it. The InstructGPT paper gives the numbers for its 175B model: SFT took 4.9 petaflop/s-days and PPO took 60, against 3,640 for GPT-3 pretraining. That is under 2% of the pretraining compute.
How much data and how large a model to train? That's the Chinchilla question, covered in detail in scaling laws.

post-training: making it an assistant
SFT (supervised fine-tuning)
Curate 10,000-100,000 examples of (prompt, ideal response). Continue training with the same loss function at a much smaller learning rate. The model learns to respond in a useful format.
SFT is cheap. The knowledge is already in the weights; you're redirecting it. The base model knows what "the capital of France" is. SFT teaches it to answer instead of continuing the sentence.
OpenAI says it trained ChatGPT's first SFT model on dialogues that human AI trainers wrote, mixed with the InstructGPT dataset converted to dialogue format. The InstructGPT SFT set has 12,725 training prompts, with demonstrations written by contractors.
The loss is the same next-token loss as pretraining. The input is the prompt followed by the ideal answer, and the loss counts only the answer tokens:
logits = model(prompt + answer) # token IDs in, logits out
loss = cross_entropy(logits[len(prompt)-1:-1], answer)Problem: "ideal" is subjective. Different annotators write different ideal responses. The loss treats every output token equally. It gives no signal for tone, helpfulness, or avoiding harmful content.

Figure: one SFT example in (prompt, response) format, taken from the Stanford Alpaca dataset.
RLHF (reinforcement learning from human feedback)
Code and math have verifiable correct answers. Writing and brainstorming don't, so you need a reward model to score them.
Four steps:
- The SFT model generates several responses to each prompt. InstructGPT showed labelers between 4 and 9.
- Human annotators rank them: A > C > B > D.
- A reward model learns from these rankings. It maps (prompt, response) to one scalar score. For each pair where the labelers preferred over , the loss pushes the preferred score up (a Bradley-Terry model):
- PPO (Proximal Policy Optimization) updates the SFT model to maximize the reward model's score. A KL-divergence penalty stops it drifting too far from the SFT starting point:
The first term maximizes reward. The second term keeps the model close to the SFT model. Without the penalty, the model learns to exploit the reward model and produces unnatural outputs that score high (reward hacking).
RLHF training loop
4-9 responses
A > C > B > D
R(prompt, response)
maximize R − β·KL
| Stage | Purpose | Data | Objective |
|---|---|---|---|
| Pretraining | Learn language | Internet text | Next-token prediction |
| SFT | Follow instructions | (instruction, response) pairs | Supervised loss |
| RLHF | Align to human preference | Ranked responses | Maximize reward |

Figure: the four training stages, their data, compute and objective. The figure's dataset sizes and GPU counts are rough orders of magnitude.
DPO: a simpler alternative to PPO
DPO (Direct Preference Optimization) reframes alignment as supervised learning. Given a preferred response and a rejected response for the same prompt , the loss is:
is the model you train and is the frozen SFT model. is the implicit reward: how much more likely the trained model makes a response than the reference does. No reward model. No RL loop. The reward is implicit in the policy itself. It uses the same preference data as RLHF with far less machinery. Llama 3, Mixtral and Phi-3 use DPO instead of PPO in post-training, and variants such as ORPO and SimPO change the loss further.
PPO keeps four models in memory at the same time: the policy, a frozen reference, the reward model, and a value function. The optimization is fragile and sensitive to hyperparameters. DPO trains on a fixed set of preference pairs, while PPO and GRPO sample new responses during training. For reasoning models, where the reward comes from checking the answer, these online RL methods still dominate.
thinking models
o1 and DeepSeek-R1 are RL-trained to emit reasoning tokens before the final answer. DeepSeek-R1 writes them in a <think>...</think> block and works through the problem step by step before it commits to a response. o1 hides its reasoning tokens from the user.
User: "What is 237 x 194?"
Normal model:
-> "237 x 194 = 45,978" (immediate, sometimes wrong)
Thinking model:
<think>
237 x 194 = 237 x 200 - 237 x 6
237 x 200 = 47,400
237 x 6 = 1,422
47,400 - 1,422 = 45,978
</think>
-> "237 x 194 = 45,978" (verified via reasoning)GRPO: how R1 was trained
DeepSeek-R1 uses GRPO (Group Relative Policy Optimization) instead of PPO. PPO needs a separate critic network to estimate a value baseline. GRPO removes the critic. It samples a group of G responses per prompt and uses the group's own rewards as the baseline:
import numpy as np
# PPO: advantage = reward - V(state), where V is a learned value network
# GRPO: normalize each reward against its own group
rewards = np.array([1.0, 0.0, 0.0, 1.0]) # G=4 responses to one prompt
advantages = (rewards - rewards.mean()) / rewards.std()
print(advantages) # [ 1. -1. -1. 1.]For math and code, where a rule checks the answer as right or wrong, GRPO is simpler: there is no value function to train and no actor-critic mismatch. R1's training worked because "does this answer match the ground truth" is a clean reward signal. The structured chain-of-thought emerged from RL on math problems. The model discovered that working through intermediate steps improved its reward on verifiable answers.
When thinking tokens are worth the cost:
| Task | Use thinking | Reason |
|---|---|---|
| Multi-step math | Yes | Each step is verifiable, RL can optimize |
| Complex code | Yes | Logic chains benefit from working through |
| Factual lookup | No | Answer is in weights, no reasoning path needed |
| Creative writing | No | Chain-of-thought doesn't help creativity |
| Simple Q&A | No | Many times the tokens, no accuracy gain |
Thinking models are expensive: they can spend hundreds or thousands of reasoning tokens before a 50-token answer. For tasks where correctness is verifiable and errors are costly, that overhead is justified. For everything else, the standard model is better value.
decoding: how text gets generated
The model outputs logits: a vector with one float per vocabulary token, about 200,000 floats for GPT-4o. You need a strategy to pick a token.
Autoregressive decode: one forward pass per token
The model reads the whole prompt in one pass. Sampling from a 200,000-token distribution...

Figure: after "I hope you are", the model gives "well" 86% and four other tokens the rest. The decoding strategy decides which token to pick.
greedy search
Always pick the highest-probability token. Deterministic. Fast. Gets stuck in repetitive loops.

Figure: GPT-2 with greedy decoding repeats "I'm not sure if I'll ever be able to walk with my dog". The prompt is from the Hugging Face blog post "How to generate text".
beam search
Keep the B most likely sequences at each step (beam width B, often 3 to 5). Beam search finds sequences with a higher total probability than greedy, at B times the cost. It is still deterministic and often less diverse. Translation and summarization use it, where you want the most likely output and not randomness.

Figure: beam search with B = 3 after the word "How". Each step keeps the three best paths.
multinomial sampling
Sample according to probabilities. This adds randomness: you might pick a low-probability token. It can produce incoherent text if nothing constrains it.

top-K sampling
Pick the top K tokens by probability. Sample from those K. Fixed candidate set size is a problem: sometimes the model is very confident (K=1 is ideal), sometimes uncertain (K=50 makes sense). A fixed K fits neither case.

Figure: top-K with K = 3 keeps "are", "is" and "do" and samples only from those.
top-P (nucleus) sampling
Pick the smallest set of tokens whose cumulative probability reaches p (typically 0.9). The size of the candidate set adapts to the model's confidence.

Figure: with p = 0.88, a confident model keeps one token ("lot", 89%). An uncertain model keeps four (31 + 29 + 24 + 7 = 91%).

Figure: the same GPT-2 prompt with top-p = 0.92 and top-k disabled. The text no longer loops. Source: the Hugging Face "How to generate text" example.
import numpy as np
def top_p_sample(logits, p=0.9, temperature=1.0):
logits = logits / temperature
logits -= logits.max()
probs = np.exp(logits)
probs /= probs.sum()
sorted_idx = np.argsort(probs)[::-1]
sorted_probs = probs[sorted_idx]
cumsum = np.cumsum(sorted_probs)
cutoff = int(np.searchsorted(cumsum, p)) + 1
nucleus_probs = sorted_probs[:cutoff]
nucleus_probs /= nucleus_probs.sum()
chosen_rank = np.random.choice(cutoff, p=nucleus_probs)
return int(sorted_idx[chosen_rank])temperature
Temperature T divides the logits before the softmax:
Temperature < 1.0 sharpens the distribution (model becomes more confident). Temperature > 1.0 flattens it (more random). Temperature approaching 0 approaches greedy. Take the six-token distribution from the top-P widget below, with "Paris" at 0.86 after normalizing. At T = 0.5, "Paris" goes up to 0.99. At T = 2.0, it drops to 0.55.
OpenAI does not publish per-task settings for its own products. The table below is a community rule of thumb, not an official setting:

Using Hugging Face:
from transformers import set_seed
set_seed(42)
output = model.generate(
**model_inputs,
max_new_tokens=40,
do_sample=True,
top_p=0.92,
temperature=0.8,
top_k=0
)Decoding strategy comparison:
| Strategy | Type | When to use |
|---|---|---|
| Greedy | Deterministic | One best answer, formal translation |
| Beam Search | Deterministic | Summarization, a few good candidates |
| Top-K | Stochastic | Chat, creative text, fixed candidate set |
| Top-P | Stochastic | Chat, creative text, dynamic set (modern LLMs) |
Top-P sampling (p=0.9): probability distribution over next token
Paris 85% + Lyon 6% = 91%, which reaches p = 0.9. Nucleus = {Paris, Lyon}. France (4%) and the rest drop out. Sample from the nucleus only.
what happens when you press enter
One request, start to finish.
Request flow: Enter key to first token
POST /v1/chat
TLS, edge
auth/rate
tokenize
moderation
prefill+decode
tokens/sec

Figure: a chatbot request path with safety checks on the prompt and on the response, and session history fed back into the next prompt.
OpenAI does not publish per-stage latencies. The latency column is an illustrative budget, not a measurement:
| Step | Component | What it does | Latency (illustrative) |
|---|---|---|---|
| 1 | Client | POST /v1/chat/completions | - |
| 2 | CDN/Edge | TLS termination, DDoS, geo-routing | ~20ms |
| 3 | API Gateway | Auth, rate limit, route | ~5ms |
| 4 | Backend | Context build, tokenize | ~10ms |
| 5 | Safety | Input moderation classifier | ~12ms |
| 6 | Inference cluster | Prefill + decode | time to first token (TTFT) ~50-200ms, then tokens/sec |
| 7 | Streamer | Server-Sent Events (SSE) chunks to client | overlaps with decode |
| 8 | Safety | Output moderation | ~8ms |
| 9 | Post-processing | Detokenize, log, bill | ~2ms |
1. client
The ChatGPT web app talks to its own backend, but the public API takes the same kind of request. With the API, you send:
{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain transformers."}
],
"stream": true,
"temperature": 0.7,
"max_tokens": 1024
}stream: true makes the server answer with a Server-Sent Events (SSE) stream. Tokens stream back as the model generates them. SSE is one-directional (server to client), which is all you need. WebSockets are bidirectional and add complexity you don't need here. SSE is plain HTTP: one long response that the server keeps writing to.
2. CDN / edge
A content delivery network (CDN) handles TLS termination and DDoS protection at the edge. Both chatgpt.com and api.openai.com answer with server: cloudflare headers. The TLS handshake round trips go to a nearby edge server and not to a far origin.
3. API gateway
The front door. Three jobs. OpenAI does not publish its gateway design, so the details below show a typical design.
First, auth. The gateway validates the API key, for example by hashing it and looking up the hash in a fast key-value store such as Redis. An invalid key returns 401 at once, and no traffic goes deeper.
Second, rate limiting, for example with a token bucket:
Token Bucket:
Rate: 100 tokens/sec
Bucket capacity: 1000 tokens
Request arrives: costs 10 tokens -> allowed
Burst request: costs 500 -> allowed (bucket had space)
Bucket empty -> REJECTED (429 Too Many Requests)Third, routing. The model name decides which GPU cluster gets the request. OpenAI does not publish which GPUs serve which model.
4. backend service
Assembles the full context:
System Prompt (fixed per deployment)
+
Conversation History (retrieved from DB or passed in request)
+
User's new message
+
Any tool call outputs
=
Full Context (up to 128K tokens for GPT-4o)If the conversation history is too long, the backend drops the oldest messages. The backend tokenizes the full context with tiktoken, checks it against the context window limit, and estimates billing.
5. safety layer (input)
Before the expensive model sees anything, a small, fast classifier checks the prompt for hate speech, self-harm, illegal content, and jailbreak attempts. If it flags the prompt, the system rejects the request here and spends no GPU time on the big model.
output safety layer
The output gets a check too. OpenAI does not publish how it moderates output. One design runs output moderation in parallel with streaming (step 7 below), not after it: while the model generates tokens 10-20, the classifier checks tokens 1-9. If it finds a violation mid-stream, the server cuts the response and the client receives an error. Because the check runs in parallel, it adds almost nothing to the total response time.
The finish_reason field in every API response tells you what stopped generation:
"stop": the model generated an EOS token, or the output hit a stop sequence."length": the output hit themax_tokenslimit."content_filter": a content filter flagged the output and removed content."tool_calls": the model called a tool (tool calling is in step 8 below).
If you're building on the API and users report truncated responses, finish_reason is the first thing to check.
6. inference cluster
Two distinct phases for every request (the inference post goes deeper):
Prefill processes the entire input prompt in one forward pass. The transformer attends over all input tokens at the same time. The output is the KV cache: the key and value vectors for every layer and every input token. Prefill is compute-bound.
Decode generates tokens one at a time. Each step runs a forward pass for the new token only and reads the cached K/V from earlier steps. It appends the new token's K/V to the cache, samples, and repeats. Decode is memory-bandwidth-bound: each step reads every weight of the model from GPU memory once, and all sequences in the batch share that read.
Open-source serving uses engines such as vLLM, TensorRT-LLM, or SGLang, not raw PyTorch. These handle batching, KV cache management, and kernel optimization. OpenAI's own engine is not public.
The hardware is NVIDIA A100 (80GB), H100 (80GB), or H200 (141GB) class GPUs. A 100B parameter model at FP16 needs 200GB for the weights alone, so it needs several GPUs. Tensor parallelism splits each layer's matrices (attention heads and MLP) across GPUs; pipeline parallelism splits model depth across nodes.
Model Parallelism:
Node 1: [GPU0] [GPU1] [GPU2] [GPU3] <- Layers 1-48
Node 2: [GPU4] [GPU5] [GPU6] [GPU7] <- Layers 49-96the arithmetic of one request
Put real numbers on prefill and decode with an open model whose config is public. Llama 3 70B has 80 layers, 8 KV heads and a head dimension of 128 (Llama 3 paper, Table 3). Its checkpoint holds 70.6 billion parameters (the Hugging Face model files). An H100 SXM has 80 GB of memory and 3.35 TB/s of memory bandwidth (NVIDIA's H100 spec page).
The KV cache stores a K and a V vector for every layer and every KV head, at 2 bytes per number in BF16:
That is 320 KiB per token.
It adds up to 2.5 GiB for an 8K-token conversation and 40 GiB at 128K tokens, for one user.
The weights take 2 bytes per parameter in BF16, 1 in INT8 and half a byte in INT4 (the quantization section below explains these formats): 141 GB, 71 GB and 35 GB. 141 GB does not fit on one 80 GB H100.
At batch size 1, each decode step reads every weight once to produce one token. So memory bandwidth sets the speed limit:
- BF16 needs two H100s with tensor parallelism. Together they read at 6.7 TB/s: 6.7 TB/s / 141 GB = about 47 tokens/s.
- INT4 (35 GB) fits on one H100: 3.35 TB/s / 35 GB = about 95 tokens/s.
These are upper bounds. Real kernels never reach full bandwidth. Batching shares that one read of the weights across many requests, so 32 users cost almost the same weight traffic as one. That is why continuous batching exists.
7. streaming back
Each token streams back via SSE as the model generates it. Each event is one data: line followed by a blank line (fields shortened here):
data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"The"}}]}
data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" transformer"}}]}
data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" architecture"}}]}
data: [DONE]For a 500-token response at 50 tokens/sec: 10 seconds total. Without streaming you stare at a blank screen for 10 seconds. With streaming you start reading after the first token, about 130ms in the illustrative budget below.
8. post-processing
After generation: detokenize (token IDs back to text), strip control tokens, normalize whitespace, count tokens for billing.
Tool calling (function calling) works like this. When the model needs real-time data, it generates a structured tool call instead of text. In the Chat Completions API, the assistant message carries it, and arguments is a JSON string:
{
"role": "assistant",
"tool_calls": [{
"id": "call_abc123",
"type": "function",
"function": {
"name": "web_search",
"arguments": "{\"query\": \"current weather in Mumbai\"}"
}
}]
}The backend intercepts this, runs the tool, puts the result back into the context, and the model generates its final answer. That's what makes an AI agent: it takes actions in a loop, not just text in response to text. For how retrieval fits into this (RAG, vector search, chunking), see rag.
logging and observability
Every request emits structured metrics at each layer:
request_id: "req_abc123"
user_id: "usr_456"
model: "gpt-4o"
input_tokens: 512
output_tokens: 248
total_latency_ms: 2340
ttft_ms: 210 <- Time To First Token
tps: 116 <- Tokens Per Second during decode
region: "us-east-1"
gpu_node: "h100-node-42"
finish_reason: "stop"
safety_flagged: falseThe record is consistent: 210ms + 248 tokens / 116 tokens per second = about 2,340ms total.
TTFT (time to first token) and TPS (tokens per second) are the two numbers anyone running inference cares about. TTFT measures how quickly you start responding; prefill and queue wait dominate it. TPS measures throughput during decode; model size, quantization, and GPU memory bandwidth dominate it. Optimizing one doesn't improve the other by default. Disaggregated serving exists because prefill and decode respond to different hardware improvements.
full latency breakdown
An illustrative budget for one GPT-4o request ("Explain the transformer architecture", ~400 token response). OpenAI does not publish these numbers. Only the token count comes from a measurement (about 20 input tokens with o200k_base, counting the system prompt and the chat-format overhead):
| Stage | Time |
|---|---|
| CDN / TLS handshake | ~20ms |
| API gateway (auth + rate limit) | ~5ms |
| Backend context build | ~10ms |
| Input safety check | ~12ms |
| Queue wait (continuous batching) | ~30ms |
| Prefill (~20 input tokens) | ~50ms |
| Decode (400 output tokens at 100 tok/s) | ~4,000ms |
| Output safety check | ~8ms |
| Network streaming | ~15ms |
| TTFT (sum of the first six rows) | ~127ms |
| Total wall-clock | ~4,150ms |
The bottleneck is decode. Quantization, speculative decoding, and better hardware all target decode throughput.
inference optimizations
KV cache
Without a cache, decode step n reruns all n previous tokens to rebuild their K/V, which is O(n^2) work for the whole response. With the cache, each step computes K/V for the new token only, and the cache grows in GPU memory (VRAM) by 320 KiB per token for Llama 3 70B (from the arithmetic above). The inference post works through the cache size.
KV cache growing during decode
PagedAttention (from vLLM) stores the KV cache in fixed-size pages with a page table, like OS virtual memory, instead of one large contiguous block per sequence. The vLLM paper measured that older systems used only 20-38% of their KV cache memory for real token states, and vLLM gets 2-4x their throughput at the same latency.
continuous batching
Static batching waits for every request in a batch to finish before it starts the next batch, so one long request holds everyone else. Continuous batching checks at each decode step which sequences are done and fills their slots with new requests at once; the Orca paper (OSDI 2022) reported 36.9x the throughput of NVIDIA FasterTransformer on GPT-3 175B at the same latency.
Static vs continuous batching: GPU slot utilization over time →
Static batching: the whole batch waits for the slowest request
Continuous batching: a new request fills a slot the moment one finishes
Same time span and same request lengths in both charts. Static batching leaves 1.5 slot-units idle and starts 6 requests. Continuous batching leaves none idle and starts 8.
quantization
Quantization stores the weights in INT8 (1 byte) or INT4 (half a byte) instead of BF16 (2 bytes), and GPTQ, AWQ or QLoRA (fine-tuning on a 4-bit base) keep the quality loss small. Decode is memory-bound, so Llama 3 70B drops from 141 GB to 35 GB in INT4, fits on one H100, and decodes faster (see the arithmetic above). The inference post covers the formats in depth.
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
# Load the base model in 4-bit NF4, the storage format QLoRA uses
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-13b-hf",
quantization_config=bnb_config,
)speculative decoding
Each decode step requires one full forward pass through the large model. At 100 tokens/sec for a 4000ms response, the large model is the bottleneck.
Fix: a small draft model generates 4-5 candidate tokens ahead. The large model checks all of them in a single forward pass with rejection sampling. It accepts a draft token x with probability min(1, p(x)/q(x)), where p is the large model's probability and q is the draft model's. Even 3 of 5 accepted is a net win, because the check is one pass and the draft model is fast.
Draft model (small, fast): "The capital of France is Paris."
Large model (70B, slow): check all 6 tokens in ONE pass -> all accepted
Result: 6 tokens, plus 1 bonus token from the same pass, for 1 large-model forward passIf the large model rejects a draft token, it discards the rest of the draft and samples its own token at that position. The output distribution is the same as sampling from the large model alone. Leviathan et al. (2022) measured 2-3x on T5-XXL. Chen et al. (2023) measured 2-2.5x on Chinchilla 70B with a 4B draft model. It works because text is predictable enough that a good small model gets most tokens right.
Speculative decoding: draft 5, verify 1 pass
4 draft tokens accepted, "was" rejected and replaced by the large model's "is". 5 tokens from 1 large-model pass.
flash attention
Standard attention writes the full seq x seq score matrix to slow HBM (high-bandwidth memory, the GPU's main memory) and reads it back: 4096 x 4096 = 16.8 million scores, 32 MiB in FP16, per head per layer. FlashAttention computes the same exact result in tiles that fit in fast on-chip SRAM, keeps a running softmax, and never writes the full matrix to HBM; the paper reported a 3x training speedup on GPT-2 at 1K tokens, and FlashAttention-2 is about 2x faster again. The interview post walks through the kernel.

Figure: bytes read and written (FP16, 2 bytes per number) and FLOPs for each step of standard attention, with N tokens and head dimension d. The N x N matrices S and P make the round trip to HBM.
Standard attention vs Flash Attention: where the matrix lives
Standard attention
HBM (slow DRAM): O(N²) memory
Flash Attention
SRAM (on-chip, fast): O(N) extra memory
Left: full NxN matrix written to slow HBM every layer. Right: 2x2 tiles computed one at a time in fast SRAM, result accumulated, matrix never materialized.
Sparse attention helps for very long contexts. Even with FlashAttention, full attention at 128k tokens costs a lot, because compute still grows as seq^2. Options:
- Sliding window: each position attends only to the last w positions. Compute grows as seq x w instead of seq^2. Mistral 7B uses a 4,096-token window.
- Local/global mix: most layers use a sliding window and a few use full attention. Gemma 2 alternates them; Gemma 3 uses 5 local layers (1,024-token window) for every global layer.
import torch
from transformers import AutoModelForCausalLM
# Using FlashAttention-2 in Hugging Face
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Meta-Llama-3-8B",
attn_implementation="flash_attention_2",
torch_dtype=torch.bfloat16,
)
Figure: a full inference stack, with model performance techniques and serving engines on top of the infrastructure.
cost vs latency tradeoffs
Every production decision is a trade between these three:
| Optimization | Latency | Cost/token | Quality |
|---|---|---|---|
| Larger batch size | higher (more queuing) | lower | unchanged |
| INT4 quantization | lower | lower | slight loss |
| Smaller model (3.5 vs 4) | much lower | much lower | lower |
| More GPUs per request | lower | higher | unchanged |
| Speculative decoding | lower | slightly higher | unchanged |
| Streaming | same total, lower perceived | unchanged | unchanged |
| KV cache reuse | lower | lower | unchanged |
Output tokens cost several times more than input tokens. GPT-4o costs $2.50 per million input tokens and $10.00 per million output tokens, 4x. The model generates output tokens one at a time, while it processes input tokens in parallel. Cached input (a repeated system prompt) is cheaper: $1.25 per million for GPT-4o, half price.
One request with 500 input and 300 output tokens on GPT-4o costs:
If 400 of the input tokens are a cached system prompt, those 400 cost $1.25 per million instead: 100 × $2.50/1M + 400 × $1.25/1M + 300 × $10/1M = $0.00375. (Prices from OpenAI's API pricing page, read on 22 October 2026.) Multiply by your volume, then check whether open weights on your own GPUs beat provider pricing at your scale.
engineering tricks at scale
prompt caching
The system prompt ("You are a helpful assistant...") is identical for every request in a deployment. Computing its KV cache from scratch every time wastes compute.
Cache the KV states for the system prompt once, reuse across all requests:
Without prompt caching:
Request 1: compute KV for [system(400 tokens) + user(100 tokens)] -> 500 tokens prefill
Request 2: compute KV for [system(400 tokens) + user(80 tokens)] -> 480 tokens prefill
With prompt caching:
Startup: compute KV for [system(400 tokens)] -> cached
Request 1: load cached + compute [user(100 tokens)] -> 100 tokens prefill (5x less)
Request 2: load cached + compute [user(80 tokens)] -> 80 tokens prefillOpenAI bills cached input tokens for GPT-4o at half price. Anthropic keeps a cache entry for 5 minutes by default (1 hour as an option) and bills cache reads at a tenth of the base input price for most models. Caching saves both cost and latency, since prefill is compute-bound. The inference post covers prefix caching inside vLLM.
model routing
Not every question needs GPT-4. "What's 2+2?" doesn't need the same compute as "Write a distributed cache in Rust."
A small classifier routes each request to the cheapest model that can handle it. The routes below are illustrative, not OpenAI's:
| Query | Model |
|---|---|
| "Hi" | a small, cheap model |
| "Summarize this email" | GPT-4o-mini |
| "Debug this kernel" | GPT-4o |
| "Prove this theorem" | a reasoning model such as o3 |
OpenAI says GPT-5 in ChatGPT is "a unified system" with a real-time router that picks between a fast model and a reasoning model. The RouteLLM paper (2024) reports more than 2x lower cost from routing, without a drop in response quality.
semantic caching
If 1000 users ask "What is the capital of France?" within an hour, there's no reason to run inference 1000 times.
Embed user queries. Check cosine similarity against a cache. If similarity > 0.95, return the cached response and skip the model.
User: "What's the capital of France?"
-> embed query
-> cosine similarity search against cache
-> match found (similarity=0.97) with "What is France's capital?"
-> return cached response (0ms inference)Breaks for creative or personalized queries: two users asking for a poem should get different answers, not a cache hit.
prefix sharing (RadixAttention)
In multi-turn conversation, every new message re-sends the entire conversation history. The KV cache for previous turns was already computed.
SGLang's RadixAttention stores KV caches in a radix tree indexed by token prefix. New requests sharing a prefix with an old one reuse the cached states:
Turn 1: [system + user_1] -> compute KV, cache
Turn 2: [system + user_1 + assistant_1 + user_2] -> reuse first chunk
Turn 3: [system + user_1 + ... + assistant_2 + user_3] -> more reuseOn turn 3, everything before the newest messages is already in the tree. Prefill runs only on the new tokens, as long as the cache still holds the rest.
disaggregated serving
Prefill and decode have different hardware requirements:
- Prefill is compute-bound (lots of matrix math, GPU cores matter)
- Decode is memory-bandwidth-bound (loading model weights for each token)
Run them on separate GPU pools:
Figure: disaggregated serving puts prefill and decode on separate GPU pools.
Neither pool's workload slows the other. You scale each pool on its own.
chunked prefill
For very long inputs (32k+ tokens), prefill can take seconds and blocks the entire GPU.
Break the input into chunks (e.g., 2048 tokens each) and interleave prefill chunks with decode steps from other requests. This stops long prompts from causing latency spikes for everyone else in the batch.
graceful degradation under load
When traffic spikes (viral tweet about ChatGPT), the system can't crash. An illustrative ladder (OpenAI does not publish its policy):
| Load level | Action |
|---|---|
| Normal | Full model, full context, streaming |
| High | Route new requests to a smaller model |
| Very high | Reduce max_tokens, for example from 4096 to 1024 |
| Extreme | Queue with an estimated wait time |
| Critical | "We're experiencing high demand" |
Priority queuing is a common addition: paying customers go ahead of free users.
evaluation
Perplexity (cross-entropy loss on held-out text) tracks how well a model predicts unseen text. Useful for comparing checkpoints during training. Useless for predicting whether the model gives good answers.
The standard benchmarks share the same failure mode: MMLU (57-subject multiple choice), HumanEval (164 Python problems run against test cases) and GSM8K (math word problems). Once a benchmark matters, labs optimize for it. Training data accumulates benchmark-adjacent content. Labs select checkpoints by score. GPT-4 scored 86.4% on MMLU (5-shot) at launch, and later models score higher. The number goes up without the capability following.
Chatbot Arena avoids this. Real users compare two anonymous models on their actual tasks. No fixed test set. Elo-style ratings come from millions of blind comparisons. When Arena rankings disagree with benchmark rankings, Arena is usually right.
Human evaluation (annotators rating outputs on helpfulness rubrics) is what RLHF trains on. It's also slow, expensive, and biased in a consistent direction: annotators prefer longer and more confident answers, so models learn to sound helpful. For open-ended questions there's no ground truth, and that bias compounds across training.
the full picture
Pretraining a GPT-4 class model costs more than $100M and runs for months on thousands of GPUs. SFT and RLHF need a small fraction of that compute: under 2% for InstructGPT. The ongoing engineering challenge is inference: routing, batching, caching, safety, streaming, and observability for millions of concurrent users.
Next-token prediction on trillions of tokens is a simple objective. The weights that result encode facts, reasoning patterns, and enough of a world model to score in the top 10% on a simulated bar exam (GPT-4). The model generates the most probable continuation regardless of truth.
further reading
- InstructGPT (RLHF in practice)
- LLaMA 3 (training at scale)
- vLLM/PagedAttention (inference at scale)
- FlashAttention-2 (memory-efficient attention)
- Inside the transformer (a token's journey through a modern decoder)
- Quantization explained (ngrok - INT4/INT8 quantization in practice)
- Karpathy - Zero to Hero
- ChatGPT in 200 lines