import numpy as np
rng = np.random.default_rng(7)
samples = rng.normal(size=5)Dive into Deep Learning · §39.1
Notebooks: Local Interactive Development, Kernel State, and Remote GPUs
document vs. kernel · out-of-order state · restart & run all · uv lock files · debugging & timing · SSH tunneling
Motivation
The Execution Model
A notebook consists of two distinct components whose state can diverge during an editing session:
.ipynb / .md): Stores prose, code cells, and saved outputs ordered top to bottom—this is what you read, share, and commit to Git.In [1], In [2], \dots).data already exists) but fails with NameError on a fresh top-to-bottom run.State Dependencies
Cross-cell state is benign when dependencies flow strictly downward in reading order:
samples; the second cell computes float(samples.mean()).In [k]): Record the sequence number since kernel startup—they are historical breadcrumbs, not a dependency graph.Reproducibility Hazards
lr = 1e-4) and re-running an upper training cell causes silent numerical drift on a fresh top-to-bottom replay (lr = 1e-2).pixels = pixels / 255 twice scales data by 1/255^2 interactively vs. 1/255 on a clean run.NameError on replay) or displayed code that no longer matches its saved output.Verification
NameErrors, double in-place mutations, and stale un-executed edits.features.npy), hard-coded personal paths (/home/alice/...), and unseeded random generators.Local Setup
uv pip sync pylock.*.toml): Installs pinned dependencies and removes stray packages that could shadow imports.uv run --no-sync jupyter lab): Starts JupyterLab without re-resolving or altering the locked .venv..venv/bin/python.Environment Audit
Before running experiments or debugging import errors, execute a compact identity check at the top of the notebook:
sys.executable: Confirms that the active notebook kernel actually points to the Python interpreter inside your locked virtual environment rather than a global system Python.os.getcwd(): Confirms the working directory so relative dataset paths (../data) resolve properly.~ and printing os.path.basename avoids leaking personal usernames into committed notebook outputs.{'python': '~/d2l-neu/.venv-pytorch/bin/python',
'version': '3.12.3',
'working_directory': 'chapter_appendix-tools-for-deep-learning'}
Editor Workflow
I, I) vs. Restart (0, 0): Interrupt stops a hung loop while preserving the stack trace for inspection; Restart wipes Python state and frees GPU VRAM.Project Architecture
.py modules while keeping the notebook for narrative, plots, and ablations..py modules fix DataLoader(num_workers > 0): Worker processes under spawn (macOS/Windows) and forkserver (Python 3.14+ Linux) import functions by module path and fail on notebook __main__ definitions.Diagnosing Failures
%debug in the next cell opens ipdb right inside the failed stack frame with all local tensors still in memory.NaNs.try / except: Catching and printing "failed" destroys the stack frame needed by %debug.Performance Measurement
IPython’s %timeit magic automatically runs warmups and multiple loops to measure fast host operations reliably:
values @ values), %timeit measures actual arithmetic completion time.torch.cuda.synchronize() or .block_until_ready()) before stopping the timer.Remote Architecture
Your browser or editor UI, the Jupyter server, the Python kernel, and the GPU need not reside on the same physical machine:
Network & Multi-User Safety
--ip 0.0.0.0: Anyone reaching an exposed Jupyter port can run arbitrary shell commands as you; always bind --ip 127.0.0.1 and tunnel over SSH (ssh -N -L).8888 may already belong to a colleague (token mismatch) or your own laptop’s local server; use a distinct port and -o ExitOnForwardFailure=yes.Check Your Understanding
Work through these three diagnostic questions:
In [3], In [8], In [9]. Does this prove the outputs are irreproducible, and would counters In [1], In [2], In [3] guarantee reproducibility?time.perf_counter() without device synchronization and observe 25\,\mu\text{s}. Why is this physically impossible?Answers:
3, 8, 9) show cells were re-run or deleted, which warns of possible hidden state but doesn’t prove outputs are wrong; conversely, 1, 2, 3 still does not guarantee reproducibility if a cell was edited after it ran. Only a fresh Restart and Run All verifies agreement.Key Takeaways
uv pip sync, and verify sys.executable in cell 1.127.0.0.1 and tunnel via SSH with ExitOnForwardFailure=yes or VS Code Remote SSH.