Lookups, scatters and sums#

Read a table, scatter into shared bins, and let each sample total its own contributions — three plane kinds every earlier tutorial skipped.

Time: ~8 min · Runs on: CPU · You need: hawk, NumPy and matplotlib; read first: Stop when you’re done

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

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

Table: a per-sample lookup#

Table[...] is a per-sample lookup, read with .at(index) through an Index plane. Every sample here reads a DIFFERENT table entry, by its own index:

import numpy as np

import hawk
from hawk import Index, Mutable, Scalar, Table


@hawk.kernel
def gather(table: Table[Scalar], where: Index, y: Mutable[Scalar]):
    y = table.at(where)


gather
<Kernel gather slots=3>

hawk.artifact.build + hawk.load/hawk.run build and run it on the host:

import pathlib, tempfile

import hawk.artifact

work_dir = pathlib.Path(tempfile.mkdtemp())
n = 8
table_vals = np.arange(n, dtype=float) * 3.0
where = ((np.arange(n) * 7 + 3) % n).astype(np.int32)   # Index plane: int32
y = np.zeros(n)
hawk.artifact.build(gather, work_dir, targets=("host",))
hawk.run(hawk.load(work_dir, "gather"), table=table_vals, where=where, y=y)
print("gather:", y)
gather: [ 9.  6.  3.  0. 21. 18. 15. 12.]

where is int32: an Index plane is a 4-byte column. An int64 array that fits is converted for you, one with a value past int32 is refused (Index[int64] declares the 8-byte plane).

A by-key store: a cross-sample scatter#

Writing hawk.scatter(acc)[lane] += value on a Mutable output adds each sample’s value into the bin lane names — many samples can land in the same bin, like a histogram:

rng = np.random.default_rng(0)


@hawk.kernel
def histogram(lane: Index, acc: Mutable[Scalar]):
    hawk.scatter(acc)[lane] += 1.0


histogram
<Kernel histogram slots=3>

Build and run it the same way:

n_samples, n_bins = 2000, 10
lane = rng.integers(0, n_bins, size=n_samples).astype(np.int32)
acc = np.zeros(n_bins)
hawk.artifact.build(histogram, work_dir, targets=("host",))
hawk.run(hawk.load(work_dir, "histogram"), lane=lane, acc=acc)
expect = np.bincount(lane, minlength=n_bins).astype(float)
print("the by-key store matches np.bincount:", np.allclose(acc, expect))
the by-key store matches np.bincount: True

Hide code cell source

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5, 3.4), constrained_layout=True)
bins = np.arange(n_bins)
ax.bar(bins - 0.18, acc, width=0.36, color="#2a78d6", label="hawk by-key store")
ax.bar(bins + 0.18, expect, width=0.36, color="#eb6834", label="np.bincount")
ax.set_xlabel("bin"); ax.set_ylabel("count"); ax.legend(frameon=False, ncol=2, loc="lower center", bbox_to_anchor=(0.5, 1.0))
ax.grid(alpha=0.3, axis="y")
show()
Chart

A sum over all samples#

hawk.sum(value) adds a value over every sample. Store it to a Mutable and bind that name to a one-element array: hawk.run sums the kernel’s partial results for you and writes the total there. hawk.max, hawk.min and hawk.mean work the same way:

from hawk import Vector
from hawk.math import dot


@hawk.kernel
def energy(v: Vector[3], total: Mutable[Scalar]):
    total = hawk.sum(dot(v, v))


energy
<Kernel energy slots=3>

Build and run it:

n = 8
v = rng.normal(size=(3, n))
total = np.zeros(1)                      # the cell: one value
hawk.artifact.build(energy, work_dir, targets=("host",))
hawk.run(hawk.load(work_dir, "energy"), v=v, total=total)
print("energy over all samples:", total[0], "expect", (v * v).sum())
energy over all samples: 30.633777685161363 expect 30.633777685161366

A value carried across several launches#

The same bound best array, the same kernel, called once per step: each launch reads the value the previous launch committed, simply by reading best before writing it — the same convention Stop when you’re done used to step a trajectory:

from hawk import Terminated
from hawk.math import maximum


@hawk.kernel
def running_max(value: Scalar, terminated: Terminated, best: Mutable[Scalar]):
    best = maximum(best, value)


running_max
<Kernel running_max slots=3>

Build it once, then call it five times, reading best back each time:

hawk.artifact.build(running_max, work_dir, targets=("host",))
running_max_k = hawk.load(work_dir, "running_max")
best = np.zeros(n)
terminated = np.zeros(n, dtype=bool)
for value in (3.0, 7.0, 2.0, 9.0, 4.0):
    hawk.run(running_max_k, value=np.full(n, value), terminated=terminated, best=best)
print("running max after 5 launches (expect 9.0 everywhere):", best)
running max after 5 launches (expect 9.0 everywhere): [9. 9. 9. 9. 9. 9. 9. 9.]

A table you can differentiate#

A lookup at a computed position is the heart of a spline. hawk.math.index(x, n) turns a float into an index into n slots (cut to a whole number, then held inside 0 .. n-1), and theta[i] reads that slot. Its gradient is one add into the slot that was read, not a column of selects across the whole width, so a wide table stays cheap to differentiate. Here is a 16-point piecewise-linear curve with its own row of coefficients per sample:

import hawk.math as m
from hawk import Kernel, Vector
from hawk.diff import vjp


@hawk.kernel
def curve(x: Scalar, theta: Vector[16], y: Mutable[Scalar]):
    u = x * 15.0
    f = m.floor(u)
    i = m.index(f, 15)                 # the slot to the left of x, a runtime index
    w = u - f
    y = theta[i] * (1.0 - w) + theta[i + 1] * w


curve_vjp = Kernel("curve_vjp", vjp(curve, wrt=("theta",)))
curve_dir = pathlib.Path(tempfile.mkdtemp())
hawk.build([curve, curve_vjp], curve_dir, targets=("host",))
curve_f, curve_b = hawk.load(curve_dir, "curve"), hawk.load(curve_dir, "curve_vjp")

xs = rng.uniform(0.0, 1.0, 5)
theta = rng.normal(size=(16, 5))
bar_theta = np.zeros((16, 5))
hawk.run(curve_b, x=xs, bar_y=np.ones(5), bar_theta=bar_theta)


def curve_at(th):
    y = np.zeros(5)
    hawk.run(curve_f, x=xs, theta=th, y=y)
    return y


fd = np.zeros_like(theta)
for k in range(16):
    up, down = theta.copy(), theta.copy()
    up[k] += 1e-6
    down[k] -= 1e-6
    fd[k] = (curve_at(up) - curve_at(down)) / 2e-6
print("slots with a gradient, per sample:", (bar_theta != 0).sum(axis=0))
print("largest gap to finite differences:", np.abs(bar_theta - fd).max())
slots with a gradient, per sample: [2 2 2 2 2]
largest gap to finite differences: 5.324163332431908e-11

Each sample’s gradient lives in the two slots it read, and it matches finite differences. The same shape scales: a local spline layer of 8 to 32 inputs differentiates, also through a for over its edges, with no stack or spill, and builds in seconds (Gradients through branches and stops shows the loop).

Limits.

  • index clamps, so a position that is wrong reads the end slot instead of failing; while you write the kernel, compare it with the unclamped float to see the mistake. An index you build yourself and that falls outside the width is not checked on a read or a write: hawk leaves that bound to the kernel’s author.

A wrong binding, refused by name#

hawk.run checks every bound argument against the kernel’s own declaration before taking its address — the SAME gather kernel from above, with where bound as float32 instead of an integer:

from hawk.ir import HawkError

gather_host = hawk.load(work_dir, "gather")
try:
    hawk.run(gather_host, table=table_vals, where=where.astype(np.float32), y=y)
except HawkError as exc:
    print("refused:", exc)

Reading a keyed sum back#

hawk.sum(x, over=...) and hawk.mean(x, over=...) can be read back in the same kernel, for example x / hawk.sum(x, over="col") or x - hawk.mean(x, over="col"); a vector payload works per component. The kernel then runs in stages, like one that reads hawk.sum(x): the first stage adds into a plane the runtime owns and zeroes for every run. policy='auto' and 'compensated' work. 'ordered', a keyed max or min, group= and a stepping kernel are refused by name. See Across lanes for what the policies mean.

What just happened#

  • Table[...].at(index) is a per-sample lookup; hawk.scatter(acc)[lane] += value scatters across samples into shared bins; hawk.sum(value) totals a value over every sample — three different ways data crosses between samples, none of them a hidden Python loop.

  • Index planes (where, lane) are int32 columns (an int64 array that fits is converted); a wrong dtype is refused by name rather than silently misread.

  • Reading a Mutable before writing it carries a value from one launch to the next — the same mechanism Stop when you’re done used to step a trajectory, here running a max across five launches.

Try this#

Change the sum to hawk.max(dot(v, v)) and check that the result is the largest per-sample energy.

Next#

Describe your system once — declare a reusable kernel shape once, so a whole family of models shares one vocabulary. Deeper: One sample, one lane (reading neighbours by position), Across lanes (masks, named axes, vector cells, the reduction policies), and the API reference for every plane kind and sink policy.