Neural Mastery

Foundation Model & Transformer Internals

The engineering details that turn the Transformer architecture (see Attention & Transformers) into a model you can actually run efficiently at billions of parameters.

A giant language model is really just "predict the next word, over and over" — run through a lot of clever engineering to make that fast and reliable at scale. Text gets chopped into small chunks (tokenization), those chunks become numbers the model can actually compute with (embeddings), the model figures out how each chunk relates to every other chunk it's seen so far (attention, repeated through a stack of layers), and out comes a ranked guess for what comes next. Everything on this page is either "how do you make that guess-the-next-word loop fast and cheap enough to run in production" (KV cache, quantization, attention variants) or "once you have a ranked list of next-token guesses, how do you actually pick one" (sampling).

Everything below makes each of those engineering pieces exact.

The Full Pipeline: Text to Token

Every section below is one step of this same pipeline — worth seeing end to end once before the pieces are covered individually:

Text

Tokenizer (BPE/WordPiece/SentencePiece)

Token IDs

Embeddings (learned lookup table)

+ Positional Encoding (RoPE / ALiBi)

┌─────────────────────────────┐
│  Transformer Block × N       │
│  Q K V projections           │
│   ↓                          │
│  Self-Attention (+ GQA/MQA/MLA, masking) │
│   ↓                          │
│  Residual + RMSNorm          │
│   ↓                          │
MLP / SwiGLU (or MoE router)│
│   ↓                          │
│  Residual + RMSNorm          │
└─────────────────────────────┘

LM Head (linear projection to vocab size)

Logits

Softmax → probability distribution

Sampling (temperature / top-k / top-p)

Token  →  fed back in as the next input, autoregressively

Every arrow above is one section of this page or Attention & Transformers — the goal of what follows is that none of these steps stay a black box.

The same pipeline, clickable, with a live sampling playground at the end:

Interactive
LLM Inference Flow Visualizer
× N layersautoregressive feedback
Text
Tokenizer
Token IDs
Embeddings
+ Positional Encoding
QKV Projections
Self-Attention
Residual + RMSNorm
MLP / MoE
Residual + RMSNorm
LM Head
Logits
Softmax
Sampling
Token
Sampling: Turns the probability distribution into one actual next token -- temperature, top-k, and top-p all shape exactly how. Try the playground below.
Sampling playground
"the cat sat on the ___" -- next-token candidates and their logits
mat69.2%
chair22.5%
table8.3%
floor (cut)0.0%
roof (cut)0.0%
moon (cut)0.0%
Click any stage of the pipeline for what it does, and use the sampling playground to see how temperature / top-k / top-p actually reshape a probability distribution -- real softmax and truncation math over a small fixed candidate set.

Tokenization

Models don't see raw text — they see a sequence of integer token IDs from a fixed vocabulary. BPE (Byte Pair Encoding) builds this vocabulary by starting with individual characters/bytes and iteratively merging the most frequent adjacent pair into a new token, until reaching a target vocabulary size. WordPiece and SentencePiece are close variants (WordPiece used by BERT; SentencePiece treats the input as a raw stream, sidestepping the need for pre-tokenized words, useful for languages without clear word boundaries).

Why subword tokenization at all, instead of whole words or single characters: whole-word vocabularies explode in size and can't handle unseen words; single-character vocabularies produce very long sequences (expensive, given attention's O(n2)O(n^2) cost — see Algorithms & Data Structures). Subwords are the practical middle ground — common words stay as one token, rare/novel words decompose into recognizable pieces.

l
o
w
e
r
raw chars
merge 1
merge 2
merge 3
word: "lower" — click a step to watch its symbol sequence shrink as merges accumulate.
Step 1: merge the most frequent adjacent pair "l"+"o" → "lo" -- added to the vocabulary as one new symbol.

Embeddings

The first layer of any Transformer is an embedding table — a lookup mapping each token ID to a learned vector. These vectors start random and, through training, come to encode meaning: semantically related tokens end up with similar embeddings (high cosine similarity — see Linear Algebra).

Positional Encoding

Attention & Transformers — Positional Encoding covers RoPE (the dominant modern choice) in depth. ALiBi (Attention with Linear Biases) is the other approach worth knowing: instead of modifying the Q/K vectors like RoPE does, ALiBi adds a fixed, non-learned penalty directly to the attention scores, proportional to the distance between the two positions — the further apart two tokens are, the more their attention score gets penalized before the softmax. This is simpler than RoPE and was designed specifically for strong length extrapolation (performing well at sequence lengths longer than anything seen in training), though RoPE (often combined with explicit scaling techniques for long context) has become the more common choice in current frontier models.

0-3.01-2.52-2.03-1.54-1.05-0.560.07-0.58-1.09-1.5key position →score penalty ↑
Farther keys (darker) get penalized more before softmax — no learned parameters, purely a function of distance.
score(i,j)=qikjmij\text{score}(i,j) = q_i \cdot k_j - m \cdot |i - j|
Unlike RoPE (which rotates Q/K vectors themselves), ALiBi leaves Q/K untouched and instead subtracts a distance-proportional penalty directly from the attention score matrix, before softmax -- simpler, and specifically designed for extrapolating well past training-time sequence lengths.

KV Cache

During autoregressive generation, the model produces one token at a time, and naively would recompute Key and Value vectors for the entire sequence so far at every single step — wasteful, since those K/V vectors for already-generated tokens never change. The KV cache stores them once and reuses them, so each new token only requires computing Q/K/V for itself. This is the single biggest practical speedup in LLM inference, and it's also the primary consumer of GPU memory during generation — which is exactly why GQA and Paged Attention (below) exist.

Mode
t=0t=1t=2t=3t=4
■ recomputed this step■ reused from cache
Total K/V computations over 5 steps: 5
Cached: each token's K/V is computed exactly once, ever, and reused -- only 5 total K/V computations across 5 steps, growing linearly. This is the single biggest inference speedup, and the primary consumer of GPU memory during generation.

Architecture Families

  • Encoder-only (BERT-style): sees the full input at once (bidirectional attention) — good for understanding tasks (classification, embeddings), not for generation.
  • Decoder-only (GPT-style): only attends to earlier tokens (causal/masked attention) — the dominant architecture for modern LLMs, since next-token prediction naturally trains a model that can also generate.
  • Encoder-decoder (T5-style): separate encoder for the input and decoder for the output, connected via cross-attention — well-suited to translation/summarization where input and output are distinct sequences.
Architecture family
01234key →
Filled cell = query (row) allowed to attend to key (col).
Causal/masked attention -- each position can only attend to itself and earlier positions. The dominant architecture for modern LLMs, since next-token prediction naturally trains a model that can also generate.

Mixture of Experts (MoE)

Instead of every token passing through the same dense feed-forward layer, an MoE layer has many "expert" feed-forward sub-networks, and a small router network picks a small subset (e.g. 2 of 8) of experts to actually run for each token. This decouples a model's total parameter count from its per-token compute cost — you get a much larger model (more knowledge capacity) without a proportional increase in inference cost, since most parameters sit idle for any given token. Mixtral and several frontier-scale models use this.

The
cat
sat
E0
0.71
E1
0.04
E2
0.03
E3
0.02
E4
0.05
E5
0.09
E6
0.03
E7
0.03
Click a token — its router distribution changes, and a different top-2 of 8 experts light up.
Router scores every expert for "cat"; only the top-2 (experts 0, 5) actually run. The other 6 experts' parameters sit idle for this token -- a different token activates a different subset.

Attention Variants: MHA, GQA, MQA, MLA

Every variant below changes how many Key/Value projections are computed relative to Query heads — a design decision made at training time whose consequence is entirely about inference-time KV cache memory (see LLM Inference Optimization — Attention Variants for the full memory-tradeoff math):

  • MHA (Multi-Head Attention): the original design — every head gets its own full Q, K, and V projections. Highest quality, largest KV cache.
  • MQA (Multi-Query Attention): all heads share one K/V projection, only Q stays per-head — smallest KV cache, some quality cost.
  • GQA (Grouped-Query Attention): the middle ground most current production LLMs actually use — heads are split into groups, each group shares one K/V projection.
  • MLA (Multi-Head Latent Attention): introduced by DeepSeek-V2 — compresses K/V into a smaller shared latent representation, decompressed per head, recovering MHA-like quality at MQA-like KV cache cost.
Attention variant
Q0Q1Q2Q3Q4Q5Q6Q7KV0KV1KV pairs stored per token: 2
8 query heads (top) throughout — only the K/V side (bottom) changes between variants.
Heads split into groups; each group shares one K/V projection -- the middle ground most current production LLMs use (here: 4 heads per group, 2 K/V pairs stored).

Sparse and Sliding-Window Attention

Full self-attention costs O(n2)O(n^2) in sequence length — every token attends to every other token. Two families of techniques restrict which pairs of tokens actually attend to each other, trading some long-range connectivity for much cheaper long-context compute:

  • Sliding-window attention: each token only attends to a fixed-size window of nearby tokens (e.g. the previous 4096 tokens), not the entire sequence — reduces the cost to linear in sequence length. Information from outside the window can still propagate indirectly across multiple layers (token A attends to B within its window, and B's own window reached C in an earlier layer), but not directly in a single attention operation. Mistral's models popularized this as a practical way to support long context without paying full quadratic cost.
  • Sparse attention (more generally): fixed or learned patterns where each token attends to only a subset of positions — combinations of local windows, strided/dilated patterns, and a small number of global tokens that everything attends to — trading the guarantee of full connectivity for sub-quadratic cost, useful when full O(n2)O(n^2) attention is the actual bottleneck at very long context lengths.
Row = query position, column = key position. Hover a row to trace one query's window.
Attended pairs: 33 vs. 78 for full causal attention at this sequence length -- the window keeps cost linear in sequence length instead of quadratic, while information can still propagate indirectly across multiple layers (row 8 reaches row 5 via row 6 and 7's own windows in an earlier layer).

The MLP Block: SwiGLU

Every Transformer block's feed-forward sublayer (see Attention & Transformers — The Full Transformer Block) needs an activation function between its two linear projections. Modern LLMs (LLaMA and most successors) use SwiGLU instead of the original Transformer's plain ReLU:

SwiGLU(x)=Swish(xW1)(xW3)W2\text{SwiGLU}(x) = \text{Swish}(xW_1) \odot (xW_3)\,W_2

Where Swish(x)=xσ(x)\text{Swish}(x) = x \cdot \sigma(x) (see Activation Functions) and \odot is elementwise multiplication. The key structural idea is the gating mechanism: xW3xW_3 acts as a learned, per-element gate controlling how much of Swish(xW1)\text{Swish}(xW_1) passes through, before the result is projected back down by W2W_2 — the network learns which features to let through, rather than applying the same fixed nonlinearity uniformly everywhere. This costs more parameters than a plain ReLU MLP (three weight matrices instead of two, for the same hidden dimension), which LLaMA-family models compensate for by shrinking the hidden dimension slightly — and empirically, SwiGLU-based MLPs train to better loss than ReLU-based ones at the same parameter budget, which is why virtually every current open-weight LLM uses it or a close variant (GeGLU, using GELU instead of Swish, is functionally similar).

Swish=1.76×gate=0.70=out=1.23
Gate near 0 -- this feature is blocked regardless of its Swish activation. Gate near 1 -- it passes through nearly unchanged.
SwiGLU(x)=Swish(xW1)(xW3)W2\text{SwiGLU}(x) = \text{Swish}(xW_1) \odot (xW_3)\, W_2
Two parallel projections of the same input x: Swish(xW1) is the 'content' branch, xW3 is a learned per-element GATE in (roughly) [0,1]-ish range controlling how much of that content passes through, before W2 projects the product back down. The gate itself is learned, not fixed.

Sampling: From Logits to a Token

The LM head's output is logits — one raw score per vocabulary token — turned into a probability distribution via softmax (see Probability & Statistics). Turning that distribution into one actual next token is a deliberate choice, not a fixed step, and it's the part of generation most tutorials skip:

  • Greedy decoding: always pick the single highest-probability token. Deterministic and fast, but tends to produce repetitive, generic text — greedy decoding has no mechanism to recover from committing to a locally-optimal-but-globally-poor token early in a generation.
  • Temperature: rescale the logits by dividing by TT before softmax — T<1T < 1 sharpens the distribution (more confident, closer to greedy, less diverse), T>1T > 1 flattens it (more random, more diverse, more likely to produce incoherent text at extremes). T0T \to 0 recovers greedy decoding exactly.
  • Top-k sampling: restrict sampling to only the kk highest-probability tokens (renormalizing their probabilities to sum to 1), discarding the long tail entirely — prevents the rare but real failure mode of sampling a wildly implausible token from the distribution's tail.
  • Top-p / nucleus sampling: instead of a fixed count kk, keep the smallest set of tokens whose cumulative probability exceeds threshold pp (e.g. 0.9) — adapts automatically to how peaked or flat the distribution is at each step (a very confident next-token prediction keeps very few candidates; a genuinely ambiguous one keeps more), which is why top-p is generally preferred over a fixed top-k in production systems.
  • Repetition penalty: directly reduce the logits of tokens that have already appeared in the generated output, discouraging the model from looping — a practical patch for a real failure mode (especially at low temperature) rather than a principled part of the probability model.
  • What production APIs actually expose: most LLM APIs (see LLM Hosting & Serving Patterns) let you set temperature and top_p directly — temperature=0 for maximally deterministic/reproducible output (useful for structured extraction tasks), higher values for creative/varied generation.
Strategy
the
a
this
my
that
some
one
each
any
no
3 of 10 tokens eligible for sampling.
Keeps the smallest set of tokens whose cumulative probability exceeds p=0.85 -- adapts automatically: a peaked distribution keeps very few tokens, a flat one keeps more.

Context Window

The maximum sequence length a model can process at once. Limited fundamentally by (a) the O(n2)O(n^2) compute/memory cost of attention, and (b) the fact that positional encoding and attention patterns learned during training may not generalize well to sequence lengths never seen in training. Longer context comes from a combination of architectural tricks (RoPE scaling, sparse/sliding-window attention above), more efficient attention kernels (FlashAttention), and training specifically on long sequences.

compute costsequence length →
■ full attention — O(n²)■ sliding-window — O(n·w)
At 8,000 tokens: full attention costs 3.9x more than sliding-window attention (window=2048). That multiplier only grows as context length grows -- exactly why long-context models lean on sparse/sliding-window attention plus efficient kernels rather than paying full O(n²) at scale.

Next: Training Pipeline — how a raw Transformer becomes a helpful, aligned assistant.

Last updated Sep 5, 2026Edit this pageReport an issue
← Previous
LLMs & GenAI — Roadmap
Next →
Training Pipeline