Notebooks

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

Why Interactive Notebooks Create a New Failure Mode

Motivation

  • Why interactive state is powerful: Keep a multi-gigabyte dataset resident in RAM or VRAM while iterating on model layers and plots cell by cell.
  • Why persistent state is hazardous: Variable bindings outlive the cells that created them—editing or deleting a cell does not erase its side effects from memory.
  • Core discipline: Explore interactively cell by cell, but always verify by replaying the entire document from a fresh kernel in reading order.

The Document vs. the Kernel: Two Different Orders

The Execution Model

A notebook consists of two distinct components whose state can diverge during an editing session:

  • The Document (.ipynb / .md): Stores prose, code cells, and saved outputs ordered top to bottom—this is what you read, share, and commit to Git.
  • The Kernel (live process): Holds imported modules, tensors, PRNG states, open files, and GPU allocations ordered by execution history (In [1], In [2], \dots).
  • Classic out-of-order bug: Running a data loader first and later inserting a model cell above it succeeds in the live kernel (where data already exists) but fails with NameError on a fresh top-to-bottom run.

Document-Ordered State and Execution Counters

State Dependencies

Cross-cell state is benign when dependencies flow strictly downward in reading order:

  • Downward dataflow: The first cell seeds a NumPy generator and binds samples; the second cell computes float(samples.mean()).
  • Execution counters (In [k]): Record the sequence number since kernel startup—they are historical breadcrumbs, not a dependency graph.
  • Defensive cell structure: Keep cells focused, separate pure function definitions from stateful experiment invocations, and pass tensors explicitly rather than mutating globals across cells.
import numpy as np

rng = np.random.default_rng(7)
samples = rng.normal(size=5)
float(samples.mean())
-0.2638849576850524

Three Categories of Hidden Kernel State

Reproducibility Hazards

  • 1. Out-of-order / re-executed cells: Running a lower cell (lr = 1e-4) and re-running an upper training cell causes silent numerical drift on a fresh top-to-bottom replay (lr = 1e-2).
  • 2. In-place self-mutation: Re-running pixels = pixels / 255 twice scales data by 1/255^2 interactively vs. 1/255 on a clean run.
  • 3. Deleted or edited-after-run cells: Leaves stale variables in RAM (NameError on replay) or displayed code that no longer matches its saved output.

The Golden Rule: Restart Kernel and Run All Cells

Verification

  • What Restart & Run All catches: Terminates the Python process, frees all RAM/VRAM, and catches use-before-define NameErrors, double in-place mutations, and stale un-executed edits.
  • What still escapes a local clean run: Uncommitted local cache files (features.npy), hard-coded personal paths (/home/alice/...), and unseeded random generators.

Deterministic Local Environments with uv Lock Files

Local Setup

  • Exact lock sync (uv pip sync pylock.*.toml): Installs pinned dependencies and removes stray packages that could shadow imports.
  • Locked launch (uv run --no-sync jupyter lab): Starts JupyterLab without re-resolving or altering the locked .venv.
  • Server vs. kernel: Always verify the notebook’s selected kernel actually points to .venv/bin/python.

Kernel Identity and Working Directory Sanity Check

Environment Audit

Before running experiments or debugging import errors, execute a compact identity check at the top of the notebook:

  • Verifying 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.
  • Verifying os.getcwd(): Confirms the working directory so relative dataset paths (../data) resolve properly.
  • Privacy-safe output: Replacing the home path with ~ and printing os.path.basename avoids leaking personal usernames into committed notebook outputs.
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'}

Working Effectively in JupyterLab

Editor Workflow

  • Interrupt (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.
  • Beware of orphaned GPU kernels: Closing a browser tab does not kill its kernel process—a single forgotten notebook tab can hold 10–20 GB of VRAM indefinitely.
  • Running panel audit: Shut down idle kernels explicitly in the Running Terminals and Kernels sidebar.

Scaling from Notebooks to Modules in VS Code

Project Architecture

  • Separate reusable logic from narrative: Move tested data loaders, model classes, and losses into .py modules while keeping the notebook for narrative, plots, and ablations.
  • Why .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.

Post-Mortem Debugging with %debug

Diagnosing Failures

  • Instant post-mortem inspection: When a cell raises an exception, running %debug in the next cell opens ipdb right inside the failed stack frame with all local tensors still in memory.
  • Visual breakpoints: Set line breakpoints directly inside JupyterLab or VS Code cells to step through tensor shapes and NaNs.
  • Avoid broad try / except: Catching and printing "failed" destroys the stack frame needed by %debug.

Microbenchmarking with %timeit and Async GPU Traps

Performance Measurement

IPython’s %timeit magic automatically runs warmups and multiple loops to measure fast host operations reliably:

  • Host vs. accelerator timing: On CPU arrays (values @ values), %timeit measures actual arithmetic completion time.
  • The asynchronous GPU dispatch trap: CUDA and XLA kernel launches return control to Python immediately after queuing work on the device stream.
  • Three rules for GPU timing:
    1. Warm up first to exclude JIT/CUDA compilation.
    2. Synchronize explicitly (torch.cuda.synchronize() or .block_until_ready()) before stopping the timer.
    3. Record tensor shapes, dtype, device name, and library versions with every benchmark.
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)

Remote GPU Development Across Process Layers

Remote Architecture

Your browser or editor UI, the Jupyter server, the Python kernel, and the GPU need not reside on the same physical machine:

  • Decoupled architecture: A lightweight laptop runs the browser UI or VS Code client while the notebook server and kernel execute directly on a remote workstation or cloud VM attached to the GPU.
  • Where code actually runs: Tensors and GPU memory belong to the remote kernel process. In VS Code Remote SSH, always verify the status bar shows SSH before selecting the Python interpreter—a local laptop kernel cannot see the remote GPU.

Secure Remote Access via SSH Port Forwarding

Network & Multi-User Safety

  • Never bind --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).
  • Remote & local port collisions: On shared servers, port 8888 may already belong to a colleague (token mismatch) or your own laptop’s local server; use a distinct port and -o ExitOnForwardFailure=yes.

Concept Check: Kernel State and Remote Timing

Check Your Understanding

Work through these three diagnostic questions:

  1. A saved 3-cell notebook displays execution counters In [3], In [8], In [9]. Does this prove the outputs are irreproducible, and would counters In [1], In [2], In [3] guarantee reproducibility?
  2. You time an 8192 \times 8192 BF16 matrix multiplication on an RTX 4090 with time.perf_counter() without device synchronization and observe 25\,\mu\text{s}. Why is this physically impossible?
  3. Before committing a finished notebook to Git, what five checks belong on your pre-share checklist?

Answers:

  1. Gaps (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.
  2. An 8192^3 matmul requires 2 \times 8192^3 \approx 1.1 \times 10^{12}\text{ FLOPs}. At 25\,\mu\text{s}, that would imply 44{,}000\text{ TFLOP/s} (\sim 130\times the 4090’s datasheet peak)—you measured host-side CUDA kernel launch overhead, not GPU execution.
    1. Restart & run all; (ii) no personal paths/unrecorded downloads; (iii) scrub secrets/tokens from outputs; (iv) trim noisy progress logs; (v) record environment and hardware specs.

Summary: Reproducible Interactive Development

Key Takeaways

  • Reproducibility & Environment: Always run Restart Kernel and Run All Cells, lock dependencies with uv pip sync, and verify sys.executable in cell 1.
  • Resource & Timing Discipline: Shut down orphaned GPU kernels in JupyterLab’s Running panel, and synchronize GPU streams before stopping benchmark timers.
  • Remote Safety: Bind Jupyter to 127.0.0.1 and tunnel via SSH with ExitOnForwardFailure=yes or VS Code Remote SSH.