Gradients through branches and stops#

Differentiate a kernel that switches between two behaviours, and one that stops itself — and know exactly what the gradient means at the switch.

Time: ~8 min · Runs on: CPU · You need: hawk and NumPy; read first: Gradients, backward

Real models branch: a contact force that only acts on touching, a saturation, a stop condition. hawk’s vjp handles these directly — each branch is differentiated on its own, and the derived kernel takes the same path the primal took.

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}"])
    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  # noqa: F401
except ImportError as err:
    raise ImportError(
        "hawk not found. Install with `pip install raptor-hawk`. For a GPU, add [cuda12] (or [cuda13]) to raptor-hawk."
    ) from err
import hawk
from hawk import Mutable, Scalar, Terminated


@hawk.kernel
def contact(x: Scalar, v: Scalar, k: Scalar, terminated: Terminated,
            v_new: Mutable[Scalar]):
    if x < 0.0:                    # touching: a stiff spring pushes back
        a = -9.81 - k * x
    else:                          # airborne: free flight
        a = -9.81
    v_new = v + 0.01 * a           # one explicit step of 10 ms
    terminated = x < -0.5          # pressed in too deep: stop this sample


contact
<Kernel contact slots=7>

An if becomes a select#

if x < 0.0: on a per-sample value is not a Python branch that runs once; hawk reads it as a select — “take this value where the condition holds, that value where it does not” — and evaluates the condition per sample. That is what lets one kernel serve a whole batch where some samples touch and others fly. It is also what makes it differentiable: the derivative of a select is the derivative of the branch it took, and nothing from the branch it did not.

Gradient, checked away from the switch#

import pathlib, tempfile
import numpy as np
from hawk import Kernel
from hawk.diff import vjp

contact_vjp = Kernel("contact_vjp", vjp(contact, wrt=("x", "k")))
work_dir = pathlib.Path(tempfile.mkdtemp())
_ = hawk.build([contact, contact_vjp], work_dir, targets=("host",))
def run_primal(x, v, k, stopped=None):
    n = len(x)
    flags = np.zeros(n, dtype=bool) if stopped is None else stopped.copy()
    out = np.zeros(n)
    hawk.run(hawk.load(work_dir, "contact"), x=x, v=v, k=k, terminated=flags, v_new=out)
    return out, flags


def run_grad(x, v, k, stopped):
    n = len(x)
    bar_x, bar_k = np.zeros(n), np.zeros(n)
    hawk.run(hawk.load(work_dir, "contact_vjp"), x=x, k=k, terminated=stopped,
             bar_v_new=np.ones(n), bar_x=bar_x, bar_k=bar_k)
    return bar_x + 0.0, bar_k + 0.0     # + 0.0 turns a signed zero into plain 0


x = np.array([0.3, 0.1, -0.1, -0.3])    # two airborne, two touching
v = np.full(4, -1.0)
k = np.full(4, 1000.0)
none_stopped = np.zeros(4, dtype=bool)
bar_x, bar_k = run_grad(x, v, k, none_stopped)

h = 1e-6
fd_x = (run_primal(x + h, v, k)[0] - run_primal(x - h, v, k)[0]) / (2 * h)
fd_k = (run_primal(x, v, k + h)[0] - run_primal(x, v, k - h)[0]) / (2 * h)
print("d v_new / d x :", bar_x)
print("finite diff   :", np.round(fd_x, 6))
print("d v_new / d k :", bar_k)
print("finite diff   :", np.round(fd_k, 6))
d v_new / d x : [  0.   0. -10. -10.]
finite diff   : [  0.   0. -10. -10.]
d v_new / d k : [0.    0.    0.001 0.003]
finite diff   : [0.    0.    0.001 0.003]

Airborne samples (x >= 0) have zero gradient: the spring is not in play. Touching samples pick up -0.01 * k for x (the spring’s stiffness times the step) and -0.01 * x for k. Each matches a central finite difference, because none of these points sits on the switch.

What happens exactly at the switch#

Away from a switch the slope is unambiguous. At the switch there is a choice to make, and hawk makes the same one every time, so results are reproducible. The rules, each pinned by a test:

Operation

At the tie

Gradient goes to

if x < y: / where(c, a, b)

condition false at x == y

the else branch

minimum(a, b), maximum(a, b)

a == b

the first operand

abs(x)

x == 0

+1

clip(x, lo, hi)

x == lo or x == hi

x (closed interval)

clip with lo > hi

always

hi

clip with a NaN x

always

nothing (zero)

copysign(a, b)

a == 0

a by abs’s rule; b gets zero

floor, round, sign, comparisons

everywhere

exactly zero

Check the first row on our kernel: a sample sitting exactly at x = 0 takes the else branch (free flight), so its gradient is the airborne one.

tie_x = np.array([0.0])
print("gradient at x == 0:", run_grad(tie_x, v[:1], k[:1], np.zeros(1, dtype=bool))[0])
gradient at x == 0: [0.]

Stops: a stopped sample adds nothing#

contact also sets terminated = x < -0.5. A sample flagged stopped is skipped by the forward kernel, and the derived kernel is an ordinary guarded kernel too: it skips the same samples, so a stopped sample contributes exactly zero to the reverse pass — no mask array to manage and no extra work, since the work is simply not done.

Let us run five samples; the last one is pressed in past -0.5:

x5 = np.array([0.3, 0.0, -0.1, -0.2, -0.8])
v5, k5 = np.full(5, -1.0), np.full(5, 1000.0)

_, stopped = run_primal(x5, v5, k5)
print("stopped flags    :", stopped)

bar_x5, bar_k5 = run_grad(x5, v5, k5, stopped)
print("d v_new / d x    :", bar_x5)
print("d v_new / d k    :", bar_k5)
stopped flags    : [False False False False  True]
d v_new / d x    : [  0.   0. -10. -10.   0.]
d v_new / d k    : [0.    0.    0.001 0.002 0.   ]

The stopped sample (x = -0.8) shows 0 in both columns while its touching neighbours do not. In a long rollout this is the behaviour you want: a trajectory that has ended stops influencing the gradient the moment it ends.

What is not differentiated#

A parameter can change where or when a system switches or stops: a stiffer or softer surface, a different threshold, a different landing time. That effect — an event-time term — is not part of the gradient hawk returns. The gradient is the piecewise one: exact at every point away from a switch, treating the switch location as fixed.

In practice this means:

  • Inside a branch, trust the gradient as you would any other (the finite-difference check above is the way to confirm it).

  • Right at a switch, you get the convention from the table; a finite difference straddling the switch measures something different, because it also sees the jump.

  • If your loss depends on when something happens, treat that dependence as separate from what vjp gives you. hawk supplies the pieces a launching runtime needs to add it — the stop rule as a smooth guard and a taping twin of the step (Tapes and events); eagle’s events="refine" uses them to differentiate the stop time.

A switch the parameter moves: jump=#

The gradient above treats the switch as fixed. That is no use when the parameter is the switch: in if x < t: the output is a staircase in t, flat everywhere except at the step, so the gradient with respect to t is zero and t can never be fitted.

hawk finds these by itself: an if, ternary or where whose comparison depends on a differentiated input. By default it changes nothing. Declare a width on the kernel, @hawk.kernel(jump=0.05), and vjp and jvp return the gradient of the loss with the edge slightly blurred: a sample within about 0.11 of the switch (sqrt(5) * 0.05) passes on the difference between its two branches, more the closer it sits. Samples farther away cost one comparison. The forward kernel does not change.

Here a step at t = 0.3 is planted in the data and t starts at 0.55:

from hawk import Param


@hawk.kernel(jump=0.05)
def step(x: Scalar, t: Param, y: Mutable[Scalar]):
    if x < t:
        y = 1.0
    else:
        y = 0.0


step_vjp = Kernel("step_vjp", vjp(step, wrt=("t",)))

n = 400
xs = np.random.default_rng(0).uniform(0.0, 1.0, n)
target = (xs < 0.3).astype(float)          # the planted step
t = 0.55
for _ in range(80):
    y = np.asarray(step(x=xs, t=t))
    bar_t = np.asarray(step_vjp(x=xs, t=t, bar_y=2 * (y - target) / n))
    t -= 0.01 * bar_t.sum()                # plain gradient descent on the loss
print(f"fitted t = {t:.3f} (planted 0.3)")
fitted t = 0.309 (planted 0.3)

Without jump= the same loop never moves t.

Choosing the width. It is in the units of the compared values: how far from the switch a sample still pulls on it. About 0.02 of their range works. Smaller is more precise but noisier; more samples allow a smaller width.

  • jump="h" reads the width from a Param[Scalar] named h, so you can change it per call, for example a schedule that narrows as the fit settles. h gets no gradient.

  • jump="auto" sets the width to 0.02 * sqrt(12) times the standard deviation of the compared difference over the batch, recomputed on every call. It costs one tiny extra stage (the derivative is built as stages), and the width it used comes back as the cell jump_h<g> for each group of comparisons g (one value, the mean width).

  • A switch inside a for body, such as the edges of a spline layer, is differentiated like any other, with a number or a Param width. "auto" there is refused: it needs a statistic over samples, and a loop has none per iteration.

With eagle’s JAX bridge, jax.grad works through a jump= kernel, "auto" included, with a trainable Param.

A switch that decides a future. Sometimes the value a switch picks goes on to another comparison, a break or a nonlinear function: a walker that dies at the first failed test and so never reaches the later ones, or exp of a flag. Handing on the difference of the two branches is then wrong, because the other side of the switch is not the straight-line continuation of this one. hawk finds these kernels and, for them only, runs the other side. For each sample it picks one comparison that fell near its edge, at random and in proportion to how near, flips that comparison and lets the sample run on. The difference between the two outcomes, scaled by the picked comparison’s share of the total, is the sample’s gradient, and averaged over samples it is the gradient of the blurred loss. The same seed picks the same comparison in jvp and vjp, so the two agree sample by sample. The seed is the integer input jump_seed of the derived kernel (default 0); change it for an independent pick.

It costs more and is noisier than the plain jump: every engaged loop does extra work per sample, and a sample with several comparisons near an edge carries the noise of the pick. On a transport problem it needs more samples than the likelihood-ratio gradient for the same error, so use that where it applies. The jump= gradient is correct there, not the cheapest.

Limits.

  • == and != on a differentiated value are refused: a jump needs an ordered comparison.

  • With jump=, a break whose condition depends on a differentiated value is refused: that is an event (use events="refine" in eagle).

  • A rounding, sign or integer cast between the differentiated value and the comparison is refused: the compared value must move smoothly.

  • Differentiating a jump= derivative again (second order) is refused.

  • jump= is a positive number, "auto" or the name of a Param[Scalar]; a Param named auto is refused.

  • A switch that no sample crosses, or whose two branches are equal, gives a gradient that drifts rather than an error. Whether the parameter can be recovered from the data is the model’s job.

  • A branch whose two sides meet (relu written as if) picks up a small extra noise term; write max/min for continuous shapes.

  • A row or a bin picked by a rounding, sign or integer cast of a differentiated value, in a kernel with jump= and a switch, is refused: where the pick changes is a switch the jump does not see.

  • A switch that decides a future is differentiated within one launch. step_vjp of such a kernel, and a rollout over launches (steps=, time_step, eagle’s stepping), are refused; write the rollout as one kernel.

  • For those kernels a nested for, a break in the middle of a body that also holds a switch, and a value read across samples (hawk.sum read back) downstream of a switch are refused.

  • A loss applied outside the kernel to a jumped output stays first order in the width.

  • The jump term costs time: on a GPU with slow FP64 the gradient of a spline (KAN) edge with jump= runs about 1.25 times as long as without it.

A dispatch inside a loop#

Several formulas per sample, chosen by data, inside a for over edges: this is the shape of a KAN-style layer, one spline, polynomial or power per edge. vjp reverses the loop as a loop (the gradient is committed once per iteration, so nothing is kept per edge), and the spline read in each edge is the runtime-indexed lookup from Lookups, scatters and sums:

import hawk.math as m
from hawk import Vector

n_in, W = 4, 16


@hawk.kernel
def layer(x: Vector[n_in], theta: Vector[n_in * W], kinds: Vector[n_in], y: Mutable[Scalar]):
    total = 0.0
    for e in range(n_in):
        u = x[e] * 15.0
        f = m.floor(u)
        i = m.index(f, 15)
        w = u - f
        spline = theta[e * W + i] * (1.0 - w) + theta[e * W + i + 1] * w
        cases = [spline, x[e] * x[e], m.sin(x[e])]
        total = total + m.dispatch(m.int32(kinds[e]), cases, policy="switch")
    y = total


layer_vjp = Kernel("layer_vjp", vjp(layer, wrt=("theta",)))

rng = np.random.default_rng(1)
ns = 3
lx = rng.uniform(0.0, 1.0, (n_in, ns))
ltheta = rng.normal(size=(n_in * W, ns))
kinds = np.array([[0, 1, 0], [1, 0, 2], [0, 0, 0], [2, 0, 0]], dtype=float)   # a kind per edge and sample
lbar = np.asarray(layer_vjp(x=lx, theta=ltheta, kinds=kinds, bar_y=np.ones(ns)))


def layer_at(th):
    return np.asarray(layer(x=lx, theta=th, kinds=kinds))


lfd = np.zeros_like(ltheta)
for k in range(n_in * W):
    up, down = ltheta.copy(), ltheta.copy()
    up[k] += 1e-6
    down[k] -= 1e-6
    lfd[k] = (layer_at(up) - layer_at(down)) / 2e-6
print("largest gap to finite differences:", np.abs(lbar - lfd).max())
largest gap to finite differences: 8.344680502148094e-11

The gradient lands only in the coefficients each edge’s kind used, and agrees with finite differences. On a GPU this layer builds in seconds at 8 to 32 inputs with no stack or spill, where the unrolled form held every edge live at once.

Limits.

  • A kernel with jump= and a dispatch inside the loop body is refused. Way out: drop jump= there, or write the switch outside the loop. The jump plan’s comparisons are not applied under a branch yet.

  • A runtime-indexed read (theta[i]) inside a dispatch branch of a loop differentiates: the gradient is one scatter outside the dispatch, at the row the gathering branch computes, and a lane whose branch did not gather adds a zero at row 0. A dispatch nested in a dispatch branch with such a read in the inner one is refused; read the plane before the outer dispatch.

  • A promoted parameter (param_planes) whose gradient is accumulated in the loop is refused. Way out: pass it as a plain Param, or read the table outside the loop. The per-sample accumulate that feeds a sum over samples is not built.

  • Second order through the loop (jvp(vjp(...)) of the rolled form) is refused, as for any loop that commits a gradient per iteration. Way out: difference the gradient.

A loop that leaves early#

A for with a break in the middle of its body differentiates too: the iteration that exits is reversed through a select on the exit condition, so the gradient matches a difference of the kernel even when different samples leave on different iterations.

@hawk.kernel
def decay(x: Scalar, g: Scalar, lim: Scalar, y: Mutable[Scalar]):
    s = x
    t = x
    for _k in range(20):
        s = s * 1.1 + g * t
        if s > lim:
            break                      # in the middle: some work is done before it
        t = m.tanh(t) + 0.1
    y = s + t


decay_vjp = Kernel("decay_vjp", vjp(decay, wrt=("x", "g")))

dx = np.array([0.1, 0.5, 1.0, 2.0])
dg, dlim = np.full(4, 0.3), np.full(4, 3.0)
got = decay_vjp(x=dx, g=dg, lim=dlim, bar_y=np.ones(4))
bar_x, bar_g = np.asarray(got["bar_x"]), np.asarray(got["bar_g"])


def decay_at(x, g, lim):
    return np.asarray(decay(x=x, g=g, lim=lim))


h = 1e-6
print("left early:", decay_at(dx, dg, dlim) != decay_at(dx, dg, np.full(4, 1e9)))
print("bar_x:", bar_x)
print("fd   :", (decay_at(dx + h, dg, dlim) - decay_at(dx - h, dg, dlim)) / (2 * h))
left early: [ True  True  True  True]
bar_x: [7.39165505 3.92314155 2.42829109 1.63184607]
fd   : [7.39165505 3.92314155 2.42829109 1.63184607]

All four samples crossed lim and left early, on different iterations, and their gradients still agree. Reverse over reverse through such a loop refuses by name; for a second derivative use jvp(vjp(k)).

What just happened#

  • A Python if on a per-sample value becomes a select; vjp sends the gradient to the branch taken and zero to the other.

  • At a tie, fixed rules decide (table above), the same on every run.

  • Stopped samples are skipped by the reverse kernel just as by the forward one, so they add exactly zero at no extra cost.

  • The piecewise gradient is exact away from a switch; the movement of the switch itself is not included, unless you ask for jump= (above).

Try this#

Change x = np.array([0.3, 0.1, -0.1, -0.3]) so one sample sits at -1e-9 and compare the finite difference with the vjp: the finite difference with h = 1e-6 crosses the switch and disagrees, as the last section describes.

Next#

Choosing a dispatch policy — branch between several formulas per sample, and pick how that is compiled.