AI For Engineers, Part 1: Core AI Foundations, Neural Networks, Tokens & Prompts
Series Track: AI For Engineers · Part 01 of 09
Episode Scope: Modules 01–15 & Backup Glossary Appendices A1–A3 (ai-for-engineers-part-1) [9]
Architectural Focus: Neural Network Matrix Mechanics, BPE Tokenization, Scaled Dot-Product Self-Attention, Context Budgets, Post-Training Alignment & Engineering Prompt Verification [1][2][5][8]
1. Foundational Terminology, Historical Trajectory, and Neural Network Matrix Mechanics
Reliable engineering deployment of generative artificial intelligence begins by separating what a neural network computes mathematically, what the engineer controls at runtime, and what must be verified against primary evidence across this 15-module plus 3-appendix technical briefing [8][9]. Rather than emerging from a single sudden invention, modern Large Language Models (LLMs) reflect cumulative advances in symbolic logic, gradient optimization, parallel hardware, and self-attention [1][2]:
- 1955–1956 (Symbolic Foundations): The 1955 Dartmouth research proposal organized the 1956 summer workshop that formally named Artificial Intelligence, launching explicit rule-based reasoning alongside early connectionist models [2].
- 1986 (Chain-Rule Backpropagation): Rumelhart, Hinton, and Williams formalized multi-layer error backpropagation using the calculus chain rule, enabling systematic gradient updates of internal weights and biases [2].
- 2000s–2010s (Parallel Deep Learning Scaling): Large digital corpora, dense GPU matrix accelerators, and improved nonlinear activations made deep representation learning practical at scale [1][2].
- 2017–Present (Transformer Decoder Stacks): Vaswani et al. introduced the Transformer in 2017, replacing sequential recurrence and convolutions with parallelizable self-attention [1], which modern decoder-only LLMs scale across massive corpora and align via post-training preference optimization [1][7].
1.1 Single-Neuron Scalar Math vs. Hardware Matrix Execution
At the unit level, a neuron multiplies inputs x_k by learned weights w_k, adds bias b, and applies a nonlinear activation f to compute y = f(∑_k (x_k · w_k) + b) [2]. Nonlinearity (ReLU, GELU, SwiGLU) is essential: without f, stacked linear projections (X · W₁) · W₂ collapse into a single linear transformation [2]. Whereas teaching diagrams show dots and lines, production GPUs and TPUs execute dense matrix algebra across numerical arrays [1][2]:
During a forward pass, layer ℓ outputs become layer ℓ + 1 inputs [1][2]. During training, a loss function scores prediction error, backpropagation computes gradients ∂Loss / ∂W and ∂Loss / ∂b, and an optimizer updates parameters before validation checks generalization [2].
1.2 Frozen Runtime Inference and Data-Control Boundaries
During ordinary inference, learned weights W and biases b remain strictly frozen [2]. Submitting a prompt modifies only input activations X traversing the network—never running backpropagation or retraining weights [2]. Engineers must separate four distinct runtime state controls: (1) frozen inference weights and training opt-outs [2], (2) provider operational or safety request-log retention, (3) TTL-bounded accelerator Key-Value (KV) prefix caches [3], and (4) external workspace or Retrieval-Augmented Generation (RAG) file stores [8].
| Core Term / Quantity | Mathematical & Structural Definition | Runtime Engineering Behavior |
|---|---|---|
| Large Language Model (LLM) | Deep Transformer neural network trained at scale on tokenized text [1][7]. | Predicts conditional next-token distributions; fluent continuation never guarantees truth [7][8]. |
Depth (L) |
Number of stacked Transformer processing blocks [1]. | Fixed architectural constant at runtime; longer prompts never add layers [1]. |
Width (d_model) |
Hidden vector dimension carried per token position [1]. | Fixed representation width across residual streams [1]. |
Parameters (P) |
Total learned weights W and biases b across the model [1][2]. |
Updated during training/fine-tuning; strictly read-only during inference [2]. |
Active Tokens (N) |
Discrete subword units across instructions, context, and output [2][6]. | Dynamic per call; drives O(N² · d_model) prefill FLOPs and linear O(N) KV memory [1][3][4]. |
| Training vs. Inference | Gradient parameter optimization vs. fixed-weight forward pass [2]. | Inference transforms input X without modifying parametric weights W [2]. |
2. Model Geometry, Deterministic BPE Tokenization, and Static Embedding Lookups
Engineers must separate static model capacity from dynamic prompt length: a multi-billion-parameter LLM does not have billions of layers, and sending a longer prompt never creates extra layers L or widens d_model [1]. Longer prompts simply pass more token positions N through the existing L-block stack, increasing prefill compute as O(N² · d_model) and KV-cache footprint linearly without guaranteeing better engineering results [1][3][4].
2.1 Subword Byte-Pair Encoding (BPE) Compilation vs. Runtime Splitting
Before text enters matrix layers, a tokenizer segments raw strings into discrete tokens representing words, subwords, punctuation, or raw bytes [2]. Most modern tokenizers build upon Byte-Pair Encoding (BPE) formalized for neural text processing by Sennrich et al. [2]:
- Offline Vocabulary Merge Compilation: During tokenizer training, frequently co-occurring adjacent byte or character units are iteratively merged to build a fixed vocabulary of size
|V|[2]. - Deterministic Inference Segmentation: At runtime, the compiled tokenizer applies those saved merge rules deterministically—averaging roughly
0.75English words per token—and never learns new vocabulary entries from user messages [2]. Leading spaces, capitalization, numeric strings, and multilingual UTF-8 bytes shift exact subword boundaries [2].
2.2 Vocabulary Identifiers and Context-Free Embedding Lookups
Each token maps to an integer identifier id ∈ {0, …, |V| − 1} in the vocabulary table [2]. That integer is strictly a categorical lookup key—not a score of importance or physical magnitude [2]. The model retrieves row E[id] from the learned embedding matrix E ∈ ℝ^(|V| × d_model) and injects positional encodings so sequence order is preserved [1][2]. Tokenization and embedding lookup are distinct steps, and static lookup involves zero contextual mixing: "bank" in "river bank" and "bank" in "bank account" start with the identical row vector E[id] until downstream attention blocks incorporate surrounding context [1][2].
3. Transformer Block Architecture, Scaled Dot-Product Self-Attention, and IO-Aware Execution
Inside each Transformer block, self-attention mixes information across available token positions to resolve contextual dependencies, such as determining whether "it" refers to the valve or the pump in "The valve on the pump was closed because it leaked" [1]. Attention is a deterministic matrix operation, not human cognitive awareness [1].
Raw Text ──► Static BPE Tokenizer [2] ──► Integer IDs ──► Embedding E[id] + Position [1][2]
│
┌─────────────────────── Repeats Across L Fixed Blocks ───────▼───────────────────────┐
│ Input X ──► LayerNorm ──► Causal Multi-Head Self-Attention (Q · K⊤ / √d_k) [1] │
│ │ │ (FlashAttention SRAM Tiling [4] │
│ └──────► (+) Residual ◄───────┘ + Uncompressed KV Cache Reuse [3]) │
│ │ │
│ ├──► LayerNorm ──► Position-Wise FFN ──► (+) Residual ──► X_next [1] │
└─────────────────────────────────────────────────────────────────────────────────────┘
│
Engineering Verification [8] ◄── Argmax / τ Decoding [5] ◄── Vocabulary Logits z ∈ ℝ^|V|
3.1 Scaled Dot-Product Attention, Causal Masking, and Residual Stacks
Linear projections map token states into Query (Q), Key (K), and Value (V) matrices [1]:
Attention(Q, K, V) = Softmax((Q · K⊤) / √d_k + M_causal) · V [1]
- Scaled Compatibility & Value Mixing: Dot products
Q · K⊤are scaled by1 / √d_k(head dimensiond_k) to prevent Softmax gradient saturation, normalized to sum to1.0, and multiplied byV[1]. - Causal Masking (
M_causal): Decoder models apply an upper-triangular mask setting future positions (j > t) to-∞before Softmax so positiontattends strictly to positions≤ t[1]. - Multi-Head Subspaces, FFN & Normalization: Parallel
H_Qheads capture distinct relationships simultaneously, followed by a position-wise Feed-Forward Network (FFN), Layer Normalization, and residual highwaysX + SubLayer(X)across deep stacks [1].
3.2 IO-Aware Exact Execution with FlashAttention
Materializing the full N × N attention matrix in GPU High-Bandwidth Memory (HBM) bottlenecks memory bandwidth [4]. FlashAttention (Dao et al., 2022) tiles Q, K, and V blocks in fast on-chip SRAM with online Softmax statistics (running maximums and exponential sums) without materializing the full N × N matrix in HBM—computing exact attention with O(N) activation memory while prefill compute remains O(N² · d_model) [1][4].
4. Autoregressive Decoding, KV Caching, Greedy Argmax Caveats, and the 4-Tier Context Budget
During generation, the final block projects the latest hidden vector into vocabulary logits z ∈ ℝ^|V|, converts scores to probabilities, selects one token via a decoding rule, appends it to the sequence, and repeats [1][3][5].
4.1 Uncompressed KV Caching and Grouped-Query Attention (H_Q / G)
Storing previously computed K and V projections in accelerator memory (KV caching) converts per-step work from full-prefix recomputation to single-token incremental updates [3]. Standard uncompressed KV caching reuses exact K and V tensors without dropping tokens; memory grows linearly with sequence length N, depth L, and KV head groups G, where Grouped-Query Attention (GQA) reduces KV-cache size by the architecture-dependent ratio H_Q / G [3].
4.2 Positive Temperature Scaling vs. Greedy argmax (temperature = 0)
For positive temperature τ > 0, engines scale logits as z_i / τ prior to Softmax [5]. Because division by zero (z_i / 0) is undefined, temperature = 0 directly invokes the greedy argmax rule to pick the highest-logit token [5]. Even with temperature = 0 and a fixed seed, token sequences remain mostly deterministic rather than strictly immutable, owing to GPU floating-point reduction non-associativity, dynamic request batching, Mixture-of-Experts routing, and backend updates (system_fingerprint)—and greedy decoding never guarantees factual truth [5].
4.3 Four-Tier Context Window Budget and Lost in the Middle Recall
All active tokens share a single finite context window spanning four competing layers [6][8]:
| Context Tier | Operational Contents | Engineering Risk & Control |
|---|---|---|
| 1. System Layer | Global instructions, role rules, tool and schema definitions [5][8]. | Consumes baseline budget every turn; keep directives concise [6][8]. |
| 2. Reference Layer | Attached test logs, acceptance specs, retrieved RAG chunks [6][8]. | Burying key specs mid-context triggers U-shaped recall loss [6]. |
| 3. Interaction Layer | Multi-turn dialogue history and current engineering task [6]. | Redundant history dilutes Softmax weights; prune stale turns [3][6]. |
| 4. Output Layer | Generated reasoning steps, tables, or structured JSON [5]. | Reaching max_output_tokens truncates outputs; verify finish reason [5]. |
Liu et al. (Lost in the Middle) demonstrated an empirical U-shaped recall curve: models retrieve evidence most reliably at the very beginning (primacy) or very end (recency) of the context and degrade substantially across middle positions due to attention dilution [3][6]. Large advertised windows (128K–1M tokens) set capacity limits rather than uniform recall guarantees, motivating chunked subsystem reviews and boundary placement of acceptance criteria [6][8].
5. Learning Paradigms, Offline DPO vs. Online RLHF, and Workflow Wrappers
Engineering architecture decisions also require separating training paradigms from runtime wrappers [2][7][8]:
- Machine Learning Categories & Self-Supervision: Supervised learning trains on labeled pairs (e.g., pass/fail sensor traces); unsupervised learning clusters unlabeled patterns; reinforcement learning optimizes control policies from environmental rewards; and self-supervised pre-training derives next-token targets directly from unlabeled text [1][2][7].
- Fine-Tuning, Online RLHF & Offline DPO: Optional Parameter-Efficient Fine-Tuning (PEFT) such as LoRA (
ΔW = B · A) adapts domain behavior without full weight updates [2][7]. For preference alignment, classical online RLHF (Ouyang et al., 2022) fits an explicit neural reward model and runs online RL rollouts (such as PPO) with KL regularization, whereas offline DPO (Rafailov et al., 2023) reparameterizes the objective in closed form to update policy weights directly on preferred/dispreferred pairs via binary cross-entropy loss without an explicit reward model or online RL loop [7]. Because preference raters can reward confident prose over abstention, external verification remains mandatory [7][8]. - RAG, Skills & Agents vs. Weights: RAG (Lewis et al., 2020) grounds frozen weights with non-parametric retrieved documents at runtime [8]. Skills (reusable procedural instructions and tools), Agents (models paired with tool-calling control loops), and Persistent Agents (saved session state enabling multi-session resumption) are workflow wrappers around fixed-weight inference—none automatically retrain neural parameters [2][8].
6. The RCTF Engineering Prompt Framework and Deterministic Verification Protocol
Effective engineering prompts define four explicit controls—Role, Context, Task, and Format (RCTF)—plus concrete examples when formatting nuances are hard to describe [8]:
- Role: Sets perspective and terminology (e.g.,
"Act as a reliability engineer"), guiding style without granting professional competence or accuracy [7][8]. - Context: Supplies primary logs, acceptance limits, and audience constraints [6][8].
- Task: Specifies exact analytical deliverables: isolating deviations, separating observations from hypotheses, and proposing a falsifiable next test [8].
- Format: Mandates structured outputs (such as a 4-column table or strict JSON Schema) and explicit
"UNKNOWN"labels for missing measurements [5][8]. Strict JSON Schema Structured Outputs guarantee syntax only on completed, non-refused responses; callers must still handle refusals,max_output_tokenstruncation, and semantic errors [5][8].
6.1 Prototype Pump Review and Synthetic Case Continuity
Episode E1's prototype pump review demonstrates RCTF in practice and establishes the analytical baseline for the series' illustrative, reproducible synthetic engineering case bundle (LOG-104.csv, SPEC-201.json, pump_report_draft.md, verify_document.py, audit_report.json), where LOG-104 external seal-housing temperature peaked at housing_temp_c = 84.2 °C (14:05:00)—staying within SPEC-201's max_housing_temp_c = 85.0 °C ceiling (0.8 °C margin, while internal seal-face temperature is unmeasured / UNKNOWN)—whereas discharge_drop_psi = 18.4 psi (14:08:12) breaches SPEC-201's max_allowed_drop_psi = 5.0 psi limit [8]:
| Observed Evidence & Citation | Acceptance Check (SPEC-201.json) [6] |
Separated Hypothesis | Missing Data & Next Test [1] |
|---|---|---|---|
discharge_drop_psi = 18.4 psi at 14:08:12 (LOG-104.csv) [8]. |
BREACH: Exceeds max_allowed_drop_psi = 5.0 psi limit by 13.4 psi [8]. |
Candidate internal mechanical seal bypass (unconfirmed hypothesis) [8]. | Internal seal-face temp: UNKNOWN; run static pressure-hold test [8]. |
housing_temp_c = 84.2 °C at 14:05:00 (LOG-104.csv) [8]. |
PASS: Within max_housing_temp_c = 85.0 °C ceiling (0.8 °C margin) [8]. |
External housing temperature alone cannot confirm internal face flashing [8]. | Audit drafts via verify_document.py to block 94.2 °C drift or phantom SPEC-992 [8]. |
6.2 Five-Step Post-Generation Engineering Verification Workflow
Following NIST AI 600-1 confabulation mitigations and Ragas faithfulness auditing [8], engineers close the loop with five reproducible checks: (1) Format & Completion Check against truncation or refusal [5][8]; (2) Evidence Provenance Tracing back to primary logs and specs [8]; (3) Independent Quantitative Recalculation via deterministic scripts (verify_document.py) [5][8]; (4) Hypothesis & UNKNOWN Labeling until empirically tested [8]; and (5) Iterative Benchmark Refinement across representative evaluation cases [6][8].
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] Rumelhart et al. (1986) Backpropagation & Sennrich et al. (2016) Subword BPE Tokenization (arXiv:1508.07909) — Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors, Nature 323:533-536; Sennrich, R., Haddow, B., & Birch, A. (2016). Neural Machine Translation of Rare Words with Subword Units, ACL 2016 (arXiv:1508.07909). · Official Primary Source · Highlighted Verification Note
- [3] 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
- [4] 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
- [5] 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
- [6] Liu et al. (2023/2024) — Lost in the Middle: How Language Models Use Long Contexts (arXiv:2307.03172, S7 / R7) — Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F., & Liang, P. (2024). Lost in the Middle: How Language Models Use Long Contexts. TACL 12:157-173 (arXiv:2307.03712 / 2307.03172). Consulted 15 November 2026. · Official Primary Source · Highlighted Verification Note
- [7] 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
- [8] Lewis et al. (2020) RAG (arXiv:2005.11401), Es et al. (2024) Ragas & NIST AI 600-1 Generative AI Profile — Lewis, P. et al. (2020) Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (NeurIPS, arXiv:2005.11401); Es, S. et al. (2024) Ragas (EACL, arXiv:2309.15217); NIST AI 600-1 (2024) Generative AI Profile. · Official Primary Source · Highlighted Verification Note
- [9] Episode Production Provenance & Module Transcript — AI For Engineers, Part 1: Core AI Foundations, Neural Networks, Tokens & Prompts — Generator Studio Remediated Episode Transcript (ai-for-engineers-part-1, Consulted 15 November 2026 — Module Continuity Provenance Only). · Open Studio Video · Module Transcript Reader
Related Topic Artifacts
- Topic Briefing: AI For Engineers, Part 1: Core AI Foundations, Neural Networks, Tokens & Prompts
- Interactive 3D LLM & Transformer Architecture Atlas
- Verified Sources & Runnable Case (9): AI For Engineers, Part 1: Core AI Foundations, Neural Networks, Tokens & Prompts
- Infographic: AI For Engineers, Part 1: Core AI Foundations, Neural Networks, Tokens & Prompts
- Interactive Mind Map: AI For Engineers, Part 1: Core AI Foundations, Neural Networks, Tokens & Prompts
- Studio Master Video: AI For Engineers, Part 1: Core AI Foundations, Neural Networks, Tokens & Prompts