1 Getting Started 1 / 4
  1. In this chapter
  2. What Is a Large Language Model? From Next-Word Prediction to General Assistants
  3. LLM Learning Roadmap
  4. Learning Resources Map
  5. LLM Cheat Sheet
All chapters →

Chapter 1 · Getting Started 1.1

What Is a Large Language Model? From Next-Word Prediction to General Assistants

A large language model (LLM) is a neural network, usually a Transformer, trained on huge amounts of text to predict the next token; pre-training, post-training and inference decoding turn it into an assistant that can chat, write code and reason.

Beginner 13 min read Updated Companion code ↓

After this page you will be able to

  • Describe how an answer is generated: text becomes tokens, vectors flow through a Transformer, and the output is a probability distribution.
  • Explain why predicting only the next token can teach so much.
  • Tell pretraining, post-training and inference decoding apart, and a base model from an assistant.
  • Read the three numbers people ask about most (parameters, tokens, context), and know what LLMs are good at and where they tend to fail.
On this page
  1. The big picture: how an answer is generated
  2. Stop 1: text becomes tokens
  3. Stop 2: vectors and the Transformer
  4. Stop 3: the output is a probability distribution
  5. Why predicting the next word teaches so much
  6. From base model to assistant: three stages
  7. Parameters, tokens, context: the three most-asked numbers
  8. What it is good at, and where it tends to fail
  9. Glossary
  10. Summary and exercises
  11. Quick self-check
  12. What to read next
  13. FAQ

The big picture: how an answer is generated

When you type a message into a chat box, the model does not write the whole answer in one shot. It repeats one operation many times: read all the text so far, predict the most suitable next piece of text (a token), append it, and predict again.

The loop an LLM runs to generate an answer The input text is split into tokens, passed through embeddings and many Transformer layers to produce a probability distribution over the next token, one token is sampled and appended to the input, and the loop repeats until an end-of-sequence token is produced. An answer is generated one token at a time Input “The weather” Tokenize text → ids Embed + Transformer reads the context Probabilities next-token scores Sample pick one token Append the new token to the input and repeat, until the model emits an end-of-sequence token
One answer is this loop run many times. Each round produces a single token, but every round re-reads the whole context.

Understanding an LLM means understanding each stop on this pipeline:

  1. Tokenization: how text becomes integers the model can process.
  2. Embeddings and the Transformer: how integers become vectors, and how vectors “read” the context.
  3. Probabilities and sampling: what the model actually outputs, and how the next word is picked from it.
  4. Training: how the parameters are learned and how the model is shaped into an assistant.

Let’s walk through the stops one by one.

Stop 1: text becomes tokens

The unit a model reads and writes is neither a character nor a word but a token. Tokens are pieces cut out by a tokenizer according to statistical regularities: an English word may be one to a few tokens, a Chinese character costs anywhere from under one token to a little over two on average (it depends on the tokenizer), and common phrases are sometimes merged into a single token.

Take “unbelievably good” as an example. Different tokenizers might split it into un / believ / ably / good, and each piece is then mapped to an integer id in the vocabulary, for instance [403, 17231, 1604, 922] (the ids differ from tokenizer to tokenizer). All the model ever sees is this sequence of integers.

  • Vocabulary sizes of mainstream models range from tens of thousands to a couple of hundred thousand.
  • Pricing, context length and inference speed are all measured in tokens, not in words.
  • The tokenization scheme affects multilingual efficiency and how well numbers and code are handled.

For the details, see Tokenizers and Embeddings: BPE, Vocabulary Size and the Embedding Table.

Stop 2: vectors and the Transformer

An integer id carries no “meaning” by itself, so the first layer of the model is an embedding table: each token id maps to one row of learnable vectors. These vectors are then fed into a stack of Transformer blocks.

The key component of a Transformer is the attention mechanism: when the model processes a position, it can look back directly at all earlier tokens and gather useful information from them, weighted by relevance. When it processes the word “it”, for example, attention puts more weight on “cat” than on the other words.

After dozens of such layers of reading and processing, the vector at the last position has condensed the information about what is most likely to come next. The details are covered in:

Stop 3: the output is a probability distribution

The vector at the last position is multiplied by an output matrix to get a score for every token in the vocabulary (the logits), and softmax turns the scores into probabilities:

pθ(xt=v∣x<t)=exp⁡(zv)∑u∈Vexp⁡(zu)p_\theta(x_t = v \mid x_{<t}) = \frac{\exp(z_v)}{\sum_{u \in \mathcal{V}} \exp(z_u)}

Here x<tx_{<t} stands for all earlier tokens, zvz_v is the score of token vv in the vocabulary V\mathcal{V}, and θ\theta denotes all parameters of the model.

For the prompt “The capital of France is”, the output distribution looks roughly like this (numbers are illustrative only):

Candidate tokenProbability (illustrative)
Paris0.93
Lyon0.02
Marseille0.01
Other0.04

The model does not “know” the answer; it just scores every candidate. Which one is picked depends on the decoding strategy: you can always take the most likely token (greedy decoding), or sample randomly according to the probabilities and control the randomness with parameters such as temperature and top-p. That is why the same question can get different answers each time. See Decoding and Sampling.

The widget below makes these two things hands-on with illustrative numbers: change the temperature and top-p to see the same distribution move, pick greedily or sample a few times; then produce a sentence one token at a time until the end-of-sequence token.

Why predicting the next word teaches so much

The training objective of a language model can be written as a product: the probability of a piece of text is the product of the probability of each token given the text before it.

P(x1,…,xT)=∏t=1TP(xt∣x<t)P(x_1, \dots, x_T) = \prod_{t=1}^{T} P(x_t \mid x_{<t})

During training the model predicts the next token at every position, cross-entropy measures the gap between the prediction and the real token, and gradient descent adjusts the parameters:

L(θ)=−1T∑t=1Tlog⁡pθ(xt∣x<t)\mathcal{L}(\theta) = -\frac{1}{T} \sum_{t=1}^{T} \log p_\theta(x_t \mid x_{<t})

The objective looks simple, yet it carries an enormous amount of information. To predict each of the following continuations well, the model has to learn completely different things:

  • “The capital of France is ____”: factual knowledge.
  • “He put the cup on the table and then picked ____ up”: grammar and reference.
  • “def add(a, b): return ____”: the structure of a programming language.
  • “3 + 5 × 2 = ____”: some degree of arithmetic and reasoning patterns.

Doing this on trillions of tokens forces the model to compress the statistical regularities of language, facts and reasoning into its parameters. That is why “predict the next word” produces general capabilities: it is a very cheap supervised signal (the text labels itself), yet it requires the model to capture how the whole world is described.

The objective is “plausible”, not “true”

The training objective rewards continuations that look like the training text, not verified facts. So when the model is unsure it can still produce fluent but wrong content, which is called a hallucination. Post-training, retrieval-augmented generation (RAG) and tool use all mitigate the problem, but no method eliminates it completely.

From base model to assistant: three stages

A model that has only gone through the training above is called a base model. It is good at continuing text but not at following instructions: ask it a question and it may simply go on to invent a few more questions. Turning it into an assistant takes three stages:

StageGoalTypical dataOutput
Pre-trainingPredict the next token and learn language and world knowledgeTrillions of tokens of web pages, books, code and papersBase model
Post-trainingFollow instructions, match preferences, learn step-by-step reasoningInstruction data, human or AI preference pairs, verifiable reasoning problemsChat models, reasoning models
Inference and servingGenerate reliably under latency and cost constraintsUser requestsOnline service

Pre-training sets the ceiling of what the model knows and is the most expensive step. In Meta’s published Llama 3 technical report, for example, the 405B-parameter model was trained on about 15.6 trillion tokens; the DeepSeek-V3 technical report describes a model with 671B total parameters (about 37B activated per token) trained on 14.8 trillion tokens.

Post-training decides whether the model is pleasant to use. It usually includes:

  1. Supervised fine-tuning (SFT): teaching the model to answer in a chat format with high-quality “instruction, response” examples.
  2. Preference optimization (RLHF, DPO and others): using preference signals from humans or models to make answers more helpful and safer.
  3. Reinforcement learning for reasoning: rewarding correct answers on automatically verifiable problems such as math and code, so the model learns longer and more reliable chains of thought.

Inference and serving decide cost and experience: the same model can differ in cost by several times depending on batching, caching and quantization.

These three stages map to three main lines of this wiki: Pre-training, Post-training and Alignment and Inference and Serving.

Parameters, tokens, context: the three most-asked numbers

Parameter count is the total number of learnable numbers in the model. The 7B and 70B in model names mean 7 billion and 70 billion parameters. Counting weights only, the memory needed is roughly:

memory (bytes)≈parameters×bytes per parameter\text{memory (bytes)} \approx \text{parameters} \times \text{bytes per parameter}

A 7B model stored in FP16/BF16 (2 bytes per parameter) needs about 14 GB for the weights alone; with 4-bit quantization (about 0.5 bytes) it needs about 3.5 GB plus a little overhead. Actually running it also needs the KV cache and intermediate activations; see KV Cache and Inference Performance.

Training tokens is how much text the model has “read”. With the same parameter count, different numbers of training tokens can give very different quality; how to balance parameters and data is the question Scaling Laws answers.

The context window is the maximum number of tokens the model can process at once, input and output together. The longer the window, the more KV has to be cached and the higher the cost, and the model does not necessarily use every part of the window equally well.

What it is good at, and where it tends to fail

Usually does wellNeeds extra care
Rewriting, summarizing, translating, classifyingQuestion answering that needs exact facts (especially obscure or recent information)
Code completion, explanation and debuggingMulti-digit arithmetic and tasks that need strict symbolic reasoning (tools can help)
Extracting structured information from a templateInformation in the middle of a very long context
Brainstorming, style transferPrompts that are very sensitive to wording, where rephrasing changes the result

A practical rule: treat the model as an assistant who has read a lot, reacts quickly, but needs to be fact-checked. Where reliability matters, supply evidence through retrieval (RAG), use tools for exact computation, and verify behaviour with evaluation.

Glossary

TermOne-line explanation
TokenThe basic unit of text the model processes, cut by a tokenizer
EmbeddingA learnable table that maps discrete tokens to continuous vectors
TransformerA neural network architecture built around attention; the mainstream architecture of today’s LLMs
Pre-trainingNext-token prediction on a huge unlabeled text corpus
SFTSupervised fine-tuning: teaching the model to follow instructions with “instruction, response” data
RLHF / DPOAlignment methods that use preference data to make outputs match human expectations
InferenceThe usage phase after training, generating an answer token by token; not the same as “logical reasoning”
Context windowThe maximum number of tokens that can be processed at once
HallucinationFluent generated content that is not true

Summary and exercises

Key points of this page:

  1. In every round an LLM reads the whole context so far, predicts the next token, appends it and repeats; an answer is generated token by token.
  2. The model outputs a probability distribution over the vocabulary, and the decoding strategy (greedy, sampling, temperature, top-p) decides which token to pick, so the same question can get different answers each time.
  3. “Predict the next word” is a cheap supervision signal that nonetheless forces the model to compress the regularities of language, facts and reasoning into its parameters; the goal is “plausible”, not “true”, which is why hallucinations happen.
  4. A base model becomes an assistant only after post-training (SFT, preference optimization, reasoning RL), and it can serve users only after inference deployment.
  5. Parameter count, training tokens and context window are the three most-asked numbers; the memory for the weights alone is roughly the parameter count times the bytes per parameter.

Quick self-check

1. What is an LLM actually doing when it generates an answer?

  • Writing the whole answer at once and then displaying it character by character
  • Reading all the text so far, predicting the next token, appending it to the end and repeating the process
  • Looking up the closest answer in a database and rewriting it
  • Reading only the most recent token in each round

Each round produces just one token, but every round reads the whole context. The length of the answer is the number of loop iterations.

2. Why can the single objective of “predicting the next word” teach a model grammar, facts and reasoning?

  • Because the training data comes with human annotations of every piece of knowledge
  • Because to predict continuations well the model has to model grammar, facts, code structure and reasoning patterns, and text carries its own labels, so the supervision signal is cheap
  • Because the loss function has a knowledge base built in
  • Because the model looks things up on the internet during training

Doing this over trillions of tokens of text forces the model to compress the statistical regularities of language, facts and reasoning into its parameters.

3. The same question can get a different answer every time. What is the main reason?

  • The model’s parameters are retrained for every answer
  • The model outputs a probability distribution over the next token and by default samples from it at random; temperature, top-p and similar parameters control the amount of randomness
  • The server picks a different model at random each time
  • The prompt is randomly rewritten in transit

If you always pick the most probable token (greedy decoding) the randomness drops a lot, although hosted services usually still do not guarantee byte-identical output.

4. A 7B-parameter model is stored in FP16. Roughly how much memory do the weights alone need?

  • About 3.5 GB
  • About 7 GB
  • About 14 GB
  • About 28 GB

Memory in bytes is roughly the parameter count times the bytes per parameter: 7×10^9×2 bytes≈14 GB. With 4-bit quantization (about 0.5 bytes per parameter) it is about 3.5 GB. Actually running the model also needs the KV cache and intermediate activations.

5. What is the main difference between a base model and an assistant model that can chat?

  • The assistant model always has more parameters
  • A base model is good at continuing text but not at following instructions; only after post-training (SFT, preference optimization, reasoning RL) does it learn to follow instructions and match preferences
  • A base model is not a Transformer
  • An assistant model needs no pre-training

Pre-training sets the upper limit of knowledge, post-training decides how useful the model is, and inference deployment decides cost and experience.

6. Why do LLMs produce “hallucinations”, that is, fluent content that is not true?

  • Because the model has too few parameters
  • Because the training objective rewards plausible continuations that resemble the training text, not verified truth; when unsure, the model still produces fluent content
  • Because the model is deliberately deceiving the user
  • Because the tokenizer loses information

Post-training, retrieval-augmented generation (RAG) and tool calling all mitigate the problem, but no method eliminates it completely.

Exercises:

  1. A 70B-parameter model is stored in FP16 and in 4-bit quantization (about 0.5 bytes per parameter). How much memory do the weights alone need in each case? Does either fit on a 24 GB GPU?
  2. Implement softmax and compute the probabilities for the scores [3.0,1.0,0.2][3.0, 1.0, 0.2]; then add 10 to every score and compute again. What changes, and why?
  3. For each of the four scenarios, decide whether asking the model directly is enough or whether you need retrieval, tools or evaluation, and explain why: (a) translating a paragraph from Chinese into English; (b) looking up the closing price of a stock today; (c) computing 123456 × 654321; (d) answering an expense-reimbursement question from a company’s internal documents.
Reference answers
  1. FP16 takes 2 bytes per parameter, so 70×109×2=14070 \times 10^9 \times 2 = 140 GB; 4-bit takes about 0.5 bytes, so 70×109×0.5=3570 \times 10^9 \times 0.5 = 35 GB. Neither fits on a 24 GB GPU, and even the 4-bit version needs more than one card, before counting the KV cache and activations; you need several GPUs in parallel or to offload part of it to CPU memory.

  2. A reference implementation:

    import math
    
    
    def softmax(z):
        e = [math.exp(x) for x in z]
        total = sum(e)
        return [x / total for x in e]
    
    
    z = [3.0, 1.0, 0.2]
    shifted = [x + 10 for x in z]
    print([round(p, 3) for p in softmax(z)])        # [0.836, 0.113, 0.051]
    print([round(p, 3) for p in softmax(shifted)])  # [0.836, 0.113, 0.051]

    The results are identical: numerator and denominator are both multiplied by e10e^{10}, which cancels, so softmax depends only on the differences between scores and is insensitive to a shift of all of them. Implementations subtract the maximum before exponentiating, relying on this property, to avoid overflow.

  3. (a) Ask directly: translation is a task the model usually does well, though important text should still be spot-checked. (b) Needs retrieval or an API: today’s price is not in the parameters, and the model would only continue with a plausible-looking number. (c) Needs a tool: multi-digit arithmetic is error-prone for a model, so let it call a calculator or Python, which gives 80,779,853,376. (d) Needs retrieval (RAG): the internal documents are not in the training data, so the relevant passages must be put into the context and the model asked to answer from them.

FAQ

How is an LLM different from a traditional machine learning model?
Traditional models are usually trained separately for a single task such as classification or translation. An LLM is first pre-trained on a huge text corpus with one unified objective (predict the next token) and is then adapted to many tasks through prompts or a small amount of extra data, so the same weights can answer questions, write, code and translate.
Does an LLM really understand language?
There is no agreed answer. What is clear is that, to predict the next token well, a model has to represent grammar, facts and reasoning patterns internally, so on many tasks it behaves as if it understood. But its objective is a plausible continuation, not a guarantee of truth, which is why factual errors (hallucinations) still happen.
Does more parameters always mean a stronger model?
No. With enough data and compute, bigger models are usually stronger, but data quality, the number of training tokens, post-training methods and inference strategy matter just as much. For a fixed compute budget, parameters and training tokens have to be balanced; the scaling-laws page covers this.
What is the relationship between ChatGPT and GPT?
GPT is the name of a family of language models; ChatGPT is a chat product built on such models. Besides pre-training, the models behind the product go through instruction tuning and preference alignment, which is what lets them follow instructions and decline inappropriate requests.