By Sagi Shaier · 14 November 2026 · 14 min read
How do LLMs work? Foundation models and pretraining explained
How one next-token objective on a huge pile of text gives a model grammar, facts and some reasoning, what makes a language model large, and how a base model turns into a chat assistant.
A large language model (LLM) is a neural network that predicts the next token of text. It has billions of parameters and is trained on hundreds of billions or trillions of tokens. An LLM is one kind of foundation model, which is one large model pretrained on broad data and then adapted to many different tasks. Chat assistants, code completion tools and many text classifiers are built on models like this.
Models read text as tokens, which can be whole words or pieces of words. The small examples below sometimes say "word" to keep them simple.
What is a foundation model?
Before reusable base models, the usual way to build a language system was one model per task. Sentiment analysis meant collecting labeled reviews and training a sentiment model. Translation meant collecting sentence pairs and training a translation model. Named entity recognition (NER) tags the names of people, places and companies in text. It got its own dataset and its own model too. Each task started from its own labeled data and its own training run.
A foundation model moves the most expensive training earlier. You pretrain one broad base once, then adapt that same set of weights to each task in front of you. Adapting can still take serious effort, but it is usually much smaller than pretraining a new base from scratch.

The name is about reuse. The foundation model is the base layer that other systems are built on. The broad data does not have to be text either. The same base can then be adapted to sentiment, question answering (QA), summarization or translation.

Pretrained, foundation model and LLM are three different labels
The three terms are related, and each one points at something different:
- Pretrained describes the training stage. The model went through broad initial training before any specific task.
- Foundation model describes the role. It is a broad base that many systems can build on.
- LLM describes the domain and the size. It is a large model for language.
So a base LLM is usually a pretrained foundation model for language. A chat LLM is usually that base plus later adaptation. The result of pretraining is a checkpoint, which is a saved set of trained weights.

How pretraining works
Pretraining starts before there is any product task. The recipe has four steps:
- Collect a broad text corpus, such as web pages, books and code.
- Tokenize it, turning the text into a sequence of token ids.
- Pick a self-supervised objective, a training task whose answers come from the text itself.
- Train a transformer to predict missing or future tokens.
The labels come from the corpus. Nobody has to label the sentence "the cute axolotl swims" as a summarization example or a reasoning example. The training task is built from the words already there.
![The pretraining recipe as five boxes in a row (broad text corpus, tokenizer, self-supervised objective, transformer model, prediction target) with two objectives below: next-token, where "the cute" predicts "axolotl", and masked-token, where "the [MASK] axolotl swims" predicts "cute".](images/pretraining_recipe.png)
Two objectives are common for text. Causal language modeling predicts the next token from the tokens before it. Given "the cute", the target is "axolotl". Masked language modeling hides tokens inside a complete sentence and asks the model to recover them. Given "the [MASK] axolotl swims", the target is "cute".
The difference is what context the model can use. A causal model attends only to earlier positions, while a masked model can use the words on both sides of the gap. Chat and code LLMs are usually trained with the causal objective, which causal masking explained covers in detail.

The pretraining loss
"Lowering the loss" during pretraining refers to one formula. A language model scores a whole sequence of tokens $x_1 \dots x_T$ as a product of next-token probabilities:
$$P(x_1 \dots x_T) = \prod_{t=1}^{T} P(x_t \mid x_{<t})$$
$x_t$ is the token at position $t$, $x_{<t}$ is every token before it, and $T$ is the number of tokens. $P(x_t \mid x_{<t})$ is the probability the model gave to the token that actually came next.
Pretraining minimizes the average negative log of those probabilities, which is the cross-entropy loss:
$$L = -\frac{1}{T}\sum_{t=1}^{T} \log P(x_t \mid x_{<t})$$
For example, say a 3-token sequence gets probabilities 0.5, 0.25 and 0.8 for the tokens that really came next. The product is $0.5 \times 0.25 \times 0.8 = 0.1$. The loss is $-(\ln 0.5 + \ln 0.25 + \ln 0.8)/3 = (0.69 + 1.39 + 0.22)/3 \approx 0.77$. If the model put probability 1 on every correct token, $L$ would be 0. The more often it spreads probability thin or bets on the wrong token, the higher $L$ climbs.
Perplexity is the same loss passed through the exponential, $\exp(L)$. It reads as roughly how many tokens the model is choosing between at each step. For the example above, $\exp(0.77) \approx 2.2$. A model that guesses uniformly over a 50,000-token vocabulary gets $L = \ln 50000 \approx 10.8$ and a perplexity of 50,000. A model at $L = 2.6$ has a perplexity of about 13. The code below checks both numbers with PyTorch's built-in cross-entropy:
1import math
2import torch
3import torch.nn.functional as F
4
5vocab_size = 50_000
6T = 8
7targets = torch.randint(0, vocab_size, (T,))
8
9uniform_logits = torch.zeros(T, vocab_size)
10loss = F.cross_entropy(uniform_logits, targets)
11print(f"uniform guess: loss {loss.item():.2f}, perplexity {math.exp(loss.item()):,.0f}")
12
13print(f"loss 2.6: perplexity {math.exp(2.6):.0f}")1uniform guess: loss 10.82, perplexity 50,000
2loss 2.6: perplexity 13uniform_logits gives every token the same score, so the model spreads probability evenly and the loss is $\ln 50000$ no matter which targets were drawn. Masked language modeling uses the same cross-entropy, averaged over the masked positions only. Perplexity explained goes further into reading these numbers.

Why predicting the next token teaches so much
The pretraining objective is narrow. Predict the next token, or recover a hidden one. The loss never asks for grammar, facts or logic as separate labels. The objective is still demanding because human writing carries grammar, meaning, facts and traces of reasoning. To predict the next token well, a model is pushed to pick up parts of those patterns.
![Causal LM ("the cute" to "axolotl") and masked LM ("the [MASK] axolotl" to "cute") both feed five skills (grammar, word meaning, world facts, reasoning, style), because good prediction rewards useful regularities in text, and these skills are not separate labels in the loss.](images/one_objective_many_skills.png)
Syntax, the rules of how words combine, comes in early. After "the cute axolotl", a verb is likely next, and a verb form that agrees with a single axolotl is more likely than one that does not. Semantics, what words mean, follows. "Swims" is more likely than "sleeps" partly because the model has picked up what axolotls tend to do in text. Neither of these is a separate training task. Both lower the loss.

Facts come next. To finish "The Eiffel Tower stands in", knowing the actual city helps, so world knowledge builds up in the weights because it lowers the loss. A limited form of reasoning shows up the same way. If a story says every bird in it can fly and the pet in it is a bird, then "so the pet can" is best finished with "fly". A model that follows that chain predicts the token better than one that does not.

You can see the breadth by handing the model fill-in-the-blank sentences. "The Eiffel Tower stands in the city of ___" needs a world fact. "The trophy didn't fit in the suitcase because the ___ was too big" needs coreference, working out which earlier noun a word refers to, since "trophy" fits and "suitcase" does not. "Worst meal I have had all year. The service was ___" needs the sentiment of the line. One objective and one set of weights handle all three blanks.

A useful way to see this is as compression. The corpus has billions of tokens and the model has a fixed number of parameters. A model that captures recurring structure can predict text far more efficiently than one that treats every phrase as unrelated. Models do memorize some rare, repeated or distinctive passages. The pressure toward reusable patterns is stronger, because a pattern helps on far more text than a memorized string.

How a foundation model gets adapted
A pretrained base is pointed at a specific task in a few ways:
- Fine-tuning keeps training its weights on a smaller labeled dataset for the task.
- Prompting describes the task in plain language in the input.
- In-context examples put a few input-output demonstrations inside the prompt.
- Alignment and systems add instruction and preference training. They also add safety rules, document retrieval, tools and evaluation.
Each path builds on the base instead of starting over from raw data. Fine-tuning vs transfer learning goes through the first path in code.

The recipe is not specific to language. It needs broad data that is cheap to collect, a training signal that can be created from the data itself, and a model large enough to reuse. Image models can be pretrained by hiding patches of an image and predicting them. Audio models can hide short spans of sound. Code models often use the same next-token objective as text, and models of protein and DNA sequences can hide tokens in those sequences. Models that combine several of these inputs are called multimodal. This is why "foundation model" is a broader term than "language model".

What a language model computes
A language model predicts a distribution over the next token. Given the prefix "the cute", it assigns a probability to every token in its vocabulary. The network first produces one raw score per token, called a logit, and softmax turns the scores into probabilities that add up to 1:
1import torch
2import torch.nn.functional as F
3
4vocab = ["axolotl", "dog", "cat", "idea", "other"]
5logits = torch.tensor([2.0, 1.15, 0.75, -0.64, 1.47])
6probs = F.softmax(logits, dim=-1)
7for token, p in zip(vocab, probs):
8 print(f"{token:8s} {p.item():.2f}")1axolotl 0.42
2dog 0.18
3cat 0.12
4idea 0.03
5other 0.25A real vocabulary has tens of thousands of tokens, and "other" stands in for all the rest here. During generation, one token is picked from this distribution and appended to the prefix, and the model runs again on the longer prefix. LLM decoding strategies covers the ways that pick is made.

What the "large" in LLM means
An LLM is a language model scaled to billions of parameters and trained on very large text corpora, often hundreds of billions or trillions of tokens. There is no official parameter count where a model becomes an LLM. The term points to language models large enough that one set of pretrained weights can serve as a base for many text tasks.

Base LLM and chat LLM
The word LLM can point to different stages of the same model. A base LLM is the model right after pretraining. It is trained to continue text. You can prompt it, and a large base model can often pick up a task from instructions or examples in the prompt, but its output is shaped like a continuation and can be brittle. Ask it a question and it may continue with three more questions.
A chat LLM usually starts from a base LLM and then gets more training and system work. That includes instruction tuning, preference training and safety work, plus retrieval and tools. Retrieval-augmented generation (RAG) is one such system, where documents found by a search step are placed into the prompt. An agent is a system where the model can call tools such as a search engine or a code runner. This later work makes a request read like a request to the model, instead of more text to continue.

Why many chat LLMs are decoder-only
Transformers come in three families. Encoder-only models read the whole input at once, with every position attending to both sides, which suits tasks like classification. Encoder-decoder models map a source sequence to a target sequence, with the decoder reading the encoder's output through cross-attention, which suits translation. Decoder-only models condition on a prefix and generate the continuation one token at a time, using a causal mask so each position can attend only to itself and earlier positions.
For a general text engine, decoder-only fits well. The training objective and the way the model is used line up: condition on the prefix, predict the next token, append it and repeat. One sequence can hold instructions, examples, retrieved passages and the answer being generated. A KV cache, which stores the keys and values of earlier tokens so they are not recomputed at every step, makes that loop cheaper to run. None of this makes decoder-only the best family for every job. Encoder vs decoder vs encoder-decoder compares the three in more depth.

Scaling the decoder stack
Many text LLMs are a stack of decoder blocks. Each block uses masked self-attention to mix in information from earlier positions, then a feed-forward network to update each token's representation. At the top, the model predicts a distribution over the vocabulary at every position.
The core shape stays recognizable as the stack gets deeper and wider and is trained on far more text. Details change from model to model. One is the positional encoding, which tells the model where each token sits. Others are the normalization layers that rescale activations between steps, variants of attention, and how the model is served to users. What changed in transformers since the original covers those variants.

Where the parameters live
Learned weights in a transformer LLM sit in the token embeddings and the attention projections. More sit in the feed-forward networks, the normalization layers and the output projection. The repeated blocks usually hold most of them.
A plain block gives a rough count. With hidden width $d$, the four attention projections hold about $4d^2$ weights. They are the query, key, value and output projections. A feed-forward network that expands to $4d$ and back holds about $8d^2$. One block is about $12d^2$:
1d = 4096
2blocks = 32
3per_block = 4 * d**2 + 8 * d**2
4print(f"one block: {per_block:,} parameters")
5print(f"{blocks} blocks: {blocks * per_block / 1e9:.1f} billion")1one block: 201,326,592 parameters
232 blocks: 6.4 billionThat is before the embeddings. Treat $12d^2$ as a rough estimate for a plain block. Tied embeddings, where the input and output layers share one matrix, change the count. So does grouped-query attention, where several query heads share one key and value head. Mixture-of-experts routing sends each token through only some of several feed-forward networks, so a model can hold many parameters and use a fraction of them per token. The headline parameter count is a summary of choices like these.

Training data and the compute bill
The other axis of scale is data. Many LLMs are pretrained on broad mixtures of web pages, books and code, plus forum posts and reference text. The text is filtered to remove duplicates and low-quality or unsafe content, then tokenized and streamed through the training objective. The corpora are collected in bulk, not curated example by example.

Training at this scale takes a very large number of floating-point operations (FLOPs). For a dense transformer with $N$ parameters trained on $D$ tokens, a standard rough estimate of the total training compute $C$ is:
$$C \approx 6ND$$
The 6 comes from about 2 FLOPs per parameter per token in the forward pass and about twice that again in the backward pass. Doubling $N$ or $D$ doubles $C$. For example, a 1-billion-parameter model trained on 20 billion tokens needs about $1.2 \times 10^{20}$ FLOPs:
1N = 1e9 # parameters
2D = 20e9 # training tokens
3C = 6 * N * D
4print(f"training compute: {C:.1e} FLOPs")1training compute: 1.2e+20 FLOPsFaster hardware changes how long those operations take and what they cost. It does not change how many operations the run needs.

Runs this large need engineering around the model. Training is split across many accelerators (distributed training). Much of the math runs in 16-bit numbers to save memory (mixed precision). Some intermediate values are recomputed in the backward pass instead of stored (activation checkpointing). Attention runs in GPU code written to move less data (optimized attention kernels). At serving time the KV cache and mixture-of-experts routing cut the work per generated token. KV cache and grouped-query attention shows the cache in detail.

What scale changes
A small model trained on next-token prediction is a decent text predictor. Given "the capital of France is", it continues with "Paris". Asked to summarize, translate or classify, it often fails. A large model trained the same way can be pointed at many of those tasks by writing a prompt, with no retraining. It still makes mistakes, so its output needs evaluation like any other system.
Which tasks start working at which size is the subject of emergent abilities in LLMs. How much the loss improves for each extra unit of parameters, data and compute is the subject of scaling laws explained.

Common mistakes
- Treating "LLM" as "chatbot". A base LLM continues text. The assistant behavior comes from later adaptation on top of it.
- Thinking pretraining teaches facts on purpose. Facts and grammar have no separate labels in the loss. They show up because they help predict the next token.
- Reading the parameter count as the full story. That one number hides width and depth, embedding size and data, plus design choices such as mixture-of-experts.
- Assuming a lower loss means a specific skill. The loss is an average over all the text. A lower number does not say which task the model can now do.
- Training from scratch by default. Many projects adapt an existing pretrained model by prompting or fine-tuning, since pretraining a new base needs a very large corpus and compute budget.
Related concepts
How language models are trained covers the training loop for a smaller language model step by step. Masked language modeling explained goes into the masked objective that encoder models such as BERT use. Open-weight vs closed LLMs covers the two ways to get access to a pretrained model, and build a small GPT from scratch writes a decoder-only model in PyTorch.
QuiddityML teaches foundation models and large language models as two concepts in the Intro to NLP track. The exercises on them include putting the foundation-model workflow in order, from collecting broad data to reusing one base across tasks, and ordering one pass of a decoder-only generation loop.