PX457 · Course contents

Measuring and Accelerating: Higher Abstractions and Automatic Differentiation

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:

AbstractionWhat it expressesWhat the author still owns
OpenACC / OpenMP offloadDirective-based parallel loops and data regionsDependencies, movement and supported compiler features
OpenCLPortable kernel/execution APIsKernels, memory and target-specific tuning
SYCL, Kokkos, AlpakaC++ execution/memory abstractionsAlgorithmic structure and performance portability choices
CuPyGPU array operations resembling NumPyDevice residency, temporary arrays and supported operations
Numba ecosystem / TaichiCompiled Python-authored kernels or embedded simulation DSLsSupported 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 A←BC+DA\leftarrow BC+D 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 f:Rn→Rf:\mathbb R^n\to\mathbb R depends on millions of parameters. A gradient-based update needs all nn partial derivatives. A forward finite difference is

∂f∂xi(x)≈f(x+hei)−f(x)h.\frac{\partial f}{\partial x_i}(x) \approx\frac{f(x+he_i)-f(x)}h.

One reused baseline still leaves approximately nn additional evaluations. For a smooth function, forward differencing has truncation error O(h)O(h), while roundoff in the subtraction can contribute an error proportional to u/hu/h, with scale-dependent constants. Making hh 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 x1>0x_1>0 and x2∈Rx_2\in\mathbb R, consider

y=f(x1,x2)=log⁡x1+x1x2−sin⁡x2.y=f(x_1,x_2)=\log x_1+x_1x_2-\sin x_2.

Use the primal trace

v1=log⁡x1,v2=x1x2,v3=sin⁡x2,v4=v1+v2,y=v4−v3.v_1=\log x_1,\quad v_2=x_1x_2,\quad v_3=\sin x_2, \quad v_4=v_1+v_2,\quad y=v_4-v_3.

The trace preserves reuse: x1x_1 feeds both logarithm and product, and x2x_2 feeds both product and sine. Those multiple paths will require adding derivative contributions in reverse mode.

One computation, two derivative directions
x₁x₂log x₁x₁x₂sin x₂+ + −ytangents → ← sensitivities
The forward graph computes the function. Forward mode carries input perturbations along arrows; reverse mode carries output sensitivities against them and adds contributions at shared inputs. The two incoming paths to each input explain the two terms in each final partial derivative. ↗

4. Forward mode asks: what does one input perturbation do?

Seed an input direction (x˙1,x˙2)(\dot x_1,\dot x_2) and propagate directional derivatives:

v˙1=x˙1/x1,v˙2=x2x˙1+x1x˙2,v˙3=cos⁡(x2)x˙2,y˙=v˙1+v˙2−v˙3.\begin{aligned} \dot v_1&=\dot x_1/x_1,\\ \dot v_2&=x_2\dot x_1+x_1\dot x_2,\\ \dot v_3&=\cos(x_2)\dot x_2,\\ \dot y&=\dot v_1+\dot v_2-\dot v_3. \end{aligned}

Collecting coefficients gives

y˙=(1/x1+x2)x˙1+(x1−cos⁡x2)x˙2.\dot y=(1/x_1+x_2)\dot x_1+(x_1-\cos x_2)\dot x_2.

One pass computes JvJv, a Jacobian–vector product. For f:Rn→Rmf:\mathbb R^n\to\mathbb R^m, J∈Rm×nJ\in\mathbb R^{m\times n}. Seeding coordinate vectors constructs its columns in nn 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.

Carry a perturbation through the program

Choose one input direction, then follow its tangent through log, product and sine to the output.

Play, pause, or scrub to inspect a moment.

x₁2dot = 1x₂0.7dot = 0log0.693dot = ?multiply1.4dot = ?sin0.644dot = ?+ + −1.449dot = ?primal values stay fixed; tangents travel forward

Paused. Unit seed along x₁. The completed forward directional derivative is 1.2.

The source function is log(x₁)+x₁x₂−sin(x₂), evaluated at (2,0.7). Forward mode propagates one chosen unit input direction. Primal values and local derivative contributions are kept distinct. ↗

5. Reverse mode asks: which inputs influenced one output?

Let vˉ=∂y/∂v\bar v=\partial y/\partial v. Seed yˉ=1\bar y=1 and initialise other adjoints to zero. The output subtraction gives vˉ4=1\bar v_4=1 and vˉ3=−1\bar v_3=-1. The addition gives vˉ1=1\bar v_1=1 and vˉ2=1\bar v_2=1. Propagating through the remaining operations accumulates

xˉ1+=vˉ1/x1,xˉ1+=vˉ2x2,xˉ2+=vˉ2x1,xˉ2+=vˉ3cos⁡x2.\begin{aligned} \bar x_1&\mathrel{+}=\bar v_1/x_1,& \bar x_1&\mathrel{+}=\bar v_2x_2,\\ \bar x_2&\mathrel{+}=\bar v_2x_1,& \bar x_2&\mathrel{+}=\bar v_3\cos x_2. \end{aligned}

Consequently,

∇f(x1,x2)=(1/x1+x2x1−cos⁡x2).\nabla f(x_1,x_2)= \begin{pmatrix}1/x_1+x_2\\x_1-\cos x_2\end{pmatrix}.

At (x1,x2)=(2,0)(x_1,x_2)=(2,0) the function is log⁡2\log2 and the gradient is (1/2,1)(1/2,1). A forward seed (1,0)(1,0) yields 1/21/2; seed (0,1)(0,1) yields 11; seed (1,1)(1,1) yields 3/23/2. Reverse mode obtains both partials from one output seed. The bar means derivative sensitivity here, not complex conjugation.

For general output seed w∈Rmw\in\mathbb R^m, reverse mode computes JTwJ^Tw, a vector–Jacobian product in the common column-vector convention. A scalar loss has m=1m=1, 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 nn 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.

Send sensitivity back along every path

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.

x₁2bar = 0x₂0.7bar = 0log0.693bar = ?multiply1.4bar = ?sin0.644bar = ?+ + −1.449bar = 1shared inputs add contributions from every path

Paused. Output seed 1. The completed reverse sensitivities are (1.2, 1.235); both paths into each input are added.

Same function and point as the forward sweep. Reverse mode multiplies local derivatives by the output seed and accumulates at shared inputs. The bar denotes derivative sensitivity, not complex conjugation. ↗

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

  1. Derive both AD sweeps without first differentiating the expanded expression. Where must reverse contributions be added rather than overwritten?
  2. Verify the analytic gradient at (2,0)(2,0) and a point with nonzero x2x_2 using several finite-difference step sizes. Explain the truncation/roundoff trade-off.
  3. For f:R1000→R2f:\mathbb R^{1000}\to\mathbb R^2, compare full-Jacobian costs with the costs of one JVP or one VJP. Why does a requested product change the preferred method?
  4. 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.