QuiddityML

By · 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.

Two panels compare the old pattern, where each task (sentiment, translation, NER) has its own dataset and its own model, with the foundation pattern, where one model is pretrained broadly on text, images, audio and code and then adapted many times to the same three tasks, so the expensive base training is reused.

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.

Text, images, audio and code all feed one box labeled pretrained on broad data, and four arrows labeled adapted after pretraining lead from it to sentiment, QA, summarize and translate, showing one reusable base for many tasks.

Pretrained, foundation model and LLM are three different labels

The three terms are related, and each one points at something different:

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.

Three panels: pretrained is the training stage (broad data to a base checkpoint), foundation model is the reuse role (one base for chat, search, code, analytics and more), and LLM is language plus scale (a token stream into a large model), with base LLM shown as a pretrained foundation model for language and chat LLM as base plus adaptation.

How pretraining works

Pretraining starts before there is any product task. The recipe has four steps:

  1. Collect a broad text corpus, such as web pages, books and code.
  2. Tokenize it, turning the text into a sequence of token ids.
  3. Pick a self-supervised objective, a training task whose answers come from the text itself.
  4. 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".

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.

Causal language modeling, where "the" and "cute" both point to the target "axolotl" because context comes from earlier positions, and masked language modeling, where "the", "axolotl" and "swims" all point to the hidden second position because context comes from both sides of the mask.

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 13

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

The sequence probability as a product of next-token probabilities, the loss L as minus the average log probability, and perplexity as exp(L): a uniform guess over 50000 tokens gives L = 10.8, and a trained model at L = 2.6 has perplexity 13, so it behaves as if choosing among about 13 tokens.

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.

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.

The prefix "the cute axolotl" with the predicted position "swims": syntax (subject-verb agreement, word order, phrase shape) and semantics (word meaning, concept relations) both feed a prediction for the last position of swims 0.62, floats 0.14 and sleeps 0.09, and both can lower pretraining 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.

World knowledge: "The Eiffel Tower stands in" predicts Paris 0.82, Rome 0.09 and Tokyo 0.04. Reasoning trace: every bird in the story can fly, the pet in the story is a bird, so the pet can, with "fly" as the next token, since the objective rewards useful structure in text.

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.

Three probes for one objective: "The Eiffel Tower stands in the city of __" leans on world facts, "The trophy didn't fit in the suitcase because the ___ was too big" leans on coreference, and "Worst meal I have had all year. The service was ___" leans on sentiment.

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.

A broad text corpus from many sources goes through the pretraining objectives (predict next token, recover masked token) into model parameters, a compact representation of patterns in text made of billions of numbers. Some passages can be memorized, while a strong pressure favors patterns repeated across contexts.

How a foundation model gets adapted

A pretrained base is pointed at a specific task in a few ways:

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.

A pretrained base, costly once and then reused, leads to four adaptation paths: fine-tuning, prompting, in-context examples, and alignment and systems, which in turn uses instruction data, preferences, retrieval, tools and evaluation.

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

The recipe beyond text: broad data, a self-supervised task and adaptation applied to text (causal LM, MLM), images (masked patches), audio (masked spans), code (causal LM) and protein and DNA (masked tokens), with multimodal models combining several of them.

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

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

The prefix "the cute" goes into a language model, which outputs a next-token distribution of axolotl 0.42, dog 0.18, cat 0.12, idea 0.03 and other 0.25. After appending, the prefix is "the cute axolotl", and the loop is predict, append, repeat.

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.

A language model that predicts the next token after "the cute axolotl swims", plus scale (billions of parameters, trillions of tokens), equals an LLM that can summarize, classify, answer and write code.

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.

Base LLM versus chat LLM: a broad corpus and a next-token objective produce a base LLM that continues text, and adaptation (instruction data, preferences, safety, retrieval, tools, evals) turns it into a chat or assistant LLM that follows requests more reliably and feeds chat, assistants, RAG systems, agents and apps.

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.

Three families: an encoder-only model where every position reads the whole input for representation tasks, an encoder-decoder that maps "the cute axolotl swims" to "l'axolotl mignon nage" through cross-attention, and a decoder-only model with a 3 by 3 causal mask over "the cute axolotl" that outputs swims 0.62, floats 0.14 and sleeps 0.09. Next-token objective, prompt as one sequence, a simple generation loop and the KV cache fit together.

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.

Three decoder blocks, each with masked self-attention and feed-forward, turn the prefix "the cute" into a next-token distribution (axolotl 0.42, other 0.25, dog 0.18, cat 0.12, idea 0.03). Depth, width and training tokens grow, while positional encoding, normalization, attention variants and serving vary.

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 billion

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

Larger vocabulary grows the token embeddings, wider hidden width grows the attention projections and larger feed-forward width grows the feed-forward network, both repeated many times, plus the output projection. Other choices that change the count: more repeated blocks, tied embeddings, grouped-query attention, mixture-of-experts routing and normalization parameters.

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.

Sources (web pages, books, code, forums, reference text) feed a filter that deduplicates and removes low-quality and unsafe content, then a tokenizer that splits text into subword tokens, then a token stream of billions to trillions of tokens, so raw text becomes next-token training examples.

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 FLOPs

Faster hardware changes how long those operations take and what they cost. It does not change how many operations the run needs.

The compute bill: model size and training tokens both set the FLOPs, while system efficiency (hardware utilization, communication overhead, the input and output pipeline) sets how long they take, which can mean weeks to months on a large cluster of accelerators. More model and more data both raise the bill.

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.

A decoder-only LLM with attention layers, feed-forward layers and an output projection. Distributed training, mixed precision, activation checkpointing and optimized attention kernels are on the training side, while the KV cache acts on the attention layers and mixture-of-experts routing acts on the feed-forward layers on the serving side.

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.

A small model gives a good local continuation for "the capital of France is" but is not reliable at summarize, translate and classify as one shared base. A large model handles all three through one shared model, though it is still not reliable without evaluation. Same objective family, much larger scale.

Common mistakes

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.