LVL 01SK
Project overview
FIRST-PRINCIPLES FIELD GUIDE

Transformer from Scratch

Reimplement the original encoder-decoder Transformer with multi-head attention, scheduling, and beam search.

01 · MOTIVATION

Begin with the problem, not the library

Before Transformer from Scratch is a collection of classes and functions, it is an answer to a constraint. Reimplement the original encoder-decoder Transformer with multi-head attention, scheduling, and beam search. The useful question is not “which API should I call?” but “what information is available, what decision must be made, and what evidence proves the decision is good?”

A first-principles implementation makes hidden assumptions visible. It forces us to specify the input, the transformation, the objective, and the failure conditions. That discipline is valuable even when a production system later uses a mature library.

02 · FIRST PRINCIPLES

Reduce the system to four questions

01

Representation

How is the raw problem expressed as numbers, states, tokens, tensors, or events?

02

Objective

What quantity tells the system that one answer is better than another?

03

Update

How does evidence change parameters, state, policy, or decisions?

04

Evaluation

Which controlled test separates real improvement from noise or leakage?

Transformer from Scratch becomes understandable when each implementation step answers exactly one of these questions. The walkthrough keeps those boundaries explicit so a bug can be localized instead of disappearing inside an end-to-end pipeline.

03 · CONCEPT ATLAS

The ideas you must genuinely understand

01

Multi-head attention

Attention builds a content-dependent weighted average. Queries describe what each position needs, keys describe what each position offers, and values carry the information. Scaling by the square root of key dimension prevents dot products from pushing softmax into saturation.

In Transformer from Scratch, implement this idea first on a tiny hand-computable example. Write down every shape, legal range, and invariant; compare the code with the manual result; then profile and scale only after the reference agrees.

Verification rule: test the normal case, a boundary case, an invalid case, and an invariant that must remain true after the operation.

02

Positional encoding

Attention alone is permutation-equivariant, so it cannot know token order. Positional features inject location into the representation, either as fixed sinusoids, learned vectors, rotations such as RoPE, or relative biases.

In Transformer from Scratch, implement this idea first on a tiny hand-computable example. Write down every shape, legal range, and invariant; compare the code with the manual result; then profile and scale only after the reference agrees.

Verification rule: test the normal case, a boundary case, an invalid case, and an invariant that must remain true after the operation.

03

Beam search

Beam search defines one of the project’s main information transformations. Understand its input representation, objective, numerical invariants, computational cost, and failure modes before relying on a library implementation.

In Transformer from Scratch, implement this idea first on a tiny hand-computable example. Write down every shape, legal range, and invariant; compare the code with the manual result; then profile and scale only after the reference agrees.

Verification rule: test the normal case, a boundary case, an invalid case, and an invariant that must remain true after the operation.

THE COMPLETE TECHNICAL HANDBOOK

From first principles to production evidence

The following chapters deliberately slow the build down. They connect every major milestone to its contract, derivation, implementation choices, tests, failure modes, systems cost, and production responsibilities.

Verified as part of a 10,000+ word project article
07 · DEEP FOUNDATION

Formulate the problem before choosing the machinery

Transformer from Scratch begins with a decision problem, not a framework. Reimplement the original encoder-decoder Transformer with multi-head attention, scheduling, and beam search. Restate that sentence as an observable input, a desired output, and a criterion for preferring one output over another. Identify who or what supplies supervision, whether feedback is immediate or delayed, and whether examples can be considered independent. These choices determine what can be learned and what remains an assumption. The implementation is honest only when those assumptions are visible near the data contract rather than buried in training code.

The raw material becomes a token representation. Representation decides which distinctions the system can express and which distinctions disappear. List categorical domains, numerical units, missing-value semantics, sequence or spatial axes, masks, player or client perspective, and precision. Then consider invariances: should translation, permutation, rescaling, token position, client identity, or board symmetry change the answer? An architecture that ignores the required invariance wastes data; one that imposes the wrong invariance makes the target impossible to represent.

Finally define the baseline and the abstention point. A baseline can be a constant predictor, random policy, linear rule, naive kernel, synchronous algorithm, or human heuristic. It anchors complexity in evidence. The abstention point describes inputs for which the system lacks support and should decline, defer, or fall back. Together they prevent Transformer from Scratch from being judged only by an impressive end-to-end demonstration while basic correctness, calibration, robustness, or operational usefulness remains unknown.

08 · OBJECTIVE

Connect the objective to the behavior you actually want

An objective compresses preferences into a scalar, but no scalar captures every product or scientific goal. For Transformer from Scratch, distinguish the training objective from the evaluation metric and the deployment utility. The training objective must provide a usable signal to parameters or state; evaluation must estimate generalization under a controlled protocol; deployment utility includes latency, cost, safety, and the consequence of errors. When these three disagree, optimization can succeed while the system becomes less useful.

Study each term dimensionally and statistically. Ask what happens if one term is multiplied by ten, one class becomes rare, a sequence becomes longer, a client contributes more samples, or rewards are shifted. Determine whether averages are per token, example, client, action, spatial position, or batch. Regularization is not decorative: it encodes a preference over solutions and changes units unless normalized consistently. A correct derivation names the population quantity of interest, its finite-sample estimator, and the approximation introduced by minibatches, replay, sampling, or surrogate losses.

Identifiability is the deeper constraint. Data may not contain enough information to separate competing explanations. Multi-head attention, Positional encoding, Beam search can improve computation or inductive bias, but they cannot manufacture missing evidence. State causal assumptions, observability limits, support conditions, and equivalence classes of solutions. Use sensitivity analysis and targeted interventions where possible. When identification is impossible, report uncertainty or a set of plausible answers rather than converting an arbitrary modeling choice into unwarranted confidence.

09 · COMPUTATION

Make mathematical equivalence survive finite precision

Paper algebra assumes exact real numbers; the implementation uses finite precision, bounded memory, and discrete execution order. In Transformer from Scratch, audit exponentials, logarithms, divisions, reductions, norms, probabilities, recursive values, and accumulated updates. Rewrite unstable expressions with max subtraction, log-sum-exp, compensated accumulation, safe denominators, or higher-precision reductions. Track where a mathematically harmless reordering changes rounding and where mixed precision needs scaling or master copies.

Shapes are part of the proof. Annotate each intermediate with semantic axes rather than only dimensions: batch, token, head, channel, client, action, expert, feature, row, column, or sample. Broadcasting should be intentional and verified with asymmetric dimensions so an accidental match cannot hide. Record contiguous layout and stride assumptions when performance code depends on them. For every reshape or transpose, write both the precondition and the inverse operation needed during backward, decoding, aggregation, or reconstruction.

Build a numerical ladder: scalar example, tiny vector or matrix example, batched reference, optimized path, then realistic workload. At each rung compare values and invariants before increasing scale. This catches defects while they are still interpretable. The acceptance test should specify absolute and relative error, exceptional values, deterministic modes, and the hardware or library versions used. Numerical stability is not a final cleanup task; it is part of the algorithm’s definition.

10 · EVALUATION

Design evidence that can falsify the implementation

Evaluation is an experiment. For Transformer from Scratch, specify the unit of analysis, split strategy, temporal boundary, randomization, baseline, metric, and uncertainty before viewing final results. Prevent duplicates, transformed copies, future information, opponent leakage, and shared-client information from crossing the boundary. A single aggregate score can hide subgroup collapse, unstable seeds, poor calibration, tail latency, or rare catastrophic behavior, so pair it with distributions and stratified slices.

Ablations connect outcomes to mechanisms. Remove or replace Multi-head attention, Positional encoding, Beam search one at a time while controlling data, compute, and evaluation. Compare equal wall-clock or equal resource budgets when efficiency is part of the claim. Repeat stochastic runs and report variation rather than selecting the best seed. Inspect learning curves and intermediate metrics because two systems with the same final score may differ radically in sample efficiency, stability, or cost.

The test suite and the benchmark answer different questions. Unit and property tests prove local contracts; integration tests prove components agree; benchmarks estimate behavior at scale; task evaluation estimates usefulness. Preserve all four. A benchmark that bypasses validation or uses a different code path from production is weak evidence. The strongest release gate reruns the exact packaged implementation with recorded configuration and produces an artifact that another person can inspect.

11 · PRODUCTION

Turn the learning artifact into an operable system

Production structure separates pure computation from orchestration, configuration, persistence, and interfaces. Package the core of Transformer from Scratch behind typed contracts. Keep data loading, model or state construction, training, evaluation, serialization, and serving independently invocable. Configuration should be validated, versioned, and printable. Random seeds, data identifiers, source commit, dependency lock, hardware, and metric definitions belong in the run record so an apparent regression can be reproduced instead of guessed at.

Capacity planning follows the critical path. Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage across representative input sizes and concurrency. Report warm-up separately, distinguish throughput from latency, and include tail percentiles. Define memory ownership and lifetime so caches, activations, buffers, replay, or optimizer state cannot grow without a bound. Backpressure and admission control are preferable to unpredictable collapse. Where hardware-specific acceleration exists, preserve a portable reference path for correctness and degraded operation.

Observability must explain decisions and failures without exposing sensitive content. Log stable identifiers, shapes, versions, summary statistics, timings, and error categories. Monitor input drift, output distribution, task quality, saturation, retries, and fallback rate. Establish rollback and shadow-evaluation procedures before the first risky change. A production-grade implementation is not merely more abstract than a notebook; it makes dependencies, state, failure, and evidence explicit enough for another engineer to operate safely.

12 · RESEARCH PRACTICE

Read claims as reproducible hypotheses

The research surrounding Transformer from Scratch improves representations, objectives, algorithms, systems, or evaluation protocols. Classify each paper by which lever it changes. Then identify the comparison budget: data, parameters, tokens, environment steps, hardware, communication, wall-clock time, and tuning effort. A claimed improvement may disappear when budgets are normalized or when the baseline receives equal tuning. Read methods and appendices for details that determine reproducibility, not only the abstract and headline table.

Reproduction begins with the smallest claim. Recreate one table row or ablation before attempting the entire system. Preserve the authors’ preprocessing and metric definitions, then deliberately vary one assumption. Document deviations, failed attempts, and environment details. When a result does not reproduce, distinguish an implementation defect from missing procedural knowledge, stochastic uncertainty, and genuine sensitivity. Negative evidence is useful when it narrows the conditions under which the method works.

Extension should start from a mechanism and a falsifiable prediction. The skills developed here—Attention, Sequence models, Inference—suggest multiple directions, but change one major factor at a time. Predict which metric and intermediate signal should move if the explanation is correct. Use confidence intervals and preregistered stopping rules for expensive experiments where possible. Publish code, configuration, data provenance, and failure cases so the work contributes more than another isolated score.

13 · PROOF LEDGER

Maintain a chain of evidence from equation to outcome

A proof ledger for Transformer from Scratch links each important claim to the smallest evidence that could disprove it. For a mathematical claim, keep a hand-worked example and a high-precision reference. For a software contract, keep unit and property tests. For an optimization claim, keep profiler traces and equal-budget baselines. For a learning claim, keep per-seed results, confidence intervals, and ablations. For a production claim, keep load tests, failure injection, monitoring queries, and rollback evidence. This structure prevents one successful end-to-end run from being treated as proof of every layer beneath it.

Record evidence beside the versioned artifact it evaluates. A metric without its dataset revision, configuration, dependency lock, hardware, and commit cannot reliably settle a regression. Likewise, a screenshot or generated sample is qualitative evidence, not a distribution. Name the claim, evidence type, acceptance threshold, owner, and date. When the implementation changes, rerun the smallest affected evidence first and then the downstream integration gates. The ledger becomes a map of confidence: it shows what is known, what is assumed, what has become stale, and where another experiment is required.

Use the ledger during review. Ask whether each test would fail for a realistic defect, whether each benchmark measures the packaged code path, whether every aggregate retains inspectable raw values, and whether uncertainty is reported at the correct independent unit. Include counterexamples and failed experiments because they define the boundary of the method. Over time this habit turns Attention, Sequence models, Inference from isolated implementation skills into a reproducible engineering practice that survives new data, new hardware, new collaborators, and changing product constraints.

IMPLEMENTATION ATLAS · 01

Build Token To Id Vocab — from contract to production evidence

Build Token To Id Vocab is the construction at milestone 1 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between tokenization and batching and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Build Token To Id Vocab as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Build Token To Id Vocab depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Build Token To Id Vocab needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Build Token To Id Vocab can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Build Token To Id Vocab changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Tokenization and Batching. Build the vocabulary, encode and decode token ids, and pack padded sequences into batched tensors.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 02

Pad Id Sequence — from contract to production evidence

Pad Id Sequence is the pipeline boundary at milestone 5 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between tokenization and batching and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Pad Id Sequence as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Pad Id Sequence depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Pad Id Sequence needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Pad Id Sequence can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Pad Id Sequence changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Tokenization and Batching. Build the vocabulary, encode and decode token ids, and pack padded sequences into batched tensors.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 03

Build Position Index Column — from contract to production evidence

Build Position Index Column is the construction at milestone 9 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between embeddings and positional encoding and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Build Position Index Column as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Build Position Index Column depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Build Position Index Column needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Build Position Index Column can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Build Position Index Column changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Embeddings and Positional Encoding. Scale embeddings and construct the sinusoidal positional encoding matrix added to input embeddings.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 04

Build Padding Mask — from contract to production evidence

Build Padding Mask is the construction at milestone 14 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between masks and scaled dot-product attention and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Build Padding Mask as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Build Padding Mask depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Build Padding Mask needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Build Padding Mask can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Build Padding Mask changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Masks and Scaled Dot-Product Attention. Build padding and causal masks and assemble scaled dot-product attention step by step.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 05

Scale Attention Scores — from contract to production evidence

Scale Attention Scores is the measurement at milestone 18 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between masks and scaled dot-product attention and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Scale Attention Scores as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Scale Attention Scores depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Scale Attention Scores needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Scale Attention Scores can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Scale Attention Scores changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Masks and Scaled Dot-Product Attention. Build padding and causal masks and assemble scaled dot-product attention step by step.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 06

Scaled Dot Product Attention — from contract to production evidence

Scaled Dot Product Attention is the pipeline boundary at milestone 22 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between masks and scaled dot-product attention and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Scaled Dot Product Attention as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Scaled Dot Product Attention depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Scaled Dot Product Attention needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Scaled Dot Product Attention can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Scaled Dot Product Attention changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Masks and Scaled Dot-Product Attention. Build padding and causal masks and assemble scaled dot-product attention step by step.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 07

Project To Query Key Value — from contract to production evidence

Project To Query Key Value is the measurement at milestone 27 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between multi-head attention and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Project To Query Key Value as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Project To Query Key Value depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Project To Query Key Value needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Project To Query Key Value can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Project To Query Key Value changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Multi-Head Attention. Split, permute, and merge heads, project Q/K/V, and assemble the full multi-head attention module.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 08

Assemble Multi Head Attention Forward — from contract to production evidence

Assemble Multi Head Attention Forward is the transformation at milestone 31 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between multi-head attention and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Assemble Multi Head Attention Forward as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Assemble Multi Head Attention Forward depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Assemble Multi Head Attention Forward needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Assemble Multi Head Attention Forward can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Assemble Multi Head Attention Forward changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Multi-Head Attention. Split, permute, and merge heads, project Q/K/V, and assemble the full multi-head attention module.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 09

Normalize And Scale With Gamma Beta — from contract to production evidence

Normalize And Scale With Gamma Beta is the transformation at milestone 36 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between feed-forward, layernorm, and dropout and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Normalize And Scale With Gamma Beta as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Normalize And Scale With Gamma Beta depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Normalize And Scale With Gamma Beta needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Normalize And Scale With Gamma Beta can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Normalize And Scale With Gamma Beta changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Feed-Forward, LayerNorm, and Dropout. Implement the position-wise feed-forward network, layer normalization, residual add-and-norm, and dropout primitives.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 10

Encoder Layer Feed Forward Sublayer — from contract to production evidence

Encoder Layer Feed Forward Sublayer is the transformation at milestone 40 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between encoder, decoder, and full model and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Encoder Layer Feed Forward Sublayer as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Encoder Layer Feed Forward Sublayer depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Encoder Layer Feed Forward Sublayer needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Encoder Layer Feed Forward Sublayer can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Encoder Layer Feed Forward Sublayer changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Encoder, Decoder, and Full Model. Stack encoder and decoder layers, tie output projections to embeddings, and run the complete forward pass.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 11

Decoder Layer Cross Attention Sublayer — from contract to production evidence

Decoder Layer Cross Attention Sublayer is the decision at milestone 44 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between encoder, decoder, and full model and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Decoder Layer Cross Attention Sublayer as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Decoder Layer Cross Attention Sublayer depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Decoder Layer Cross Attention Sublayer needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Decoder Layer Cross Attention Sublayer can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Decoder Layer Cross Attention Sublayer changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Encoder, Decoder, and Full Model. Stack encoder and decoder layers, tie output projections to embeddings, and run the complete forward pass.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 12

Tie Output Projection To Token Embeddings — from contract to production evidence

Tie Output Projection To Token Embeddings is the transformation at milestone 49 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between encoder, decoder, and full model and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Tie Output Projection To Token Embeddings as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Tie Output Projection To Token Embeddings depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Tie Output Projection To Token Embeddings needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Tie Output Projection To Token Embeddings can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Tie Output Projection To Token Embeddings changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Encoder, Decoder, and Full Model. Stack encoder and decoder layers, tie output projections to embeddings, and run the complete forward pass.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 13

Init Decoder Layer Parameters — from contract to production evidence

Init Decoder Layer Parameters is the decision at milestone 53 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between parameter initialization and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Init Decoder Layer Parameters as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Init Decoder Layer Parameters depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Init Decoder Layer Parameters needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Init Decoder Layer Parameters can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Init Decoder Layer Parameters changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Parameter Initialization. Allocate the raw weight tensors (with requires_grad) for encoder/decoder layers and embeddings, and gather them for the optimizer.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 14

Build Uniform Smoothing Distribution — from contract to production evidence

Build Uniform Smoothing Distribution is the construction at milestone 58 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between training objective and schedule and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Build Uniform Smoothing Distribution as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Build Uniform Smoothing Distribution depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Build Uniform Smoothing Distribution needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Build Uniform Smoothing Distribution can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Build Uniform Smoothing Distribution changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Training Objective and Schedule. Implement teacher forcing, Noam warmup, label-smoothed KL loss, and token-level accuracy.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 15

Average Loss Over Non Pad Tokens — from contract to production evidence

Average Loss Over Non Pad Tokens is the measurement at milestone 62 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between training objective and schedule and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Average Loss Over Non Pad Tokens as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Average Loss Over Non Pad Tokens depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Average Loss Over Non Pad Tokens needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Average Loss Over Non Pad Tokens can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Average Loss Over Non Pad Tokens changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Training Objective and Schedule. Implement teacher forcing, Noam warmup, label-smoothed KL loss, and token-level accuracy.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 16

Update Adam Second Moment — from contract to production evidence

Update Adam Second Moment is the learning update at milestone 66 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between adam optimizer from scratch and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Update Adam Second Moment as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Update Adam Second Moment depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Update Adam Second Moment needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Update Adam Second Moment can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Update Adam Second Moment changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Adam Optimizer From Scratch. Build the Adam optimizer step by step: moment buffers, exponential-moving-average updates, bias correction, the parameter update rule, and gradient zeroing.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 17

Run Training Step With Backprop — from contract to production evidence

Run Training Step With Backprop is the learning update at milestone 72 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between training step and loop and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Run Training Step With Backprop as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Run Training Step With Backprop depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Run Training Step With Backprop needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Run Training Step With Backprop can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Run Training Step With Backprop changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Training Step and Loop. Tie everything together: run a forward pass, compute the label-smoothed loss, backpropagate, and step Adam across many iterations.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
IMPLEMENTATION ATLAS · 18

Compute Candidate Scores — from contract to production evidence

Compute Candidate Scores is the measurement at milestone 76 of Transformer from Scratch. Its purpose is not merely to make the next function run. It establishes a contract between decoding and beam search and every downstream stage. Begin by naming the accepted inputs, their axes, units, legal ranges, ownership rules, and whether mutation is permitted. Then name the output with the same precision. In this project the surrounding ideas—Multi-head attention, Positional encoding, Beam search—only compose correctly when this boundary preserves those invariants. A useful implementation note records one representative shape, one smallest valid example, one boundary example, and one invalid example before any optimization is attempted.

From first principles, treat Compute Candidate Scores as a mapping from available information to a new token representation. Ask which information is genuinely known at this point and which information would leak from the future, evaluation set, opposing player, held-out client, or later pipeline stage. Write the transformation symbolically before translating it into array operations. Every reduction must state its axis; every probability must state its normalization set; every random choice must state its distribution and seed; every learned quantity must state the objective that changes it. This discipline turns an appealing formula into an executable specification that can be challenged with small counterexamples.

The reference implementation should favor clarity over cleverness. Separate validation, the mathematical core, and state updates so each can be tested independently. Use explicit intermediate names that correspond to the derivation rather than compressing the work into one expression. Confirm dtype promotion, broadcasting, device placement, and empty-input behavior. If Compute Candidate Scores depends on randomness, pass a generator instead of reading hidden global state. If it owns mutable state, return or document the updated state explicitly. The optimized implementation may later fuse operations or reuse buffers, but it must remain numerically comparable with this small version on deterministic fixtures.

Verification for Compute Candidate Scores needs more than a happy-path assertion. Prove a hand-computable normal case, a boundary case, an invalid case, and at least one invariant. Compare against loss curves, held-out generations, ablations, and human or automated evaluations. Add metamorphic tests when an exact answer is awkward: permutation, scaling, symmetry, conservation, monotonicity, or equivalence under a harmless representation change. Run the test repeatedly under fixed seeds to distinguish deterministic defects from statistical variation. When floating-point arithmetic is involved, justify tolerances from expected rounding error instead of choosing a loose threshold simply because the test passes.

Failure analysis asks how Compute Candidate Scores can look plausible while being wrong. Inspect data leakage, exposure bias, hallucination, unstable preference signals, and unsafe deployment behavior. Trace one example through every intermediate value and preserve enough logging to reproduce it. Distinguish a contract violation from an optimization failure and from an evaluation-design failure; each requires a different repair. A numerical answer within range is not automatically meaningful, and a rising training metric is not proof that the intended signal is being learned. The strongest debugging move is usually to shrink the input until the complete computation fits on paper, then compare the paper trace with the program line by line.

Productionizing Compute Candidate Scores changes the question from “does it work once?” to “does it remain trustworthy under load and change?” Measure tokens, parameter memory, attention work, decoding latency, and evaluation coverage. Define observability for inputs, outputs, latency, failures, drift, and resource saturation. Decide what happens on malformed data, cancellation, partial worker failure, unavailable accelerators, or a distribution outside the training envelope. Version configuration and schemas with the code, preserve reproducible seeds where appropriate, and expose a safe fallback. Optimization is accepted only when the reference tests, numerical comparisons, and task-level metrics remain within an explicitly documented budget.

  • Part: Decoding and Beam Search. Generate sequences with greedy argmax and a length-penalized beam search over candidate hypotheses.
  • Normal case: choose the smallest input that exercises the intended transformation.
  • Boundary case: use an empty, singleton, saturated, masked, terminal, or maximum-size input as appropriate.
  • Invariant: verify shape, range, conservation, normalization, symmetry, immutability, or monotonicity.
  • Production evidence: record correctness, latency, memory or cost, and the exact configuration.
04 · REAL-WORLD USE

Where this pattern becomes useful

Attention

Use this capability when the product must make repeatable decisions under the same structural constraints studied in the project. Begin with an offline baseline, define a business-facing metric, and add monitoring before automation.

Use case 1

Sequence models

Use this capability when the product must make repeatable decisions under the same structural constraints studied in the project. Begin with an offline baseline, define a business-facing metric, and add monitoring before automation.

Use case 2

Inference

Use this capability when the product must make repeatable decisions under the same structural constraints studied in the project. Begin with an offline baseline, define a business-facing metric, and add monitoring before automation.

Use case 3
05 · RESEARCH EVOLUTION

How the field keeps improving

Sequence-to-sequence learning moved from recurrent encoder-decoders to content-based attention, then to a fully attention-based Transformer with positional information and parallel training. Later work exposed quadratic attention memory as the key systems bottleneck. A faithful build should first reproduce masking, scaling, residual paths, normalization, scheduling, and beam search before exploring relative position methods or efficient attention.

Improvements usually change one of four levers: representation, learning signal, computation path, or evaluation protocol. Read each source with its assumptions and comparison budget in view.

Treat paper claims as hypotheses: reproduce the baseline, inspect ablations, normalize compute budgets, and verify whether the evaluation matches your intended use.

06 · AFTER THE BUILD

Your next-study roadmap

  1. Re-derive

    Explain each core equation without looking at the code.

  2. Rebuild

    Implement the smallest version again from an empty file.

  3. Stress test

    Create adversarial, boundary, numerical, and distribution-shift tests.

  4. Read critically

    Choose one foundational paper and two recent follow-ups; reproduce one reported comparison.

  5. Extend

    Change one assumption, record the hypothesis, and run a controlled experiment.

  6. Publish

    Document architecture, tradeoffs, failures, metrics, cost, and reproducible commands.