Implement a protocol#

Give an object the right methods and it satisfies raptor’s contracts — whether or not it has ever heard of raptor.

Time: ~5 min · Runs on: CPU, no GPU needed · You need: raptor-core; read first: What the contracts buy you

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, "raptor-core"])
    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) / "raptor"
    for rel in (
        "docs/content/_shared/nb_diagrams.py",
        "docs/content/_shared/themed_figure.py",
    ):
        (root / rel).parent.mkdir(parents=True, exist_ok=True)
        urllib.request.urlretrieve(f"{base}/amasat01/raptor/{ref}/{rel}", root / rel)
    (root / "docs/content/tutorials").mkdir(parents=True, exist_ok=True)
    os.chdir(root / "docs/content/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 raptor  # noqa: F401
except ImportError as err:
    raise ImportError(
        "raptor not found. Install with `pip install matplotlib raptor-core`."
    ) from err

Hide code cell source

import sys; sys.path.insert(0, "../_shared")
from nb_diagrams import capability_grid
capability_grid()
Chart: Declared capabilities() decide what a call may do

The code#

An Executable is a compiled, callable program: it declares forward, vjp (reverse-mode: given a cotangent — a weighting of the output — produces the matching weighting of the input), jvp (forward-mode: given a tangent — a direction in the input — produces the matching direction in the output), and parameters. Below, ToyExecutable implements that shape by hand:

from raptor.protocols import CapabilityError, Executable

class ToyExecutable:
    def __init__(self, fn): self._fn = fn
    def forward(self, inputs): return self._fn(inputs)
    def vjp(self, cotangents): raise CapabilityError("no vjp")
    def jvp(self, tangents): raise CapabilityError("no jvp")
    def parameters(self): return []

print("Executable?", isinstance(ToyExecutable(lambda x: x), Executable))
Executable? True

What vjp/jvp actually compute does not matter below — only that calling one ToyBackend has not declared will raise CapabilityError (a dedicated exception, explained below), not guess.

A Backend builds one of those: capabilities() is its own declaration of what it supports:

from raptor.protocols import Backend

class ToyBackend:
    name = "toy"
    def capabilities(self): return frozenset({"forward"})
    def compile(self, program): return ToyExecutable(program)

print("Backend?", isinstance(ToyBackend(), Backend))
Backend? True

Both checks pass by shape alone — “duck typing”: judged by which methods exist, never by which class an object inherits from.

Now use them together: compile a program, call the one capability ToyBackend declared, then call the one it did not — which raises CapabilityError (a dedicated exception: this object cannot do that, by declaration) rather than returning a silent wrong answer:

backend = ToyBackend()
executable = backend.compile(lambda x: x * 2)
print("forward(21) =", executable.forward(21))
try:
    executable.vjp(None)
except CapabilityError as exc:
    print("caught:", exc)
forward(21) = 42
caught: no vjp

forward runs; the undeclared vjp raises instead of returning a silent wrong answer.

The kernel-provider protocol#

ManifestProvider is satisfied by anything with a matching build(directory) method — it duck-types hawk’s own Bundle, the object that writes a kernel’s manifest, without either side importing the other:

from raptor.protocols import ManifestProvider

class ToyBundle:
    def build(self, directory):
        """Pretend to emit a manifest; return its path."""
        return f"{directory}/manifest.json"

print("ManifestProvider?", isinstance(ToyBundle(), ManifestProvider))
print("A plain object is not:", isinstance(object(), ManifestProvider))
ManifestProvider? True
A plain object is not: False

A plain object() fails the check; ToyBundle passes it on the strength of its one method alone.

What just happened#

  • capabilities() is a declaration a backend makes about itself; calling a capability it never declared raises CapabilityError rather than returning a silent wrong answer.

  • ManifestProvider is satisfied the same structural way as Backend/Executable — by shape, checked with isinstance, never by inheritance.

  • None of the toy objects above import hawk or eagle, yet each one is exactly what a real engine checks for before it will run a kernel.

Try this#

Add "vjp" to ToyBackend.capabilities() without adding a real vjp method to ToyExecutable — isinstance(executable, Executable) still reports True (the protocol only checks that the method exists, not that the declared capability set agrees with it); the mismatch only shows up when you actually call it.

Next#

Read the interop matrix reads the family’s own certification declaration. Deeper: Concepts.

Going deeper (optional)#

Marshal mirrors eagle’s own per-role input coercion — the shape a launcher (the code that actually calls a compiled kernel) needs once it must bind real arguments: state vectors, per-sample scalars, uniform constants, lookup tables. ToyMarshal below is the minimal object satisfying all seven methods, each returning an empty/default value:

from raptor.protocols import Marshal

class ToyMarshal:
    def coerce_vec_inputs(self, *a, **kw): return ({}, 1)
    def coerce_mat_inputs(self, *a, **kw): return {}
    def coerce_per_sample(self, *a, **kw): return {}
    def coerce_uniforms(self, *a, **kw): return {}
    def coerce_tables(self, *a, **kw): return {}
    def coerce_terminated(self, *a, **kw): return None
    def require_n(self, n, **kw): return n

print("Marshal?", isinstance(ToyMarshal(), Marshal))
Marshal? True

True — none of the seven methods above do real work, but all seven exist, and that is all the protocol asks.