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.
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
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.
indexclamps, 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] += valuescatters 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.Indexplanes (where,lane) areint32columns (anint64array that fits is converted); a wrong dtype is refused by name rather than silently misread.Reading a
Mutablebefore 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.