How LLMs Actually Generate Text — The Full Inference Pipeline
INPUT
TOKENIZER text → integers
EMBEDDING + POSITIONAL ENCODING the step everyone skips
sinusoidal / learned / RoPE
d_model = 4096
Attention is order-blind — without position, “dog bites man” = “man bites dog”. Modern models (Llama, Qwen) rotate Q/K by position (RoPE) instead of adding vectors.
TRANSFORMER BLOCK × N layers (32–120)
A) Multi-head self-attention
causal: no future
KV cache (per layer)
past K,V stored — only the new token is computed
d_model × d_ff→ →Linear
d_ff × d_model →Add & LayerNorm ×96 layers in GPT-4-class models
LM HEAD linear + softmax
d_model × 128K→
The model’s entire output = one probability per vocabulary token. Nothing else.
SAMPLING picking one token
SPECULATIVE DECODING speed trick
small, fast → Theskylooksgreen → target model
verifies in 1 pass → ✓✓✓✗
accepted prefix kept, wrong tail regenerated — same distribution, fewer slow steps
DETOKENIZER integers → text
STREAMING OUTPUT then loop back to step 4
one token at a time, appended to the context, until a stop token