From keyboard to token
The exact, complete trace of a message. No metaphors, no summaries. Everything that happens, in order, from the moment you let go of the Enter key until you see the last letter of the answer.
The example numbers come from a real large model (GPT-4 / Claude / LLaMA 70B class). In square brackets, the equivalent in your model from stage 06.
0. Before you type anything
The model already exists. Somebody spent months and millions producing a file of weights. That file is loaded into the memory of several GPUs and it does not change.
It does not learn from you. It does not remember the previous conversation. Between your message and somebody else's there is no difference at all as far as it is concerned. It is a fixed mathematical function: numbers in, numbers out.
Everything that looks like memory, personality or learning happens outside the model: in the text the server sends it again every time.
1. The browser sends the message
POST /api/chat
{
"mensajes": [
{"rol": "sistema", "contenido": "Eres un asistente útil..."},
{"rol": "usuario", "contenido": "¿Qué es un token?"}
],
"temperatura": 0.7,
"max_tokens": 1024
}
Nothing special: it is an ordinary HTTP request.
[In the project: etapas/11_servidor_chat/servidor.py, do_POST.]
2. The server builds the prompt with the CHAT TEMPLATE
This step is invisible and it determines an enormous amount. The list of messages gets turned into a single string of text:
<|im_start|>system
You are a helpful assistant...<|im_end|>
<|im_start|>user
What is a token?<|im_end|>
<|im_start|>assistant
Key points:
- Each model family has its own template. ChatML (OpenAI),
[INST]...[/INST](Mistral),<|start_header_id|>(LLaMA 3). Using the wrong one raises no error at all: it simply degrades quality, sometimes enormously. It is one of the most common causes of "this model is terrible" when in fact it is being invoked wrongly. - The string ends open, right after the assistant marker. The model only knows how to continue text: we are leaving the turn started so it completes it. The entire "conversation" is this trick.
- The system message is not special. It is text that goes first. Its power comes from the model having been trained to obey what appears there, not from any separate mechanism.
[In the project: ServicioChat.construir_prompt. Our template: <|usuario|>...<|asistente|>.]
3. Tokenization
The string is split into tokens and each one becomes an integer.
"What is a token?"
-> ['What', ' is', ' a', ' token', '?']
-> [3923, 374, 264, 4037, 30]
- 100 words of English is roughly 130-150 tokens.
- Those integers are indices into a table. They mean nothing on their own.
- This is where you get billed. API pricing is per token, in and out.
[In the project: etapas/01_tokenizador/bpe.py. Our model uses characters, so each letter is a token.]
4. Context check
prompt tokens + tokens to generate ≤ context window
If it does not fit, something has to go. The options are all bad:
| Strategy | What you lose |
|---|---|
| Truncate from the front | the first turns of the conversation |
| Truncate from the back | the current question (nobody ever does this) |
| Summarize the old part | nuance, and you spend another model call |
| Retrieve only what is relevant (RAG) | whatever the search does not find |
This is exactly what people perceive as "it has forgotten what I told it at the start". There is no forgetting and no degradation: there is a truncation. The text stopped existing as far as the model is concerned.
[In the project: the while len(ids) > limite loop in construir_prompt, and the turnos_recortados field the API returns.]
5. PREFILL
All the prompt tokens go into the model at once. For each one:
- Embedding: the integer
4037becomes vector 4037 from the table. At dimension 8192, that is 8192 numbers. [128 numbers.] - Position: the information about which position it is in gets added (or rotated in, with RoPE).
- 80 transformer blocks, each one: [4 blocks.]
- LayerNorm → causal multi-head attention → add to the residual
- LayerNorm → MLP (expand ×4, GELU, contract) → add to the residual
- The keys and values of each layer are stored in the KV cache.
This phase is parallel (we already know all the tokens) and it is limited by compute. That is why a 10,000-token prompt takes considerably longer than a 100-token one to produce the first word: it is the famous "time to first token".
[In the project: MotorGPT.generar, the for t in ids_inicio loop.]
6. The output: a probability distribution
After the last layer and the output projection, the model produces one number for every token in the vocabulary:
logits = [2.31, -0.44, 5.12, ...] 128,256 numbers [65 numbers]
A softmax is applied and it turns into probabilities that add up to 1:
- P = 1
- loss 0. You knew it
- P = 0,5
- loss 0.69. You were torn between two
- P ≈ 0
- huge loss. You were sure, and you were wrong
- perplexity = eL
- how many options the model is hesitating between, on average
P(" A") = 0.31
P(" It") = 0.18
P(" The") = 0.09
...
This is the key moment almost nobody understands. The model has not "decided" anything. It has produced a probability distribution over the next token. No more and no less. Its job ends here.
[In the project: etapas/08_inferencia/01_muestreo.py shows you this distribution, token by token, with real numbers.]
7. SAMPLING: picking one
This is no longer the model's doing, it is the code wrapped around it:
- Temperature: divide the logits by T. Low = predictable, high = creative.
- Top-k / top-p: discard the tail of improbable options.
- Penalties: lower the probability of what has already been said.
- Roll the dice over what is left.
All of the system's randomness lives here. It is the reason the same prompt gives different answers.
[In the project: the muestrear function in etapas/06_transformer/gpt.py.]
8. DECODE: token by token, in a loop
The chosen token gets added to the context and round we go again — but now only the new token is processed, because the past is in the KV cache.
while <end> has not come out and the limit is not exhausted:
run the model with 1 token
get logits
sample
add to the cache
This phase is strictly sequential: you cannot compute token 5 without having chosen token 4. And it is limited by memory bandwidth: to produce one token you have to read all the model's weights out of memory.
A 70B model in fp16 takes 140 GB. A GPU with 3 TB/s of bandwidth cannot exceed 3000/140 ≈ 21 tokens per second per sequence, whatever it does. That is physics, not software.
That is why quantization exists (fewer bytes to read) and speculative decoding (a small model proposes, the large one verifies several at once).
[In the project: MotorGPT.paso, and the 17× speedup measured in etapas/08_inferencia/02_kv_cache.py.]
9. STREAMING: sending it as it is generated
Each token is decoded to text and sent to the browser over an SSE stream:
data: {"tipo":"texto","texto":" A"}
data: {"tipo":"texto","texto":" token"}
The detail everybody skips: a token can be half a character. In UTF-8 'ñ' is two bytes, and a byte-level tokenizer can split them across two tokens. If you send the first one on its own, the browser draws �.
You have to accumulate bytes and emit only what decodes cleanly.
[In the project: the DecodificadorEnStreaming class, which really implements it.]
10. The end
The loop ends when:
- the model generates the end-of-turn token (
<|im_end|>,<|eot_id|>,<|fin|>) — that is a learned decision: during SFT it was taught to shut up there; max_tokensis reached;- the context window is exhausted;
- the user cancels.
The server closes the stream. The KV cache is freed. The model is back exactly as it was.
The journey, at a glance
YOU SERVER MODEL
│ │ │
├─ "What is a token?" ──>│ │
│ ├─ chat template │
│ ├─ tokenize -> [3923,374…] │
│ ├─ does it fit the context? │
│ ├──── prefill (parallel) ────>│
│ │ ├─ 80 layers
│ │<─── logits + KV cache ──────┤
│ ├─ sample -> " A" │
│<──── " A" ─────────────┤ │
│ ├──── 1 token (sequential) ──>│
│ │<─── logits ─────────────────┤
│ ├─ sample -> " token" │
│<──── " token" ─────────┤ │
│ ... │ ... │
│<──── <end> ────────────┤ │
The five things to take away
- The model has no memory. The server resends it the whole conversation every time. What looks like memory is a
forloop over a list of messages.
- The model does not choose words. It produces a probability distribution. The choice is made by the sampler, which is perfectly ordinary code.
- The chat template is part of the contract. Getting it wrong degrades the model without raising any error.
- Generating is slow because of memory, not computation. Prefill is fast; decoding goes token by token, reading the entire model every time.
- Everything is text in one single sequence. Your instructions, what the user writes, what a tool returns and what the model itself generates are tokens indistinguishable from one another. That is where prompt injection comes from, and that is why it is such a hard problem: there is no structural separation to restore, there never was one.
Next: 02-como-nace-un-modelo.md — where those weights come from.