The compile cache#

hawk saves every compiled kernel. Building the same kernel again copies it from the cache instead of recompiling it.

Mechanically: a compile is a pure function of its inputs — the same source, backend, scalar mode (the host CPU profile or the device’s own float handling; see installation) and compiler flags always produce the same lookup key, and therefore the same cache slot. hawk.compile is content-closure keyed: the key covers not just the kernel’s own source but everything the compiler reports it depends on (headers, flags), so a HIT never runs a compiler and a changed dependency never serves a stale one.

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}"])
    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 raptor-hawk`. For a GPU, add [cuda12] (or [cuda13]) to raptor-hawk."
    ) from err
import pathlib
import tempfile

import hawk
import hawk.artifact
from hawk import Mutable, Param, Scalar
from hawk.compile import cache_stats, reset_cache_stats


@hawk.kernel
def affine(x: Scalar, a: Param, y: Mutable[Scalar]):
    y = a * x

A miss, then a hit#

Building the same kernel twice into two different output directories, against the same cache_dir, compiles once.

cache_dir = tempfile.mkdtemp()
out_dir_1 = pathlib.Path(tempfile.mkdtemp())
out_dir_2 = pathlib.Path(tempfile.mkdtemp())

reset_cache_stats()
first = hawk.artifact.build(affine, out_dir_1, targets=("host",), cache_dir=cache_dir)
second = hawk.artifact.build(affine, out_dir_2, targets=("host",), cache_dir=cache_dir)

print("first build  — cache hit:", first.entries["host"].hit,
      f"({first.entries['host'].seconds:.3f}s)")
print("second build — cache hit:", second.entries["host"].hit,
      f"({second.entries['host'].seconds:.3f}s)")
print(cache_stats())
first build  — cache hit: False (0.992s)
second build — cache hit: True (0.000s)
{'hits': 1, 'misses': 1}

The second build’s compiled .so is byte-identical to the first’s — it is copied out of the cache slot, not recompiled — which is why its reported compile time is zero.

A changed kernel is a different key#

Change the arithmetic — even trivially — and the lookup key changes with it: a different source is a different compile, by construction, never a stale hit.

@hawk.kernel
def affine_scaled(x: Scalar, a: Param, y: Mutable[Scalar]):
    y = 2.0 * a * x   # one constant added: a different kernel body

out_dir_3 = pathlib.Path(tempfile.mkdtemp())
third = hawk.artifact.build(affine_scaled, out_dir_3, targets=("host",), cache_dir=cache_dir)
print("changed kernel — cache hit:", third.entries["host"].hit)
changed kernel — cache hit: False

Where the cache lives#

cache_dir=None (the default) resolves to hawk.compile.default_cache_dir() — a persistent directory under the user’s cache home, shared across processes. Passing an explicit cache_dir= (as this page does, above) is how a reproducible docs build, or a CI job, keeps its compiles isolated from a developer’s own cache.