What is a Large Language Model?

In one line A Large Language Model (LLM) is a very large neural network, trained on huge amounts of text, whose basic job is to predict the next token given all the tokens before it.

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.
Next-token prediction: the model outputs a probability for every possible next token "The cat sat on the" LLM(transformer) Probability of next token mat0.54 floor0.24 sofa0.12 roof0.07 moon0.03 … one entry for every token in the vocabulary (~100k+) Illustrative numbers. The model picks one token, appends it, and repeats.
Figure 1. At every step an LLM outputs a probability distribution over its whole vocabulary.
Analogy It is like the autocomplete on your phone keyboard, scaled up enormously. Your phone looks at the last few words; an LLM looks at up to hundreds of thousands of previous tokens and has learned far richer patterns about language, facts and reasoning.

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):

Tokenization is not the same as splitting by words!
unbelievably 2026 🙂

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.

Text becomes tokens, then token IDs, then embedding vectors 1. Text 2. Tokens 3. Token IDs 4. Embeddings "I love tea" I ␣love ␣tea 40 3021 9234 [0.12, -0.53, … ][0.88, 0.07, … ][-0.31, 0.64, … ] IDs shown are made up for illustration. Each embedding vector has thousands of dimensions in a real model.
Figure 2. The tokenizer turns text into IDs; the model looks up a learned vector for each ID.

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

TopicWhy tokens matter
CostAPIs charge per input token and per output token (output usually costs more).
LimitsThe context window and maximum output length are measured in tokens.
SpeedGeneration speed is measured in tokens per second.
LanguageThe same sentence often needs more tokens in languages other than English, so it costs more and fills the context faster.
Odd failuresCounting letters ("how many r's in strawberry?") or reversing words is hard because the model sees tokens, not individual characters.
Rule of thumb (English text) 1 token ≈ 4 characters ≈ ¾ of a word, so 100 tokens ≈ 75 words and a 300-page book (~100,000 words) is roughly 130,000 tokens. This varies by tokenizer and language. Try the OpenAI tokenizer or the Tokenizer Playground to see real splits.

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).

Words placed in a two-dimensional embedding space, with similar words grouped together dimension 1 dimension 2 cat kitten dog puppy Paris Berlin Rome man woman king queen same "male→female"direction animals capital cities
Figure 3. A 2-D sketch of embedding space. Real embeddings have hundreds or 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.

Decoder-only transformer: embeddings, a stack of N blocks each with masked self-attention and a feed-forward network, then output probabilities Input token IDs Token embedding + position information × N blocks (e.g. 32 to 120+) Masked multi-head self-attention Add (residual) & normalise Feed-forward network (MLP) Add (residual) & normalise Linear layer + softmax Probabilities for the next token Tokens exchange information:"which earlier words matter here?" Each token is processed on its own:much of the stored "knowledge" lives here Words → vectors (see Embeddings)
Figure 4. A decoder-only transformer, the design used by GPT, Llama, Claude and most chat LLMs. (Simplified: modern models usually normalise before each sub-layer and use rotary position embeddings.)

Each block has two main parts:

  1. Self-attention lets each token gather information from the other tokens it can see.
  2. 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".

Attention weights from the token "it" to earlier tokens; the highest weight is on "animal" Theanimaldidn'tcrossthestreetbecauseit .04.48.07.06.03.18.08.06 How much "it"attends to eachtoken (sums to 1) Illustrative weights for one attention head. Real models have many heads, each learning different relationships.
Figure 5. Self-attention lets "it" pull information mostly from "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.

Analogy Searching a library: your query is the question you bring, each book's key is its catalogue entry, and its value is the content. You read mostly from the books whose catalogue entries best match your question.
Cost of attention Standard attention compares every token with every other token, so its compute and memory grow with the square of the sequence length. Doubling the context roughly quadruples the attention work, which is one reason long contexts are expensive.

Encoder, decoder, or both

TypeSeesGood atExamples
Encoder-onlyThe whole input in both directionsUnderstanding: classification, search embeddings, named-entity recognitionBERT, RoBERTa, many embedding models
Decoder-onlyOnly earlier tokens (causal)Generating text; general-purpose chatGPT series, Claude, Llama, Mistral, Qwen, Gemma
Encoder-decoderEncoder reads input; decoder generates outputSequence-to-sequence tasks: translation, summarisationOriginal 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.

Training pipeline: pre-training creates a base model, supervised fine-tuning creates an instruction model, preference tuning creates the assistant 1. Pre-training Trillions of tokens ofweb, books, codeTask: predict next token Basemodel 2. Supervised fine-tuning Thousands to millions of(instruction → good answer)examples 3. Preference tuning RLHF, DPO, RLAIF: learn whichof two answers people prefer;reinforcement learning on tasks Weeks to months onthousands of GPUs Continues any text;does not follow instructions well Learns the chat formatand to follow instructions Becomes more helpful, honestand harmless; better reasoning Knowledge comes mostly from stage 1. Stages 2 and 3 shape behaviour, style and safety.
Figure 6. The typical three-stage pipeline from raw text to a chat assistant.
StageDataLearning typeResult
Pre-trainingHuge unlabelled text corpusSelf-supervised (next-token prediction)Base model: broad knowledge of language and facts
Supervised fine-tuning (SFT)Curated prompt–response pairsSupervisedInstruction-tuned model: follows requests
RLHF (Reinforcement Learning from Human Feedback)Human rankings of model answers → a reward modelReinforcement learning (e.g. PPO)Answers people prefer; fewer harmful outputs
DPO (Direct Preference Optimization)Pairs of preferred / rejected answersOptimises preferences directly, without a separate reward modelSimilar goal to RLHF, simpler to train
RL with verifiable rewardsMaths, code and other tasks whose answers can be checked automaticallyReinforcement 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.

ModelYearParametersNote
GPT-12018117 millionFirst GPT
BERT-Large2018340 millionEncoder-only
GPT-220191.5 billionInitially released in stages over misuse concerns
GPT-32020175 billionFew-shot learning from prompts
Llama 220237B / 13B / 70BOpen weights
Mixtral 8x7B202346.7B total, ~12.9B active per tokenMixture-of-Experts
Llama 3.120248B / 70B / 405BOpen 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.

Autoregressive generation loop step 1The capital of France is→ ␣Paris step 2The capital of France is Paris→ . step 3The capital of France is Paris.→ ␣It …… until an end-of-sequence token or the max-token limit At each step 1. Run the model on all tokens 2. Get next-token probabilities 3. Sample one token 4. Append it and repeat The model never "plans the whole answer" as text up front; each token is chosen given everything before it.
Figure 7. Generation is a loop: predict, pick, append, repeat.

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}} \)

The same logits at temperature 0.5, 1.0 and 1.5: lower temperature concentrates probability on the top token T = 0.5 (focused)T = 1.0 (default)T = 1.5 (more random) .79.16.04.01.00 .54.24.12.07.03 .43.25.16.11.06 matfloorsofaroofmoon matfloorsofaroofmoon matfloorsofaroofmoon Computed with logits mat 3.0, floor 2.2, sofa 1.5, roof 1.0, moon 0.0
Figure 8. Temperature reshapes the distribution: low T is more predictable, high T is more varied.
SettingWhat it doesExample (T = 1 values above)
Greedy (T → 0)Always pick the most probable token. Deterministic in principle, but can be repetitive.Always "mat"
TemperatureDivides logits by T. T < 1 sharpens, T > 1 flattens.See Figure 8
Top-kSample 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

MisconceptionReality
"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

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


Some other interesting things to know: