Python quickstart#

Write one sample’s step, hand it to eagle.simulate, and it runs every sample until it’s done — on the CPU or the GPU, no loop of your own.

Time: < 1 min · Runs on: CPU (GPU: this notebook picks it up automatically) · You need: eagle, hawk and matplotlib

You will build the figure at the bottom of this page: where each oscillator in the batch ends up, as a function of its own frequency.

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").mkdir(parents=True, exist_ok=True)
    os.chdir(root / "docs/content/userguide")
    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

The code#

Write the step as a hawk kernel: a Mutable plane is what it updates, a Param is one number shared by every sample, a Scalar one number per sample, and the line terminated = ... says when a sample is done. eagle.simulate takes the kernel, then its arguments exactly as you would call it – an array gives each sample its own value, a plain number is shared by every sample – and runs every sample until it finishes (or max_steps is reached).

Hide code cell source

import sys, pathlib
sys.path.insert(0, str(pathlib.Path.cwd().parent / "_shared"))
from nb_helpers import gpu_available, plot_style, to_numpy, xp_for
plot_style()
DEVICE = "gpu" if gpu_available() else "cpu"
xp = xp_for(DEVICE)
print("running on", DEVICE)
running on gpu
import eagle
import hawk
from hawk import Mutable, Param, Scalar, Terminated


@hawk.kernel
def oscillator(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  # CPU: a smaller batch, same call
omega = xp.linspace(1.0, 3.0, n)
result = eagle.simulate(
    oscillator,
    omega=omega, t_end=1.0, dt=1e-3,
    x=xp.ones(n), v=xp.zeros(n), t=xp.zeros(n),
    max_steps=10_000,
)
print(result.status, result.steps, "launches:", result.report.launches)
finished 1000 launches: 1

What it printed#

"finished" and the step count the batch took; every sample here shares the same stop time (t_end), so they all take exactly the same number of steps. result.x is the very array passed in, updated in place.

import matplotlib.pyplot as plt
from themed_figure import show

omega_host, x_host = to_numpy(omega), to_numpy(result.x)

fig, ax = plt.subplots(figsize=(5, 3.2))
sc = ax.scatter(omega_host, x_host, s=3, c=omega_host, cmap="viridis")
ax.set_xlabel(r"$\omega$ (per sample)")
ax.set_ylabel(r"$x(t_\mathrm{end})$")
ax.set_title(f"{n:,} oscillators, one eagle.simulate call")
fig.colorbar(sc, ax=ax, label=r"$\omega$")
fig.tight_layout()
show()
Chart: 1,000,000 oscillators, one eagle.simulate call

What just happened#

  • eagle.simulate ran every sample’s kernel until its own terminated fired, and wrote the final state back into the arrays you gave it.

  • The data decided where it ran: numpy arrays run on the CPU through eagle’s OpenMP team; cupy arrays run the exact same call on the GPU.

  • result.report counts what the call did underneath (launches, steps) — one call, no loop you had to write.

Try this#

Change dt to 1e-4 and re-run: result.steps grows tenfold, the kernel is unchanged.

Next#

  • What a graph is — see what one launch replaying many times buys you, and why that kills launch overhead.

  • Load a compiled kernel (how-to) — load a kernel someone else compiled instead of writing one, and call it directly.

  • deeper: Performance — the full measurement behind “one call, no loop”, on both a GPU and a CPU.