How does an LLM generate text?
How does a large language model generate text?
TL;DR
An LLM is a transformer neural network trained to predict the next token. Text is split into tokens, each token becomes a vector (an embedding), and stacked transformer layers use attention to build context-aware representations. The final layer outputs a probability distribution over the vocabulary for the next token. Generation is autoregressive: pick a token (the sampling step), append it, and repeat until a stop token or a length limit. Chat models start from a pretrained base and are then post-trained (instruction tuning, then RLHF-style preference training) to follow instructions and be helpful and safe.
Key points
- Pretraining: next-token prediction on huge text corpora. This is where knowledge and language ability come from.
- Post-training: supervised fine-tuning on instruction-and-answer examples, then preference optimization (RLHF, DPO), and for reasoning models, reinforcement learning on verifiable tasks.
- The model has no memory between calls: everything it knows about the conversation must be in the context window on each request.
- Knowledge cutoff: it knows nothing after its training data unless you provide it (RAG, tools).
- Output is probabilistic, so the same prompt can give different answers unless sampling is deterministic.
- Prefill vs decode: the prompt is processed in parallel (prefill), then output tokens are generated one at a time (decode), which is why output tokens dominate latency.
Example
Input: "The capital of France is"
Model: P(" Paris") = 0.92, P(" a") = 0.02, P(" located") = 0.01, ...
Pick " Paris" → append → predict the next token → ... → stopCommon follow-ups
- Why are LLMs bad at counting letters? They see tokens, not characters: "strawberry" may be two or three tokens.
- Does the model "understand"? It learns rich statistical representations that generalize well, but it has no ground truth check, which is why it can hallucinate confidently.
What interviewers look for
Tip
Tokens → embeddings → transformer layers → next-token distribution → sampling loop, plus pretraining vs post-training and statelessness.
- Red flag: "the model looks up answers in a database."