MODEL FOUNDATION · ARCHITECTURE
Large Language Model Architecture and Training: Tokens, Attention and Pretraining
Follow text through tokenization, embeddings, causal attention and decoder blocks to understand how a model produces its next-token distribution.
Large language model architecture is a decoder-only Transformer that converts text into tokens, maps each token to a learned embedding with positional information, processes the sequence through stacked self-attention layers with causal masking, and produces a probability distribution over the vocabulary for the next token. Training uses next-token prediction on large corpora with causal language modelling objectives, optimised with gradient-based methods over billions of tokens.
Architecture building blocks
How Is Text Converted Into Tokens?
Tokenization is the first step in processing text through a large language model. A tokenizer splits input text into subword units called tokens. Modern tokenizers use byte-pair encoding (BPE) or SentencePiece algorithms, which learn a vocabulary of subword pieces from a training corpus. Common words become single tokens; rare words are split into multiple subword tokens.
The tokenizer is not part of the neural network—it is a deterministic preprocessing step. The same text always produces the same token sequence given the same tokenizer. The tokenizer's vocabulary is fixed at training time and cannot change without retraining the model's embedding layer.
Tokenization affects cost, context length and multilingual coverage. A model with a vocabulary optimised for English may produce more tokens for non-English text, increasing inference cost and reducing effective context length. This is an engineering consideration, not just a linguistic one.
Transformer Data-Flow Explorer
Conceptual data flow—follows the path from input text to next-token probability.
Conceptual visualisation — not a live computation.
What Do Embeddings and Positional Information Represent?
After tokenization, each token ID is mapped to a learned embedding vector. The embedding is a high-dimensional real-valued vector (typically 768 to 12288 dimensions) that the model learns during training. Tokens that appear in similar contexts tend to have similar embedding vectors—a property that emerges from training, not from manual design.
Positional information is added because self-attention is permutation-invariant by default—without position information, the model cannot distinguish "cat sat on the" from "the on sat cat." Modern large language models use rotary position embeddings (RoPE) or similar methods that encode relative positions into the attention computation, allowing the model to generalise to longer sequences than seen during training.
The embedding layer and positional encoding together determine the model's context window—the maximum number of tokens the model can process in a single forward pass. Context length is a design decision with direct implications for memory, compute and cost.
How Does Causal Self-Attention Work?
Self-attention is the core mechanism of the Transformer. For each token in the input, self-attention computes a weighted combination of all other tokens' representations. The weights are determined by a similarity score between the current token (query) and each other token (key), scaled and normalised through softmax.
Causal self-attention applies a mask that prevents each token from attending to future tokens. This is essential for language modelling: when predicting the next token, the model must not see the answer. The causal mask sets attention scores for future positions to negative infinity before softmax, resulting in zero attention weight.
Multi-head attention runs multiple attention computations in parallel, each with its own learned query, key and value projections. This lets the model attend to different relationships simultaneously—one head might focus on syntactic dependencies, another on semantic similarity. The outputs of all heads are concatenated and projected back to the model dimension.
What Happens Inside a Decoder-Only Transformer?
- Token embeddings with positional encoding
- Residual stream from previous layers
- Layer norm → multi-head causal self-attention
- Residual connection adds attention output to stream
- Layer norm → feed-forward network (MLP with activation)
- Residual connection adds FFN output to stream
- Repeat for N stacked decoder blocks
- Contextualised hidden states for every token position
- Final hidden state fed to LM head for next-token prediction
How Are Large Language Models Pretrained?
Pretraining is the process of training a large language model on a large corpus of text using the next-token prediction objective. The model receives a sequence of tokens and is asked to predict the next token at each position. The loss is the cross-entropy between the predicted probability distribution and the actual next token.
Pretraining requires significant compute. The model is trained on billions or trillions of tokens using stochastic gradient descent or AdamW optimiser, with a learning rate schedule (warmup followed by cosine decay). Training runs for multiple epochs over the corpus, typically on clusters of GPUs or TPUs with data and model parallelism.
The training data mixture matters. Most large language models are trained on a blend of web text, books, code and structured data. The composition of this mixture affects the model's capabilities—a model trained on more code will be better at code generation, while one trained on more books may produce more formal prose. Data quality, deduplication and filtering are as important as data quantity.
Which Architecture Choices Affect Context, Memory and Output?
Key architecture decisions and their operational impact.
| Decision | Options | Trade-off | Recommendation |
|---|---|---|---|
| Number of layers | Fewer (6–32) vs more (48–96) | Expressivity vs compute and memory per forward pass | Match to parameter budget and target inference hardware |
| Hidden dimension | Narrow (768–2048) vs wide (4096–12288) | Representation capacity vs memory and latency | Determine from target parameter count and GPU memory constraints |
| Attention heads | Few (8–16) vs many (32–96) | Parallel relationship modelling vs per-head capacity | Enough heads to capture distinct relationships without reducing per-head dimension too far |
| Context length | Short (2k–4k) vs long (32k–128k+) | Input capacity vs KV cache memory and attention compute (quadratic) | Set by application requirements; use RoPE or ALiBi for length generalisation |
| Vocabulary size | Small (32k) vs large (64k–128k) | Token count per text (cost) vs embedding matrix size | Larger for multilingual; smaller for English-only to save embedding memory |
| Positional encoding | Learned vs RoPE vs ALiBi | Training flexibility vs length generalisation | RoPE for most modern models; ALiBi for extrapolation to longer contexts |
Key takeaways
- Tokenization is a deterministic preprocessing step—same text, same tokens, same tokenizer.
- Embeddings are learned vectors; positional encoding adds position information to attention.
- Causal self-attention prevents future-token leakage; multi-head attention captures parallel relationships.
- Pretraining uses next-token prediction with cross-entropy loss over billions of tokens.
- Architecture choices (layers, dimensions, context length, vocabulary) directly determine memory, latency and cost.
The Transformer architecture is established in the foundational paper (Vaswani et al., 2017). Implementation details (RoPE, GQA, SwiGLU) are verified against Hugging Face Transformers documentation and model-specific technical reports.
- Architecture variants (Mixture-of-Experts, multi-query attention, grouped-query attention) are not covered in detail here.
- Specific parameter counts and configurations change with each model generation.
Review cadence: Reviewed every 90 days. Next review by December 2026.
Understanding the method is the first step. Can you defend the model decision?
In the Large Language Model Course, you move through the same engineering lifecycle with an open-source model: establish a baseline, prepare data, fine-tune with LoRA or QLoRA, evaluate failures, document limitations and make a release, revise or reject decision.
Advanced eight-week live course · Approximately 4–5 hours per week · Python, statistics, machine learning and neural-network foundations expected.
- Tier 1
- Tier 1