What the contracts buy you

What the contracts buy you#

You will see two unrelated classes pass the same raptor check, just by having the right methods.

Time: ~5 min · Runs on: CPU, no GPU needed · You need: raptor-core

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 two_engines_diagram
two_engines_diagram()
Chart: One manifest, two engines that never import each other

The code#

A typing.Protocol is a list of required methods: Python checks an object against it with isinstance, by shape alone, never by whether it inherits from anything. Below, two engines (an engine = the object that actually runs a kernel) each implement the same shape; the methods beyond what gets called exist only to complete that shape, so their return values do not matter here:

First engine. ToyHostEngine implements KernelLauncher + Backend (both explained below) by shape alone — no inheritance, no shared base class:

class ToyHostEngine:
    name = "host"
    def launch(self, *a, **kw): return "ran on CPU threads"
    def assemble_args(self, *a, **kw): return ()
    def pure_origin(self, *a, **kw): return "numpy"
    def pure_prepare(self, *a, **kw): return ()
    def capabilities(self): return frozenset({"forward"})
    def compile(self, program): return program

print(ToyHostEngine().launch())
ran on CPU threads

Just a plain class — nothing about it mentions raptor yet.

A second, independent engine with the same shape. ToyDeviceEngine never imports ToyHostEngine, and neither one imports raptor’s own runtime:

class ToyDeviceEngine:
    name = "device"
    def launch(self, *a, **kw): return "ran on the GPU"
    def assemble_args(self, *a, **kw): return ()
    def pure_origin(self, *a, **kw): return "cupy"
    def pure_prepare(self, *a, **kw): return ()
    def capabilities(self): return frozenset({"forward"})
    def compile(self, program): return program

print(ToyDeviceEngine().launch())
ran on the GPU

Also just a plain class — the two have not heard of each other.

Now check both against KernelLauncher (the four methods a launcher needs) and Backend (the two more a backend needs) with isinstance — the same runtime check a real caller such as eagle would make. The other five methods on each class above exist only to complete that shape, so their return values never mattered:

from raptor.protocols import Backend, KernelLauncher

for engine in (ToyHostEngine(), ToyDeviceEngine()):
    ok = isinstance(engine, KernelLauncher) and isinstance(engine, Backend)
    print(f"{engine.name:>6}: KernelLauncher+Backend={ok}")
  host: KernelLauncher+Backend=True
device: KernelLauncher+Backend=True

Both report True — the protocol checked their shape, never their ancestry.

What just happened#

  • KernelLauncher and Backend are typing.Protocols: an object satisfies them by having the right methods, checked at runtime with isinstance, never by inheriting from a shared base class.

  • The two toy engines above never import each other, yet both pass the exact same checks a real engine such as eagle would.

  • A compiled kernel ships with a small manifest describing it — covered next — but running one needs an engine shaped like these first.

Try this#

Rename launch to run on ToyDeviceEngine and re-run the loop: isinstance(..., KernelLauncher) drops to False — the protocol checks names, not intentions.

Next#

Write a manifest covers the document a compiler such as hawk writes once, and that an engine like these would read. Deeper: Concepts.