Steps per launch#

Fuse several steps into one launch to cut how often the host and the device talk to each other — pick the number yourself, or let eagle pick it as the batch runs.

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

You will build the figure below: how many launches the automatic kernel used, grouped by how many steps each one ran.

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, xp_for
DEVICE = "gpu" if gpu_available() else "cpu"
xp = xp_for(DEVICE)
print("running on", DEVICE)
running on gpu

The code: the same step, three ways#

@hawk.kernel takes a steps= argument: 1 (the default you have been using so far: one launch advances every sample by exactly one step), a fixed K (one launch advances every sample by K steps, in registers, no intermediate host read), or "auto" (eagle picks the number itself, launch by launch, from how many samples just finished).

import eagle
import hawk
from hawk import Mutable, Param, Scalar, Terminated

# The step body is repeated in each kernel 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 oscillator_k1(omega: Scalar, t_end: Param, dt: Param, terminated: Terminated,
                   x: Mutable[Scalar], v: Mutable[Scalar], t: Mutable[Scalar]):
    x0, v0 = x, v
    x = x0 + dt * v0
    v = v0 - dt * omega * omega * x0
    t += dt
    terminated = t >= t_end


@hawk.kernel(steps=16)
def oscillator_k16(omega: Scalar, t_end: Param, dt: Param, terminated: Terminated,
                    x: Mutable[Scalar], v: Mutable[Scalar], t: Mutable[Scalar]):
    x0, v0 = x, v
    x = x0 + dt * v0
    v = v0 - dt * omega * omega * x0
    t += dt
    terminated = t >= t_end


@hawk.kernel(steps="auto")
def oscillator_auto(omega: Scalar, t_end: Param, dt: Param, terminated: Terminated,
                     x: Mutable[Scalar], v: Mutable[Scalar], t: Mutable[Scalar]):
    x0, v0 = x, v
    x = x0 + dt * v0
    v = v0 - dt * omega * omega * x0
    t += dt
    terminated = t >= t_end
n = 1_000_000 if DEVICE == "gpu" else 100_000
omega = xp.linspace(1.0, 3.0, n)
reports = {}
for name, kernel in [("k=1", oscillator_k1), ("k=16", oscillator_k16),
                     ("auto", oscillator_auto)]:
    reports[name] = eagle.run_until_done(
        eagle.deploy(kernel), max_steps=10_000,
        x=xp.ones(n), v=xp.zeros(n), t=xp.zeros(n),
        omega=omega, t_end=1.0, dt=1e-3)
    r = reports[name]
    print(f"{name:>5}: {r.launches:4d} launches, {r.steps:5d} steps, "
          f"exact_steps={r.exact_steps}")
  k=1: 1000 launches,  1000 steps, exact_steps=True
 k=16:   63 launches,  1008 steps, exact_steps=False
 auto:    1 launches,  1000 steps, exact_steps=True
import matplotlib.pyplot as plt
from themed_figure import show

by_k = reports["auto"].launches_by_k
fig, ax = plt.subplots(figsize=(5, 3.2))
ks = sorted(by_k)
ax.bar([str(k) for k in ks], [by_k[k] for k in ks], color="C2")
ax.set_xlabel("steps in that launch (k)")
ax.set_ylabel("number of launches")
ax.set_title("steps=\"auto\": launches by k -- on the machine that built this page")
fig.tight_layout()
show()
Chart: steps="auto": launches by k -- on the machine that built this page

What just happened#

  • k=1 took exactly 1000 launches for 1000 steps (exact_steps=True): one launch, one step, nothing to round.

  • k=16 took one launch per 16 steps; the last launch is cut short so no sample overshoots max_steps (exact_steps=False — the reported step count can include a partial launch).

  • "auto" grew k as the batch ran: few launches total, each covering many steps once the policy trusted it would help. The bar chart above is that history.

Small batches: the automatic policy#

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

On a small batch there is not enough work to amortize a launch per step, so a fixed K pays for launches it does not need. The automatic policy takes the whole run in a single launch there, and that is what eagle.simulate does (it also picks between a fused and a persistent launch by batch size, which you will meet at larger N). Finished samples picks this back up for where compaction changes that story.

On the CPU: eagle picks the tile, not you#

The host loop does not guess a step count the way the GPU policy does. Instead it asks the compiled kernel whether its fused side is a tiled loop: hawk interchanges the per-sample loop so a whole tile of samples advances together, their state held in cache, each lane masked once its own sample is done. When it is tiled, every host launch simply asks for the artifact’s largest step count (cut to the cap on the last one) — no sweep, no probe. (A kernel whose fused side is not tiled is different: the host then measures, as described under host_policy.) The tile itself comes from the kernel’s own per-sample state size against the host’s cache size, below.

import eagle.exec as eexec

part = eexec.Partition(0, n, n)
bytes_per_sample = 3 * 8  # oscillator's state: x, v, t -- three float64 per sample
tiles = eexec.HostTeam.tile_count(part, bytes_per_sample)
print(f"{tiles} tiles for {n:,} samples -- about {-(-n // tiles):,} samples per tile")
245 tiles for 1,000,000 samples -- about 4,082 samples per tile

A kernel with a bigger per-sample state (more planes, wider vectors) gets a smaller tile; eagle works this out once from the compiled kernel, not from n. That is also why Finished samples’s active-set map has little left to do on the CPU: a tile already skips a finished lane instead of computing it, for the samples still in cache together.

Try this#

Change dt to 1e-4 (ten times more steps) and compare auto’s launch count against k=16’s — auto should still win on launch count.

Next#

  • Finished samples — the other side of a thinning batch: skip finished samples’ lanes, not just their steps.

  • deeper: Workloads (“The ways of running it”, the K-fused-steps arms).