AI For Engineers, Part 3: Inside the LLM Engine — Matrices, Attention & Weights

Series Track: AI For Engineers · Episode 03 of 09 (E3) [12]
Architectural Scope: Affine Manifolds, Scaled Dot-Product Attention, Decoder Blocks, GPU HBM/SRAM Physics, Quantization, Weight Alignment, and Deterministic Verification [1][5][7][9][11]

Treating a Large Language Model (LLM) as an opaque oracle invites silent numeric drift and confabulated standards [8][9][11]. Every token emerges from linear algebra, probability normalization, and GPU memory-hierarchy physics across five pillars: (1) fixed-width affine manifolds and Pre-Norm residual highways, (2) scaled dot-product self-attention and causal routing, (3) modern decoder blocks using Rotary Position Embeddings (RoPE) and gated SwiGLU MLPs, (4) High Bandwidth Memory (HBM) versus SRAM execution and Key-Value (KV) caching, and (5) logit sampling, quantization, and parameter training stages [1][4][5][7][9].

To ground each mechanism in measurable outcomes, this report pairs primary ML literature with the illustrative, reproducible synthetic engineering case bundle (evidence/LOG-104.csv, evidence/SPEC-201.json, pump_report_draft.md, verify_document.py, pump_report_verified.md, and audit_report.json in -sources.zip) [11]. In that audit, an unverified draft shifted peak external seal-housing temperature in LOG-104 from 84.2 °C (within SPEC-201's 85.0 °C ceiling by 0.8 °C) to 94.2 °C (a false +9.2 °C breach) and invented aerospace standard SPEC-992—requiring greedy decoding plus verify_document.py to quarantine both errors [8][11].


1. Pillar 1 — Matrix Manifolds, Pre-Norm Residual Highways, and Superposition

1.1 Fixed-Width Activation Manifolds and Nonlinear Projections (Modules 01–02)

Tokenized inputs form a 3D activation tensor X of shape [B, T, d_model] (B batch, T or N sequence length, d_model hidden width such as 4,096) [1]. Depth L and width d_model remain fixed constants at inference; longer prompts expand T and O(N²·d_model) prefill FLOPs without adding layers or changing weights [1]. Dense projections compute Z = X·W + b followed by nonlinear gate σ (ReLU, GELU, SwiGLU), preventing stacked matrices from collapsing by associativity into one linear transform (W₂·(W₁·X) = W_eff·X) [1].

1.2 Pre-Norm Residual Streams and RMSNorm Stability (Module 03)

Multiplying unnormalized activations across 80–100 layers drives singular values toward 0 (vanishing gradients) or ∞ (exploding activations) [1]. Modern blocks stabilize propagation via Pre-Norm Residual Streams and RMSNorm [1]:

1.3 Distributed Superposition and the 84.2 °C → 94.2 °C Drift Hypothesis (Module 04)

Networks encode concepts via distributed representations and superposition rather than one neuron per concept [2]. Elhage et al. (2022) show in toy models that sparse features let layers pack m ≫ d concepts into width d along nearly orthogonal directions (|v_i·v_j| < ε), creating polysemantic neurons and non-zero cross-talk interference (W⊤·W·x = x + interference) [2].

[!IMPORTANT] Epistemic Scope Boundary: Superposition explains why weights act as lossy statistical priors rather than relational database rows [2]. Attributing a specific production error—such as shifting LOG-104's 84.2 °C peak seal-housing temperature to 94.2 °C—to superposition remains an illustrative mechanistic hypothesis unless verified via direct causal circuit interventions or activation patching [2][11].


2. Pillar 2 — Scaled Dot-Product Attention, Masking, and Induction Heads

2.1 Replacing Sequential Recurrence with O(1) Routing (Module 05)

Pre-2017 RNN and LSTM cells computed h_t = f(h_(t−1), x_t) sequentially in O(N) steps, starving GPU tensor cores during training and compressing distant context into one lossy vector [1]. Vaswani et al. (2017) replaced recurrence with direct self-attention (N = 6 layers, d_model = 512, d_ff = 2,048, 8 heads of d_k = 64), linking any token pair in an O(1) path [1]. Frontier LLMs drop the bidirectional encoder and scale a causal decoder stack [1].

2.2 Scaled Dot-Product Q, K, V Math and Causal Masking (Module 06)

Self-attention computes weighted mathematical routing across token vectors—never conscious awareness [1]. Tokens project Queries Q, Keys K, and Values V via Attention(Q, K, V) = softmax((Q·K⊤ + M) / √d_k)·V [1]:

2.3 Multi-Head Subspaces and Induction Heads vs. SPEC-992 (Module 07)

Multi-Head Attention splits d_model across H heads (d_head = d_model/H) via W_Q, W_K, W_V and merges outputs via W_O [1]. Olsson et al. (2022) identify coupled two-layer induction heads ([A][B] … [A] → [B]) that match prefixes and copy structural patterns [3]. Attributing confabulated SPEC-992 (CLAIM-03 near SPEC-201) to induction heads is an illustrative background circuit hypothesis rather than a proven single-circuit cause without direct circuit tracing—motivating Unknowns Contracts plus file-existence checks in verify_document.py [3][11].


3. Pillars 3 & 4 — Decoder Blocks, GPU HBM Physics, KV Cache, GQA, and FlashAttention

3.1 Tokenization, RoPE Relative Angles, and SwiGLU MLPs (Module 08)

Modern decoders refine the 2017 block across three components [1]:

  1. Subword Tokenization & Embeddings: Byte-level tokenizers (V ≈ 128,000, ~0.75 words/token) split text and decimals like 84.2 into IDs initialized via x₀ = E[id] [1][11].
  2. Rotary Position Embeddings (RoPE): Rotates 2D pairs of Q at m and K at n by angles m·θ and n·θ so inner products encode relative offset m − n [1][4].
  3. Gated SwiGLU MLPs: Feed-forward layers (SwiGLU(x) = (Swish(x·W_gate) ⊙ (x·W_up))·W_down) hold roughly two-thirds of dense weights as associative pattern memory [1][10].

3.2 Compute-Bound Prefill vs. HBM-Bandwidth-Bound Decode (Module 09)

Inference executes with frozen weights W: uploading LOG-104.csv alters transient activations without updating parameters [1][4][11]. (Governance must distinguish frozen inference weights/training opt-outs, provider operational/safety request log retention—requiring stateless store=false or Enterprise ZDR where applicable—TTL-bounded KV/prefix caches, and workspace file stores [4][8].) Throughput hinges on arithmetic intensity (FLOPs/Bytes moved between HBM and on-chip SRAM) [5]:

3.3 Exact KV Caching, GQA (H_Q / G), and FlashAttention (Module 10)

[Prompt + LOG-104.csv + SPEC-201.json] -> Subword IDs -> x₀ = E[id]
  |
  v  L × Decoder Blocks (Fixed Width d_model, Frozen Weights W)
  +---------------------------------------------------------------+
  | 1. x_mid = x + GQA_FlashAttn(RMSNorm(x), RoPE, CausalMask)    |
  |    * Prefill: Tiles Q,K,V in SRAM (No N×N HBM Matrix, Exact)  |
  |    * Decode : Reads Exact KV Cache (Compressed by H_Q / G)    |
  | 2. x_out = x_mid + SwiGLU_MLP(RMSNorm(x_mid))                 |
  +---------------------------------------------------------------+
  |
  v  RMSNorm + W_U -> Logits z -> [τ>0: softmax(z/τ) | τ=0: argmax(z)]
  |
  v  verify_document.py(pump_report_draft.md) -> audit_report.json
     +-- PASS: CLAIM-01 (18.4 psi drop) & CLAIM-04 (120 psi hold)
     +-- QUARANTINE: CLAIM-02 (94.2 °C drift) & CLAIM-03 (SPEC-992)
Engine Subsystem Core Operation / Scaling Hardware or Reliability Bottleneck Exact Architectural Guardrail
Pre-Norm + RMSNorm x + F(RMSNorm(x)); I + ∂F/∂x [1] Unnormalized deep stacks vanish/explode [1] Fixed L, d_model at inference; preserves gradient highway [1]
Scaled Attention softmax((Q·K⊤ + M)/√d_k)·V [1] Variance d_k saturates softmax without 1/√d_k [1] Mathematical routing (M_(i,j)=−∞ for j>i), never awareness [1]
FlashAttention SRAM tiling + online softmax [5] O(N²) HBM intermediate matrix I/O [5] Exact attention (0 error) in O(N) memory; FLOPs stay O(N²·d_model) [1][5]
KV Cache + GQA Linear KV in N; ratio H_Q / G [4][6] Linear VRAM growth & HBM-bound decode [4][6] Uncompressed KV is exact; recall drops come from attention dilution [4][6]
NVFP4 Precision 4-bit + 16-elem FP8 + FP32 scales [7] 2-byte binary FP16/BF16 reads stall HBM [7] ~3.5× footprint cut vs FP16 (~1.8× vs FP8); benchmark accuracy [7]
Greedy (τ = 0) argmax(z_i) limit (τ→0⁺, never z_i/0) [8] GPU FP non-associativity, batching, MoE [8] Mostly deterministic (seed + system_fingerprint), never proves truth [8]

4. Pillar 5 — Decoding Determinism, NVFP4 Quantization, and Weight Stages

4.1 Temperature Scaling (τ > 0) vs. Greedy argmax (τ = 0) (Module 11a)

Final RMSNorm and unembedding W_U map hidden states to logits z [1][8]. Positive temperatures τ > 0 scale z_i / τ prior to softmax, whereas temperature = 0 invokes the greedy argmax rule (τ → 0⁺ limit, never z_i / 0) [8]. Pairing temperature = 0 with seed yields mostly deterministic token sequences still subject to GPU floating-point reduction non-associativity, dynamic batching, sparse MoE tie-breaks, and backend changes tracked by system_fingerprint [8]. Decoding determinism never guarantees factual truth, and strict JSON Schema Structured Outputs guarantee syntax only on completed, non-refused responses (callers must handle refusals, max_output_tokens truncation, and semantic errors) [8][11].

4.2 Binary FP16/BF16, Sparse MoE, and NVFP4 (~3.5× Reduction) (Module 11b)

Sparse Mixture-of-Experts (MoE) layers activate top-k MLP experts per token while quantization cuts HBM weight traffic [7][8]. IEEE FP16 (1 sign, 5 exponent, 10 mantissa bits) and BF16 (1 sign, 8 exponent, 7 mantissa bits) are 16-bit binary floating-point formats (2 bytes/weight), not decimal digit formats [7]. While raw 4-bit weights represent an idealized 4× bit-width ratio against 16-bit weights, NVIDIA NVFP4 adds 16-element micro-block FP8 scale factors plus a tensor-level FP32 scale—yielding ~3.5× memory footprint reduction versus FP16 (~1.8× vs FP8) with near-FP8 accuracy on Blackwell Tensor Cores once validated on target tasks [7].

4.3 Pre-Training, Optional LoRA SFT, and Offline DPO vs. Online RLHF (Module 12)

Three training stages update parameters via Cross-Entropy loss (−log P(y_true)), backpropagation (∇W = X⊤·ΔY), and AdamW [1][9][10]:

  1. Self-Supervised Pre-Training: Updates all base weights W₀ across trillions of unlabeled tokens via next-token prediction, forming broad capabilities and lossy priors [1][2][9].
  2. Supervised Fine-Tuning (SFT) — Full Weights or Optional LoRA: Trains on curated instruction pairs via full-parameter updates or optional PEFT with Low-Rank Adaptation (LoRA, Hu et al., 2021), freezing W₀ and learning low-rank adapters ΔW = B·A (r ≪ min(d, k), W_adapted = W₀ + B·A) to cut optimizer memory [10].
  3. Preference & RL Alignment (Online RLHF/RLVR vs. Offline DPO): Online RLHF (Ouyang et al., 2022) trains an explicit neural reward model and updates policy weights via online RL (PPO) with KL regularization (extended by verifiable-reward RLVR) [9]. Conversely, offline Direct Preference Optimization (DPO, Rafailov et al., 2023) analytically reparameterizes the KL-constrained objective to optimize policy weights directly on offline preferred/dispreferred pairs via binary cross-entropy loss without an explicit reward model or online RL loop [9]. Because raters can reward confident prose over abstention (UNKNOWN), deterministic verification remains mandatory [9][11].

5. Reproducible Engineering Verification Case: LOG-104, SPEC-201, and verify_document.py

The companion archive's illustrative, reproducible synthetic engineering case bundle (evidence/LOG-104.csv, evidence/SPEC-201.json, pump_report_draft.md, verify_document.py, pump_report_verified.md, and audit_report.json) demonstrates deterministic hallucination quarantine [11].

In LOG-104.csv, prototype pump telemetry records 14:05:00 (suction_psi = 34.2, vapor_pressure_psi = 14.8, discharge_drop_psi = 1.2, housing_temp_c = 84.2 °C), 14:08:12 (suction_psi = 33.8, vapor_pressure_psi = 14.8, discharge_drop_psi = 18.4 psi, housing_temp_c = 83.9 °C), and 14:12:00 (suction_psi = 34.0, vapor_pressure_psi = 14.8, discharge_drop_psi = 17.9 psi, housing_temp_c = 82.5 °C) [11]. SPEC-201.json specifies max_housing_temp_c = 85.0 °C, max_allowed_drop_psi = 5.0 psi, min_suction_margin_psi = 10.0 psi, and next_verification_test = "30-minute pressure hold at 120 psi" [11]. External seal-housing temperature peaked at 84.2 °C—staying within SPEC-201's 85.0 °C ceiling (0.8 °C margin, while internal seal-face temperature is unmeasured / UNKNOWN)—whereas discharge_drop_psi = 18.4 psi breached the 5.0 psi limit by 13.4 psi [11].

Claim ID Draft Claim (pump_report_draft.md) [11] Ground Truth (LOG-104.csv / SPEC-201.json) [11] verify_document.py Status Engine Hypothesis & Deterministic Gate [8]
CLAIM-01 discharge_drop_psi = 18.4 psi (14:08:12, LOG-104) [11] LOG-104.csv (14:08:12): 18.4 psi (> 5.0 psi limit) [11] PASS [11] Exact CSV float match confirms 13.4 psi breach [11]
CLAIM-02 Peak housing_temp_c = 94.2 °C (LOG-104) [11] LOG-104.csv: [84.2, 83.9, 82.5]; 84.2 °C ≤ 85.0 °C [11] FAIL_NUMERIC_DRIFT [11] Illustrative superposed prior pull (84.2 → 94.2 °C) quarantined [2][8][11]
CLAIM-03 Seal rated 150.0 °C per SPEC-992 [11] SPEC-992 missing; seal-face temp UNKNOWN [11] FAIL_PHANTOM_CITATION [11] Illustrative pattern completion (SPEC-992) blocked by file check [3][9][11]
CLAIM-04 30-minute pressure hold at 120 psi (SPEC-201) [11] SPEC-201.json: "30-minute pressure hold at 120 psi" [11] PASS [11] Procedural test verified directly against SPEC-201.json [8][11]

[!TIP] Operational Takeaway & Episode 4 Continuity: Bound prompt context against attention dilution despite exact KV caching [4], pair temperature = 0 greedy decoding (system_fingerprint logged) with verify_document.py [8][11], and validate NVFP4 accuracy before rollout [7]. Next, Episode 4 (E4) compares how frontier platforms wrap these Transformer engines inside tool harnesses, Skills, and persistent agents [12].

Primary References, Runnable Case Bundles & Provenance

  • [1] Vaswani et al. (2017) — Attention Is All You Need (NeurIPS 2017, arXiv:1706.03762) — Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention Is All You Need. NeurIPS 30 (arXiv:1706.03762). · Official Primary Source · Highlighted Verification Note
  • [2] Elhage et al. (2022) — Toy Models of Superposition (Anthropic Transformer Circuits, S9 / R5) — Elhage, N., Hume, T., Olsson, C., Schiefer, N., Henighan, T., Kravec, S., et al. (2022). Toy Models of Superposition. Transformer Circuits Thread. Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
  • [3] Olsson et al. (2022) — In-Context Learning and Induction Heads (Transformer Circuits, R6) — Olsson, C., Elhage, N., Nanda, N., Joseph, N., DasSarma, N., Henighan, T., et al. (2022). In-Context Learning and Induction Heads. Transformer Circuits Thread. Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
  • [4] Hugging Face Transformers v5.12 — Key-Value (KV) Cache Explanation (R3) — Hugging Face (2026). Transformers Documentation: Cache Explanation (KV Caching Mechanics). Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
  • [5] Dao et al. (2022) — FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (arXiv:2205.14135, R17) — Dao, T., Fu, D. Y., Ermon, S., Rudra, A., & Re, C. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS 2022 (arXiv:2205.14135). Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
  • [6] Ainslie et al. (2023) — GQA: Training Generalized Multi-Query Transformer Models (arXiv:2305.13245, R18) — Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., Lebron, F., & Sanghai, S. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. EMNLP 2023 (arXiv:2305.13245). Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
  • [7] NVIDIA Technical Blog — Introducing NVFP4 for Efficient and Accurate Low-Precision Inference (R16) — NVIDIA Developer Blog (2025/2026). Introducing NVFP4 for Efficient and Accurate Low-Precision Inference. Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
  • [8] OpenAI API Guide — Reproducible Outputs, Greedy Decoding & System Fingerprint Caveats (S5 / R10) — OpenAI Developer Documentation (2026). Advanced Usage: Reproducible Outputs, temperature, and seed parameters. Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
  • [9] Rafailov et al. (2023) — Direct Preference Optimization (DPO) & Ouyang et al. (2022) RLHF (arXiv:2305.18290, S10 / R8) — Rafailov, R., Sharma, A., Mitchell, E., Ermon, S., Manning, C. D., & Finn, C. (2023). Direct Preference Optimization: Your Language Model is Secretly a Reward Model. NeurIPS 2023 (arXiv:2305.18290); Ouyang, L. et al. (2022) InstructGPT (arXiv:2203.02155). Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
  • [10] Hu et al. (2021) — LoRA: Low-Rank Adaptation of Large Language Models (arXiv:2106.09685, R9) — Hu, E. J., Shen, Y., Wallis, P., Allen-Zhu, Z., Li, Y., Wang, S., Wang, L., & Chen, W. (2022). LoRA: Low-Rank Adaptation of Large Language Models. ICLR 2022 (arXiv:2106.09685). Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
  • [11] Reproducible Synthetic Engineering Case Bundle — LOG-104.csv, SPEC-201.json & Runnable verify_document.py — AI Foundations Reproducible Synthetic Engineering Dataset (Bundled in -sources.zip: LOG-104.csv, SPEC-201.json, pump_report_draft.md, verify_document.py, audit_report.json). · Highlighted Case Dossier & Runnable Files · Download Runnable .zip
  • [12] Episode Production Provenance & Module Transcript — AI For Engineers, Part 3: Inside the LLM Engine — Matrices, Attention & Weights — Generator Studio Remediated Episode Transcript (ai-for-engineers-part-3, Consulted 15 November 2026 — Module Continuity Provenance Only). · Open Studio Video · Module Transcript Reader

Related Topic Artifacts