Grow your vocabulary as your model grows

Grow your vocabulary as your model grows#

Add to a vocabulary the ordinary Python way: subclass it.

Time: ~5 min · Runs on: CPU (same code on GPU) · You need: hawk and NumPy; read first: a family of kernels

class Perturbed(Orbit, slug="perturbed") carries Orbit’s whole vocabulary forward and adds its own entries; a kernel built on Perturbed sees both. Re-declaring an inherited entry is fine if it matches exactly, and refuses – by name – if it does not.

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-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) / "hawk"
    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/hawk/{ref}/{rel}", root / rel)
    (root / "docs/content/vocabulary").mkdir(parents=True, exist_ok=True)
    os.chdir(root / "docs/content/vocabulary")
    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 hawk  # noqa: F401
except ImportError as err:
    raise ImportError(
        "hawk not found. Install with `pip install matplotlib raptor-hawk`. For a GPU, add [cuda12] (or [cuda13]) to raptor-hawk."
    ) from err

Hide code cell source

import sys, pathlib
sys.path.insert(0, str(pathlib.Path.cwd().parent / "_shared"))
from nb_helpers import plot_style
plot_style()
from hawk import Param, Vector
from hawk.ext import DATA_ONLY, KernelKind


class Orbit(KernelKind, slug="orbit"):
    r: Vector[3]
    v: Vector[3]
    dt: Param
    g: Param
    guard = DATA_ONLY


Orbit
__main__.Orbit

Extend it by subclassing:

from hawk import Scalar


class Perturbed(Orbit, slug="perturbed"):
    """Adds ONE entry, `cd` -- a per-sample drag coefficient."""
    cd: Scalar


print("Perturbed's vocabulary:", [name for name, _ in Perturbed.kind.vocabulary])
Perturbed's vocabulary: ['r', 'v', 'dt', 'g', 'cd']

drag_fall, built on Perturbed, sees r, v, dt, g (Orbit’s own) AND cd (its own) without re-declaring any of them:

import numpy as np
from hawk import Mutable
from hawk.math import norm, vec


@Perturbed
def drag_fall(r, v, dt, g, cd, r_next: Mutable[Vector[3]], v_next: Mutable[Vector[3]]):
    a = vec(0.0, 0.0, -g) - cd * norm(v) * v
    v_new = v + dt * a
    v_next = v_new
    r_next = r + dt * v_new


drag_fall
<Kernel drag_fall slots=7>

Calling a kernel builds it on first use and runs it on the host (the build is taught in Your first kernel):

n = 4
r0 = np.zeros((3, n)); r0[2] = 2.0
v0 = np.zeros((3, n)); v0[0] = 3.0
step = drag_fall(r=r0, v=v0, dt=0.1, g=9.81, cd=np.array([0.0, 0.01, 0.05, 0.1]))
print("x after one step, by drag coefficient 0 / 0.01 / 0.05 / 0.1:", np.asarray(step["r_next"])[0])
x after one step, by drag coefficient 0 / 0.01 / 0.05 / 0.1: [0.3    0.2991 0.2955 0.291 ]

When a re-declaration disagrees#

Equal re-declarations are harmless (a subclass restating a base’s own entry verbatim); a DIFFERENT one for the same name refuses, naming the entry, the base and both declarations – never a silent shadow:

from hawk.ir import HawkError

try:
    class BadPerturbed(Orbit, slug="bad_perturbed"):
        r: Scalar  # Orbit already declares `r` as a Vector[3] -- disagrees
except HawkError as exc:
    print("refused:", exc)
refused: class 'BadPerturbed'(KernelKind, ...): vocabulary entry 'r' is declared differently by 'Orbit' (Plane(form='in', ttype=TensorType(shape=(3,), dtype='f64', tag=None), dims=(), staged=False, grid=(), sorted=False)) and 'BadPerturbed' (Plane(form='in', ttype=TensorType(shape=(), dtype='f64', tag=None), dims=(), staged=False, grid=(), sorted=False)) — an inherited entry may only be re-declared with an EQUAL resolved declaration

The instance-form twin#

Kind.extend does the same merge without a class statement – the same object the class form built, for the same inputs:

extended = Orbit.kind.extend("perturbed", vocabulary={"cd": Scalar})
extended == Perturbed.kind
True

What just happened#

  • Perturbed(Orbit, slug=...) merged Orbit’s vocabulary with its own ONE new entry (cd); drag_fall used both without re-declaring anything.

  • A conflicting re-declaration refuses by NAME, at class-creation time – before any kernel built from it can ever run.

  • Kind.extend(...) is the same merge, spelled on an instance instead of a class statement – one mechanism, two spellings.

Try this#

Add a second child, class Lofted(Orbit, slug="lofted"): lift: Scalar, and a kernel that uses lift alongside r, v, dt, g.

Next#

Supply the derivatives your field already knows – give a kernel on Perturbed a custom primitive. Deeper: the inheritance rules in hawk.ext.KernelKind’s own docstring (API reference).