Utility Functions and Classes

Dive into Deep Learning · §39.9

Utility Functions and Classes: The Internal Plumbing of the d2l Package
HyperParameters · plot & ProgressBoard · uncertainty bands · RL seed aggregation & JAX JIT bucketing · FeatureCNN · custom_vjp Embed

Why the d2l Library Exists and How It Is Built

Motivation

  • Zero hidden magic: Every helper in d2l (plot, ProgressBoard, Trainer, FeatureCNN, Embed) is defined in an executable notebook cell marked with #@save.
  • Automatic extraction (make lib): Generates d2l/torch.py, d2l/jax.py, d2l/tensorflow.py, and d2l/mxnet.py directly from chapter sources.
  • Active vs. legacy helpers: §39.9 houses core PyTorch/JAX plotting, RL, and vision utilities alongside legacy MXNet/TF loops (train_ch6).

Automatic Constructor Introspection: HyperParameters

Base Class Mechanics

Every d2l.Module, d2l.DataModule, and d2l.Trainer inherits from d2l.HyperParameters so subclasses can bind constructor arguments without repetitive self.x = x boilerplate:

  • Stack-frame inspection (inspect.currentframe().f_back):
    • Reads the caller’s __init__ local variable dictionary via inspect.getargvalues(frame).
    • Filters out 'self', private names starting with '_', and any names listed in ignore.
    • Stores the clean dictionary in self.hparams and binds each key as an instance attribute via setattr(self, k, v).
def save_hyperparameters(self, ignore=None):
    """Save function arguments into instance attributes."""
    ignore = [] if ignore is None else ignore
    frame = inspect.currentframe().f_back
    _, _, _, local_vars = inspect.getargvalues(frame)
    self.hparams = {k:v for k, v in local_vars.items()
                    if k not in set(ignore+['self']) and not k.startswith('_')}
    for k, v in self.hparams.items():
        setattr(self, k, v)

Publication Plotting: d2l.plot and Log-Axis Formatting

Visualization Primitives

  • Flexible curve normalization (d2l.plot): Broadcasts a shared X across multiple Y curves, infers index x-axes when Y is None, and auto-extends the 4 default line formats across C0–C9 for 5+ curves.
  • Narrow-range log ticks (set_log_ticks): Places major ticks at 1, 2, 5 per decade whenever \text{hi} < 100 \cdot \text{lo} so narrow log axes never collapse to a single tick label.

Live Streaming Curves: ProgressBoard.show and _plot

Training Telemetry

  • Dual-axis loss & accuracy (_plot): Plots losses on the left axis (ax) and any series ending in 'acc' on a secondary right axis (ax.twinx()) with a shared top legend.
  • Single-point markers & build gating (show): Draws marker='o' on 1-point or val_* series, and skips intermediate redraws when D2L_NB_CAPTURE=1 so book builds store only the final frame.

2D Optimization Trajectories and Image/Heatmap Grids

Spatial Visualization

  • show_trace_2d(f, results): Evaluates f on an auto-widened 100 \times 100 contour grid with equal aspect ratio (set_aspect('equal')) so gradients appear orthogonal to level sets.
  • show_images & show_heatmaps: Converts tensors via d2l.numpy, and locks 4D heatmap grids (rows, cols, H, W) to a shared Normalize(min, max) color scale and single colorbar (cbar=True).

Statistical Uncertainty Plots: plot_intervals

Confidence Bars & Bands

  • Containment check & two modes (kind): Asserts \text{lo} \le \text{mean} \le \text{hi}; renders translucent fill_between envelopes (kind='band') or horizontally offset error bars in linear/log space (kind='errorbar').
  • Baselines & secondary estimators: Supports dashed reference lines, auto-rotated categorical x-labels, and secondary marks overlays.

RL Visualization and Multi-Seed Aggregation

RL Chapter Utilities

  • Multi-seed pipeline (run_seeds \to on_grid \to plot_curves): Executes K seeded runs, interpolates variable-length episodes onto a common step grid with causal smoothing, and plots the seed median with IQR (25–75%) or min–max bands.
  • Distributions & gridworlds: plot_hist overlays return histograms and show_grid renders V(s) heatmaps with greedy \pi(s) action arrows.

FeatureCNN: Perceptual Image Scoring on CIFAR-10

Generative Model Evaluation

  • Verified GPU dataset (load_cifar10_arrays): Verifies SHA-1 checksums, scales pixels to [-1, 1], and places CIFAR-10 directly on the GPU in the framework’s native image layout.
  • 128-D perceptual features (FeatureCNN): Resizes inputs to 32 \times 32 across 3 Conv-BN-ReLU-MaxPool blocks ([32, 64, 128]) and trains for 15 epochs with One-Cycle Adam using isolated local PRNG streams.

Data Caching, Sequence Masking, and Legacy Parity

I/O & Framework Coverage

  • Atomic SHA-1 dataset cache (download_extract): Streams downloads to tempfile.mkstemp, verifies 1 MB SHA-1 chunks against DATA_HUB, swaps atomically via os.replace, and writes a .extracted marker.
  • Masking & legacy loops: sequence_mask and MaskedSoftmaxCELoss zero out padded tokens, while legacy helpers (train_ch6, train_seq2seq) preserve compatibility for older MXNet/TF tabs.

Concept Check: d2l Utility Internals

Check Your Understanding

Test your understanding of the systems and numerical tricks inside d2l:

In d2l.ProgressBoard.show(), why does the method check os.environ.get('D2L_NB_CAPTURE') == '1' and skip rendering whenever final=False?

Answer: During interactive notebook runs, show(final=False) updates the live SVG figure after every few minibatches. During the automated book build (D2L_NB_CAPTURE=1), skipping intermediate redraws avoids running matplotlib hundreds of times per epoch and ensures the saved notebook output stores only one clean final figure per board.

Summary: Core Utilities in Section 39.9

Key Takeaways

Category Key Symbols (d2l.*) Primary Engineering Mechanism
Introspection HyperParameters.save_hyperparameters Inspects caller stack frame f_back to bind __init__ args into self.hparams
Plotting & Axes plot, set_axes, set_log_ticks, ProgressBoard SVG output, 1,2,5 narrow-decade log ticks, dual-axis loss/acc layout, build-time frame gating
Spatial & Intervals show_trace_2d, show_images, show_heatmaps, plot_intervals Shared heatmap color norms, adaptive contour grids, side-by-side log/linear error bars & bands
RL & JAX JIT run_seeds, on_grid, plot_curves, show_grid, forward_np, padded Multi-seed median/IQR bands, gridworld policy arrows, power-of-two batch bucketing for XLA reuse
Vision & NLP FeatureCNN, Embed, sequence_mask, download_extract CIFAR-10 perceptual features, @jax.custom_vjp one-hot embedding backward, atomic SHA-1 cache