Supply the derivatives your field already knows#

Write a function with a derivative YOU supply, and prove hawk really uses it.

Time: ~7 min · Runs on: CPU (same code on GPU) · You need: hawk, NumPy and matplotlib; read first: extend it by inheritance

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/vocabulary").mkdir(parents=True, exist_ok=True)
    os.chdir(root / "docs/content/vocabulary")
    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

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()

The vocabulary, reused#

Perturbed is the same Kind the last tutorial built:

import hawk
from hawk import Mutable, Param, Scalar, Vector
from hawk.ext import DATA_ONLY, KernelKind


class Orbit(KernelKind, slug="orbit"):
    r: Vector[3]
    v: Vector[3]
    dt: Param
    g: Param
    guard = DATA_ONLY


class Perturbed(Orbit, slug="perturbed"):
    cd: Scalar

A primitive: your own forward, your own rules#

hawk.ext.primitive(name, vjp=..., jvp=...) registers a plain Python function that gets inlined everywhere it is CALLED INSIDE A KERNEL, plus a reverse (vjp) and/or forward (jvp) derivative rule you supply — the derivative table’s own rule for that arithmetic is never consulted. speed_ramp smoothly turns a force on past a threshold speed; its exact derivative, by hand, is the logistic sigmoid 1 / (1 + exp(-s)) — exactly what both lambdas below compute (the finite-difference check later on this page confirms it numerically):

from hawk.ext import primitive
from hawk.math import exp, log


@primitive("speed_ramp",
           vjp=lambda s, bar: bar / (1.0 + exp(-s)),
           jvp=lambda s, ds: ds / (1.0 + exp(-s)))
def speed_ramp(s):
    return log(1.0 + exp(s))

A kernel that uses it#

eased_drag is the drag family from the last tutorial, but the quadratic term ramps on smoothly past v_crit instead of applying in full from v=0. It only reads v and cd from Perturbed’s vocabulary — a kernel is never required to use every name its Kind declares, only the ones its own body needs:

import numpy as np
from hawk.math import norm


@Perturbed
def eased_drag(v, cd, v_crit: Param, a_mag: Mutable[Scalar]):
    a_mag = cd * speed_ramp(norm(v) - v_crit)


eased_drag
<Kernel eased_drag slots=4>

Calling a kernel builds it on first use and runs it on the host (the build is taught in Your first kernel):

speeds = np.linspace(0.0, 40.0, 6)
v = np.zeros((3, 6)); v[0] = speeds
a_mag = np.asarray(eased_drag(v=v, cd=np.full(6, 0.004), v_crit=25.0))
drag_by_speed = dict(zip(speeds.tolist(), a_mag.round(4).tolist()))
print("drag magnitude by speed:", drag_by_speed)
drag magnitude by speed: {0.0: 0.0, 8.0: 0.0, 16.0: 0.0, 24.0: 0.0013, 32.0: 0.028, 40.0: 0.06}

Proving the SUPPLIED rule is the one used#

A correct derivative is not enough proof: the table’s own rule for log(1 + exp(s)) is ALSO correct, so a right answer alone cannot tell you which one ran. Declare the derivative deliberately wrong – three times too big – and check that the wrong number comes out:

from hawk import Kernel
from hawk.diff import vjp


@primitive("deliberately_wrong", vjp=lambda s, bar: 3.0 * bar)
def deliberately_wrong(s):
    return s + 0.0          # the identity -- its TRUE gradient is 1, not 3


@hawk.kernel
def control(x: Scalar, y: Mutable[Scalar]):
    y = deliberately_wrong(x)


control_vjp = Kernel("control_vjp", vjp(control, wrt=("x",)))
bar_x = np.asarray(control_vjp(bar_y=np.array([1.0, 1.0])))
print("gradient (expect 3, not 1):", bar_x)
gradient (expect 3, not 1): [3. 3.]

deliberately_wrong’s TRUE derivative is 1 (it is the identity); the declared rule said 3, and 3 is what came back. If hawk had differentiated THROUGH the inlined forward instead of applying the supplied rule, this would print [1. 1.] – proof the rule you write is the one that runs, not a decoration beside the real derivative.

speed_ramp’s own rule is correct, not a deliberate trick – check it against a finite difference:

@hawk.kernel
def ramp_only(x: Scalar, y: Mutable[Scalar]):
    y = speed_ramp(x)


ramp_only_vjp = Kernel("ramp_only_vjp", vjp(ramp_only, wrt=("x",)))

Run it, and check the supplied rule against a finite difference:

xs = np.linspace(-6.0, 6.0, 25)
H = 1e-5
fd = (np.asarray(ramp_only(x=xs + H)) - np.asarray(ramp_only(x=xs - H))) / (2 * H)

bar_x = np.asarray(ramp_only_vjp(x=xs, bar_y=np.ones(25)))
print("max|supplied vjp - central difference|:", np.max(np.abs(fd - bar_x)))
max|supplied vjp - central difference|: 5.410094594537895e-11

Hide code cell source

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(fd, bar_x, "o")
lims = [fd.min(), fd.max()]
ax.plot(lims, lims, "--", color="gray")
ax.set_xlabel("finite difference"); ax.set_ylabel("supplied vjp")
ax.set_title("speed_ramp's supplied derivative vs. a finite difference")
show()
Chart: speed_ramp's supplied derivative vs. a finite difference

Differentiating a Kind-built kernel#

Everything above differentiated a plain @hawk.kernel. vjp works exactly the same way on a kernel built from a Kind — here, eased_drag itself, your vocabulary and your primitive, differentiated with respect to cd:

eased_drag_vjp = Kernel("eased_drag_vjp", vjp(eased_drag, wrt=("cd",)))

Run it, and check against a finite difference of eased_drag itself:

bar_cd = np.asarray(eased_drag_vjp(v=v, v_crit=25.0, bar_a_mag=np.ones(6)))

H = 1e-6
a_plus = np.asarray(eased_drag(v=v, cd=np.full(6, 0.004 + H), v_crit=25.0))
a_minus = np.asarray(eased_drag(v=v, cd=np.full(6, 0.004 - H), v_crit=25.0))
fd_cd = (a_plus - a_minus) / (2 * H)
diff_cd = np.max(np.abs(bar_cd - fd_cd))
print("max|d(a_mag)/d(cd), supplied - central difference|:", diff_cd)
max|d(a_mag)/d(cd), supplied - central difference|: 3.4567904094728874e-12

Your Kind, your primitive, and hawk.diff are the same three pieces the capstone runs at scale — this is that whole chain in ten lines.

What just happened#

  • @primitive(name, vjp=..., jvp=...) registers a forward that is INLINED everywhere it is called, plus the derivative rule(s) that replace the table’s for that subgraph.

  • A deliberately wrong rule proves the point: the SUPPLIED rule is what runs, not the table’s correct rule for the same arithmetic.

  • speed_ramp’s own rule lands exactly on the finite-difference line, and so does vjp applied directly to a Kind-built kernel like eased_drag — differentiation does not care whether a kernel came from a plain @hawk.kernel or a vocabulary.

Try this#

Register a second primitive with only a vjp= (no jvp=), use it in a kernel, then call hawk.diff.jvp on that kernel – hawk refuses by name rather than falling back to the table.

Next#

Capstone: your physics, end to end – the same Kind and the same primitive, run at scale and handed to PyTorch. Not ready for a primitive, or need raw C++ instead? See when hawk can’t spell it.