How Large Language Models Work

Tokens, embeddings, the transformer, attention, context windows, sampling and the training stages that turn a next-token predictor into an assistant — explained simply, with diagrams and review questions.

On this page

Simple definition#

A large language model (LLM) is a neural network trained to predict the next piece of text. Given “The capital of France is”, it assigns a probability to every possible next token and “Paris” scores highest. Repeating that prediction one token at a time produces sentences, code, plans and answers.

Everything else — chat, reasoning, tool use — is built on that single ability.

Why architects need to know this#

You do not need to train models, but the mechanics explain the constraints you design around:

Mechanic Consequence for your architecture
Text is split into tokens Cost, latency and limits are measured in tokens, not characters or words.
The model sees a fixed context window Anything not in the prompt does not exist for the model. You must retrieve knowledge and manage memory.
Output is sampled from probabilities Responses are non-deterministic. You need evaluation, validation and retries.
Knowledge is frozen at the training cutoff Recent or private facts must come from RAG or tools.
The model is stateless Conversation history is re-sent on every call; your application stores it.
It generates the most plausible text It can be fluently wrong (hallucination). Grounding and citations are a design concern.

The pipeline from text to text#

One generation step inside an LLM
flowchart LR
    A["Input text"] --> B["Tokenizer<br/>text → token IDs"]
    B --> C["Embedding layer<br/>IDs → vectors"]
    C --> D["Transformer blocks × N<br/>self-attention + feed-forward"]
    D --> E["Output layer<br/>scores for every token in vocabulary"]
    E --> F["Sampling<br/>temperature, top-p"]
    F --> G["Next token"]
    G -->|"append and repeat"| B

1. Tokens#

A tokenizer splits text into sub-word units using an algorithm such as Byte-Pair Encoding (BPE). Common words become one token; rare words split into several.

  • Rule of thumb for English: 1 token ≈ 4 characters ≈ 0.75 words. 1,000 tokens ≈ 750 words.
  • Code, non-English text and numbers usually take more tokens per word.
  • Each model family has its own tokenizer, so the same text has different token counts on different models.

2. Embeddings#

Each token ID is mapped to a vector of a few thousand numbers. Vectors for tokens with similar meaning end up close together. The same idea — meaning as a position in space — powers the embedding models used for search in RAG.

3. The transformer and attention#

The core of every modern LLM is the transformer (Vaswani et al., 2017). It is a stack of identical blocks. Each block has two parts:

  • Self-attention — every token looks at every earlier token and decides how much each one matters to it. In “The bank raised its rates because it …”, attention lets “it” link to “bank”.
  • Feed-forward network — transforms each token’s vector independently; this is where much of the model’s stored knowledge lives.
Inside one transformer block (decoder-only)
flowchart TB
    IN["Token vectors from previous block"] --> ATT["Masked multi-head self-attention<br/>each token attends to earlier tokens"]
    ATT --> ADD1["Add & normalise<br/>residual connection"]
    ADD1 --> FFN["Feed-forward network<br/>per-token transformation"]
    FFN --> ADD2["Add & normalise"]
    ADD2 --> OUT["To next block"]

How attention works, simply. Each token produces three vectors: a query (“what am I looking for?”), a key (“what do I contain?”) and a value (“what do I pass on?”). A token’s query is compared with every earlier token’s key; the similarity scores become weights; the output is the weighted sum of the values. Multi-head attention runs several of these in parallel so different heads can track grammar, references, facts and so on.

Why it matters: attention compares every token with every other token, so cost grows roughly with the square of the sequence length. That is why long contexts are expensive and why inference engines cache keys and values (the KV cache).

Decoder-only. Chat models (GPT, Claude, Gemini, Llama, Mistral) are decoder-only: each token can only attend to tokens before it (“causal masking”), which is exactly what next-token generation needs. Encoder-only models such as BERT see the whole text at once and are used for classification and embeddings.

Mixture of Experts (MoE). Many large models replace the single feed-forward network with several “expert” networks and a router that sends each token to only a few of them. The model has many parameters in total but uses a fraction per token, so it is cheaper to run than a dense model of the same size.

4. Sampling: turning scores into text#

The output layer produces a probability for every token in the vocabulary. Decoding picks one.

Setting What it does Typical use
Temperature Sharpens (low) or flattens (high) the distribution. 0 ≈ always pick the most likely token. 0–0.3 for extraction, classification, code; 0.7–1.0 for creative text
Top-p (nucleus) Sample only from the smallest set of tokens whose probabilities add up to p. 0.9–1.0
Top-k Sample only from the k most likely tokens. Rarely tuned in enterprise apps
Max tokens Hard limit on output length. Always set it: it caps cost and latency
Stop sequences Strings that end generation. Structured formats

5. The context window#

The context window is the maximum number of tokens the model can process in one call — input and output together. Current frontier models offer roughly 128K to over 1M tokens.

What fills the context window on a typical enterprise call
flowchart LR
    subgraph CW["Context window, for example 200K tokens"]
        direction LR
        S["System prompt<br/>rules, persona"] --> T["Tool definitions"]
        T --> R["Retrieved documents<br/>RAG"]
        R --> H["Conversation history"]
        H --> U["User message"]
        U --> O["Space for the output"]
    end

Bigger is not automatically better:

  • Cost and latency grow with input size.
  • “Lost in the middle” — models attend best to the beginning and end of long contexts; facts buried in the middle are used less reliably.
  • Context rot / distraction — irrelevant material lowers answer quality.

So even with a 1M-token window, selecting the right context (RAG, memory) remains an architecture task. This discipline is often called context engineering.

How a model is trained#

This section is the short version. For training data, scaling laws, SFT, RLHF and DPO, test-time compute and structured outputs in depth, see training, scaling and sampling.

From raw text to a helpful assistant
flowchart LR
    P["1 · Pretraining<br/>trillions of tokens of web, books, code<br/>learns language and world knowledge"] --> B["Base model<br/>completes text, does not follow instructions"]
    B --> S["2 · Supervised fine-tuning SFT<br/>curated instruction → answer pairs"]
    S --> R["3 · Preference tuning<br/>RLHF, RLAIF, DPO, constitutional methods"]
    R --> RL["4 · Reinforcement learning<br/>on verifiable tasks: maths, code, tool use"]
    RL --> A["Assistant model<br/>helpful, follows instructions, refuses harmful requests"]
  1. Pretraining — self-supervised next-token prediction over a huge corpus. Expensive (weeks on thousands of GPUs). Produces a base model.
  2. Supervised fine-tuning (SFT) — teaches the model the format of helpful answers using examples.
  3. Preference tuning — humans or AI judges rank answers; the model is optimised toward preferred ones. RLHF (reinforcement learning from human feedback) and DPO (direct preference optimisation) are the common methods.
  4. Reinforcement learning on verifiable rewards — the model practises tasks with checkable answers (unit tests pass, maths is correct). This is how reasoning models learn to think step by step.

Reasoning (“thinking”) models#

Reasoning models generate an internal chain of thought before the final answer. They are markedly better at multi-step maths, planning, coding and agentic tasks, at the price of more output tokens and higher latency. Most providers let you set a thinking budget or effort level, so you can choose per request. Use them where correctness on hard problems matters more than speed.

Capabilities and limits to design around#

Strong at: summarising, extracting, classifying, transforming formats, drafting, translating, writing and explaining code, following instructions, calling tools, and reasoning over text you provide.

Weak at, without help:

  • Facts after the training cutoff or private facts → add RAG or tools.
  • Exact arithmetic and counting → call a calculator or code tool.
  • Guaranteed correctness → validate, evaluate, keep a human in the loop for high-stakes actions.
  • Long-running state → store it outside the model.

Why models hallucinate#

The model is trained to produce plausible continuations. When it lacks the facts, a confident-sounding wrong answer can still be the most “plausible” text. Reduce it by:

  1. Grounding answers in retrieved sources and asking for citations.
  2. Allowing “I don’t know” explicitly in the prompt.
  3. Lower temperature for factual tasks.
  4. Verifying outputs: schema validation, a second checking call, or faithfulness evaluation.

Common mistakes#

Review questions#

What is a token and why does it matter? A sub-word unit produced by the model’s tokenizer; about four characters of English. Pricing, context limits, rate limits and latency are all measured in tokens, so they drive cost and capacity planning.

Explain attention in one minute. Each token creates a query, key and value vector. Its query is compared with the keys of earlier tokens to get weights, and its new representation is the weighted sum of their values. This lets every token pull in information from the most relevant other tokens. Multi-head attention does this several ways in parallel. Cost grows quadratically with sequence length.

Why are LLMs non-deterministic and how do you handle it? Output is sampled from a probability distribution; even at temperature 0, infrastructure effects cause variation. Handle it with low temperature for factual tasks, structured outputs with validation, retries, and evaluation on datasets rather than single examples.

What is the difference between a base model and an instruction-tuned model? A base model only continues text. An instruction-tuned model has been through SFT and preference tuning so it follows instructions, uses a chat format and refuses harmful requests. Applications almost always use instruction-tuned models.

What is a context window and does a bigger one remove the need for RAG? The maximum tokens per call, input plus output. Larger windows help, but cost and latency scale with input, models use information in the middle of long contexts less reliably, and enterprise corpora are far larger than any window. Retrieval stays necessary; large windows let you include more retrieved context.

What are reasoning models and when would you use one? Models trained, largely with reinforcement learning, to think step by step before answering. Use them for complex planning, maths, code and multi-step agent tasks; avoid them for simple, latency-sensitive tasks such as classification or short extraction.

What causes hallucinations and how do you reduce them? The model generates plausible text even when it lacks facts. Reduce with grounding (RAG), citations, permission to say “I don’t know”, low temperature, tool use for facts and maths, and automated faithfulness checks.

Summary#

  • An LLM predicts the next token; repeated, that produces text.
  • Tokens drive cost, latency and limits. The context window is all the model can see.
  • The transformer’s attention lets tokens use each other’s information; its cost grows with sequence length.
  • Base models are pretrained on huge corpora, then tuned with SFT, preference tuning and RL into assistants and reasoning models.
  • The model is stateless, frozen in time and probabilistic — your architecture supplies knowledge, memory, tools, validation and safety.

References#