How Large Language Models Work
How LLMs turn text into tokens, use Transformer attention to predict the next token, learn through pretraining and RLHF, and why they still hallucinate.
A large language model (LLM) is a neural network trained on a vast amount of text to do one thing: predict the next token, a word or piece of a word, given everything before it. It generates a reply by making that prediction, appending the result and repeating, often hundreds of times per answer. Nearly all of today's LLMs are built on the Transformer architecture, whose attention mechanism lets every token draw on the context of every earlier token.
The core idea: next-token prediction
Strip away the interface and an LLM is a function. Text goes in; out comes a probability for every possible next token in its vocabulary. OpenAI described GPT-4 as "a Transformer-based model pre-trained to predict the next token in a document" [13]. Anthropic describes its own models' pretraining the same way: they are "pretrained to predict the next word, given the previous context of text in the document" [4].
That sounds too simple to produce essays and working code. The trick is scale and context. To predict the next word of a legal brief, a physics derivation or a Python function well, a model has to absorb grammar, facts, styles and a good deal of reasoning structure. The GPT-3 paper showed that a large enough model (175 billion parameters) could perform new tasks from just a few examples in the prompt, "without any gradient updates or fine-tuning" [5].
Step by step: what happens when you send a prompt
The diagram traces one pass of inference. Here is each stage.
1. Tokenization
The model never sees letters or words directly. A tokenizer splits text into tokens drawn from a fixed vocabulary and maps each to an integer ID. Most LLM tokenizers use subword units, an approach popularized for neural translation by Sennrich and colleagues, who used byte pair encoding to represent rare words as "sequences of subword units" [2]. Common words become one token; rare words split into several.
OpenAI's rule of thumb for English is that one token is about four characters, or about three-quarters of a word, so 100 tokens is roughly 75 words [3]. Ratios vary by language and by model: Anthropic notes that the characters per token depend on the model and the language [4]. Tokens matter in practice because pricing, speed and context limits are all counted in them.
2. Embeddings and position
Each token ID is looked up in a table that turns it into a long list of numbers, an embedding. Tokens with related meanings end up with similar embeddings. Because attention by itself has no sense of order, the original Transformer added positional encodings so the model knows where each token sits in the sequence [1].
3. The Transformer stack
The embeddings then flow through a stack of identical layers, called Transformer blocks. The 2017 paper that introduced the design described a network "based solely on attention mechanisms," dropping the recurrent layers that earlier language systems used, which made training far more parallel [1]. Each block has two main parts:
- Self-attention. For every token, the model computes how relevant each other token is and blends in information from them. In "The bank raised interest rates," attention lets "bank" draw on "interest rates" and lean toward the financial meaning. Running several attention "heads" in parallel lets the model track different relationships at once [1]. For generation, attention is masked so each position can only look at earlier tokens, never future ones [1].
- Feed-forward network. A small neural network applied to each position separately, which further transforms each token's representation [1].
Each sub-layer is wrapped in a residual connection followed by layer normalization, which helps a deep stack train stably [1]. The original base model stacked six such layers in its encoder and six in its decoder [1]; today's large models use many more. The original Transformer paired an encoder and a decoder for translation [1]. Most of today's generative LLMs, such as the GPT family, keep only a decoder-style stack with masked self-attention, because their job is to continue text one token at a time [5][13].
4. Probabilities over the vocabulary
After the final block, the representation of the last position is projected onto the whole vocabulary and converted, via a softmax function, into a probability for every possible next token, the same step the original paper used to produce "predicted next-token probabilities" [1].
5. Sampling
The model then picks one token. Always taking the single most likely token tends to produce flat, repetitive text, so systems usually sample. Temperature controls how much: lower values give "more conservative and deterministic outputs," higher values more varied ones [4]. Anthropic notes that even at temperature 0, API results are not fully deterministic [4].
6. Repeat
The chosen token is appended to the input and the whole process runs again to pick the next one. This loop, called autoregressive generation, continues until the model emits an end-of-sequence token or hits a length limit. It is why responses stream out word by word, and why the time to first token is a separate performance measure from total generation time [4].
How an LLM is trained
Building a chat model typically involves three stages.
Stage | What the model sees | What it learns | Key reference |
|---|---|---|---|
Pretraining | Huge unlabeled text corpus | Language, facts and patterns via next-token prediction | GPT-3 [5]; Anthropic glossary [4] |
Supervised fine-tuning | Human-written example responses | The format and style of a helpful answer | InstructGPT [8] |
Preference tuning (RLHF and variants) | Human rankings of model outputs | Which answers people prefer; refusal of harmful requests | InstructGPT [8]; Anthropic glossary [4] |
Pretraining is where nearly all the compute goes. The model starts with random parameters and is corrected billions of times as it predicts held-out tokens. The result is powerful but awkward: pretrained models "are not inherently good at answering questions or following instructions" [4].
Fine-tuning and RLHF shape behavior. In the InstructGPT work, researchers fine-tuned GPT-3 on demonstrations, trained a reward model on human rankings, then optimized the model against it with reinforcement learning. Labelers preferred the 1.3-billion-parameter InstructGPT over the 175-billion-parameter GPT-3, despite a 100-fold size gap [8].
Why scale mattered
In 2020, Kaplan and colleagues reported that language model loss "scales as a power-law with model size, dataset size, and the amount of compute used for training," across more than seven orders of magnitude [6]. That gave labs a predictable reason to build bigger. In 2022, the Chinchilla study by Hoffmann and colleagues refined the recipe: for a fixed compute budget, model size and training tokens should grow in equal proportion. Its 70-billion-parameter Chinchilla, trained on about four times more data, outperformed the 280-billion-parameter Gopher on the same compute [7]. Since then, data quality and training method have mattered as much as parameter count.
The context window: an LLM's working memory
An LLM has no memory between requests. Everything it can use in a reply has to sit in its context window: the system instructions, the conversation so far, any documents, tool results and its own output. Anthropic calls it "a 'working memory' for the model," distinct from the training data [9]. In a chat, each turn is appended, so the context grows until it approaches the limit [9].
As of November 2026, Anthropic's documentation lists context windows of up to 1 million tokens for some Claude models and 200,000 tokens for others [9]. Bigger is not automatically better. Anthropic warns that "as token count grows, accuracy and recall degrade," a phenomenon it calls context rot [9], so curating what goes into context matters.
Reasoning models and test-time compute
A newer class of models spends extra tokens thinking before answering. OpenAI introduced o1 in September 2024 as a model "trained with reinforcement learning to perform complex reasoning" that "can produce a long internal chain of thought before responding" [10]. OpenAI reported that performance improved both with more reinforcement learning during training and "with more time spent thinking (test-time compute)" [10]. Several developers now offer comparable "thinking" modes; Anthropic's documentation notes that thinking tokens count toward the context window and are billed as output [9].
Tools and retrieval: getting past the training cutoff
A model's built-in knowledge is frozen at training time. The RAG paper put the problem crisply: LLMs "store factual knowledge in their parameters," but accessing, updating and citing that knowledge is hard [12]. Two techniques help:
- Retrieval-augmented generation (RAG) fetches relevant documents at query time and places them in the context so the model can ground its answer [4][12].
- Tool use (function calling) lets the model ask the application to run a function, such as a search, a calculator or a database query, and read the result. In Anthropic's API, the model returns a structured
tool_userequest, the application runs it and sends back atool_result[15]. Tool use is the foundation of AI agents.
What LLMs are good and bad at
Strong at | Weak at |
|---|---|
Drafting, summarizing and rewriting text | Guaranteeing factual accuracy |
Translating and explaining code | Knowing events after their training data, without tools |
Following format instructions | Precise arithmetic over long chains without tools |
Answering questions about supplied documents | Admitting uncertainty consistently |
Adapting from a few examples in the prompt [5] | Recalling details buried in very long contexts [9] |
Why they hallucinate
NIST calls the problem confabulation: "confidently stated but erroneous or false content" [14]. OpenAI researchers trace it to two causes. Pretraining text carries no true or false labels, so rare facts "cannot be predicted from patterns alone," and benchmarks reward lucky guesses over saying "I don't know" [11]. Their proposed fix is to "penalize confident errors more than you penalize uncertainty" [11]. In practice, grounding answers in retrieved sources and asking for citations reduces the problem but does not remove it.
How to choose and use an LLM
- Match the model to the job. Smaller, faster models suit classification and simple extraction; larger or reasoning models suit multi-step analysis and coding.
- Count tokens, not words. Context size and price are both measured in tokens [3][9].
- Ground important answers. Use retrieval or tools for anything that must be current or exact.
- Test on your own data. Public benchmarks rarely reflect a specific workload.
- Keep a human check on outputs that carry legal, medical or financial weight.
Outlook
The next step is less about bigger single models and more about what surrounds them: longer and better-managed context, more test-time reasoning, and models that call tools in a loop to complete tasks. That last shift is covered in our guide to agentic AI. Expect the core mechanism, a Transformer predicting one token at a time, to stay recognizable even as everything around it changes.
Frequently asked questions
Do LLMs understand language?
They model language statistically at a scale that captures a great deal of meaning, which is why they can follow instructions and explain ideas. Whether that counts as understanding is debated. In practice, they lack a built-in way to check claims against the world, which is why they can be fluently wrong.
What is a parameter?
A parameter is one of the adjustable numbers inside the network, mostly the weights in attention and feed-forward layers. Training sets their values. GPT-3, for example, had 175 billion [5]. Parameter count alone is a poor guide to quality, as the Chinchilla and InstructGPT results show [7][8].
What is the difference between an LLM and a chatbot?
The LLM is the underlying model. A chatbot is an application that wraps it with instructions, a conversation interface, safety filters and often tools or retrieval. The same LLM can power many different products.
Why do I get different answers to the same question?
Generation involves sampling from a probability distribution, controlled by settings like temperature [4]. Even at the lowest setting, Anthropic notes, API outputs may vary between calls [4].
Can an LLM learn from my conversation?
Within a conversation, it can use anything in its context window. It does not update its parameters as you chat. Whether your data is later used to train future models depends on the provider's policies and your settings.
Sources
- Vaswani et al., "Attention Is All You Need," arXiv:1706.03762. https://arxiv.org/abs/1706.03762
- Sennrich, Haddow, Birch, "Neural Machine Translation of Rare Words with Subword Units," arXiv:1508.07909. https://arxiv.org/abs/1508.07909
- OpenAI Help Center, "What are tokens and how to count them?" https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them
- Anthropic, "Glossary." https://platform.claude.com/docs/en/about-claude/glossary
- Brown et al., "Language Models are Few-Shot Learners," arXiv:2005.14165. https://arxiv.org/abs/2005.14165
- Kaplan et al., "Scaling Laws for Neural Language Models," arXiv:2001.08361. https://arxiv.org/abs/2001.08361
- Hoffmann et al., "Training Compute-Optimal Large Language Models," arXiv:2203.15556. https://arxiv.org/abs/2203.15556
- Ouyang et al., "Training language models to follow instructions with human feedback," arXiv:2203.02155. https://arxiv.org/abs/2203.02155
- Anthropic, "Context windows." https://platform.claude.com/docs/en/build-with-claude/context-windows
- OpenAI, "Learning to reason with LLMs" (September 12, 2024). https://openai.com/index/learning-to-reason-with-llms/
- OpenAI, "Why language models hallucinate" (September 5, 2025). https://openai.com/index/why-language-models-hallucinate/
- Lewis et al., "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks," arXiv:2005.11401. https://arxiv.org/abs/2005.11401
- OpenAI, "GPT-4 Technical Report," arXiv:2303.08774. https://arxiv.org/abs/2303.08774
- NIST, "Generative Artificial Intelligence Profile," NIST AI 600-1. https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.600-1.pdf
- Anthropic, "Tool use with Claude." https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview