页面简介
正文摘录
Every section you have read so far placed code next to its prose, with the output of each code cell printed below it. While reading, you may have wanted to change one of those cells: try a smaller learning rate, a wider layer, or half of the training data, and see what happens. The book is written for this. Each section is a Jupyter notebook, a single document that holds prose, mathematics, code, and results, and that you can edit and run one cell at a time. Running cells one at a time raises a question that a script never raises: which code produced the result on the screen? A notebook remembers everything you have run, in the order you ran it, and that order need not match the page. A notebook can therefore show a result that nobody, its author included, can reproduce after a restart. The remedy is to restart the notebook and run it from the top before trusting or sharing a result. Below we explain where a notebook keeps its state and how to check it, set up the book’s notebooks on your own machine, and work with them from an editor and on a remote GPU. If you would rather not install anything, Section 27.2 runs the same notebooks free of charge on Colab or Kaggle. If you need more hardware than your laptop offers, see Section 27.3. 27.1.1 The Notebook Execution Model A plain Python script re-runs from the top every time, so a slow step, such as loading and preprocessing a dataset, repeats on every experiment. A notebook keeps a live Python process (the kernel) between executions: load the data once, then iterate on the model as often as you like while the data stays in memory. Inline plots and interleaved explanations make this execution model useful for both teaching and research. The same memory also outlives the code that filled it: a variable keeps its value after you edit or delete the cell that assigned it. We therefore need to know where this state lives and how long it lasts. 27.1.1.1 The Document and the Kernel A notebook has two parts. The document stores cells and saved outputs: it is what you read, share, and commit. The kernel holds the live state: imported modules, variables, random-number generators, open files, compiled programs, and accelerator memory. The document orders cells top to bottom; the kernel only knows the order in which you executed them. Confusing these two orders causes many notebook bugs. Figure 27.1.1: The document orders cells top to bottom; the kernel accumulates state in execution order. Restart and run all replays document order (the only order a reader can reproduce) and exposes the mismatch. Figure 27.1.1 shows the classic failure. During an editing session you executed a data-loading cell first, then wrote a model-definition cell above it, and everything worked because the kernel already held data. The document now tells a story that never happened. A reader who runs the cells in the order shown, or you tomorrow after a restart, hits a NameError. The execution counters (In [3], In [1], …) number the cell executions since the kernel started; they are historical clues, not a dependency graph. The following pair of cells demonstrates benign, document-ordered state: the second cell works only because the first ran. import numpy as np rng = np.random.default_rng(7) samples = rng.normal(size=5) float(samples.mean()) -0.2638849576850524 That dependency is fine, because it follows the reading order. A cell that depends on an assignment below it, or on a cell you have since deleted, is not. Keep cells small, keep function definitions separate from experiments, and pass data explicitly rather than mutating globals across many cells. 27.1.1.2 Restart and Run All Restart kernel and run all cells discards the kernel’s accumulated state and replays the document from a blank slate, in reading order. It catches hidden kernel state and order dependencies before a notebook is shared. Run it before saving, sharing, or committing a notebook. The book’s build applies the same test: it executes every notebook from top to bottom in a fresh kernel, and the outputs on the website come from those runs. 27.1.2 Running the Book Locally 27.1.2.1 Setting Up Numerical results and even APIs change between package versions, so the book pins its environments. The notebook archive for each framework, described in Installation, contains the notebooks, the d2l package, and uv lock files for a CPU and a GPU environment. From the extracted directory, create the environment once and launch JupyterLab in it: uv venv --python 3.12 uv pip sync pylock.cpu.toml uv run --no-sync jupyter lab On Linux with an NVIDIA GPU, synchronize pylock.gpu.toml instead. The --no-sync option keeps uv from altering the environment that the lock selected. A clone of the GitHub repository builds its environments with make instead (as we will set up in Section 27.8). The kernel selected inside a notebook must belong to the environment where the packages were installed. A Jupyter server can see many kernels; its own Python process does not determine which one executes your notebook. 27.1.2.2 A Quick Sanity Check Before changing code, record a compact identity check: import os import platform import sys { "python": sys.executable.replace(os.path.expanduser("~"), "~"), "version": platform.python_version(), "working_directory": os.path.basename(os.getcwd()), } {'python': '~/d2l-neu/.venv-pytorch/bin/python', 'version': '3.12.3', 'working_directory': 'chapter_appendix-tools-for-deep-learning'} This catches two common setup mistakes in one cell: a kernel from the wrong environment (sys.executable points somewhere unexpected) and a notebook opened from a directory where relative data paths no longer resolve. The cell abbreviates the home directory to ~ and prints only the last component of the working directory, so that its saved output reveals no personal path. 27.1.3 Working in an Editor 27.1.3.1 JupyterLab JupyterLab combines a file browser, notebook editor, terminals, a text editor, debugger support, and a view of running kernels. The essentials are stable even as the interface evolves: Run a cell with Shift+Enter; use a terminal tab for uv, Git, and inspecting files. Select the kernel by environment name, then verify sys.executable. Interrupt a long computation before restarting. Restarting releases Python state and, normally, the accelerator memory owned by that process. Use Restart Kernel and Run All Cells before saving a result for others. Inspect the Running panel and stop kernels you no longer use: closing a browser tab does not stop its kernel, and an orphaned kernel can hold gigabytes of GPU memory. 27.1.3.2 VS Code Visual Studio Code edits and runs .ipynb files with kernel selection, a variable inspector, cell-level debugging, and notebook-aware diffs. Open the extracted directory as a folder, choose the interpreter of the environment created above, and select that interpreter as the notebook kernel. When a notebook grows into a project, VS Code can navigate definitions, run tests, format code, and review Git diffs. Keep testable logic in .py modules and use the notebook for explanation and experiment records. This repository also includes a VS Code extension for the book’s authoring workflow (switching framework views, previewing slides, and syncing edits back to the source), described in Section 27.8. 27.1.3.3 Debugging and Timing An exception ends the cell but not the kernel, which keeps the traceback along with every variable. Running %debug in the next cell therefore opens a debugger in the frame where the exception was raised. Use the notebook debugger when the kernel supports it, or move a small failing call into a module and debug it in a terminal. Resist broad try/except blocks that print “failed”: they discard the exception type and location that diagnosis needs. For quick measurements, IPython’s magics are built in: values = np.arange(100_000, dtype=np.float64) %timeit values @ values 9.77 μs ± 113 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) One caveat when timing accelerators: GPU operations are asynchronous, so a host-side timer may measure only the dispatch of work, not its completion. Synchronize explicitly (or use the framework’s benchmarking utilities), warm up compiled kernels first, and record the shapes, precision, device, and library versions alongside the number. 27.1.4 Remote Machines Your editor, the notebook server, the kernel, and the accelerator need not be on the same machine. A common setup runs JupyterLab next to the GPU while you edit from a laptop. Figure 27.1.2: A local editor reaches a remote Jupyter server and kernel through an SSH tunnel; the accelerator stays attached to the remote kernel. Bind the remote server to loopback and forward it over SSH: # Remote machine uv run --no-sync jupyter lab --no-browser --ip 127.0.0.1 --port 8888 # Local machine ssh -N -L 8888:127.0.0.1:8888 myserver Then open the tokenized http://127.0.0.1:8888/... URL locally. Never bind an unauthenticated Jupyter server to all network interfaces: anyone who can reach the port can execute code as you. The SSH tunnel provides encryption and access control; Jupyter’s token remains a useful second boundary. VS Code’s Remote SSH installs a small server-side component so the editor UI runs locally while terminals, extensions, files, and kernels all live on the remote machine. Confirm the status bar shows SSH before selecting the Python environment, since a local kernel cannot use the remote GPU. In either setup, treat remote compute as disposable: commit code and copy checkpoints to durable storage before it is rebooted, preempted, or deleted (Section 27.3). Before sharing or committing a notebook, perform a final reproducibility and privacy check: restart and run all; check that setup does not rely on personal paths or unrecorded downloads; remove secrets and private data from outputs; keep the outputs that teach or verify something and delete noisy progress logs; and note the environment and hardware ne