How Large Language Models Work
What is a Large Language Model?
That simple objective, applied to trillions of words with billions of parameters, produces models that can answer questions, summarise, translate, write code and reason through problems. ChatGPT, Claude, Gemini, Llama, Mistral and Qwen are all LLMs, or chat assistants built on them.
- Large: billions of parameters (weights), trained on trillions of tokens.
- Language: trained mostly on text (many modern models also accept images and audio, and are called multimodal).
- Model: a mathematical function, specifically a transformer neural network.
Tokens & tokenization
LLMs do not read characters or whole words. Text is first split into tokens, which are common chunks of characters: whole words, parts of words, punctuation or spaces. Each token has an integer ID in the model's vocabulary (typically 32,000 to 200,000+ entries).
Example (illustrative; the exact split depends on the tokenizer):
Common words are usually one token; rare words, numbers, code and non-English text are split into more pieces. Spaces are typically attached to the start of the following token.
How tokenizers are built
Most LLMs use subword tokenization, usually Byte-Pair Encoding (BPE) or a close variant (SentencePiece, WordPiece). BPE starts with single characters (or bytes) and repeatedly merges the most frequent adjacent pair into a new token until the vocabulary reaches the desired size. This gives a good balance: frequent words get one token, while any rare word can still be spelled out from smaller pieces, so there is no "unknown word".
Why tokens matter to you
| Topic | Why tokens matter |
|---|---|
| Cost | APIs charge per input token and per output token (output usually costs more). |
| Limits | The context window and maximum output length are measured in tokens. |
| Speed | Generation speed is measured in tokens per second. |
| Language | The same sentence often needs more tokens in languages other than English, so it costs more and fills the context faster. |
| Odd failures | Counting letters ("how many r's in strawberry?") or reversing words is hard because the model sees tokens, not individual characters. |
Embeddings: meaning as numbers
An embedding is a list of numbers (a vector) that represents a token, word, sentence or document. The model learns these vectors so that items with similar meaning end up close together in a high-dimensional space (hundreds to thousands of dimensions).
The famous word2vec result (Mikolov et al., 2013) showed that relationships can appear as directions: \(\vec{king} - \vec{man} + \vec{woman} \approx \vec{queen}\). This works approximately and not for every pair, but it shows that meaning is encoded geometrically.
Closeness is usually measured with cosine similarity, the cosine of the angle between two vectors (1 = same direction, 0 = unrelated, −1 = opposite):
\( \text{cosine}(\mathbf{a},\mathbf{b}) = \dfrac{\mathbf{a}\cdot\mathbf{b}}{\lVert\mathbf{a}\rVert\,\lVert\mathbf{b}\rVert} \)
Embeddings are used inside every LLM (the first layer), and separate embedding models are used for semantic search and RAG.
The transformer
Almost every modern LLM is built on the transformer architecture, introduced by Vaswani et al. in "Attention Is All You Need" (2017). Earlier language models (RNNs and LSTMs) read text one word at a time, which was slow to train and made it hard to connect words far apart. The transformer processes all tokens of the input in parallel and lets every token look directly at every other token through self-attention.
Each block has two main parts:
- Self-attention lets each token gather information from the other tokens it can see.
- Feed-forward network processes each token's vector independently. Research suggests these layers store much of the factual knowledge the model has learned.
Residual connections (adding each sub-layer's input to its output) and normalisation keep training stable when dozens of blocks are stacked. Because attention by itself ignores word order, position information is added. The original paper used fixed sine/cosine patterns; most current LLMs use rotary position embeddings (RoPE).
Self-attention
Consider: "The animal didn't cross the street because it was too tired." To understand "it", the model needs to work out that it refers to "animal", not "street". Self-attention does this by letting the vector for "it" take a weighted mix of the other tokens' vectors, with high weight on "animal".
Mechanically, each token's vector is projected into three vectors:
- Query (Q): what this token is looking for.
- Key (K): what this token offers, used to match queries.
- Value (V): the information this token passes on if selected.
The attention output is then computed as:
\( \text{Attention}(Q,K,V) = \text{softmax}\!\left(\dfrac{QK^{\top}}{\sqrt{d_k}}\right)V \)
The dot products \(QK^{\top}\) score how well every query matches every key; dividing by \(\sqrt{d_k}\) (the key dimension) keeps the scores in a stable range; softmax turns the scores into weights that sum to 1; and the weights are used to average the values. Multi-head attention runs several of these in parallel so different heads can track different relationships (grammar, coreference, topic). In a chat LLM the attention is masked (causal): a token may only attend to tokens before it, never to future ones.
Encoder, decoder, or both
| Type | Sees | Good at | Examples |
|---|---|---|---|
| Encoder-only | The whole input in both directions | Understanding: classification, search embeddings, named-entity recognition | BERT, RoBERTa, many embedding models |
| Decoder-only | Only earlier tokens (causal) | Generating text; general-purpose chat | GPT series, Claude, Llama, Mistral, Qwen, Gemma |
| Encoder-decoder | Encoder reads input; decoder generates output | Sequence-to-sequence tasks: translation, summarisation | Original Transformer, T5, BART |
How LLMs are trained
A chat assistant is made in stages. The first stage creates the knowledge; the later stages teach behaviour.
| Stage | Data | Learning type | Result |
|---|---|---|---|
| Pre-training | Huge unlabelled text corpus | Self-supervised (next-token prediction) | Base model: broad knowledge of language and facts |
| Supervised fine-tuning (SFT) | Curated prompt–response pairs | Supervised | Instruction-tuned model: follows requests |
| RLHF (Reinforcement Learning from Human Feedback) | Human rankings of model answers → a reward model | Reinforcement learning (e.g. PPO) | Answers people prefer; fewer harmful outputs |
| DPO (Direct Preference Optimization) | Pairs of preferred / rejected answers | Optimises preferences directly, without a separate reward model | Similar goal to RLHF, simpler to train |
| RL with verifiable rewards | Maths, code and other tasks whose answers can be checked automatically | Reinforcement learning | "Reasoning" models that think step by step before answering |
Parameters & scaling
The parameter count is the number of learned weights. More parameters let a model store more patterns, but also need more memory and compute.
| Model | Year | Parameters | Note |
|---|---|---|---|
| GPT-1 | 2018 | 117 million | First GPT |
| BERT-Large | 2018 | 340 million | Encoder-only |
| GPT-2 | 2019 | 1.5 billion | Initially released in stages over misuse concerns |
| GPT-3 | 2020 | 175 billion | Few-shot learning from prompts |
| Llama 2 | 2023 | 7B / 13B / 70B | Open weights |
| Mixtral 8x7B | 2023 | 46.7B total, ~12.9B active per token | Mixture-of-Experts |
| Llama 3.1 | 2024 | 8B / 70B / 405B | Open weights, 128k-token context |
Scaling laws (Kaplan et al., 2020) showed that loss falls predictably as a power law when model size, data and compute increase together. The Chinchilla study (Hoffmann et al., 2022) found that many models were under-trained and that, for a fixed compute budget, the number of training tokens should grow in proportion to the parameter count (roughly 20 tokens per parameter). Recent models are often trained on far more tokens than this so that smaller models are cheaper to run.
Many large models now use a Mixture-of-Experts (MoE) design: each block has several feed-forward "experts", and a router sends each token to only a few of them. The model has many parameters in total but uses only a fraction of them for each token.
How text is generated
LLMs generate text autoregressively: one token at a time, with each new token appended to the input for the next step.
Temperature, top-k and top-p
The model outputs raw scores called logits \(z_i\) for every token. These are turned into probabilities with a softmax, where the temperature \(T\) controls how peaked the distribution is:
\( p_i = \dfrac{e^{z_i / T}}{\sum_j e^{z_j / T}} \)
| Setting | What it does | Example (T = 1 values above) |
|---|---|---|
| Greedy (T → 0) | Always pick the most probable token. Deterministic in principle, but can be repetitive. | Always "mat" |
| Temperature | Divides logits by T. T < 1 sharpens, T > 1 flattens. | See Figure 8 |
| Top-k | Sample only from the k most probable tokens. | k = 2 → choose between "mat" and "floor" |
| Top-p (nucleus) | Sample from the smallest set of tokens whose probabilities add up to at least p. | p = 0.8 → mat + floor = 0.78, add sofa → 0.90 ≥ 0.8, so {mat, floor, sofa} |
See Choosing settings for practical values per task.
KV cache: why the first token is slow
When generating token number 500, the keys and values of the previous 499 tokens have not changed. Inference engines therefore store them in a KV cache and only compute Q, K, V for the new token. As a result:
- Processing the prompt (prefill) happens once, in parallel; this determines the time to first token.
- Each later token (decode) is cheaper, but runs one token at a time.
- The KV cache grows with context length and can use many gigabytes of GPU memory for long conversations.
Key terms
- TokenA chunk of text (word, sub-word, symbol) that the model reads and writes.
- VocabularyThe fixed set of all tokens a model knows.
- EmbeddingA vector of numbers that represents meaning.
- TransformerThe neural-network architecture behind LLMs, built on attention.
- Attention headOne parallel attention computation that learns one kind of relationship.
- LogitsRaw scores for every vocabulary token before softmax.
- Base vs instruct modelBase: raw pre-trained model. Instruct/chat: fine-tuned to follow instructions.
- Mixture-of-ExpertsOnly some sub-networks (experts) are used for each token.
Common misconceptions
| Misconception | Reality |
|---|---|
| "The LLM looks things up in a database of the internet." | A plain LLM has no database; its knowledge is compressed into its weights. Search only happens if the application gives it a search tool or RAG. |
| "It reads words letter by letter." | It reads tokens, which is why spelling and counting tasks can go wrong. |
| "Temperature 0 always gives exactly the same answer." | It is close to deterministic, but floating-point and batching effects on GPUs can still cause small differences. |
| "Bigger is always better." | Training data quality, training recipe and fine-tuning matter a lot; a well-trained 8B model can beat an older 70B model on many tasks. |
Next: now that you know how the model works, learn how to use it well in Working with LLMs.
References
Papers
- A. Vaswani et al. (2017). Attention Is All You Need. NeurIPS.
- T. Mikolov et al. (2013). Efficient Estimation of Word Representations in Vector Space (word2vec).
- R. Sennrich, B. Haddow, A. Birch (2016). Neural Machine Translation of Rare Words with Subword Units (BPE for NLP).
- J. Devlin et al. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.
- T. Brown et al. (2020). Language Models are Few-Shot Learners (GPT-3).
- J. Kaplan et al. (2020). Scaling Laws for Neural Language Models.
- J. Hoffmann et al. (2022). Training Compute-Optimal Large Language Models (Chinchilla).
- L. Ouyang et al. (2022). Training language models to follow instructions with human feedback (InstructGPT / RLHF).
- R. Rafailov et al. (2023). Direct Preference Optimization: Your Language Model is Secretly a Reward Model.
- A. Holtzman et al. (2019). The Curious Case of Neural Text Degeneration (top-p / nucleus sampling).
- J. Su et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding.
Books
- Build a Large Language Model (From Scratch) — Sebastian Raschka (Manning, 2024)
- Hands-On Large Language Models — Jay Alammar, Maarten Grootendorst (O'Reilly, 2024)
- Speech and Language Processing (3rd ed. draft) — Dan Jurafsky, James H. Martin. Free online: web.stanford.edu/~jurafsky/slp3
- Natural Language Processing with Transformers — Lewis Tunstall, Leandro von Werra, Thomas Wolf (O'Reilly)
Visual explainers & courses
- The Illustrated Transformer — Jay Alammar
- Attention in transformers, visually explained — 3Blue1Brown
- Transformer Explainer (interactive GPT-2 in the browser, Georgia Tech)
- Intro to Large Language Models and Let's build GPT: from scratch — Andrej Karpathy
- Hugging Face LLM Course
Some other interesting things to know:
- Visit my pages on Machine learning & Deep learning
- Visit my website on Data engineering
- Visit my website on Data, Big Data, Data-modeling, Datawarehouse, SQL, cloud-compute.