Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

7.5 Build, Break, and Resume a Tiny Decoder

Give the decoder four symbols, 12 13 16 14, and ask it to repeat them. In one held-out example it starts with 7. Does it recover on the next cycle? You can inspect that run here or train the model yourself.

Start with the Notebook

In the notebook, record your predictions before choosing Run All. Does changing future symbols alter earlier predictions? What happens if attention can read only the current symbol? The notebook generates its own data and includes the entire training script. It needs no model download or API key.

Execution verified as of 2026-11-25: both notebooks completed all ten code cells in separate fresh Jupyter kernels on Linux (Python 3.12.14) and a native Windows windows-2025 GitHub Actions runner (Python 3.12.10), both with PyTorch 2.15.0+cpu. Causal invariance, exact checkpoint replay, the deliberately broken-mask and corrupted-checkpoint diagnostics, and the seven-file result ZIP checks passed. The Windows run records the result. The English notebook also ran all ten cells on public Binder with Python 3.12.16 and the same PyTorch build. Hosted Colab execution remains unverified. [4]

Scope and Input Contract

Deliberately simplified, smoke-tested educational implementation. This is a one-layer synthetic copying task, not language pretraining or SFT. It omits distributed execution, mixed precision, chat templates, natural-language data, packed samples, remote checkpoint replication, and serving. It does not establish frontier-model scalability. Reference checkpoint: none. There is no teacher or judge model.

Save the notebook in a new folder and open a terminal there. For the script version, save causal_lab.py in that folder instead. Both use Python 3.12+ and CPU PyTorch. Exact trajectories are not promised across releases or hardware [1].

On Linux, with python3 pointing to Python 3.12 or newer:

python3 -m venv .venv
source .venv/bin/activate
python -m pip install torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu
python -m pip install jupyterlab
python -m jupyterlab tiny-decoder-lab.ipynb

On Windows PowerShell, with Python 3.12 and the py launcher installed:

py -3.12 -m venv .venv
.\.venv\Scripts\python.exe -m pip install torch==2.15.0+cpu --index-url https://download.pytorch.org/whl/cpu
.\.venv\Scripts\python.exe -m pip install jupyterlab
.\.venv\Scripts\python.exe -m jupyterlab tiny-decoder-lab.ipynb

JupyterLab opens the notebook in your browser. Choose the Python 3 kernel from this environment. For the standalone script, skip the two JupyterLab lines and run python causal_lab.py --output ./runs/causal-lab --steps 160 --seed 7 on Linux or .\.venv\Scripts\python.exe causal_lab.py --output .\runs\causal-lab --steps 160 --seed 7 on Windows. Give each script run a fresh output directory. For another platform, use the PyTorch installer. [5]

The local generator samples four distinct symbols from IDs 1–16 and repeats that motif to create a 17-token sequence. Rotations belong to the same semantic group; canonicalization happens before the 128/16/16 train/validation/test split. No external text, PII, secrets, or third-party dataset rights are involved. The immutable manifest records generator version, seed, grouping rule, mixture, integer-tokenizer version, and every group’s symbols. Group IDs can be reconstructed from their hashes. The checkpoint binds the manifest, configuration, code hash, and PyTorch version.

Input tensors are [B,16]; output logits are [B,16,17]. The first four symbols are the observed prompt. Logits at positions 3–15 predict targets at positions 4–16: 13 supervised targets per sequence. Initial prompt predictions are masked from the objective. There is no padding, BOS, EOS, chat template, generation prompt, variable length, or cross-sample attention; ID 0 is unused. The response policy is exactly 13 continuation symbols. Do not transfer this tokenizer policy to SFT: the native-template requirements in 9.1 SFT Fundamentals still apply.

Assemble the Mechanism

The program implements token plus position embeddings → pre-normalized causal two-head attention → residual addition → pre-normalized feed-forward network → residual addition → vocabulary projection. Width is 32, and the feed-forward expansion is 32 → 64 → 32 with GELU. Each batch row has its own attention matrix. Unlike some larger decoder recipes, this toy omits a final normalization layer; treat it as part of the fixed experimental architecture.

In MultiheadAttention, a boolean True masks a position. Do not assume every PyTorch attention API uses that same convention. Target shifting is separate from masking: one controls which token is predicted, the other which inputs it can see.

The ablation leaves parameters, initialization, data sampling, optimizer, and step budget unchanged but blocks attention to every position except the current one. Both models still have embeddings, position information, and nonlinear layers. The intervention asks whether access to preceding symbols explains the gain. It does not compare equal wall time or prove how a particular head represents copying.

Training and Resource Contract

AdamW uses learning-rate scale 0.003, betas (0.9,0.95), epsilon 1e-8, decay 0.01 on all parameters, batch 16, a ten-update linear warmup envelope multiplied by a cosine envelope approaching a 10% floor over the full budget, and global gradient clipping at 1.0. There are 160 updates and 33,280 supervised training tokens. The loss mask and training budget are identical in the ablation.

Because the warmup and cosine envelopes are multiplied, the learning rate does not reach exactly 0.003.

The model has 10,161 trainable parameters. FP32 parameters, gradients, and two Adam moments require approximately 158.8 KiB together, excluding small optimizer counters. This is not total process memory: embeddings/residuals, attention scores, backward buffers, optimizer temporaries, Python/PyTorch runtime, dataset tensors, checkpoint copies, and evaluation consume additional memory. There is no sharding, recomputation, collective communication, or active-expert distinction. A CPU with 1 GiB of free memory is a conservative planning allowance for this tiny run, not a measured peak. Measure peak RSS before extrapolating.

trace.json records token-normalized train loss, learning rate, pre-clipping gradient norm, batch IDs and supervised-token counts. result.json includes held-out loss, nonfinite count, parameters, timing and target throughput. Its timed interval includes training, checkpoint I/O and half-run replay; it excludes the ablation and held-out evaluation. MFU is null: no validated hardware peak/FLOP model is provided. For a production extension, also instrument activation/update norms, data wait, evaluation time, stragglers and collectives as described in 6.3.

Predict, Run, Then Explain

Before running, predict the effect of the attention ablation and whether changing future input symbols can alter earlier logits. The script verifies causal invariance, saves a midpoint checkpoint, finishes, restores, and replays the remaining updates. Its checkpoint contains weights, optimizer moments, step and target-token count, torch and sampler RNG states, schedule definition and data cursor, plus configuration and manifest hashes. FP32 has no scaler. A temporary file is renamed into place, and a SHA-256 marker must match before loading. This is a local teaching recovery protocol, not distributed atomic publication or changed-world-size recovery [2].

A recorded seed-7 run produced validation loss 0.0453, test loss 0.0508, and self-only test loss 2.7042 nats per target. A uniform predictor over the 16 valid symbols has loss log⁡16≈2.773\log16\approx2.773. These are measurements of the supplied synthetic task, not externally reported model scores. Exact replay and causal invariance passed. Greedy continuation achieved 98.08% token accuracy and 93.75% whole-sequence accuracy (15/16 held-out sequences). Teacher forcing and free-running generation therefore answer different questions. The recorded seed-7 packet preserves an example and the SHA-256 of the script used on November 17. Adding links to the script’s opening docstring changed its file hash. On 2026-11-25 a fresh run of the updated script with seed 7 and CPU PyTorch 2.15.0 reproduced every recorded numerical result and the example continuation. Other seeds and runtimes can differ.

Four wrong tokens in one sequence

With seed 7, the decoder copied 15 of the 16 test sequences perfectly. All four wrong tokens occurred in the same sequence. Its prompt was 12 13 16 14. Read each block of four from left to right. The last block contains only the thirteenth prediction.

How the next input is chosenTargets 1–4Targets 5–8Targets 9–12Target 13
Expected continuation12 13 16 1412 13 16 1412 13 16 1412
Supply the true prefix at every step7 13 16 1412 13 16 1412 13 16 1412
Feed the model its own predictions7 13 16 147 13 16 147 13 16 147

The weights, prompt and target are the same in both runs. Only the prefix supplied after the first prediction changes. With true prefixes the next three copies of 12 succeed. With its own prefixes the decoder repeats 7 every fourth position. This gives 204 correct tokens out of 208, yet only 15 completely correct sequences out of 16.

Reproduce the table in the notebook

Run the notebook with its original settings, then paste this code into a new cell. It restores the midpoint checkpoint created by that run, replays the remaining updates and prints both continuations for every failed free-running sequence. Error positions count from one.

config = result["config"]
model, optimizer, sampler, start = lab.load_checkpoint(
    output / "checkpoint.pt", config, manifest
)
lab.advance(model, optimizer, sampler, data["train"], start, config["steps"], config["steps"])
model.eval()
rows = data["test"]
expected = rows[:, 4:]
free = lab.generate(model, rows[:, :4])[:, 4:]
with torch.no_grad():
    forced = model(rows[:, :-1])[:, 3:].argmax(-1)

for i in (free != expected).any(dim=1).nonzero().flatten().tolist():
    print("prompt", rows[i, :4].tolist(), "expected", expected[i].tolist())
    for label, prediction in [("true prefix", forced), ("own prefix", free)]:
        positions = (prediction[i] != expected[i]).nonzero().flatten() + 1
        print(label, prediction[i].tolist(), "wrong at", positions.tolist())

Abort on a nonfinite loss/gradient, failed invariance, corrupt checkpoint, or replay mismatch. Do not release a changed lab artifact until those checks pass and the held-out comparison is explained. Keep the previous known-good script and output directory for rollback. Changing a recipe after examining test outcomes requires a new held-out set for a new generalization claim.

Extend the Experiment Without Fooling Yourself

  1. Repeat seeds 7, 19, and 31, preserving separate output directories. Report each run; three seeds are a sensitivity check, not a precise confidence interval for all training runs.
  2. Compare correctly shifted targets with a deliberately unshifted diagnostic branch. Explain why predicting visible inputs changes the task rather than improving the model.
  3. Inspect the program’s greedy autoregressive continuation using only the four-symbol prompt, appending one prediction at a time. Compare with teacher-forced loss, where correct previous symbols are supplied. Count whole-sequence correctness; one early error can propagate.
  4. Adapt the experiment to longer motifs and newly generated, group-disjoint data. State which mechanism the new task tests and whether position memorization is an alternative explanation. Select on validation data before opening test results.

Submit the manifest, script hash, trace, results, one failed hypothesis, and a paragraph explaining what this task cannot tell you about natural-language generalization. Use 17.7 to distinguish task uncertainty from training-seed uncertainty.

Quizzes

Quiz 1: Why are there 13 targets although the input length is 16? The first four symbols form the prompt. Positions 3–15 predict the thirteen continuation symbols at positions 4–16; the three earlier next-token predictions are excluded from the loss.

Quiz 2: Why does the self-only model retain the same parameter count? Only the attention mask changes. This isolates access to preceding positions more cleanly than deleting attention parameters, although it does not equalize measured runtime.

Quiz 3: Does an exact midpoint replay prove distributed fault tolerance? No. It tests this CPU process, fixed world size, runtime, sampler, and local checkpoint contract. Distributed atomicity, remote storage, changed topology, and numerical nondeterminism need separate tests.

References

  1. PyTorch. Reproducibility. Documentation.
  2. PyTorch. Saving and Loading Models. Documentation.
  3. Google. Colaboratory FAQ. GitHub notebooks, runtimes, and resource limits.
  4. Foundation Model Engineering. Verify decoder notebooks on Windows. Successful CPU notebook run, checked 2026-11-25.
  5. Project Jupyter. Starting JupyterLab.
  6. Project Jupyter. Binder usage guidelines.