← Back to Topic Briefing
📄 Cited Report
📚 Sources (12)
📊 Infographic
🎬 Studio Video
⚡ Short Video
🎥 Explainer Video
⬇ Download JSON
AI FOR ENGINEERS · PART 03 / 09
🧠 AI For Engineers, Part 3: Inside the LLM Engine — Matrices, Attention & Weights — Interactive Concept Mind Map
Expand All
Collapse Branches
AI For Engineers, Part 3: Inside the LLM Engine — Matrices, Attention & Weights
Ch. 01: From Part 2 Audits to the Five LLM Engine Pillars
• Core Principle: Every numeric drift and phantom citation in Part 2 traces directly to Transformer matrix math and sampling.
Why Unverified Drafts Hallucinated
• Pump draft shifted LOG-104 seal-housing peak (84.2°C → 94.2°C across SPEC-201's 85.0°C limit) and fabricated SPEC-992.
• Rule / Formula: verify_document.py @ τ = 0.0 → Quarantine Drift
Neural Manifolds & 2017 Attention
• Affine weight projections, Pre-Norm residual highways, and Q, K, V attention circuits replace sequential recurrence.
• Rule / Formula: X → Affine + Nonlinearity + Causal Attention
Decoder Layers, HBM & KV Caches
• RoPE, SwiGLU MLPs, compute-bound prefill, memory-bound decode, GQA, and FlashAttention govern context window physics.
• Rule / Formula: Prefill = Compute-Bound | Decode = HBM-Bound
Sampling, Quantization & Weights
• Temperature scaling shapes inference logits, while Pre-Training, SFT (full or LoRA), and Preference/RL alignment update weights.
• Rule / Formula: Training Updates W | Inference Freezes W
Ch. 02: Affine Projections, Fixed Width & Nonlinear Manifolds
• Core Principle: Without nonlinear activations, a hundred linear matrices algebraically collapse into one single matrix.
Activation Tensor X (B × T × d_model)
• Sequence length T varies with prompt tokens, while hidden width d_model (e.g., 4,096) remains fixed across all layers.
• Rule / Formula: Shape(X) = [Batch B, Tokens T, Width d_model]
Weights W and Bias Vector b
• Each linear projection maps d_in features to d_out features using learned weight parameters W and additive bias b.
• Rule / Formula: Z = X × W + b (W in R^(d_in × d_out))
Why Linear Stacks Collapse Without σ
• Without ReLU, GELU, or SwiGLU activations, stacked matrices reduce to one linear transform and cannot separate curved data.
• Rule / Formula: W₂ × (W₁ × X) = W_eff × X vs σ(X × W₁) × W₂
Ch. 03: Pre-Norm Residual Highways & RMSNorm Stability
• Core Principle: Additive residual skip highways preserve an identity gradient path across eighty to one hundred layers.
Repeated Matrix Products Diverge
• Multiplying 100 unnormalized matrices drives singular values to 0 or ∞, halting parameter updates in early layers.
• Rule / Formula: ∏ W_l → 0 (Vanishing) or ∞ (Exploding)
Additive Pre-Norm Residual Stream
• Attention and MLP sub-layers read normalized states from a shared stream and add bounded delta updates back into x.
• Rule / Formula: x_next = x + F(RMSNorm(x)) | ∂x_next/∂x = I + ∂F/∂x
Root Mean Square Gain Stabilization
• Divides vector x by its root-mean-square norm times learned scale γ, skipping mean subtraction to reduce memory ops.
• Rule / Formula: RMSNorm(x) = (x / √(mean(x²) + ε)) * γ
Ch. 04: Superposition & Hypothesis: How Weights Blur 84.2°C → 94.2°C
• Core Principle: Weights store lossy superposed feature directions—never treat parametric memory as a relational database.
Packing Millions of Features in R^d
• A 4,096-wide vector holds exponentially many nearly perpendicular directions, letting layers store >> 4,096 concepts.
• Rule / Formula: m >> d Directions with |dot(v_i, v_j)| < ε
Shared Neurons & Cross-Talk Noise
• Single neurons activate on unrelated syntax and physics features; overlapping projections create non-zero interference.
• Rule / Formula: x_reconstructed = W^T W x = x + Interference
How Priors Can Pull 84.2°C → 94.2°C
• Illustrates how lossy parametric priors can pull prompt numbers toward common values unless CSV scripts verify LOG-104.
• Rule / Formula: LOG-104 CSV = 84.2°C ≠ Superposed Prior 94.2°C
Ch. 05: Why Fixed-State Recurrence Failed & 2017 Attention
• Core Principle: Vaswani et al. (2017) replaced O(N) sequential recurrence with O(1) path-length all-to-all token routing.
Serial O(N) Steps & Information Loss
• State h_t waits for h_(t−1), blocking parallel GPU training and compressing distant document specs into one lossy vector.
• Rule / Formula: h_t = f(h_(t−1), x_t) → Path Length O(N)
Attention Is All You Need Blueprint
• Replaced recurrence with direct all-pairs attention: N = 6 layers, d_model = 512, d_ff = 2048, and 8 heads of width 64.
• Rule / Formula: Direct Token Routing → Path Length O(1)
Dropping the Bidirectional Encoder
• Frontier LLMs retain only the masked autoregressive Decoder stack so one unified architecture reads prompts and generates.
• Rule / Formula: Encoder-Decoder (2017) → Causal Decoder Stack
Ch. 06: Scaled Dot-Product Q, K, V Math & Causal Masking
• Core Principle: Dividing Q·K^T by √d_k prevents softmax gradient saturation while causal masks block future tokens.
Scaled Dot-Product Attention
• Queries match Keys via dot products to compute normalized routing weights that blend Value payload vectors across context.
• Rule / Formula: Attention(Q,K,V) = softmax((Q·K^T + M) / √d_k) · V
Preventing Softmax Saturation
• Unit-variance Q and K of width d_k = 64 yield dot-product variance 64; scaling by 1/√64 = 1/8 restores unit variance.
• Rule / Formula: Var(q · k) = d_k → Var((q · k)/√d_k) = 1
Upper-Triangular Future Blocking
• Mask matrix M sets entries j > i to −∞ before softmax, producing exact 0.0 weights on ungenerated future tokens.
• Rule / Formula: M_(i,j) = 0 (j ≤ i) | M_(i,j) = −∞ (j > i)
Ch. 07: Multi-Head Routing & Why Induction Heads Invent SPEC-992
• Core Principle: Induction heads complete structural citation patterns even when no matching source file exists.
Parallel Subspace Projections
• W_Q, W_K, and W_V split d_model into H heads (d_head = d_model/H); W_O merges routed head outputs back to the stream.
• Rule / Formula: MHA(X) = Concat(head₁, …, head_H) × W_O
Two-Layer Pattern Completion
• Layer-1 head indexes previous-token transitions; Layer-2 head matches the current prefix and predicts matching structure.
• Rule / Formula: [SPEC-][201] … [Seal Limit: SPEC-] → [992]
Stopping Phantom Citations
• Pair Part 2's Unknowns Contract in the prompt with verify_document.py file-existence checks against the evidence folder.
• Rule / Formula: Cite Existing ID or Output UNKNOWN + Script Audit
Ch. 08: Tokens, Embeddings, RoPE & SwiGLU Memory Layers
• Core Principle: Subword tokens, RoPE relative angles, and SwiGLU MLP banks hold nearly two-thirds of dense LLM weights.
Subword IDs & Learned Matrix E
• Tokenizer maps text/digits to IDs in V ≈ 128k (~0.75 words/token); row E[id] initializes the contextual residual vector.
• Rule / Formula: Text → Token IDs [0..V−1] → x₀ = E[id]
Relative Distance via 2D Rotation
• Rotates Q at index m and K at index n in complex 2D planes so their inner product depends directly on offset (m − n).
• Rule / Formula: dot(R_m q, R_n k) = g(q, k, m − n)
Where Two-Thirds of Weights Reside
• Gated projections W_gate and W_up detect multi-token features gathered by attention; W_down writes attributes back.
• Rule / Formula: SwiGLU(x) = (Swish(x·W_gate) * (x·W_up)) · W_down
Ch. 09: GPU HBM Bandwidth vs Compute: Prefill vs Decode
• Core Principle: Prompt prefill saturates GPU compute cores in parallel; token-by-token decode stalls on HBM weight reads.
Compute FLOPs vs HBM Byte Traffic
• GPU tensor cores compute orders of magnitude faster than off-chip HBM buses can stream gigabytes of model weights.
• Rule / Formula: Intensity = FLOPs / Bytes Moved (HBM ↔ SRAM)
Parallel Matrix-Matrix (Compute-Bound)
• Processes all T prompt tokens at once; every weight fetched into SRAM multiplies across T vectors simultaneously.
• Rule / Formula: [T × d] × [d × d] → High Weight Reuse (TTFT)
Serial Matrix-Vector (Bandwidth-Bound)
• Each generated token depends on the prior output, streaming all active weights from HBM for just 1 token vector.
• Rule / Formula: [1 × d] × [d × d] → 1 Weight Read per Token
Ch. 10: KV Cache, GQA, FlashAttention & Context Window Drift
• Core Principle: GQA and FlashAttention tame KV memory traffic, while bounded context curbs empirical middle-context recall drops.
Trading Compute for VRAM Capacity
• Caching prior K and V tensors makes decode steps O(N) instead of O(N²), but VRAM and HBM reads grow with context N.
• Rule / Formula: KV Bytes = 2 × L × n_kv × d_head × N × bytes
GQA Shares K, V Across Query Groups
• Sharing 1 Key-Value head across 8 Query heads slashes KV Cache footprint and decode HBM traffic by 8×.
• Rule / Formula: MHA (n_kv = n_q) → GQA (n_kv = n_q / 8)
SRAM Tiling & Online Softmax
• Computes exact attention inside fast on-chip SRAM blocks so the N × N score matrix never writes to slow HBM.
• Rule / Formula: Attention Memory: O(N²) HBM → O(N) Linear
KV Reuse vs. Empirical Recall Drop
• KV caching is exact math, yet empirical benchmarks show middle-context distractor logs lower recall unless staged specs bound input.
• Rule / Formula: Exact KV Math ≠ Uniform Long-Context Recall
Ch. 11: Temperature Sampling (τ → 0) & Low-Bit Quantization
• Core Principle: Zero temperature enforces greedy argmax decoding, while MoE and FP8/NVFP4 slash HBM weight streaming.
Why verify_document.py Uses τ = 0.0
• Positive τ scales logits pre-softmax, while τ = 0 invokes greedy argmax(z) for near-deterministic audits on pinned snapshots.
• Rule / Formula: τ > 0: softmax(z / τ) | τ → 0⁺ ⇒ argmax(z)
Argmax ≠ Guaranteed Ground Truth
• Greedy argmax stays repeatable up to GPU kernel/batch tie-breaks, yet still picks ungrounded top logits without CSV checks.
• Rule / Formula: τ = 0.0 Entailment + Exact CSV/File Verification
Top-k Experts & FP8 / NVFP4 Blocks
• Sparse MoE activates only top-k MLP experts per token, while 8-bit FP8 and 4-bit NVFP4 compress HBM weight transfers.
• Rule / Formula: BF16 (16-bit) → FP8 / NVFP4 (Up to 4× Less HBM)
Ch. 12: Three Weight Stages, Optional LoRA & Part 4
• Core Principle: Pre-training, full or LoRA SFT, and preference or RL alignment shape weights; Part 4 compares frontier stacks.
Self-Supervised Next-Token Loss
• Updates all base weights via Cross-Entropy loss (−log P(y_true)), matrix backprop (∇W = X^T·ΔY), and AdamW states.
• Rule / Formula: Loss = −log P(y_true) | AdamW Updates All W₀
Full SFT or Low-Rank Adapters
• Updates full checkpoints or optional LoRA adapters B × A (often <1% of weights) on curated instruction pairs.
• Rule / Formula: W_adapted = W₀ + B × A (r << d_model)
Offline DPO vs. Online RLHF / RLVR
• Aligns policy weights via offline Direct Preference Optimization or online RLHF and verifiable-reward RL.
• Rule / Formula: Offline DPO (Pairs) | Online RLHF / RLVR
Big 4 Frontier Ecosystems Overview
• Dr. Ada & Dr. Alan compare OpenAI, Anthropic, Google AI, and xAI architectures, context windows, Skills, and Agents.
• Rule / Formula: Part 03 LLM Engine → Part 04 Frontier Comparison