Finished samples#

Compaction can pay for a large batch that thins out and costs more than it saves for a small or dense one. Where that line falls depends on the device, so the tables below name the card they come from.

Time: ~5 min · Runs on: CPU (GPU recommended: this notebook picks it up automatically) · You need: eagle, hawk, NumPy and matplotlib; read first: Python quickstart

You will build the figure below: how many samples are still running, step by step, for a batch that spreads its stopping time out versus one where every sample runs the same number of steps.

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}"])
    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) / "eagle"
    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/eagle/{ref}/{rel}", root / rel)
    (root / "docs/content/userguide/tutorials").mkdir(parents=True, exist_ok=True)
    os.chdir(root / "docs/content/userguide/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 eagle, hawk, matplotlib  # noqa: F401
except ImportError as err:
    raise ImportError(
        "eagle, hawk, matplotlib not found. Install with `pip install matplotlib raptor-eagle raptor-hawk`. For a GPU, add [cuda12] (or [cuda13]) to raptor-eagle and raptor-hawk."
    ) from err

Hide code cell source

import sys, pathlib
sys.path.insert(0, str(pathlib.Path.cwd().parent.parent / "_shared"))
from nb_helpers import gpu_available, to_numpy, xp_for
import numpy as np

DEVICE = "gpu" if gpu_available() else "cpu"
xp = xp_for(DEVICE)
print("running on", DEVICE)
running on gpu

The code: a step that stops, two ways#

Same physics (a damped oscillator, one semi-implicit Euler step), each sample stopping after its own nstop steps. step_plain is an ordinary kernel: a sample that already stopped skips its own body, but its thread (or SIMD lane) stays occupied until the whole launch is done. step_compacting is the same body under hawk.ext.Guard(active_set=True) — eagle maintains a live-sample index map for it, so a launch can cover only the samples still running.

import hawk
from hawk import Mutable, Param, Scalar, Terminated
from hawk.ext import Guard, Kind

# The step body is repeated in both kernels below, not factored into a
# helper function: a Mutable/Terminated parameter is a plain variable of
# THIS traced function, so reassigning it inside a called-out helper would
# rebind the helper's own local, not the kernel's.


@hawk.kernel(steps=1)
def step_plain(omega: Scalar, zeta: Param, nstop: Scalar, dt: Param,
               terminated: Terminated, x: Mutable[Scalar], v: Mutable[Scalar],
               k: Mutable[Scalar]):
    x0, v0 = x, v
    a = -(omega * omega) * x0 - 2.0 * zeta * omega * v0
    v_new = v0 + dt * a
    v = v_new
    x = x0 + dt * v_new
    k1 = k + 1.0
    k = k1
    terminated = k1 >= nstop


ACTIVE_SET = Kind("compaction_demo", guard=Guard(active_set=True))


@hawk.kernel(steps=1, kind=ACTIVE_SET)
def step_compacting(omega: Scalar, zeta: Param, nstop: Scalar, dt: Param,
                     terminated: Terminated, x: Mutable[Scalar], v: Mutable[Scalar],
                     k: Mutable[Scalar]):
    x0, v0 = x, v
    a = -(omega * omega) * x0 - 2.0 * zeta * omega * v0
    v_new = v0 + dt * a
    v = v_new
    x = x0 + dt * v_new
    k1 = k + 1.0
    k = k1
    terminated = k1 >= nstop

Two batches: one that thins, one that doesn’t#

nstop spread log-uniformly over two decades (10 to 400 steps) means most samples stop early and a few run long — a thinning batch. nstop fixed at 400 for everyone means nobody stops early — a dense batch, the one compaction has nothing to recover from.

import eagle

n = 2000
rng = np.random.default_rng(0)
nstop_spread = xp.asarray(np.exp(rng.uniform(np.log(10.0), np.log(400.0), n)))
nstop_uniform = xp.full(n, 400.0)
plan = eagle.deploy(step_plain)


def alive_curve(nstop, steps):
    # Step `step_plain` by hand, once per launch, and count who's still
    # running. (A diagnostic loop, not how you'd run this for real --
    # `eagle.until_done` below picks its own pacing.)
    x, v, k = xp.zeros(n), xp.zeros(n), xp.zeros(n)
    terminated = xp.zeros(n, dtype=xp.bool_)
    finished_count = xp.zeros(1, dtype=xp.int32)
    run = plan.bind(omega=xp.full(n, 3.0), zeta=0.1, nstop=nstop, dt=0.05,
                     terminated=terminated, x=x, v=v, k=k,
                     finished_count=finished_count)
    alive = []
    for _ in range(steps):
        run.launch()
        alive.append(n - int(to_numpy(terminated).sum()))
    return alive


alive_spread = alive_curve(nstop_spread, 420)
alive_uniform = alive_curve(nstop_uniform, 420)
import matplotlib.pyplot as plt
from themed_figure import show

fig, ax = plt.subplots(figsize=(5.5, 3.2))
ax.plot(alive_spread, label="spread (thins out)")
ax.plot(alive_uniform, label="uniform (stays dense)")
ax.set_xlabel("step")
ax.set_ylabel("samples still running")
ax.set_title(f"{n:,} samples -- on the machine that built this page")
ax.legend()
fig.tight_layout()
show()
Chart: 2,000 samples -- on the machine that built this page

What just happened#

  • The spread batch thins fast: within a couple hundred steps, most of its 2,000 lanes are already done, but step_plain’s launches still cover every sample until the very last one finishes.

  • The uniform batch never thins: every sample is still running right up to the end, so there is nothing for compaction to skip.

  • step_compacting (built with Guard(active_set=True)) is the same body, built so a launch can cover only the live samples once eagle’s active-set map says who they are.

When compaction pays, and when it costs#

The performance pages time the arms of the ensemble card and the feature card on every device.

Compaction pays on a batch that thins and is large enough to have work to skip. On a batch that never thins, or a small one, the active-set bookkeeping costs more than it saves and the plain kernel is the better fit. The performance pages time the spread and the uniform batch on every device, so measure on yours. The reorder is requested with eagle.until_done(..., reorder=theta).

# Functional check, not a timing claim -- the numbers above are the card's.
reorder_planes = dict(omega=xp.full(n, 3.0), zeta=0.1, nstop=nstop_spread, dt=0.05,
                       x=xp.zeros(n), v=xp.zeros(n), k=xp.zeros(n))
compacting = eagle.until_done(eagle.deploy(step_compacting), max_steps=500, every=16,
                              **reorder_planes)
report = compacting.run()
print("compacting:", report.done, "compactions:", report.compactions)
compacting: True compactions: 25

On the CPU, you usually leave it off#

On the CPU, eagle’s automatic kernel (steps="auto", the plain @hawk.kernel decorator) now runs TILE by tile: a whole block of samples advances together, with its state kept in cache, and a finished sample’s lane inside that tile is simply masked rather than dropped. See Steps per launch for the tile rule. That tiling already does most of what the active-set map buys on the GPU, so the plain kernel — step_plain here, or the default @hawk.kernel with no Guard — is the one to reach for on the CPU; build the compacting kind when your data lives on cupy arrays.

Try this#

Change nstop_spread’s upper end from 400 to 4000 and re-run: the gap between the two curves above opens up earlier.

Next#

  • Steps per launch — the other knob this page didn’t touch: how many steps one launch runs.

  • deeper: Reading the numbers (the compaction and reorder discussion) for the full table, every N and both configurations.