Host or device?#

Debug one sample on the CPU, then run a whole batch on the GPU – the same call, the same compiled kernel, no flag of your own to flip.

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

You will build the figure below: the host run plotted against whichever run the switch below picked, sample by sample.

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: one call, the data decides#

eagle.deploy() builds an AutoPlan: every call to .run()/.select() looks at the planes you hand it, never the sample count, to pick where the kernel runs. A cupy-resident plane sends the whole call through eagle.exec.DeviceKernel; a Python number, a 0-d array, or a numpy array runs it through eagle.exec.HostTeam instead – the same compiled kernel either way.

import eagle
import eagle.exec as eexec
import hawk
from hawk import Mutable, Param, Scalar


@hawk.kernel
def scale(x: Scalar, a: Param, b: Param, y: Mutable[Scalar]):
    y = a * x + b


def structure_of(plan, planes):
    s = plan.select(planes).structure
    return "HostTeam (CPU)" if s is eexec.HostTeam else "DeviceKernel (GPU)"


plan = eagle.deploy(scale)

# One sample, debugged with plain floats: no GPU, no batch, no cupy import.
one = plan.run(x=0.5, a=2.0, b=-1.0)
print(f"one sample: {type(one).__name__} {float(one)} (shape {one.shape}) "
      f"-- ran on {structure_of(plan, dict(x=0.5, a=2.0, b=-1.0))}")
one sample: float64 0.0 (shape ()) -- ran on HostTeam (CPU)

A batch: still one call#

Nothing above changes for a batch of thousands: x becomes an array instead of a float, and the same plan.run sends it wherever that array already lives. Below, y_host is forced through numpy (always the CPU); y_xp goes through whichever array type the switch above picked – numpy on this run if no GPU is visible, cupy if one is.

n = 2000
rng = np.random.default_rng(7)
x_np = rng.uniform(-5.0, 5.0, n)

y_host = to_numpy(plan.run(x=x_np, a=1.7, b=-0.4))
y_xp = plan.run(x=xp.asarray(x_np), a=1.7, b=-0.4)

print("host run:", structure_of(plan, dict(x=x_np, a=1.7, b=-0.4)))
print("xp run:  ", structure_of(plan, dict(x=xp.asarray(x_np), a=1.7, b=-0.4)))
print("agree:", bool(np.allclose(y_host, to_numpy(y_xp))))
host run: HostTeam (CPU)
xp run:   DeviceKernel (GPU)
agree: True
import matplotlib.pyplot as plt
from themed_figure import show

y_xp_home = to_numpy(y_xp)
fig, ax = plt.subplots(figsize=(4.2, 4.2))
ax.scatter(y_host, y_xp_home, s=10, c="C0", alpha=0.6)
lo = float(min(y_host.min(), y_xp_home.min()))
hi = float(max(y_host.max(), y_xp_home.max()))
ax.plot([lo, hi], [lo, hi], "--", color="gray", lw=1)
ax.set_xlabel("host run (numpy, forced)")
label = "device" if DEVICE == "gpu" else "host"
array_lib = "cupy" if DEVICE == "gpu" else "numpy"
ax.set_ylabel(f"{label} run ({array_lib})")
ax.set_title(f"{n:,} samples -- on the machine that built this page")
fig.tight_layout()
show()
Chart: 2,000 samples -- on the machine that built this page

What just happened#

  • eagle.deploy returned one AutoPlan for scale; every .run() call looked only at the planes it was given – a float, or which array type x arrived as – to pick eagle.exec.HostTeam or eagle.exec.DeviceKernel.

  • A Python float is a batch of one, always on the host: the same call that drives a two-thousand-sample batch above also debugged a single value, with no separate code path and no GPU required.

  • y_host and y_xp sit on the diagonal above: the forced-host run and whichever run the switch picked agree on every sample (to the last bit, or within the one ULP a fused multiply-add on the device may contribute).

When the CPU is the right side#

Picking a side is a measurement, not a rule. The CPU route is what a machine with no GPU runs, and a small batch may have too little work to amortize a launch; on the performance cards the GPU arms lead at the largest batch sizes measured. The same mechanism above is what lets a kernel move to either side with no code change once you know which one suits your batch; deeper: Performance (the results pages, one tab per device).

Try this#

Widen the batch to 2,000,000 samples and compare structure_of’s answer on a machine with a GPU visible against one without – the call is unchanged either way.

Limits#

  • The CPU host runs float32 plugins, but not yet the ones with integer mutables, a `Terminated` mask or derivative kernels (our scope): use float64 for those on the host, or the GPU.

Next#

  • Use eagle with other frameworks – the same “host or device” idea, generalized to every array framework eagle recognizes (numpy, cupy, torch, Warp, JAX).

  • deeper: Performance – the full measurement behind the CPU and GPU routes.