A drag kernel over a large ensemble

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.

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-eagle{extra}", 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 eagle, hawk  # noqa: F401
except ImportError as err:
    raise ImportError(
        "eagle, hawk not found. Install with `pip install raptor-eagle raptor-hawk`. For a GPU, add [cuda12] (or [cuda13]) to raptor-eagle and raptor-hawk."
    ) from err
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 (numpy vs cupy) changed.

  • A kernel with two sinks (a named Mutable and a returned slot) returns both from plan.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_normal the 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.