A graph with parallel branches

A graph with parallel branches#

The main tutorials run a chain of kernels, one after another. Real steps are often wider: several independent pieces of work read the same input, their results are combined, and the combination is reduced to one number. This extra page builds exactly that, as a graph with a fork, a join and a reduce, and runs it on the GPU and on the CPU. It is optional reading; the main path does not depend on it.

x --+-- branch_a --+
    +-- branch_b --+-- join --> s --> sum(s)
    +-- branch_c --+

Time: ~6 min · Runs on: CPU, GPU if visible (the GPU route is also run when a GPU is present) · You need: eagle, hawk, NumPy and CuPy (GPU only); read first: What a graph is

You will build: three branches over one input, a join kernel that combines them, a reduction, and a check that the GPU graph and the CPU run agree.

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/extra").mkdir(parents=True, exist_ok=True)
    os.chdir(root / "docs/content/userguide/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 matplotlib raptor-eagle raptor-hawk`. For a GPU, add [cuda12] (or [cuda13]) to raptor-eagle and raptor-hawk."
    ) from err
import sys, pathlib
sys.path.insert(0, str(pathlib.Path.cwd().parent.parent / "_shared"))
from nb_helpers import gpu_available
HAVE_GPU = gpu_available()
print("GPU visible:", HAVE_GPU)
GPU visible: True
import numpy as np

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

from eagle import GraphPipeline, deploy

Four small kernels#

Each is an ordinary per-sample function. The three branches read the same x and each writes its own output array, which is what makes them independent: no branch reads anything another branch writes. join reads all three and writes s. deploy compiles them together and returns one plan per kernel, in order.

def branch_a(x: Scalar, k: Param, terminated: Terminated, a: Mutable[Scalar]):
    a = x * x + k


def branch_b(x: Scalar, k: Param, terminated: Terminated, b: Mutable[Scalar]):
    b = 3.0 * x - k


def branch_c(x: Scalar, terminated: Terminated, c: Mutable[Scalar]):
    c = 0.5 * x + 1.0


def join(a: Scalar, b: Scalar, c: Scalar, terminated: Terminated, s: Mutable[Scalar]):
    s = a * b + c


kernels = [hawk.kernel(fn) for fn in (branch_a, branch_b, branch_c, join)]
plan_a, plan_b, plan_c, plan_join = deploy(kernels)

Fork, join, reduce#

Plan.bind packs each kernel’s arguments once, against the arrays it will use. The two routes then differ only in how the bound launches are scheduled:

  • GPU: add_concurrent() registers the three branches as one fork/join stage, and add appends the join after it. The join starts only when every branch has finished. build() captures the whole thing into one CUDA graph; launch() replays it. The device is free to run the branches side by side, but is never required to.

  • CPU: there is no graph to capture; the same bound launches run on the host team, in order.

The reduce is a plain array sum of s on either route, after the graph. A reduction allocates scratch memory, which a captured graph must not do, so it sits just outside the capture rather than inside it.

def bind_all(xp, n=100_000, k=0.5):
    """Allocate the ensemble's arrays and pack each kernel's arguments once."""
    x = xp.asarray(np.linspace(-1.0, 1.0, n))
    a, b, c, s = (xp.zeros(n) for _ in range(4))
    dead = xp.zeros(n, dtype=xp.bool_)  # the `terminated` mask: nobody is finished
    runs = [
        plan_a.bind(x=x, k=k, terminated=dead, a=a),
        plan_b.bind(x=x, k=k, terminated=dead, b=b),
        plan_c.bind(x=x, terminated=dead, c=c),
        plan_join.bind(a=a, b=b, c=c, terminated=dead, s=s),
    ]
    return runs, s


def run_gpu():
    import cupy as cp

    (ra, rb, rc, rj), s = bind_all(cp)
    pipe = GraphPipeline()
    pipe.add_concurrent([ra.launch, rb.launch, rc.launch], names=["a", "b", "c"])  # fork
    pipe.add(rj.launch, name="join")                                                # join
    pipe.build()
    pipe.launch()
    cp.cuda.Device().synchronize()
    return cp.asnumpy(s), float(cp.sum(s))                                          # reduce


def run_cpu():
    (ra, rb, rc, rj), s = bind_all(np)
    for run in (ra, rb, rc, rj):  # same launches, host team, in order
        run.launch()
    return s, float(np.sum(s))

Run both and compare#

s_cpu, total_cpu = run_cpu()
print(f"cpu total = {total_cpu:.9f}")
cpu total = 58332.999996667
if HAVE_GPU:
    s_gpu, total_gpu = run_gpu()
    print(f"gpu total = {total_gpu:.9f}")
    print(f"max |gpu - cpu| over {s_cpu.size} samples = {np.abs(s_gpu - s_cpu).max():.3e}")
else:
    print("no GPU visible; the CPU route above is the whole run")
gpu total = 58332.999996667
max |gpu - cpu| over 100000 samples = 0.000e+00

Both routes agree because they are the same four launches in the same dependency order. The graph only changes how the work is issued: one replay instead of four launches, with the branches free to overlap.

Try this#

  • Add a fourth branch kernel, include it in the add_concurrent list and in join’s arguments; the graph’s shape changes, nothing else does.

  • Add a second add_concurrent stage after the join to fork again. Stages are chained, each joining fully before the next begins.

  • Branches must not write the same array. If you are unsure, eagle.pipeline._concurrent_write_conflict_check can be run on the write targets before build() (it is an internal helper, so treat it as a debugging aid).

Next#