Gradients, backward#

Get d(output)/d(input) for every sample — no hand-derived formula.

Time: ~8 min · Runs on: CPU · You need: hawk, NumPy and matplotlib; read first: Arguments and shapes

hawk.diff.vjp (“vector-Jacobian product”: the Jacobian is the matrix of every output’s derivative with respect to every input; vjp returns that matrix applied to a seed, without ever building it) reads a kernel’s own intermediate representation (IR) and derives a new IR for its gradient — no recorded tape (a log of operations replayed backward, the way some other autodiff systems work; hawk keeps none).

Colab or Kaggle: run this first cell (it installs the packages and downloads the helper files this notebook uses). Elsewhere it only checks the imports.

Hide code cell source

# Colab setup, generated by python -m raptor_docs.nb colab_setup (do not edit).
import os

try:
    import google.colab  # noqa: F401
    HOSTED = True  # a Colab runtime
except ImportError:
    HOSTED = "KAGGLE_KERNEL_RUN_TYPE" in os.environ  # a Kaggle kernel

if HOSTED:
    import importlib.metadata, pathlib, re, shutil, subprocess, sys, urllib.request

    gpu = bool(shutil.which("nvidia-smi")) and subprocess.run(["nvidia-smi", "-L"], capture_output=True).returncode == 0
    extra = ""
    if gpu:
        # the CUDA major the runtime already has: a CuPy that is installed, else torch's, else the driver's
        major = None
        for m in ("13", "12"):
            try:
                importlib.metadata.version(f"cupy-cuda{m}x")
                major = m
                break
            except importlib.metadata.PackageNotFoundError:
                pass
        if major is None:
            try:
                import torch
                major = "13" if str(torch.version.cuda).startswith("13") else None
            except ImportError:
                pass
        if major is None:
            smi = re.search(r"CUDA Version: (\d+)", subprocess.run(["nvidia-smi"], capture_output=True, text=True).stdout)
            major = "13" if smi and int(smi.group(1)) >= 13 else "12"
        extra = f"[cuda{major}]"
        print(f"GPU found: installing the {extra} extras to match this runtime.")
    pre = ["--pre"] if os.environ.get("RAPTOR_PRE") else []  # optional: test a release candidate
    ref = os.environ.get("RAPTOR_REF", "main")  # optional: fetch the helper files from this git ref
    if pre or "RAPTOR_REF" in os.environ:
        print(f"Pre-release test: installing with --pre, helper files from {ref}.")
    # our packages with --upgrade, so a runtime that kept an older release gets the current one
    subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "--upgrade", *pre, f"raptor-hawk{extra}"])
    subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "matplotlib"])
    base = os.environ.get("RAPTOR_RAW_BASE", "https://raw.githubusercontent.com")  # optional: a local mirror
    top = os.environ.get("RAPTOR_WORKDIR") or ("/kaggle/working" if "KAGGLE_KERNEL_RUN_TYPE" in os.environ else "/content")
    root = pathlib.Path(top) / "hawk"
    for rel in (
        "docs/content/_shared/nb_helpers.py",
        "docs/content/_shared/themed_figure.py",
    ):
        (root / rel).parent.mkdir(parents=True, exist_ok=True)
        urllib.request.urlretrieve(f"{base}/amasat01/hawk/{ref}/{rel}", root / rel)
    (root / "docs/content/tutorials").mkdir(parents=True, exist_ok=True)
    os.chdir(root / "docs/content/tutorials")
    if not gpu:
        print("Running on the CPU (no GPU in this runtime). For a GPU: " + ("Settings → Accelerator → GPU T4 x2." if "KAGGLE_KERNEL_RUN_TYPE" in os.environ else "Runtime → Change runtime type → T4 GPU."))

try:
    import hawk, matplotlib  # noqa: F401
except ImportError as err:
    raise ImportError(
        "hawk, matplotlib not found. Install with `pip install matplotlib raptor-hawk`. For a GPU, add [cuda12] (or [cuda13]) to raptor-hawk."
    ) from err
import hawk
from hawk import Mutable, Scalar, Vector
from hawk.math import dot


@hawk.kernel
def energy(v: Vector[3], out: Mutable[Scalar]):   # out: where the result lands
    out = 0.5 * dot(v, v)


energy
<Kernel energy slots=2>

Deriving the backward kernel#

vjp(primal, wrt=...) derives the backward IR for energy’s gradient with respect to the names in wrt; Kernel(name, ir) names it so it can be built like any other kernel (the optional third argument, planes, declares extra planes a derived kernel never needs):

Hide code cell source

import sys, pathlib
sys.path.insert(0, str(pathlib.Path.cwd().parent / "_shared"))
from nb_helpers import plot_style, show
plot_style()
from hawk import Kernel
from hawk.diff import vjp

energy_vjp = Kernel("energy_vjp", vjp(energy, wrt=("v",)))
energy_vjp
<Kernel energy_vjp slots=3>

Running it: bar_<name>#

A derived gradient kernel is an ordinary kernel: build it, run it. bar_<name> is hawk’s adjoint (reverse-mode derivative) naming convention, used throughout the family: bar_out is the derivative of the sink out (the seed — “how much does the loss change per unit of out”; 1 for every sample means “treat out itself as the loss”), and bar_v receives the derivative with respect to the input v.

import pathlib, tempfile
import numpy as np


work_dir = pathlib.Path(tempfile.mkdtemp())
hawk.build([energy, energy_vjp], work_dir, targets=("host",))

n = 4
v = np.array([[1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]])
e = np.zeros(n)
hawk.run(hawk.load(work_dir, "energy"), v=v, out=e)
print("energy:", e)
energy: [0.5 2.5 5.  9. ]
bar_out = np.ones(n)        # seed: d(loss)/d(energy) = 1 for every sample
bar_v = np.zeros((3, n))    # receives d(energy)/d(v)
hawk.run(hawk.load(work_dir, "energy_vjp"), v=v, bar_out=bar_out, bar_v=bar_v)
print("gradient d(energy)/dv:\n", bar_v)
gradient d(energy)/dv:
 [[1. 2. 3. 4.]
 [0. 1. 0. 1.]
 [0. 0. 1. 1.]]

Here energy = 0.5 |v|^2, so d(energy)/dv = v exactly — the printed gradient above is the input.

Checking it against finite differences#

The standard sanity check for any derivative, hand-derived or not: compare it to a central finite difference of the compiled primal kernel itself.

def run_energy(v):
    out = np.zeros(v.shape[1])
    hawk.run(hawk.load(work_dir, "energy"), v=v, out=out)
    return out


def run_grad(v):
    n = v.shape[1]
    bar_out, bar_v = np.ones(n), np.zeros((3, n))
    hawk.run(hawk.load(work_dir, "energy_vjp"), v=v, bar_out=bar_out, bar_v=bar_v)
    return bar_v
rng = np.random.default_rng(42)
n = 2000
v_batch = rng.normal(size=(3, n))
analytic = run_grad(v_batch)

h = 1e-6
numeric = np.zeros_like(v_batch)
for axis in range(3):
    plus, minus = v_batch.copy(), v_batch.copy()
    plus[axis] += h
    minus[axis] -= h
    numeric[axis] = (run_energy(plus) - run_energy(minus)) / (2 * h)

max_abs_error = np.max(np.abs(analytic - numeric))
msg = f"{n} samples x 3 components, max|analytic - central diff| = {max_abs_error:.3e}"
print(msg)
2000 samples x 3 components, max|analytic - central diff| = 9.426e-10

Hide code cell source

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(4, 4))
lo, hi = analytic.min(), analytic.max()
ax.plot([lo, hi], [lo, hi], color="#898781", lw=1, ls="--", zorder=1)
ax.scatter(analytic.ravel(), numeric.ravel(), s=6, color="#2a78d6", alpha=0.5, zorder=2)
ax.set_xlabel("vjp (analytic)"); ax.set_ylabel("central difference")
ax.set_aspect("equal"); ax.grid(alpha=0.4)
show()
Chart

One kernel, many parameter values#

A Param is one shared value for the whole run. To give groups of samples their own values in a single launch, make the kernel read a per-sample cell of it: param_planes(kernel, per_cell=True) turns each Param into a short array, and an int64 plane param_cell says which entry each sample reads. The gradient of an entry is the sum over the samples that read it, so a fit over several parameter values is still one launch each way. The derived kernel is named <name>_params_cells.

from hawk import Param
from hawk.diff import param_planes
import hawk.math as m


@hawk.kernel
def relax(x: Scalar, g: Param, y: Mutable[Scalar]):
    s = x
    for _k in range(5):
        s = m.tanh(g * s + x)
    y = s


cells = param_planes(relax, per_cell=True)
cells_vjp = Kernel("relax_cells_vjp", tuple(vjp(cells, wrt=("g",))))
fwd_dir, bwd_dir = pathlib.Path(tempfile.mkdtemp()), pathlib.Path(tempfile.mkdtemp())
hawk.build([cells], fwd_dir, targets=("host",))
hawk.build([cells_vjp], bwd_dir, targets=("host",))      # it scatters across samples: its own bundle
relax_f, relax_b = hawk.load(fwd_dir, cells.name), hawk.load(bwd_dir, "relax_cells_vjp")

n_cells = 3
g = np.array([0.5, 1.5, -0.8])                  # three parameter values
xs = np.random.default_rng(1).uniform(-1.0, 1.0, 12)
cell = (np.arange(12) % n_cells).astype(np.int64)   # the entry each sample reads
y = np.zeros(12)
hawk.run(relax_f, x=xs, g=g, param_cell=cell, y=y)

bar_g = np.zeros(n_cells)
hawk.run(relax_b, x=xs, g=g, param_cell=cell, bar_y=np.ones(12), bar_g=bar_g)


def total(gv):
    out = np.zeros(12)
    hawk.run(relax_f, x=xs, g=gv, param_cell=cell, y=out)
    return np.array([out[cell == c].sum() for c in range(n_cells)])


fd = [(total(g + e * 1e-6)[c] - total(g - e * 1e-6)[c]) / 2e-6
      for c, e in enumerate(np.eye(n_cells))]
print("gradient per entry:", bar_g)
print("finite differences:", np.array(fd))
gradient per entry: [ 0.48469944 -0.22811795 -0.53920768]
finite differences: [ 0.48469944 -0.22811795 -0.53920768]

One launch ran all three parameter values, and each entry’s gradient equals the difference quotient of the samples that read it. A kernel that carries reductions of its own, or a jump= plan, is refused: split it, or run one launch per value.

What just happened#

  • hawk.diff.vjp(primal, wrt=...) derives a backward kernel from the primal’s own IR — no recorded tape, no hand-written formula.

  • bar_out seeds the adjoint of a sink; bar_v receives the adjoint with respect to an input — the bar_<name> convention hawk uses everywhere.

  • A derived gradient is an ordinary kernel: build it, run it, and check it against a central finite difference of the compiled primal, the same way you would check a hand derivation.

Try this#

Change the seed bar_out = np.ones(n) to bar_out = np.full(n, 2.0) and re-run: every gradient doubles, since vjp is linear in its seed.

Next#

Gradients, forward — push a direction through the same kernel instead, and see which kernels autodiff refuses to differentiate at all.