Large Language Models (LLMs) can look mysterious from the outside: you type a prompt, the model writes back, and the response often feels more like conversation than computation. Under the hood, though, the core idea is surprisingly concrete. Most modern LLMs are built from transformers, trained to predict text one token at a time, and used during inference to repeatedly choose the next likely token.
This post is the first in a short series. We will start with transformers, then move into how LLMs learn, how they generate text, why training and inference are different, and what people mean when they talk about model parameters.
1. Text Becomes Tokens
LLMs do not read text as whole sentences. They first break text into tokens: common words, word pieces, punctuation marks, spaces, or byte-level fragments. A sentence like this:
might become a sequence of token IDs. Each ID is then mapped into an embedding, which is a vector of numbers. You can think of an embedding as the model’s internal coordinate system for meaning, syntax, and usage.
The model also needs information about order. The same words can mean different things depending on position, so transformers add positional information to token embeddings before processing them.
# Example: tokenizing with tiktoken (used by GPT-family models)
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4")
tokens = enc.encode("The evacuation plan changed.")
print(tokens) # [976, 60038, 3197, 5614, 13]
print(len(tokens)) # 5 tokens from 4 words
- Sennrich, Haddow, and Birch (2016), "Neural Machine Translation of Rare Words with Subword Units": the classic paper that popularized byte-pair encoding for open-vocabulary neural text models.
- Kudo and Richardson (2018), "SentencePiece": important for understanding modern subword tokenization pipelines that work directly from raw text.
2. Why Transformers Matter
Before transformers, many language models processed text mostly from left to right using recurrent neural networks. That worked, but it made long-range relationships difficult and slow to learn. Transformers changed the center of gravity by using self-attention.
Self-attention lets each token look at other tokens in the sequence and decide which ones matter for the current computation. For example, in “the bridge failed after it flooded,” the model needs to connect “it” with the right earlier concept. Attention is one of the mechanisms that helps.
Core intuition: a transformer does not simply store a sentence. It repeatedly rewrites every token's representation using context from nearby and distant tokens.
Attention: The Core Equation
Deeper dive:
Attention(Q, K, V) = softmax(Q·Kᵀ / √dₖ) · V
Q (queries) represent what each token is looking for. K (keys) represent what each token offers. V (values) represent the information each token carries. The dot product Q·Kᵀ measures how compatible each query is with each key — higher scores mean stronger relevance. Dividing by √dₖ (the square root of the key dimension) prevents these scores from growing too large, which would push softmax into regions with near-zero gradients. Softmax then turns the scaled scores into weights that sum to 1, so the output for each token is a weighted combination of all value vectors.
A Transformer Block
A transformer is built by stacking many similar blocks. Each block usually contains attention, a feed-forward network, normalization, and residual connections.
Input Tokens
↓
[Token Embeddings + Positional Encoding]
↓
┌─────────────────────────────────┐
│ Multi-Head Self-Attention │
│ + Residual Connection │
│ + Layer Normalization │
├─────────────────────────────────┤
│ Feed-Forward Network │
│ + Residual Connection │
│ + Layer Normalization │
└─────────────────────────────────┘
↓ (repeat N times)
[Final Layer Norm]
↓
[Linear + Softmax → Token Probabilities]
Text becomes token IDs.
IDs become vectors with position information.
Tokens exchange context with other tokens.
Each token representation is transformed.
The model scores possible next tokens.
The phrase large language model usually means a transformer with many layers, wide internal vectors, and a huge number of learned weights.
- Vaswani et al. (2017), "Attention Is All You Need": introduced the Transformer architecture and made attention the central operation.
- Bahdanau, Cho, and Bengio (2014), "Neural Machine Translation by Jointly Learning to Align and Translate": an influential precursor that made neural attention central to sequence modeling.
3. What an LLM Learns
The most common training objective is next-token prediction. During training, the model receives text and learns to predict the next token at many positions.
For a sentence like:
During a hurricane, people may choose to evacuate because ___
the model learns to assign probabilities to possible continuations such as “roads,” “officials,” “risk,” “family,” or “flooding.” It is not choosing from a fixed list of human-written answers. It is producing a probability distribution across its vocabulary.
After seeing enormous amounts of text, the model learns patterns that support grammar, style imitation, translation, summarization, code generation, and some forms of reasoning. This is why next-token prediction is more powerful than it sounds. To predict language well, the model has to build internal representations of many things language refers to.
That said, an LLM is not a database in the ordinary sense. It stores knowledge in distributed patterns across weights, and it can be wrong, outdated, or overconfident.
The training loss:
Loss = −Σ log P(correct token)
This is cross-entropy loss. The loss is higher when the model assigns low probability to the actual next token — if the correct token gets probability 0.01, the log is a large negative number and the loss contribution is large. Training minimizes this loss across many examples, gradually pushing the model to assign higher probability to plausible continuations.
- Radford et al. (2019), "Language Models are Unsupervised Multitask Learners": showed how large next-token models can display broad zero-shot behavior.
- Brown et al. (2020), "Language Models are Few-Shot Learners": the GPT-3 paper, important for understanding scale, prompting, and few-shot use.
4. Training Structure
During training, the model’s parameters are still changing.
- Text is collected and cleaned.
- Text is tokenized into long sequences.
- The model predicts the next token at many positions.
- The predicted probabilities are compared with the actual next tokens.
- The error becomes a loss value.
- Backpropagation adjusts the parameters to reduce future error.
This process is repeated over massive batches of examples. The model gradually becomes better at assigning high probability to plausible continuations and lower probability to unlikely ones.
Weights are updated.
The model sees many examples in parallel.
The goal is to reduce prediction error.
The learned weights are saved.
The model can be deployed for use.
No learning happens unless another training process is run.
Many deployed models also go through additional stages after pretraining, such as supervised fine-tuning, preference optimization, safety training, tool-use training, or domain adaptation. Those stages shape behavior, but the transformer foundation remains the same.
- Kaplan et al. (2020), "Scaling Laws for Neural Language Models": explains how model size, data size, and compute relate to training loss.
- Hoffmann et al. (2022), "Training Compute-Optimal Large Language Models": the Chinchilla paper, which shifted attention toward balancing parameters with enough training data.
- Ouyang et al. (2022), "Training Language Models to Follow Instructions with Human Feedback": a key paper for instruction tuning and reinforcement learning from human feedback.
5. Inference Structure
Inference is what happens when you use a trained model. The model receives a prompt and generates output one token at a time.
User input and system instructions.
The transformer computes next-token scores.
A decoding method chooses one token.
The selected token joins the context.
The loop continues until stopping.
The important distinction is that inference does not normally update the model’s parameters. The model may appear to learn within a conversation because previous messages remain in the context window, but that is temporary context use, not permanent weight updating.
- Dao et al. (2022), "FlashAttention": important for understanding why efficient attention kernels matter for practical transformer inference.
- Kwon et al. (2023), "Efficient Memory Management for Large Language Model Serving with PagedAttention": introduces vLLM/PagedAttention and explains the importance of KV-cache memory during serving.
- Chen et al. (2023), "Accelerating Large Language Model Decoding with Speculative Sampling": a readable entry point for inference acceleration through draft-and-verify decoding.
6. Generation and Decoding
At each generation step, the model outputs probabilities for possible next tokens. The decoding strategy controls how one token is selected.
- Greedy decoding chooses the highest-probability token every time. It is predictable but can be bland or get stuck.
- Sampling randomly draws from the probability distribution. It can be more varied, but also more error-prone.
- Temperature adjusts randomness. Lower temperature makes outputs more conservative; higher temperature makes outputs more exploratory.
- Top-k sampling restricts choices to the k most likely tokens.
- Top-p sampling restricts choices to the smallest set of tokens whose combined probability passes a threshold.
- Beam search tracks several candidate continuations at once. It is useful in some structured generation tasks, though less common for open-ended chat.
This is why the same prompt can produce different answers across runs. The model is not retrieving a single stored response. It is repeatedly constructing a continuation under a probability model and a decoding policy.
- Holtzman et al. (2019), "The Curious Case of Neural Text Degeneration": introduced nucleus sampling and explains why high-probability decoding can produce repetitive text.
- Fan, Lewis, and Dauphin (2018), "Hierarchical Neural Story Generation": an early influential use of top-k sampling for open-ended neural generation.
7. Common LLM Architectures
Not every transformer-based language model is structured the same way. Three families matter most:
Used by many chat and text-generation systems. They read previous tokens and predict the next token.
Best fit: open-ended generation, chat, code completion.
Read the full input and produce contextual representations, but are not naturally designed to generate long text one token at a time.
Best fit: classification, search, embeddings, extraction.
Use one transformer to understand the input and another to generate the output.
Best fit: translation, summarization, structured text-to-text tasks.
Route tokens through selected expert sub-networks instead of activating every parameter for every token.
Best fit: scaling capacity while controlling inference cost.
Most popular conversational LLMs are decoder-only because next-token generation maps naturally onto dialogue, writing, coding, and step-by-step responses.
Beyond text: Modern LLMs increasingly handle images, audio, video, and structured data alongside text. These multimodal models use similar transformer foundations but add encoders or tokenizers for non-text inputs. The architectural principles from this post still apply; the input space is simply wider.
- Devlin et al. (2018), "BERT": the landmark encoder-only transformer for bidirectional representation learning.
- Raffel et al. (2019), "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer": the T5 paper, a major encoder-decoder reference.
- Fedus, Zoph, and Shazeer (2021), "Switch Transformers": a key mixture-of-experts paper showing sparse scaling to very large parameter counts.
8. Model Parameters
Model parameters are the learned numbers inside the network. They include embedding tables, attention projections, feed-forward layers, normalization terms, and output weights. When people say a model has 7 billion, 70 billion, or hundreds of billions of parameters, they are talking about the number of learned values used to transform input tokens into output probabilities.
Store learned representations for vocabulary items.
Learn how tokens query, match, and exchange information.
Do much of the model's internal computation.
Maps final vectors back to vocabulary probabilities.
More parameters can increase capacity, but parameter count is not the whole story. Data quality, architecture, training recipe, context length, tokenizer, alignment process, inference settings, and tool access all affect model behavior. A smaller well-trained model can outperform a larger poorly trained model on specific tasks.
There is also an important deployment distinction:
- Total parameters: all learned weights stored by the model.
- Active parameters: the subset used for a given token, especially relevant in mixture-of-experts models.
- Context window: the amount of text the model can consider at once. This is not the same as parameter count.
- Kaplan et al. (2020), "Scaling Laws for Neural Language Models": useful for the relationship between parameter count, data, compute, and loss.
- Hoffmann et al. (2022), "Training Compute-Optimal Large Language Models": important because it shows that more parameters alone are not enough; training tokens matter too.
- Lepikhin et al. (2020), "GShard": an important sparse/mixture-of-experts scaling paper for distinguishing total parameters from active computation.
9. A Compact Mental Model
If you remember only one thing, use this:
An LLM is a large transformer trained to predict the next token. At inference time, it turns your prompt into vectors, computes next-token probabilities, selects a token, appends it to the prompt, and repeats.
That loop is simple. The scale is not. The power of LLMs comes from running this simple prediction game across huge datasets, with billions of learned parameters, and then using the trained model inside carefully designed inference systems.
- Zhao et al. (2023), "A Survey of Large Language Models": a broad survey that connects architectures, training, adaptation, evaluation, and deployment.
- Vaswani et al. (2017), "Attention Is All You Need", Brown et al. (2020), "Language Models are Few-Shot Learners", and Ouyang et al. (2022), "Training Language Models to Follow Instructions with Human Feedback": a good three-paper arc from transformer architecture to large-scale prompting to instruction-following behavior.
- A model has 70 billion parameters and a 128,000-token context window. Which number determines how much text it can consider at once? Which determines the model's learned capacity? Why are they independent?
- If you run the same prompt twice with temperature set to 0.0, you usually get the same answer. If you set temperature to 1.0, the answers may differ. Explain why, using what you know about decoding.
- A colleague says, "The model learned my writing style during our conversation." Using the distinction between training and inference from this post, explain what is actually happening.
In the next post, we can build on this foundation and look at prompting, context windows, retrieval-augmented generation, and why LLMs sometimes hallucinate.