39.8 Contributor Guide
By now you have run many of this book’s notebooks, and you may have found a sentence that confused you, a transposed subscript in an equation, or a cell that fails with a newer library. A fix should appear wherever that text or code appears: on the website, in the PDF, in the notebook of every framework, and on the slide that quotes the same cell. How does a one-line correction reach all of these places, and how do we know that it broke nothing?
The book is maintained the way open-source software is. Every page comes from one Markdown file under version control, a build system derives everything else from these files, and a change is ready for review once the notebooks it touches execute and the site renders. We describe the build, the Git workflow for proposing a change, the optional use of coding agents, and the checks a change must pass. The same concerns arise in any machine learning repository whose documents must run.
39.8.1 The Build
39.8.1.1 One Source, Many Artifacts
Each section is stored in a single Markdown file; this one is chapter_appendix-tools-for-deep-learning/developers-guide.md. The build derives everything else from these sources:
chapter_*/*.md source of truth (edit these)
├── chapter_*/*.qmd generated Quarto input → HTML site and PDFs
├── _notebooks/<fw>/... generated Jupyter notebooks, one set per framework
├── _slides/<fw>/... generated lecture slides
└── d2l/*.py generated d2l library, from the #@save blocks
outputs/<fw>/... executed outputs, captured from _notebooks/, committed
This design has three practical consequences:
- Never edit generated files. A
.qmdor.ipynbedit is destroyed by the next build. Edit the.mdsource and regenerate. - Framework tabs live in one file. A code block tagged
%%tab pytorchappears only in the PyTorch view; an untagged Python block appears in every notebook of the file. The file yields one notebook for each framework that at least one of its blocks is tagged for, and a file without tagged blocks yields a PyTorch notebook only. One source file thus yields up to four notebooks that must all execute. Chapters of the Basics, Image Models, Mathematics for Deep Learning, and Tools for Deep Learning parts carry all four frameworks; chapters of the Advanced part carry PyTorch and JAX (with Chapter 14 in PyTorch), and the Language Models part carries PyTorch. - Cell identity is stable. Every Python block carries a permanent ID (assigned by
tools/add_cell_ids.py) so that slides, executed outputs, and framework views can refer to a cell across renames and moves.
The sources are Markdown rather than notebooks because of version control. A .ipynb file is JSON that mixes code, outputs, execution counts, and editor metadata, so a one-word edit followed by a re-run changes many lines besides that word; a Markdown diff shows only the changed prose and code. Executed outputs are stored separately and are re-captured only when the code that produced them, the library code it uses, or the framework version changes.
The d2l library you have imported throughout the book is generated the same way. make lib extracts every block marked #@save into the per-framework modules d2l/torch.py, d2l/tensorflow.py, d2l/jax.py, and d2l/mxnet.py. A fix made where a function is taught reaches every later chapter after a rebuild, which is why those files carry a banner that says not to edit them directly. The Colab and Kaggle notebooks of Section 39.2 are generated too, onto a separate branch, notebooks, that is rebuilt from the sources and never edited by hand.
39.8.1.2 Repository Layout
The top level of the repository holds the sources, the build entry points, and the documentation that explains them:
d2l-neu/
├── chapter_*/ source Markdown, one directory per chapter
├── img/ figures; illustrative SVGs come from tools/gen_*_figures.py
├── d2l/ the generated d2l library
├── outputs/ committed store of executed notebook outputs
├── tools/ build scripts (preprocessing, notebooks, slides, audits)
├── docs/ build-system documentation, writing and code guides
├── Makefile, make/ entry point: make html, make lib, make capture-outputs ...
├── bootstrap.sh one-time setup of a fresh clone
└── CLAUDE.md build summary, written for coding agents
On a fresh clone, ./bootstrap.sh installs Git LFS, which stores the images of the committed outputs, fetches those images, and creates .venv-build, the environment that holds Quarto. After that, make html renders the whole site from the committed outputs on a laptop without a GPU; executing notebooks is a separate step. The Makefile needs GNU Make 4.3 or newer, which macOS provides only as an extra install (gmake from MacPorts, for example). make help lists the targets, and docs/build-system.md explains them.
39.8.2 Git Basics
Every change to the book travels as a Git commit on a branch of your own copy of the repository. If you already use Git daily, skip ahead. First, make that copy: click Fork on the repository page, then clone your fork and create a branch for your change:
git clone https://github.com/<your-username>/d2l-neu.git
cd d2l-neu
git switch -c fix-typo-in-attention # a branch per changeEdit the source .md file, then record and publish the change:
git status # what changed?
git diff # show the exact edits
git add chapter_attention/attention-scoring.md
git commit -m "Fix transposed subscript in attention equation"
git push -u origin fix-typo-in-attentionGitHub will offer to open a pull request: your branch, proposed for merging, with a diff the maintainers can review and comment on. (The gh command-line tool does the same with gh pr create.) Small, focused pull requests are easier to review than changes spanning several chapters.
39.8.3 Coding Agents
A coding agent is a language model that reads the repository, edits files, and runs commands. It helps with bounded tasks: finding where a function is defined, propagating a mechanical change across framework variants, or running the checks and reading their failures. Its use is optional, and its edits need the same review as anyone else’s. Three properties of this repository make such help practical:
- The build is documented.
CLAUDE.mdanddocs/tell an agent how to regenerate, execute, and render the artifacts. The same instructions serve human contributors. - Verification is executable. An edit works when the notebook executes top to bottom in every framework it has, the audit of the committed outputs passes, and the page renders. An agent can run the loop of editing, regenerating, executing, and inspecting failures, but the contributor reviews both the final diff and the evidence from the checks.
- The tedious parts are mechanical. Keeping framework implementations in sync, checking that every
:numref:resolves, and regenerating figures are multi-file tasks that an agent can carry out and a person can review.
A useful request states the change and how to verify it, for example: “the contour plot of the momentum section mislabels its axes; correct the source and rerun the affected notebooks.” Review for two failure modes. An agent may edit a generated file, as newcomers do, unless the project documentation warns against it (ours does). And an agent asked to make a failing check pass may weaken the check or the code instead of fixing the cause: a notebook that runs again may no longer teach the right thing.
39.8.4 Submitting Changes
Contributions range from one-line corrections to new code, and the checks grow with the change. A one-line fix does not even need a local checkout: open the source file on GitHub and press the edit (pencil) button. GitHub offers to fork the repository, and after the edit it leads you through the commit to a pull request, all in the browser.
For code and content changes, clone, branch, and edit the source .md. Check the edited file with tools/lint_source.py, which catches unbalanced tab and slide markers, duplicate cell IDs, and equation labels that would not attach; with --corpus it also checks that every cross-reference points to an existing label. Then re-execute every notebook that the edit touches, copy its outputs into the committed store, and render the site:
make venv-pytorch # once per framework
make -B _notebooks/pytorch/<chapter>/<file>.executed # repeat per framework
make capture-outputs FILES=<chapter>/<file>.md
make htmlIf you edit code that carries #@save, rebuild the library with make lib before you execute any notebook. Notebooks of other sections that use the edited symbol then become stale too, and make audit-outputs lists them. A laptop without a GPU cannot re-execute GPU notebooks; make html warns about such a notebook instead of stopping, and the pull request should name the notebooks that still need a GPU run. New prose follows docs/writing-guide.md, and new code follows docs/code-guide.md.
If you prefer editing notebooks to raw Markdown, the VS Code extension in .vscode-extension/ (its README explains how to build and install it) opens the generated notebook of the current section with the right kernel preselected, switches between its framework views, previews the slide deck live, and re-executes and captures a notebook with one command. It writes edits made in the notebook back into the Markdown source, so a generated file never becomes the thing you edited. make kernels registers the Jupyter kernels it uses.
Whatever the route, a change is ready when it executes cleanly from a fresh state in every framework it touches, and when the source, never a generated file, is what changed.
39.8.5 Summary
A single Markdown source per section generates the website, PDFs, per-framework notebooks, slides, and the d2l package, while executed outputs live separately under version control and generated files are never edited by hand. Keeping prose and code in plain Markdown yields clean, line-level Git diffs so a book of more than 600 notebooks remains straightforward to review and maintain. Every contribution follows the same loop: fork the repository, create a focused branch, edit the .md source, verify by linting, re-executing touched notebooks, capturing outputs, and rendering, and open a small pull request. Because the build rules are documented and verification is executable, coding agents can automate much of the mechanical multi-framework work while human contributors review and take responsibility for the resulting changes.
39.8.6 Exercises
- Framework tabs. A source file contains exactly five code blocks, in this order: (1) a block tagged
%%tab pytorchthat runsimport torchandx = torch.arange(6.0); (2) a block tagged%%tab jaxthat runsimport jax.numpy as jnpandx = jnp.arange(6.0); (3) an untagged blocky = x * 2; (4) a block tagged%%tab pytorchthat runsx[0] = 10.0; (5) an untagged blockprint(y.sum(), x.sum()).- Which notebooks does the build generate from this file, which blocks does each of them contain, and what does each print?
- A contributor deletes the tag of block (4) so that every framework runs it. Which notebook now fails, and with which error? Replace block (4) by tagged blocks so that both notebooks print the same values.
- You edit block (3) in the generated PyTorch notebook, and the VS Code extension writes the edit back into the source file. Which notebooks does the edit change, and which of them must you run before you submit it?
- Stale outputs. The committed store keeps the outputs of a notebook in
outputs/<fw>/<chapter>/<stem>.json, filed under the ID of the cell that produced them. With each output it stores a fingerprint: a hash of the code of that cell and of every earlier code cell of the notebook, with trailing whitespace stripped from every line. For the whole notebook it also stores the installed framework version without its local build tag (torch==2.11.0, nottorch==2.11.0+cu128) and a hash of the library blocks of every symbold2l.Xthat the code of the section mentions, together with the blocks that those symbols use in turn. An output is stale when one of these values no longer matches the current source and environment. The audittools/audit_outputs.py, whichmake htmlruns before it renders the site, reports a stale image as a warning and stops the build at a stale text output, unless the notebook needs more GPUs than the host has.- A section has ten code cells, and every framework variant of it calls
d2l.Trainer. Which outputs, in which frameworks, become stale after each of the following edits: (i) a typo fixed in a paragraph; (ii) a typo fixed in a comment of the third code cell, which has no tab; (iii) trailing spaces removed from every line;- the fifth and the sixth code cell swapped; (v) the docstring of a
Trainermethod changed in an untagged#@savecell of another section; (vi) PyTorch upgraded from 2.11.0 to 2.12.0; (vii) PyTorch 2.11.0 installed from the CPU build for macOS instead of the CUDA build for Linux?
- the fifth and the sixth code cell swapped; (v) the docstring of a
- Which of the stale marks of (a) flag outputs that cannot have changed? Which real change of an output does (vii) let pass? Why do the rules accept both kinds of error?
- Why does the build not declare an output stale when a fresh run prints something different from the stored output?
- A section has ten code cells, and every framework variant of it calls
- [code] Duplicate definitions.
make libcollects the#@saveblocks of all sections in book order. When several blocks define the same function or method, the library keeps only one of them. The methodTrainer.prepare_batchis defined in the untagged cell#linear-regression-scratch-training-1of Section 2.4, which every framework runs, and again, with device support, in the framework variants of the cell#gpus-devices-memory-the-trainer-now-with-devices-1of Section 5.7.- Add a comment line to the body of the untagged definition and of the PyTorch variant of the device-aware one, run
make lib, and searchd2l/torch.pyfor both comments. Which comment arrives, and which rule does this reveal? - Which definition does
d2l.Trainer.prepare_batchhold when the PyTorch notebook of Section 2.4 starts, and which one after its cell#linear-regression-scratch-training-1has run? - Why does the build keep the last definition rather than the first?
- A contributor changes the device-aware PyTorch
prepare_batchso that it also converts every batch to 16-bit floats. The PyTorch notebooks of which sections can print different results: those before Section 5.7 in book order, those after it, or both?
- Add a comment line to the body of the untagged definition and of the PyTorch variant of the device-aware one, run
- [extended] Dataflow staleness. ●● The fingerprint of exercise 2 marks every cell from the first edited cell on as stale. A dataflow rule marks only the cells that read, directly or through other cells, a name that the edited cell binds. The detector of exercise 3 of Section 39.1 already extracts the names that each cell binds and reads.
- Generate the PyTorch notebooks with
make notebooks-pytorchand extract, for every code cell, the names that it binds and reads. For every edit of a single cell, compute the cells that the dataflow rule marks stale and the cells that must run to recompute them, which include every earlier cell that a stale cell depends on. Report per chapter the mean fraction of cells marked stale and the mean fraction that must run, under both rules. - Find cells in the book through which an edit changes later outputs without binding a name that the later cells read, for instance through the state of a random number generator. Which other channels of this kind do the notebooks of the book use?
- Macke et al. (2021) record such dependencies while the notebook runs instead of reading them from the source. Which of the channels of (b) can a run-time tracer observe, and which stay invisible to it?
- Would you replace the prefix rule of the build by your rule? Base the answer on the savings of (a) and the failures of (b).
- Generate the PyTorch notebooks with
- [code] Noisy bisection. ●●
git bisectfinds the commit that introduced a fault by binary search: it checks out a commit halfway between a known good and a known bad commit, and a test of that commit halves the range. A test that trains a model is noisy. Suppose that a notebook’s check “validation accuracy at least 0.9” passes with probability \(p = 0.9\) on every commit before the first bad commit \(k\) and with probability \(q = 0.3\) on \(k\) and every later commit, independently across runs. Commit 0 is known good, commit 64 is known bad, and \(k\) is uniform on \(\{1, \ldots, 64\}\).- With one run per test, what is the probability that
git bisectnames \(k\)? - Repeat each test \(m\) times and call the commit good when the number of passes reaches a threshold. Find the smallest \(m\), with its threshold, for which the probability of naming a wrong commit is at most 5%. How many runs does the search take?
- The probabilistic bisection algorithm keeps a posterior distribution over the location of the fault, tests at its median, and updates the posterior with Bayes’ rule after every run (Frazier et al. 2019). Simulate it with a posterior over \(k\) and the likelihoods given by \(p\) and \(q\), until the posterior puts 0.95 on one commit. Why can testing at the median stop making progress on a discrete set of commits? Change the choice of the test commit to fix this, and compare the mean number of runs and the error rate with (b).
- Treat one run as a channel from \(\{\text{good}, \text{bad}\}\) to \(\{\text{pass}, \text{fail}\}\) and compute its capacity \(C = \max_{p(x)} I(X; Y)\), the largest mutual information between input and output over all input distributions (Section 37.6). Each run reveals at most \(C\) bits about \(k\), even when the tests are chosen adaptively. Fano’s inequality states that an estimate \(\hat k\) computed from the runs, with error probability \(P_e = P(\hat k \neq k)\), satisfies \(H_b(P_e) + P_e \log_2 63 \geq H(k \mid \text{runs})\), where \(H_b\) is the binary entropy. Use it to bound from below the mean number of runs of any strategy that names \(k\) with probability at least 0.95. How close does (c) come?
- With one run per test, what is the probability that