How Large Language Models (LLMs) Work: Architecture, Tokenization, Attention, and Training Explained
Large Language Models (LLMs) are autoregressive neural networks built on the Transformer architecture that process text as numeric subword tokens and predict the probability distribution of each subsequent token. Through trillions of tokens of self-supervised pretraining followed by supervised instruction tuning and preference alignment, modern LLMs learn syntax, software logic, domain reasoning, and structured tool invocation without hand-coded linguistic rules.
Key Highlights
- LLMs never read raw characters directly; Byte-Pair Encoding (BPE) splits text, code, and numbers into integer token IDs drawn from a fixed vocabulary of 32,000 to 256,000 subwords.
- Self-attention computes dynamic query-key-value relationships across the entire prompt in parallel during prefill, while caching past key and value tensors in GPU memory (the KV cache) during token-by-token decoding.
- Sparse Mixture-of-Experts (MoE) architectures decouple total parameter capacity from per-token inference FLOPs by activating only a small subset of specialized feed-forward networks per token.
- Raw pretrained base models merely complete documents; post-training stages—Supervised Fine-Tuning (SFT), Direct Preference Optimization (DPO), and Reinforcement Learning with Verifiable Rewards—turn base models into reliable assistants.
1. From Raw Text to Subword Tokens and Vector Space
Before a neural network can reason over a Python function, a clinical note, or a financial contract, raw UTF-8 strings must be converted into numbers. Modern Large Language Models use subword tokenizers—most commonly Byte-Pair Encoding (BPE)—trained statistically over multilingual text and source code. Common English words like ‘network’ map to a single token ID, whereas rarer compound words like ‘microsegmentation’ split into two or three reusable subword fragments.
Every integer token ID acts as an index into an embedding lookup matrix. If a model uses a hidden dimension of 4,096, each token ID retrieves a learned 4,096-dimensional floating-point vector. Because self-attention processes tokens in parallel rather than sequentially like older recurrent networks, the model injects word order mathematically using Rotary Position Embeddings (RoPE), rotating query and key vectors by angles proportional to their sequence index so attention scores naturally reflect relative token distance.
Why Tokenization Quirks Affect Cost, Latency, and Arithmetic
Tokenization directly shapes API billing and latency. Languages with denser scripts or specialized code indentation patterns can consume 1.5× to 3× more tokens than plain English prose, shrinking the effective context window and increasing Time to First Token (TTFT). Careful tokenizer vocabularies now assign dedicated single-digit tokens (0–9) or three-digit groups so multi-digit arithmetic aligns cleanly across columns.
2. Inside the Decoder Block: Self-Attention, GQA, and the KV Cache
A modern decoder-only Transformer stacks dozens of identical residual layers—each combining pre-normalization (RMSNorm), causal multi-head self-attention, and a SwiGLU feed-forward network. Inside causal self-attention, each token projects its hidden vector into three representations: a Query (what this token is looking for), a Key (what information this token advertises), and a Value (the payload passed forward when matched). Causal masking prevents any token from peeking ahead at future words during parallel training.
During live inference, LLM serving splits into two hardware regimes. In the prefill phase, the GPU processes all prompt tokens simultaneously in one massive matrix-matrix multiplication—saturating Tensor Cores. In the decode phase, the model emits one new token at a time. Recomputing keys and values for a 32,000-token prompt on every step would be prohibitively slow, so inference engines store past keys and values in High-Bandwidth Memory as the KV cache.
| Attention Architecture | KV Cache Footprint | Context Scaling | Production Adoption |
|---|---|---|---|
| Multi-Head Attention (MHA) | 100% baseline (1 K/V head per Q head) | Heavy VRAM pressure above 8K tokens | Early GPT-2 / GPT-3 generation models |
| Multi-Query Attention (MQA) | 4–8% of MHA (single shared K/V head) | Fast long-context decode, minor quality dip | High-throughput code & latency-first models |
| Grouped-Query Attention (GQA) | 12–25% of MHA (4–8 Q heads share 1 K/V) | Excellent balance of accuracy and KV savings | Industry standard across Llama, Qwen, Mistral |
| Multi-Head Latent Attention (MLA) | 5–10% of MHA (low-rank compressed latent KV) | Supports 128K+ contexts at high batch sizes | Frontier sparse MoE architectures |
3. Dense Models vs Sparse Mixture-of-Experts (MoE)
In a classical dense LLM—say, a 70-billion-parameter model—every single parameter participates in computing every generated token. While dense models are straightforward to load-balance across GPUs, scaling dense parameters past 100 billion multiplies per-token latency and electricity cost linearly.
Sparse Mixture-of-Experts (MoE) architectures replace each monolithic feed-forward layer with 8 to 256 smaller ‘expert’ sub-networks controlled by a lightweight gating router. A model may hold 400 billion total parameters in memory (preserving broad encyclopedic knowledge) while activating only 37 billion parameters per token—delivering small-model inference speed with frontier reasoning depth.
- Prefill efficiency: MoE models process long RAG prompts up to 3–5× faster per active FLOP than comparably capable dense models.
- VRAM reality check: Even though only a fraction of experts fire per token, all expert weights must still reside in fast GPU HBM memory to avoid PCIe stalls.
- Router load-balancing: Auxiliary loss free balancing keeps popular tokens from overwhelming a single GPU in expert-parallel clusters.
4. The Three-Stage Training Pipeline: Pretraining, SFT, and Alignment
Building a production-grade LLM happens in three distinct phases with starkly different compute budgets. Self-supervised pretraining consumes over 95% of total GPU hours: clusters of thousands of accelerators train on trillions of deduplicated web, academic, and code tokens using cross-entropy next-token loss. The resulting base model understands world concepts and code structure deeply, yet if you ask it ‘How do I secure an SSH server?’, it might respond by generating ten more exam questions rather than answering.
Post-training shapes raw capability into helpfulness and safety. Supervised Fine-Tuning (SFT) trains on curated demonstrations of clean instruction following, multi-turn tool use, and structured JSON formatting. Preference alignment—via Reinforcement Learning from Human Feedback (RLHF), Direct Preference Optimization (DPO), or reinforcement learning against deterministic code/math verifiers—teaches the model to refuse harmful requests, reason step-by-step before answering complex logic problems, and state uncertainty honestly when context is missing.
FAQs
Do Large Language Models store a literal copy of their training database inside weights?
No. Neural weights store compressed statistical relationships across concepts, syntax, and reasoning patterns rather than a searchable text index—which is why LLMs excel at synthesis and translation but should be paired with Retrieval-Augmented Generation (RAG) when exact, up-to-the-minute citations are required.
What does 'temperature = 0' actually do during LLM generation?
Setting temperature near zero makes token sampling greedy—selecting the single highest-probability next token at every step. Because parallel GPU floating-point reductions are slightly non-associative across varying batch sizes, even temperature 0 can occasionally vary by a token unless deterministic kernels and fixed seeds are enforced.
Why does doubling prompt length more than double prefill compute at extreme context lengths?
Standard full self-attention compares every token against every preceding token, giving O(N²) quadratic compute complexity with respect to sequence length N—though FlashAttention tiles attention inside fast GPU SRAM to keep memory scaling linear.
What is the difference between a base LLM and an instruct-tuned LLM?
A base LLM is trained purely to predict the next token in arbitrary documents, making it ideal for custom fine-tuning. An instruct-tuned LLM has undergone SFT and preference alignment to follow system prompts, chat turns, and tool schemas reliably out of the box.
References & Sources
- Vaswani, A. et al. — Attention Is All You Need, Advances in Neural Information Processing Systems (NeurIPS).
- Dao, T. — FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning, Stanford Computer Science.
- Ainslie, J. et al. — GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints, EMNLP.
- National Institute of Standards and Technology (NIST) — Artificial Intelligence Risk Management Framework (AI RMF 1.0 & Generative AI Profile NIST AI 600-1).