How Large Language Models Actually Work: Tokens, Attention and Why They Hallucinate

Jump to comments

A wooden composing stick filled with metal type, set into a case of hundreds of individual cast letters
A composing stick filled with metal type sits in a case of cast letters, spelling out a pangram about typography.
Photo: Willi Heidelbach, 2004, via Wikimedia Commons (CC BY 2.5)

You type a question, and a paragraph comes back that sounds as if a person wrote it. There isn’t a mind on the other side of the screen. A large language model is a statistical machine that has learned, from a huge amount of text, which token is likely to come next. It repeats that guess until the answer is finished.

The short answer: Text is chopped into tokens, each token is turned into a list of numbers called an embedding, and a stack of transformer layers uses attention to decide which earlier tokens matter for the next guess. The original transformer, described in 2017’s Attention Is All You Need, had about 65 million parameters and reached 28.4 BLEU on WMT 2014 English-to-German. GPT-3, in 2020, scaled a decoder-only version of that idea to 175 billion parameters, trained on 300 billion tokens, with a 2,048-token context window. A 2022 DeepMind study then showed that model size and training data should grow together: their 70-billion-parameter Chinchilla model, trained on 1.4 trillion tokens, beat a much larger model trained on far less text. After pretraining, models are often fine-tuned with human feedback so they follow instructions. They still hallucinate, because the training objective rewards a fluent next token, not a checked fact. Book prices as of November 20, 2026.

Tokens: how a model chops up language

A model does not read words the way a person does. It first splits the incoming text into tokens, the small chunks it actually computes on. A token may be a whole common word, a piece of a rarer word, a punctuation mark, or a space plus a word. The same letters can become different tokens if a leading space or a capital letter changes.

The 2017 transformer paper encoded English-German sentences with byte-pair encoding, a method that starts from characters and repeatedly merges the most common pairs. That shared source-target vocabulary had about 37,000 tokens. For English-French, the authors used a 32,000-token word-piece vocabulary and a dataset of 36 million sentence pairs. Later GPT models switched to a byte-level version of the same idea, so the tokenizer can represent any Unicode string without unknown-word gaps. OpenAI’s documentation gives a rough rule for ordinary English: one token is about four characters, or about three-quarters of a word, so 100 tokens are about 75 words. That is an estimate, not a conversion factor, and other languages, code and numbers can be much less efficient. Tokenization also sets the unit for context windows and API bills: a prompt that looks short in words can be long in tokens.

Embeddings: turning tokens into numbers

Once the text is a sequence of token IDs, each ID is replaced by an embedding: a learned list of numbers that stands for that token. In the base transformer, every embedding and every layer output had 512 dimensions. In GPT-3, that width grew to 12,288. Tokens that appear in similar contexts tend to land near one another in that space, which is why older word-vector methods such as Word2Vec, introduced by Tomas Mikolov and colleagues in 2013, could already capture analogies of the "king is to queen as man is to woman" sort. In a modern model the embedding is only a starting point. After it passes through the layers, the representation of a word depends on the sentence around it, so "bank" in a river and "bank" in a loan are no longer the same point.

A raw bag of embeddings still has a problem: attention, by itself, does not know order. The 2017 paper added sinusoidal positional encodings so the model could tell the first token from the twentieth. The authors also tried learned position embeddings and found nearly identical results, but kept the sinusoidal version because it might extend to sequences longer than those seen in training.

Attention and the transformer

Diagram of the transformer architecture, showing stacked encoder and decoder blocks with multi-head attention and feed-forward layers
A diagram of the full transformer architecture, with the encoder stack on the left and the decoder stack on the right.
Diagram: dvgodoy, 2021, via Wikimedia Commons (CC BY 4.0)

Before 2017, the leading translation models were recurrent networks. They read a sentence from left to right, or in both directions, and had to carry information through a chain of hidden states. Attention had already been added as a helper, so a decoder could look back at the source sentence. The Google Brain and Google Research team of Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser and Illia Polosukhin went further and threw the recurrence away.

We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely.

Vaswani et al., Attention Is All You Need, 2017

That line is from the abstract of Attention Is All You Need. The payoff was practical as well as conceptual. Recurrent steps are sequential: token two cannot be processed until token one is done. Self-attention can be computed in parallel across a sequence, which is why the same paper could train a strong translation model in hours rather than weeks.

What attention actually computes

At each position, the model builds three vectors from the incoming representation: a query, a key and a value. The query at one position is compared with the keys at every position, the scores are scaled and turned into weights, and those weights are used to mix the values. In the paper’s terms, attention is the softmax of the query-key products, divided by the square root of the key dimension, multiplied by the values. The scaling matters: without it, the dot products grow with the dimension and the softmax becomes extremely peaked, which makes gradients hard to use.

One attention head can only look at the sequence in one way, so the authors used multi-head attention: several smaller attentions run in parallel, then their outputs are concatenated and mixed. In the base model there were 8 heads, each with a key and value dimension of 64, because 512 divided by 8 is 64. The total cost stayed close to that of a single full-width head, but the heads could specialize. In the paper’s visualizations, some heads in layer 5 of 6 tracked a long-distance verb phrase such as "making…more difficult," and others appeared to resolve pronouns such as "its."

Detailed diagram of encoder self-attention, showing how queries, keys and values are compared across positions in a sequence
A detailed diagram of encoder self-attention, the operation that lets every token look at the others in the sequence.
Diagram: dvgodoy, 2021, via Wikimedia Commons (CC BY 4.0)

The rest of the block

Each encoder layer had two sub-layers: multi-head self-attention, then a position-wise feed-forward network applied at every position. The inner width of that network was 2,048, four times the 512-dimensional model width. A residual connection and layer normalization wrapped each sub-layer. The encoder was a stack of 6 such layers. The decoder was also 6 layers, with a third sub-layer that attended over the encoder’s output, and with a causal mask so a position could not look at future tokens. GPT-style language models later kept that mask, dropped the encoder, and predicted the next token from the left side of the sequence only.

The base model had about 65 million parameters. A "big" variant used a width of 1,024, a feed-forward width of 4,096, 16 heads and a higher dropout rate, for about 213 million parameters. Both were trained on one machine with 8 NVIDIA P100 GPUs. The base model took about 0.4 seconds per step and ran for 100,000 steps, or 12 hours. The big model took about 1.0 second per step and ran for 300,000 steps, or 3.5 days. On WMT 2014 English-to-German, the big model reached 28.4 BLEU, more than 2 BLEU above the previous best results, including ensembles. On English-to-French it reached 41.8 BLEU, a new single-model state of the art at the time, after those 3.5 days on eight GPUs.

Those numbers look small next to later language models, but the design is the one those models still use. What changed is scale, the training objective, and the decision to keep only the decoder stack for open-ended generation.

Pretraining: learning to guess the next token

A translation transformer is trained to turn a source sentence into a target sentence. A large language model is usually trained on a simpler game: given a stretch of text, predict the next token. Do that across a huge corpus, and the model has to pick up grammar, facts, style and a surprising number of skills, because all of them help it guess what comes next. This stage is pretraining. The labels are just the next tokens already in the text.

OpenAI’s 2020 paper Language Models are Few-Shot Learners, by Tom B. Brown and colleagues, is the clearest public snapshot of that idea at scale. GPT-3 used the same style of architecture as GPT-2, with some layers using dense attention and others using locally banded sparse attention. The flagship model had 175 billion parameters, which the authors described as 10 times more than any previous non-sparse language model: 96 layers, a width of 12,288, 96 attention heads of dimension 128, and a context window of 2,048 tokens. The paper’s compute appendix counts the same model at 174.6 billion parameters. The authors also trained seven smaller copies, from 125 million parameters up to 13 billion, so they could watch how performance changed with size. Every one of those eight models was trained for 300 billion tokens.

The training mix was not raw web crawl. Filtered Common Crawl contributed 410 billion tokens and 60 percent of the mix, but was seen for only 0.44 of an epoch in a 300-billion-token run. WebText2 contributed 19 billion tokens at 22 percent, Books1 12 billion at 8 percent, Books2 55 billion at 8 percent, and English Wikipedia 3 billion at 3 percent. Some of those smaller, cleaner sources were seen more than once; the noisier crawl was not. The paper’s compute appendix estimates the 175-billion-parameter run at 3.14 × 10^23 floating-point operations, or 3,640 petaflop/s-days, against tens of petaflop/s-days for a 1.5-billion-parameter GPT-2 model.

GPT-3’s headline result was not a new fine-tuning recipe. For every task in the paper, the 175-billion-parameter model was used without gradient updates. The task and a few examples were written into the prompt, and the model completed the text. That is in-context learning, and it is why the 2,048-token window mattered: few-shot examples have to fit beside the question. The model was strong on many language and reasoning checks, produced news-article samples that human evaluators often failed to tell from real articles, and, as the authors noted, could also absorb biases and occasional test-set contamination from a web crawl.

The Chinchilla correction

GPT-3, and several models that followed it, treated 300 billion training tokens as a kind of default and spent extra compute on more parameters. A 2020 OpenAI paper on scaling laws, by Jared Kaplan and colleagues, had encouraged a version of that tradeoff: given a 10-times-larger compute budget, it suggested growing the model about 5.5 times and the data only about 1.8 times. In 2022, Jordan Hoffmann, Sebastian Borgeaud and colleagues at DeepMind re-ran the question with a much larger experiment.

Their paper, Training Compute-Optimal Large Language Models, reports results from more than 400 language models, from 70 million to over 16 billion parameters, trained on 5 to 500 billion tokens. The conclusion was blunt. For compute-optimal training, model size and training tokens should be scaled equally: if you double the model, you should also double the data. Under that rule, many of the era’s flagship models were too big for the amount of text they had seen.

They tested the claim by training Chinchilla, a 70-billion-parameter model, on 1.4 trillion tokens, using the same compute budget as Gopher, DeepMind’s earlier 280-billion-parameter model trained on 300 billion tokens. Chinchilla outperformed Gopher, GPT-3, Jurassic-1 (178 billion parameters) and Megatron-Turing NLG (530 billion parameters) on a wide range of downstream tasks, and reached 67.5 percent average accuracy on the MMLU benchmark, more than 7 percentage points above Gopher. Because it was four times smaller than Gopher, it was also cheaper to fine-tune and to run. The 1.4 trillion tokens and 70 billion parameters are a ratio of 20 tokens per parameter, often called a "Chinchilla ratio," though the paper itself states the rule as equal scaling, not as a magic constant. The practical lesson has lasted: a smaller model trained on enough text can beat a larger model that ran out of data.

Model and yearParametersData seen in training
Transformer, base (2017)65 millionAbout 4.5 million English–German sentence pairs
GPT-3 (2020)175 billion300 billion tokens
Gopher (2021)280 billion300 billion tokens
Chinchilla (2022)70 billion1.4 trillion tokens

Fine-tuning and RLHF: teaching the model to be useful

Pretraining produces a model that is good at continuing text. That is not the same as being a helpful assistant. Left alone, a pretrained model may ramble, ignore a request, complete a toxic prompt in kind, or invent a confident answer. The gap is the one Long Ouyang and colleagues named in OpenAI’s 2022 paper Training language models to follow instructions with human feedback: predicting the next token on a webpage is a different objective from following a user’s instructions helpfully and safely.

Their method, now usually called reinforcement learning from human feedback, or RLHF, had three stages. First, a team of about 40 contractors wrote demonstration answers, and the researchers fine-tuned GPT-3 on those demonstrations with ordinary supervised learning. Second, the contractors ranked several model outputs for the same prompt, and a reward model was trained to predict which answer a labeler would prefer. Third, the supervised model was fine-tuned again with reinforcement learning, using the Proximal Policy Optimization algorithm, to raise the score assigned by that reward model. The resulting models were called InstructGPT.

The preference results were striking. On the authors’ test prompts, outputs from a 1.3-billion-parameter InstructGPT model were preferred to outputs from the 175-billion-parameter GPT-3, despite having over 100 times fewer parameters. The 175-billion-parameter InstructGPT was preferred to GPT-3 85 ± 3 percent of the time, and preferred 71 ± 4 percent of the time even when GPT-3 was given a few-shot prompt that asked it to follow instructions. InstructGPT also made up information less often on closed-domain tasks, with a 21 percent hallucination rate against 41 percent for GPT-3, and on the TruthfulQA benchmark it produced truthful and informative answers about twice as often as GPT-3.

Those gains come with limits the paper does not hide. The model is aligned to the preferences of a particular group of labelers and researchers, not to a universal idea of human values, and it still makes simple mistakes. Other labs have since used further preference-tuning recipes, but the structural point is the same. Pretraining teaches the texture of language. Fine-tuning, especially with human comparisons, teaches the model which continuations people actually want.

As an Amazon Associate, Aglena earns from qualifying purchases.

Inference: how a trained model writes

Once the weights are fixed, using the model is called inference. The model still works one token at a time. It reads the prompt, plus any tokens it has already written, and produces a probability distribution over the vocabulary for the next token. A decoding method then picks from that distribution, the chosen token is appended, and the step repeats until the model emits a stop pattern or hits a length limit.

If the system always picked the single most likely token, the text would often become bland or repetitive. If it sampled too wildly, it would fall apart. Decoding therefore has knobs. Temperature flattens or sharpens the distribution. Nucleus sampling, analyzed by Ari Holtzman and colleagues in The Curious Case of Neural Text Degeneration, keeps only the smallest set of tokens whose probabilities add up to a threshold such as 0.9, then samples from that set. The model proposes odds; a rule turns those odds into a token.

The context window is the model’s working memory. The prompt, the conversation so far, and the tokens it has just written all have to fit. GPT-3’s window was 2,048 tokens, a few pages of English. Later models have been trained with windows tens or hundreds of times longer, which is why a chatbot can hold a whole report in a single conversation. The original attention formula is the reason that was hard: comparing every token with every other token costs time and memory that grow with the square of the sequence length. A 2,000-token prompt is not twice as expensive as a 1,000-token prompt in the attention step; it is about four times as expensive. Engineers have since added approximations, caching of earlier key and value vectors, and other long-context designs, but the quadratic tension has not gone away. It is also why spending more compute at inference time, for example by letting a model generate hidden reasoning tokens before it shows an answer, has become a separate research bet from simply training a bigger model. Training happens once; answering happens millions of times. That is why Chinchilla’s smaller, better-trained model was not only a quality result: a 70-billion-parameter model is cheaper to serve than a 280-billion-parameter one that had seen less text.

Why they hallucinate

If the machine is only guessing likely tokens, it should not be a surprise when a fluent sentence is wrong. A hallucination, in this setting, is a plausible falsehood: a date, a citation, a legal clause or a biographical fact that reads well and is not true. The model is not lying in the human sense. It has no separate store of checked facts, and no inner flag that distinguishes a computed answer from a pattern that often appeared in training text.

Adam Tauman Kalai, Ofir Nachum, Santosh S. Vempala and Edwin Zhang make that point sharply in their 2025 paper Why Language Models Hallucinate. They argue that hallucinations begin as ordinary statistical errors. If a pretrained model cannot tell a false statement from a fact, the training objective will still push it to produce some continuation, and errors will appear even if the training data themselves were clean. The errors then persist for a second, social reason: most benchmarks award points for a correct choice and give no credit for "I don’t know." A model that guesses when uncertain will look better on the leaderboard than a model that abstains. In the authors’ opening example, a large open model asked for one researcher’s birthday, and told to answer only if it knew, produced three different wrong dates on three tries.

Language models hallucinate because the training and evaluation procedures reward guessing over acknowledging uncertainty.

Kalai, Nachum, Vempala and Zhang, Why Language Models Hallucinate, 2025

That is the paper’s core claim. It also explains why RLHF helps but does not finish the job. InstructGPT cut closed-domain hallucinations roughly in half and doubled truthful, informative answers on TruthfulQA, and still hallucinated. Preference training can punish some fabrications, but it cannot turn a next-token engine into a database. If a fact appeared rarely, appeared with errors, or never appeared at all, the model may still emit a high-probability look-alike.

Several practical habits follow from that picture. A model is more trustworthy when it can consult sources at answer time, when citations are checked, or when evaluations score abstention instead of treating it as a failure. Users can help by asking for sources, treating specific numbers and quotations as claims to verify, and not reading fluency as evidence. A smooth paragraph is not a calibrated probability that the paragraph is true.

What a language model is not

It is not a search engine, even when it sounds like one. It does not retrieve a page and read it unless some surrounding system has been built to do that. It is not a calculator, even when it can do small bits of arithmetic, which GPT-3 already could for three-digit sums in the 2020 paper and still fumbled in other formats. It is not a mind, and it does not "know" a fact in the sense of having checked it against the world. It is a compressed, statistical model of token sequences, shaped by pretraining and then by whatever fine-tuning and filters its makers added. That narrower description is also what makes it useful. The same next-token engine can draft a letter, translate a paragraph or sketch a program because those jobs are also sequences of tokens with regular structure. The skill is real. So are the failure modes: remarkable fluency, produced by a machine that was never trained to tell the truth first.

The bottom line

A large language model works because a few ideas stack cleanly. Tokens make language countable. Embeddings make those tokens into numbers. Attention lets every token look at the others without a recurrent bottleneck. Pretraining on enough text, at enough scale, turns next-token prediction into a general skill, and Chinchilla showed that the data have to grow with the model. Fine-tuning and RLHF then steer the model toward answers people prefer. Inference is that trained machine, stepping one token at a time inside a finite context window. The honest limit is the same mechanism. Because the model is always choosing a likely next token, it can write a wrong fact in the same tone as a right one. Understanding the pipeline does not make those errors disappear, but it does make them less mysterious: they are what you get from a very good guesser that was rewarded for answering, not for abstaining.

Further reading

Cover of Build a Large Language Model (From Scratch) by Sebastian Raschka, published by Manning
Build a Large Language Model (From Scratch)

Sebastian Raschka walks through coding a small GPT-style model step by step, the clearest way to see what tokens, layers and attention actually do.

Cover of Natural Language Processing with Transformers, Revised Edition, by Lewis Tunstall, Leandro von Werra and Thomas Wolf
Natural Language Processing with Transformers, Revised Edition

A practical guide to transformer models from the Hugging Face team, covering tokenization, attention, training and fine-tuning with real code.

Cover of AI Engineering: Building Applications with Foundation Models by Chip Huyen, published by O'Reilly
AI Engineering: Building Applications with Foundation Models

Chip Huyen’s guide to building on foundation models: evaluation, retrieval, fine-tuning, and serving, written for people who will ship the system around the model.

Cover of Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow by Aurélien Géron
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems

Aurélien Géron’s widely used textbook on the broader machine-learning toolkit that still sits underneath today’s language models.

Cover of Hands-On Large Language Models: Language Understanding and Generation by Jay Alammar and Maarten Grootendorst, published by O'Reilly
Hands-On Large Language Models: Language Understanding and Generation

Jay Alammar and Maarten Grootendorst’s visual guide to how large language models work and how to use them, from embeddings and transformers to generation and search.

Aglena Best Of product picks

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Aglena