After implementing a CUDA kernel, we can ask a more productive question: should this kernel have been handwritten at all? If the calculation is a matrix product, FFT or standard reduction, expressing the mathematical primitive may give a library more freedom to tune it than a scientist can afford to maintain.
This final available chapter connects the hardware course to a new mathematical operation: differentiating a program. The same computational graph that exposes dependencies can carry derivative information. We will derive those derivatives rather than treating automatic differentiation as a framework feature to memorise.
1. Choose the level at which the problem is regular
A GPU library knows more than a single loop. A matrix multiplication specifies an entire operation, allowing blocking, data reuse, specialised instructions and device-specific dispatch. NVIDIA's cuBLAS, cuFFT and cuRAND supply linear algebra, Fourier transforms and random-number facilities; AMD's ROCm ecosystem supplies corresponding categories of tools. Prefer an existing primitive when its semantics, accuracy and data layout fit the calculation.
For custom work, options from the source include:
| Abstraction | What it expresses | What the author still owns |
|---|---|---|
| OpenACC / OpenMP offload | Directive-based parallel loops and data regions | Dependencies, movement and supported compiler features |
| OpenCL | Portable kernel/execution APIs | Kernels, memory and target-specific tuning |
| SYCL, Kokkos, Alpaka | C++ execution/memory abstractions | Algorithmic structure and performance portability choices |
| CuPy | GPU array operations resembling NumPy | Device residency, temporary arrays and supported operations |
| Numba ecosystem / Taichi | Compiled Python-authored kernels or embedded simulation DSLs | Supported subset, execution model and deployment toolchain |
These are categories, not an installation or recommendation of a specific current package version. Portability of source is not guaranteed portability of performance. Coalescing, surface-to-volume ratio and serial dependencies remain mathematical constraints underneath the interface.
The source used AlexNet's 2012 results and successive Warwick GPU generations to motivate hardware specialisation. Mixed precision and tensor/matrix units make the point concrete: a fast fused operation such as can have very different precision and accumulation semantics from an ordinary scalar loop. Hardware marketing rates cannot replace an application error analysis. Changes across generations also make low-level assumptions costly to sustain; numerical libraries can absorb some of that work.
2. Why a gradient is an HPC problem
Suppose a loss depends on millions of parameters. A gradient-based update needs all partial derivatives. A forward finite difference is
One reused baseline still leaves approximately additional evaluations. For a smooth function, forward differencing has truncation error , while roundoff in the subtraction can contribute an error proportional to , with scale-dependent constants. Making arbitrarily small is therefore not a solution.
Symbolic differentiation can produce exact formulas, but expanding a large program into one expression can duplicate subexpressions and separate derivative code from its source. Neither symbolic differentiation nor finite differences is inherently “bad”: finite differences remain useful for small verification cases. We want an approach that reuses the program's own intermediate values.
Automatic differentiation (AD) applies the chain rule to elementary operations along a computational trace or transformed program. It avoids finite-difference step-size error, but still uses floating-point arithmetic and differentiates the implemented operations under their derivative rules. Nondifferentiable points, data-dependent branches and custom primitives need care.
3. Decompose the source function into reusable steps
For and , consider
Use the primal trace
The trace preserves reuse: feeds both logarithm and product, and feeds both product and sine. Those multiple paths will require adding derivative contributions in reverse mode.
4. Forward mode asks: what does one input perturbation do?
Seed an input direction and propagate directional derivatives:
Collecting coefficients gives
One pass computes , a Jacobian–vector product. For , . Seeding coordinate vectors constructs its columns in passes, but a single desired directional derivative needs just one pass. Few inputs and many outputs often favour forward mode for a full Jacobian.
Keep the primal values fixed and send one input perturbation through the trace. Changing the seed changes the directional derivative, while the computational graph remains the same.
Choose one input direction, then follow its tangent through log, product and sine to the output.
Play, pause, or scrub to inspect a moment.
Paused. Unit seed along x₁. The completed forward directional derivative is 1.2.
5. Reverse mode asks: which inputs influenced one output?
Let . Seed and initialise other adjoints to zero. The output subtraction gives and . The addition gives and . Propagating through the remaining operations accumulates
Consequently,
At the function is and the gradient is . A forward seed yields ; seed yields ; seed yields . Reverse mode obtains both partials from one output seed. The bar means derivative sensitivity here, not complex conjugation.
For general output seed , reverse mode computes , a vector–Jacobian product in the common column-vector convention. A scalar loss has , so one reverse sweep obtains all input sensitivities. For programs built from suitable primitives, its arithmetic cost is a modest multiple of evaluating the program, rather than separate function evaluations. It must retain or recompute primal information, so memory can become the limiting resource. Checkpointing trades recomputation for storage.
Forward and reverse modes compute different products of the same local linear map. Neither must materialise the full Jacobian. The JAX differentiation guide develops this JVP/VJP interpretation.
Now send an output sensitivity against the arrows. Pause where the paths meet: both contributions must be added to the input adjoint.
Seed the output and run the graph backwards. At a reused input, watch contributions add rather than overwrite.
Play, pause, or scrub to inspect a moment.
Paused. Output seed 1. The completed reverse sensitivities are (1.2, 1.235); both paths into each input are added.
6. Frameworks package the transformation; they do not erase its assumptions
AD can be implemented by source transformation, operator overloading/tapes, or graph/intermediate-representation transformations. It is misleading to describe every framework as using a precomputed static graph. PyTorch commonly records a dynamic graph; TensorFlow has eager/tape and graph execution; JAX traces computations for transformations and compilation.
For the source's example, representative interfaces are jax.grad(f, argnums=0), TensorFlow's GradientTape, and PyTorch tensors with requires_grad=True followed by backward(). These names illustrate how a scalar-loss derivative is requested; package versions, devices and supported operations still need checking in an implementation.
Tensors, AD, compilation and GPU execution make high-level code powerful because primitives expose large regular operations. They do not provide gradients for arbitrary opaque external code or automatically distribute an arbitrary program optimally. Data loading can remain CPU-bound; device transfers can dominate; large models require collectives between devices; memory limits can dictate recomputation. OpenMP, MPI and CUDA explain these costs beneath the interface.
Exercises and the available course boundary
- Derive both AD sweeps without first differentiating the expanded expression. Where must reverse contributions be added rather than overwritten?
- Verify the analytic gradient at and a point with nonzero using several finite-difference step sizes. Explain the truncation/roundoff trade-off.
- For , compare full-Jacobian costs with the costs of one JVP or one VJP. Why does a requested product change the preferred method?
- A library matrix multiply is fast but the application is slow. Use the course's ownership, movement and timing models to propose measurements before writing a custom kernel.
This completes the available substantive PX457 sources: numerical representation → instruction/data flow → shared/distributed ownership → scaling → GPU execution → differentiating computational graphs.