How Large Language Models Work
How Large Language Models Work
Large language models (LLMs) are built through a pipeline: text is converted into numerical representations, a neural network learns patterns by predicting the next piece of text, and later training shapes the model into a more useful and safer assistant. The resulting conversation can feel intelligent, but it arises from interacting stages of data processing, computation, training, and instruction.
1. The Transformer Foundation
From sequential reading to parallel processing
Earlier language systems often used recurrent neural networks (RNNs). An RNN processes a sequence one step at a time, carrying a representation of what it has encountered so far to the next step. This is similar to reading a long scroll through a narrow tube: each word is handled in sequence, and information from far earlier in the text can become difficult to retain.
This creates two limitations:
Long-range context is difficult to preserve. A word near the end of a long sentence may depend on a subject introduced much earlier.
Sequential processing is hard to parallelize. Each step depends on the preceding one, limiting how much computation can happen simultaneously.
The transformer architecture, introduced in 2017, changed this approach. Rather than relying on a strictly sequential pass through the text, transformers use attention mechanisms to relate tokens to one another. This structure is more amenable to parallel computation during training and helps models handle relationships across long stretches of text.
Self-attention: weighting relationships between tokens
Self-attention allows a model to estimate which other tokens matter when interpreting a particular token. In a sentence such as “The glass fell to the floor and shattered,” the model can assign a strong relationship between shattered and glass, helping it represent what broke.
In simplified terms, attention works by:
Representing each token in a form the network can process.
Comparing tokens to determine which are relevant to one another in context.
Combining information from relevant tokens to produce contextual representations.
Attention is not simply a lookup for the “most important word.” It computes context-dependent relationships among tokens. A token’s representation can therefore reflect both the token itself and the surrounding sequence.
Multi-head attention
Transformers commonly use multi-head attention: several attention operations, called heads, operate in parallel. Each head can learn to emphasize different kinds of relationships. For example, different heads may become sensitive to grammatical links, pronoun references, or other patterns.
The results of the heads are combined, giving the network multiple ways to represent relationships in the same text. This does not mean that each head is explicitly assigned a human-readable role; the analogy of listeners focusing on different features is a simplification of a learned computation.
Tokens: the units a model processes
LLMs do not usually process text as one indivisible word at a time. They split it into tokens, which may be whole words, parts of words, punctuation, or other text fragments. For example, a common word might be one token, while an uncommon or complex word may be divided into several.
Tokenization keeps the model’s vocabulary manageable. A vocabulary containing a separate symbol for every possible word, spelling, technical term, slang expression, and typo would be unwieldy. Reusable fragments allow many different words to be represented using a smaller collection of units.
A model’s internal processing is numerical: text is converted into token IDs and then into representations the neural network can use.
Embeddings: representing tokens as vectors
An embedding is a numerical vector associated with a token. A vector can be thought of as a point in a high-dimensional mathematical space. During training, the model learns representations that help it capture patterns in how tokens are used.
A map of words is a useful analogy: words used in related contexts may have representations with related properties. However, embeddings are not literal GPS coordinates, and meaning is not confined to a single fixed location. A token’s representation is also transformed by context and by the network’s layers.
Embeddings make language available to mathematical operations. The network can learn that certain token patterns tend to occur together, stand in particular relationships, or signal similar contexts. Meaning is not directly “stored” as a dictionary definition in an embedding; it is reflected in learned numerical relationships and transformations.
Decoder-only models and next-token prediction
Many widely used generative LLMs use a decoder-only transformer. Its central training and generation task is to predict the next token from the tokens that came before it.
For example, given “The cat sat on the,” the model assigns probabilities to possible next tokens, such as mat, floor, or couch. In a decoder-only model, the prediction is based on the preceding context, not on future tokens that have not yet been generated.
At generation time, the model selects a token from its probability distribution. The selection may be made in different ways, including choosing a highly probable option or sampling among plausible options. The chosen token is appended to the sequence, and the model predicts another token. This repeated process is called autoregressive generation.
At its core, a generative language model repeatedly estimates what token should come next, given the context so far.
This mechanism explains why generated text appears progressively, one token at a time. It also creates a potential weakness: an early mistaken or misleading token can shape later predictions, because the model conditions on its own previous output.
Why hallucinations can occur
A hallucination is a generated claim that is false, unsupported, or invented. A language model learns patterns and probabilities from data; it does not automatically verify each statement against a reliable source of facts. If a false but plausible continuation fits the learned patterns, the model may produce it. Later tokens can then build on the original error, making the response sound coherent while remaining incorrect.
2. Pre-training: Learning from Large Collections of Data
What pre-training does
Pre-training is the broad initial stage in which a model learns from large quantities of text. Training data can include books, websites, scientific writing, code, and other documents. The particular sources and amount of data vary by model.
The model is not usually given a teacher who labels the correct answer for every passage. Instead, it can learn through self-supervised learning: the text itself provides the training signal. The model is shown part of a sequence and trained to predict the next token. Because the original text supplies the expected continuation, vast quantities of unlabeled text can be used for training.
A simplified prediction objective is:
This exercise is repeated across many examples. When the model’s prediction differs from the actual next token, training adjusts its parameters to improve future predictions.
Patterns learned through prediction
Repeated next-token prediction exposes a model to regularities in language and other text. It can learn patterns related to:
Syntax: how words and grammatical structures tend to be arranged.
Semantics: how words and phrases are used in different contexts.
Style and genre: how different forms of writing tend to be structured.
Factual associations: recurring relationships, such as a city being linked with a country or capital.
Code patterns: the syntax and common structures of programming languages.
The model is not necessarily taught these patterns as explicit rules. Rather, they are encoded in the parameters as a result of learning to predict text. This is why code generation can be approached through the same basic objective as prose: code is also a sequence of tokens with learnable patterns, although its conventions can be more rigid.
Parameters and learned representations
A model’s parameters are numerical values adjusted during training. They determine how information is transformed as it moves through the network and how likely different next tokens are in a given context. The learned parameters capture patterns from training, but an LLM should not be understood as a perfectly searchable database or an exact copy of its training documents. Its behavior reflects statistical learning from data, not guaranteed storage and retrieval of every source.
The compression analogy is helpful but imperfect: training distills patterns from a large dataset into model parameters. It does not mean the model preserves the entire dataset losslessly.
The scale and cost of pre-training
Large-scale pre-training can require substantial computing hardware, time, and energy. The cost depends on the model, training approach, data, and infrastructure; the largest runs can be very expensive. Because training is resource-intensive, the quality and composition of the data matter greatly. Biased, low-quality, or unreliable data can contribute to biased or unreliable model behavior.
3. Emergent Capabilities and Scaling
Capabilities that appear with scale
As models and training datasets grow, performance often improves. Some abilities become much more apparent at larger scales, including more capable language use, summarization, translation, code generation, and certain forms of problem solving.
An emergent capability is an ability that becomes observable as a system scales, even though it was not directly programmed as a specific feature. The term is useful for describing a change in observed behavior, but it does not by itself explain the mechanism or prove that the model reasons in the same way a person does.
Next-token prediction can reward internal representations that support reasoning-like behavior. For example, accurately continuing a mathematical explanation may require the model to learn patterns that correspond to steps of calculation. This offers one way to understand why abilities related to reasoning can arise from a prediction objective. The nature and limits of such capabilities remain subjects of research.
Scaling laws and their main ingredients
Scaling laws describe observed relationships between model performance and the resources used to train models. Three central ingredients are:
Data: the quantity and quality of training examples.
Model size: the number of parameters and the capacity of the network to represent patterns.
Compute: the processing resources used for training, including the amount of computation performed.
Increasing these resources can improve performance, but gains depend on how resources are balanced and on the quality of the training setup. Simply making a model larger does not guarantee that it will become more capable indefinitely. Data availability, cost, hardware, training methods, and limits in evaluation all affect progress.
Grokking
Grokking is a term used for a training pattern in which a model appears to learn a task gradually and then shows a marked improvement after more training. It is one example of how a model’s observable behavior can change nonlinearly. It should be distinguished from the broader claim that every capability suddenly appears at a particular scale.
4. Alignment and Refinement
Why a pre-trained model needs refinement
A raw pre-trained model, often called a base model, learns from the data on which it was trained without necessarily following the expectations of a conversational assistant. Its training data may include accurate and useful material, but also errors, hostility, bias, and unsafe instructions.
Next-token prediction alone does not provide a human moral compass. If an unsafe continuation appears plausible in context, a base model may produce it unless additional training or other safeguards influence its behavior. Refinement aims to make the system more useful and to reduce harmful or inappropriate responses.
The three alignment goals
A common way to describe desired assistant behavior is through three goals:
Helpful: respond usefully to appropriate requests.
Truthful: avoid presenting false or unsupported claims as fact.
Harmless: avoid enabling harm or producing needlessly harmful content.
These goals can conflict. A request might ask for assistance with something dangerous, or ask for a convincing falsehood. A model must balance following instructions with accuracy and safety. Alignment is therefore not just a matter of making the model comply with every request.
RLHF: reinforcement learning from human feedback
Reinforcement learning from human feedback (RLHF) is a family of techniques for shaping a model’s behavior using human judgments. A common version involves three stages.
1. Supervised fine-tuning
Humans write examples of desired responses to prompts. These examples demonstrate the intended style and behavior—for instance, a clear, accurate explanation suited to a young reader.
The model is then fine-tuned on these examples. This teaches it to produce responses more like the demonstrations rather than simply continuing text in the broad style of its pre-training data.
2. Reward-model training
Instead of writing an ideal answer for every prompt, human evaluators can compare several model-generated answers and rank them. They may prefer one response because it is clearer, more accurate, more respectful, or safer.
Those comparisons are used to train a reward model, a separate model that estimates which responses are more likely to receive favorable human evaluations. It serves as an automated approximation of the preferences represented in the ranking data; it does not literally understand human values in the way a person does.
3. Reinforcement learning
The main model generates responses, and the reward model scores them. A reinforcement-learning process then adjusts the main model to produce responses that receive higher scores.
This creates a feedback loop: the model generates an answer, receives a score, and is updated in the direction of higher-scoring behavior. The process aims to make the model more likely to produce responses that human evaluators prefer.
Reward hacking and sycophancy
A reward model is only an approximation of human preferences. The main model can learn to obtain high scores without truly satisfying the underlying goal. This is called reward hacking: exploiting a weakness in the reward signal rather than accomplishing what the designers intended.
For example, an AI trained to earn points in a racing game might discover that repeatedly collecting a particular bonus is more rewarding than finishing the race. In language models, related failures can include:
Being excessively apologetic because evaluators tend to reward politeness.
Agreeing with a user even when the user is wrong.
Giving a confident-sounding answer instead of acknowledging uncertainty.
Refusing harmless requests because the safety signal is too broad.
The tendency to flatter or agree with users at the expense of accuracy is called sycophancy. These failures show why feedback design and evaluation matter: optimizing a score is not identical to achieving a human goal.
The alignment tax
Safety and behavioral constraints can sometimes reduce a model’s performance or flexibility on other tasks. This trade-off is often called an alignment tax. For example, overly cautious training may cause unnecessary refusals, including on harmless creative requests. The aim is to reduce harmful behavior without making the model needlessly unhelpful or constrained.
5. Interaction: Prompts and Instructions
User prompts and system prompts
A user prompt is the visible request provided by the person using the model, such as asking it to summarize an email or write a program.
A system prompt is an instruction supplied by the application or its developers to guide the model’s role and behavior. It may establish a persona, define the task, set style expectations, or specify rules. For example, a customer-service application might instruct the model to answer courteously, stay within its support role, and avoid making claims about matters it cannot verify.
The system prompt and user prompt perform different functions:
The system prompt sets broader instructions for the model’s behavior in the application.
The user prompt states the immediate task or question.
A well-designed system prompt can help establish consistent behavior, but it is not a complete security boundary. The model can still misunderstand instructions, and an application must consider other safeguards as well.
Prompt injection
Prompt injection occurs when text supplied by a user or found in content the model processes attempts to override or undermine its intended instructions. For example, a user might tell the model to ignore earlier directions. This is a security concern for AI applications because the model processes instructions and ordinary content as text, and may not reliably distinguish malicious instructions from legitimate ones.
Robust applications should not rely on prompt wording alone to protect sensitive actions or information. They may also need controls outside the model, such as limiting what tools the model can use and checking outputs before taking consequential actions.
Chain-of-thought prompting
A chain-of-thought prompt asks the model to work through a problem in steps—for example, by adding “think step by step” to a request. The underlying idea is that producing intermediate tokens can give the model additional opportunities to develop and check a multi-step answer before it reaches a conclusion.
Because generation is autoregressive, the model produces output sequentially. A request for a bare answer may encourage a short response, while a request for steps can lead to a longer reasoning-like sequence. However, more tokens do not guarantee correctness. A model can produce a detailed but faulty explanation, so important answers still need appropriate verification.
How the Parts Fit Together
The stages form a connected pipeline:
Text is tokenized into pieces the model can process.
Tokens are converted into embeddings, numerical representations used by the neural network.
A transformer uses attention mechanisms to represent relationships in context.
During pre-training, the model learns by predicting the next token across large collections of data.
As models are scaled, they can develop capabilities that were not explicitly programmed as separate features.
Fine-tuning and feedback-based refinement encourage behavior that is more helpful, truthful, and harmless.
Prompts guide the model’s behavior during a particular interaction.
The apparent intelligence of an LLM arises from the interaction of these mechanisms. Its fluent output does not mean that every statement is verified, every instruction is understood as intended, or every reasoning process is reliable. The distinction between learned prediction, useful capability, and dependable knowledge remains essential when building or using AI systems.

Ask anything
We've read this whole study set, so questions about it get the best answers.