A drag kernel over a large ensemble#
One task: compile a small force kernel once, then evaluate it over a large ensemble of samples on the host and, if you have one, on the GPU, and check the two match. This is the shape a batch propagator calls a force model in — many independent samples, one kernel, one launch.
Time: ~5 min · Runs on: CPU; with a GPU it also compares the two · You need: eagle, hawk, NumPy and CuPy (GPU only); read first: Your first kernel
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.
from hawk import Mutable, Param, Scalar, Vector
from hawk.ext import Kind, Output
from hawk.math import norm
# two SINKS: a named Mutable `speed`, and the returned slot `acc`
ACCEL = Kind("drag", output=Output.returned(Vector[3], slot="acc"))
@ACCEL
def drag(velocity: Vector[3], k: Param, speed: Mutable[Scalar]):
speed = norm(velocity)
return (-k * speed) * velocity
drag
<Kernel drag slots=4>
One plan, both targets#
eagle.deploy(drag) compiles drag for host and device through hawk’s
build cache and returns a plan — an object that runs this kernel on
whatever array you hand it, a cupy array on the GPU or a numpy array on
the CPU, with no manifest, registry or plugin object to assemble by
hand. plan.run returns a dict keyed by plane name when a kernel
declares several sinks: {"acc": ..., "speed": ...} here — acc the
returned slot, speed the named diagnostic.
import numpy as np
try:
import cupy as cp
if cp.cuda.runtime.getDeviceCount() == 0:
cp = None
except Exception: # no CuPy, or no GPU: the host run below still works
cp = None
import eagle
plan = eagle.deploy(drag)
rng = np.random.default_rng(1)
n = 50_000
velocity = rng.normal(size=(3, n)) # (3, n_samples), random velocities
out_host = plan.run(velocity=velocity, k=0.05) # numpy in: CPU
acc_host, speed_host = out_host["acc"], out_host["speed"]
print(f"{n} samples, host. speed[:3] = {speed_host[:3]}")
50000 samples, host. speed[:3] = [1.71802099 1.91535842 1.02095317]
if cp is None:
print("No GPU found: skipping the GPU run and the comparison.")
else:
out_gpu = plan.run(velocity=cp.asarray(velocity), k=0.05) # same plan, cupy in: GPU
np.testing.assert_allclose(speed_host, cp.asnumpy(out_gpu["speed"]))
np.testing.assert_allclose(acc_host, cp.asnumpy(out_gpu["acc"]))
print("host and GPU results match (relative 1e-7) across all", n, "samples")
host and GPU results match (relative 1e-7) across all 50000 samples
Draw the inputs inside the kernel#
Above, NumPy drew the velocities on the host and the plan copied them to the
GPU. A kernel can draw them itself. random_normal(seed, counter) is a
counter-based generator: the same (seed, counter, sample) always gives the
same number, on the host and on the GPU, and each sample has its own stream.
So the input array is never built or moved. The kernel below is the drag
kernel with its velocity drawn from the seed: three draws, one per component.
from hawk.math import random_normal, vec
from hawk.trace import decl
Seed = decl.Plane("uniform", hawk.Index) # one integer seed for the whole launch
MC_DRAG = Kind("drag_mc", output=Output.returned(Vector[3], slot="acc"))
@MC_DRAG
def drag_mc(seed: Seed, k: Param, speed: Mutable[Scalar]):
velocity = vec(random_normal(seed, 0), random_normal(seed, 1), random_normal(seed, 2))
speed = norm(velocity)
return (-k * speed) * velocity
mc_plan = eagle.deploy(drag_mc)
def run_mc(seed, xp=np):
# the output arrays set the ensemble size; there is no velocity input
return mc_plan.run(seed=seed, k=0.05, speed=xp.empty(n), acc=xp.empty((3, n)))
first = run_mc(7)
again = run_mc(7)
other = run_mc(8)
print("seed 7 twice identical:", np.array_equal(first["speed"], again["speed"]))
print("seed 8 differs from seed 7:", not np.array_equal(first["speed"], other["speed"]))
print(f"mean speed {first['speed'].mean():.3f} (a 3-D standard normal has about 1.60)")
seed 7 twice identical: True
seed 8 differs from seed 7: True
mean speed 1.598 (a 3-D standard normal has about 1.60)
if cp is None:
print("No GPU found: skipping the GPU run and the comparison.")
else:
gpu7 = run_mc(7, cp)
np.testing.assert_allclose(first["speed"], cp.asnumpy(gpu7["speed"]))
np.testing.assert_allclose(first["acc"], cp.asnumpy(gpu7["acc"]))
print("seed 7 on the GPU matches the host across all", n, "samples")
seed 7 on the GPU matches the host across all 50000 samples
A run is fixed by its seed: re-running a seed reproduces it on either target, and a new seed gives a new ensemble. To draw more than one batch from a seed, give each batch its own counter offset in the kernel.
What just happened#
One
eagle.deploy(drag)plan ran the SAME compiled kernel over 50,000 samples on the host and, with a GPU, on the GPU, from the SAME Python call — only the array type (numpyvscupy) changed.A kernel with two sinks (a named
Mutableand a returned slot) returns both fromplan.run, as a dict keyed by plane name —{"acc": ..., "speed": ...}.The GPU and host results match to
assert_allclose’s default relative tolerance of 1e-7: the same compiled arithmetic ran both times.With
random_normalthe kernel draws its own inputs from a seed: nothing is built or copied for the input, the same seed gives the same ensemble on the host and the GPU, and a new seed gives a new one.