Module 00
The Specialist's Toolkit
How do we turn mathematical ideas into correct, efficient, reproducible experiments on our own machine?
- lessons
- 24
- duration
- 31 h 40 min
- concepts
- 111
- available in English
- 24 / 24
- completed by you
0 of 24
Where it fits
Prerequisites
None, this is a starting point.
Overview
Set up a working environment for AI research and scientific computing. Use modern typed Python, study NumPy memory layout, broadcasting, advanced indexing and einsum, and work with pandas, Matplotlib, and Jupyter. Build reproducible environments with uv and explore PyTorch on a local 8 GB GPU. Finish with numerical testing, profiling, debugging, reproducibility, checkpointing, experiment tracking, and project structure with Git. Reimplement the central idea of each tool at small scale before using the full tool.
Why it matters
The rest of the course relies on these skills. Implementing linear algebra and optimization, training the project GPT in 8 GB of VRAM, simulating AlphaZero, and backtesting without leakage all require a working command of the tools. Good research practice means diagnosing failures quickly, measuring before optimizing, and reproducing a result months later.
Lessons 24
- 01Reproducible environments: uv, dependencies and the CUDA stackBuild an isolated Python environment declared in pyproject.toml and locked with uv, so it can be reproduced on another machine or a year later. Examine the GPU software stack, including the driver, CUDA runtime bundled with PyTorch wheels, and RTX 4060 architecture, to diagnose broken installations on Windows. Finish by creating the course project skeleton.
- 02Jupyter as a lab: kernels, hidden state and magicsJupyter architecture (interface, server, kernel, and message protocol), registering the project environment as a kernel, and working without the hidden state that makes so many notebooks irreproducible. IPython magics for timing, profiling, and debugging; autoreload for module development; and a workflow separating exploration from reliable code.
- 03Modern scientific Python: data model, types and dataclassesA dense review of Python idioms most important in numerical code (data-model protocols, generators, context managers, decorators), followed by what distinguishes maintainable research code: type annotations checked statically, immutable dataclasses for configurations and results, and array shape annotations that catch dimensional errors.
- 04Inside the ndarray: memory, dtypes, strides and viewsAn ndarray is a block of memory plus a recipe for interpreting it: dtype, shape, strides, and offset. This model explains why transposing is free, why some operations copy and others do not, when an array is contiguous, and how to build sliding windows without copying. The same model governs PyTorch tensors, so mastering it here pays off throughout the course.
- 05Broadcasting and vectorizationBroadcasting rules allow operations on arrays of different shapes without copying, while vectorization moves loops from the interpreter to compiled code. Learn to think in shapes, rewrite nested-loop algorithms as array operations (pairwise distances, stable softmax and log-sum-exp, particle simulations), and control the memory explosion of naive vectorization by processing blocks.
- 06Advanced indexing, masks and scatter operationsIndexing with integer and Boolean arrays allows selection, rearrangement, and grouping without loops, with its own shape rules and always copying. Master gather and scatter (take_along_axis, np.add.at, bincount), indirect sorting (argsort, argpartition, searchsorted), and patterns that recur throughout the course: top-k, histograms, group aggregation, and embedding lookup.
- 07einsum and index notation for tensorsEinstein notation describes tensor products, traces, transpositions, and contractions with one index string. Learn to read and write einsum fluently, estimate its cost and choose contraction order, and rearrange axes readably with einops. This is the language used for attention, many modern layers, and much of the mathematics in papers.
- 08Testing numerical code with pytest and HypothesisNumerical code fails silently: it returns plausible but incorrect numbers. Build a specific testing strategy: dtype-justified tolerances, tests against slow but obvious reference implementations, metamorphic relations without an oracle, Hypothesis properties over generated arrays, and stochastic-code tests with a controlled false-positive rate, all organized with pytest.
- 09pandas for tabular datapandas as table algebra: indexes and automatic alignment, selection with loc and iloc under Copy-on-Write, types (categorical, nullable, str, Arrow), split-apply-combine with groupby, joins, and reshaping. Focus on the mental model (everything aligns by labels), validating joins, and writing chained, fast, verifiable transformations saved in columnar format.
- 10Time series with pandaspandas tools for time-indexed data: DatetimeIndex, time zones, frequencies and calendars, resample, rolling and exponential windows, shifts, and alignment of asynchronous series. The focus is temporal correctness: no value may use future information, the foundation of quantitative work and honest validation with temporal data.
- 11Scientific visualization with matplotlibThe matplotlib object-oriented API (Figure, Axes, Artist) for experiment diagnostics and publication-quality figures. Covers perception principles (perceptually uniform color maps, logarithmic scales, small multiples), honest representation of uncertainty across seeds, reproducible scripted vector figures, and algorithm animation.
- 12PyTorch tensors: from ndarray to GPUPyTorch tensors extend NumPy's memory model with devices, deep-learning dtypes and operation tracking for autograd. Learn to manage views and move data between NumPy, CPU and GPU without unnecessary copies or common device and dtype errors.
- 13autograd: PyTorch's dynamic graphHow PyTorch records operations in a dynamic graph and backward traverses it to accumulate leaf gradients. Control graph recording and accumulation, compute higher derivatives, use torch.func, and verify custom autograd functions.
- 14nn.Module, optimizers and the training loopThe anatomy of PyTorch training code: nn.Module as a tree of parameters, buffers and submodules with its state_dict; torch.optim parameter groups, state and schedulers; and the canonical training and evaluation loop.
- 15Dataset, DataLoader and the data pipelineHow data reach the GPU: map-style and iterable datasets, samplers, collation, variable-length batches, worker processes and pinned memory. Diagnose data bottlenecks and account for Windows spawn behavior.
- 16The local GPU: asynchronous execution, memory and mixed precision on 8 GBGet the most from an 8 GB RTX 4060: CUDA asynchronous execution and accurate timing, the memory budget of training (weights, gradients, optimizer state and activations), PyTorch’s caching allocator and memory-error diagnosis, and practical mixed precision using autocast, GradScaler, bfloat16 and TF32. Numerical format theory is in m09 and multi-GPU scaling in m21.
- 17Profiling: measure before you optimizeA methodology for finding where time and memory go in numerical and training code: benchmarks with warm-up and repetition, deterministic and sampling Python profilers, memory profiling and torch.profiler CPU and GPU traces viewed in Perfetto. Classify a program as overhead-, memory-, compute- or data-bound and apply the matching remedy.
- 18torch.compile: graph capture and fusionHow torch.compile works: TorchDynamo captures graphs from Python bytecode with guards, AOTAutograd traces backward and Inductor generates fused kernels (Triton on GPU, C++ on CPU). Measure speedup separately from compilation, eliminate graph breaks and recompilations, select modes and know when compilation pays off, including Windows support.
- 19Debugging numerical code and training runsTraining can fail silently or produce NaN hours later. Combine classical debugging with tracing the first NaN or Inf, sanity checks, gradient and activation instrumentation, and bisection to isolate the cause.
- 20Reproducibility: random generators, seeds and determinismReproducibility at bitwise and statistical levels: modern pseudorandom generators, PCG64, Philox and SeedSequence; seeding PyTorch training including DataLoader workers; GPU nondeterminism and its control; and reporting results across seeds.
- 21Checkpoints, safe serialization and exact resumptionDesign a complete training checkpoint, including model, optimizer, scheduler, GradScaler, RNG states, DataLoader progress and configuration, with atomic writes and rotation for exact resumption. Learn about restricted weights_only loading and safetensors.
- 22Experiment tracking and configurationA free local experiment system with declarative configuration and command-line overrides, run directories with full provenance, TensorBoard metrics and pandas analysis, including resumable local sweeps.
- 23Anatomy of a research project and git for researchOrganize a research project with an installable package, separation of exploration and reliable code, data and results outside git, automated quality and a lab notebook. Use commits, branches, tags and git bisect as scientific tools.
- 24JAX: function transformations (optional)Optional introduction to pure programs transformed by grad, jit and vmap and compiled with XLA: tracing rules, static and traced values, pytrees, explicit PRNG keys and comparison with PyTorch. On native Windows JAX uses CPU; NVIDIA GPU requires experimental WSL2 support.
Module capstone
Reproducible training laboratory
Build the workbench for the rest of the course. Create a repository with uv, a src layout, pre-commit, and tests with pytest and Hypothesis. Train a supplied small MLP or CNN on the RTX 4060. Include typed configuration, complete seeding and optional deterministic mode, switches for mixed precision and torch.compile, atomic checkpoints, and full provenance in TensorBoard. Verify exact resumption by stopping a process, resuming it, and checking that its curve matches an uninterrupted run. Deliver a profile report that explains the bottleneck and the fix, a multi-seed sweep analyzed with pandas and plotted with bands in Matplotlib, and a planted regression located with git bisect run.
Check what you already know
- Create a project with uv and a lockfile, install PyTorch with CUDA, and verify the GPU from Python
- Explain hidden notebook state and use %timeit, %debug, and autoreload
- Model configuration with validated immutable dataclasses and check type annotations with mypy or Pyright
- Calculate array strides and predict when a NumPy operation returns a view or a copy
- Vectorize pairwise distances with broadcasting and manage intermediate memory
- Implement top-k and scatter-add without loops using argpartition, take_along_axis, and np.add.at
- Implement multi-head attention using einsum and reason about contraction order
- Test numerical code with justified tolerances and write property tests with Hypothesis
- Use groupby with transform and validate join cardinality in pandas
- Build time bars with resample and detect look-ahead leakage
- Plot training curves across seeds with uncertainty bands using Matplotlib's object-oriented API
- Predict when view fails in PyTorch and move data between NumPy, CPU, and GPU without unnecessary copying
- Implement a torch.autograd.Function with an analytic backward pass that passes gradcheck
- Write a training loop with parameter groups, a scheduler, and train and eval modes
- Diagnose and resolve a DataLoader bottleneck on Windows
- Estimate training memory and use mixed precision to fit within 8 GB
- Profile a training run with torch.profiler and identify the type of bottleneck
- Eliminate graph breaks and measure torch.compile speedup correctly
- Locate the first NaN in a training run and apply sanity checks
- Reproduce a training run bit for bit by seeding the DataLoader workers along with the main process
- Resume a run exactly from an atomic checkpoint and load weights safely
- Track provenance and metrics for a local sweep and analyze it with pandas
- Use git bisect run to find the commit that degraded a metric
- Combine grad, jit, and vmap in JAX while managing explicit PRNG keys