Compile options#

Two inputs control every hawk compile beyond the kernel itself: how hard the compiler optimises (opt_level), and which GPU machine code is built for (device_arch). Both are resolved by one small function each, both feed the compile cache’s own key, and both are plain keyword arguments to hawk.build/hawk.artifact.build.

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

opt_level: how hard the compiler optimises#

opt_level picks one of "O0"–"O3" (hawk.compile.OPT_LEVELS); the default is "O3". Resolution order: the compile call’s own opt_level= > $HAWK_OPT_LEVEL > "O3" — hawk.compile.opt_level() is the resolver every build door calls:

from hawk.compile import OPT_LEVELS, opt_level

print("levels:", OPT_LEVELS)
print("default:", opt_level())
print("explicit O0:", opt_level("O0"))
levels: ('O0', 'O1', 'O2', 'O3')
default: O3
explicit O0: O0

It feeds -O<n> for the host build, and BOTH -O<n> (nvcc’s own code generation) and -Xptxas -O<n> (the device assembler) for an AOT nvcc device build. NVRTC — the pip-only device compiler hawk falls back to when no nvcc is on $PATH — always optimises and takes no -O option at all, so opt_level has no effect there.

A different opt_level is a different compile#

opt_level is part of the compile cache’s key, so a build at "O0" never gets served the "O3" entry, or the other way round — both are fresh compiles, never a stale hit of each other:

import pathlib, tempfile

import hawk
from hawk import Mutable, Param, Scalar

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

cache_dir = tempfile.mkdtemp()
default = hawk.build([scale], pathlib.Path(tempfile.mkdtemp()),
                     targets=("host",), cache_dir=cache_dir)
o0 = hawk.build([scale], pathlib.Path(tempfile.mkdtemp()),
               targets=("host",), cache_dir=cache_dir, opt_level="O0")
print("default (O3) cache hit:", default.artifacts[0].entries["host"].hit)
print("O0           cache hit:", o0.artifacts[0].entries["host"].hit)
default (O3) cache hit: False
O0           cache hit: False

Both print False: each opt_level got its own cache slot, compiled once, rather than one serving the other’s (wrong) binary.

device_arch: which GPU code is built for#

A device build targets one CUDA arch ("sm_80", …), resolved by hawk.artifact.arch in this order: an explicit device_arch= > $HAWK_CUDA_ARCH > the GPU actually in this machine (probed once per process) > "sm_61" (Pascal, the oldest arch hawk targets):

import os

from hawk.artifact import arch

os.environ.pop("HAWK_CUDA_ARCH", None)
print("no override anywhere (falls to sm_61 off a GPU):", arch())
print("an explicit device_arch= always wins:", arch("sm_90"))

os.environ["HAWK_CUDA_ARCH"] = "sm_80"
print("$HAWK_CUDA_ARCH, no explicit device_arch=:", arch())
del os.environ["HAWK_CUDA_ARCH"]
no override anywhere (falls to sm_61 off a GPU): sm_61
an explicit device_arch= always wins: sm_90
$HAWK_CUDA_ARCH, no explicit device_arch=: sm_80

device_arch is part of the compile cache’s key too, but only when "cuda" is actually one of the build’s targets — resolving it may reach the device probe above, which a host-only build must never pay for.

host_profile: how the host code is generated#

A host build is compiled under one of three host profiles. native and portable give results bit-identical to the plain scalar build (no fused multiply-add, no vector math library). native-vector-math is the fast one: it lets the compiler fuse multiply-adds and call vectorised exp, sin and friends, so results stay accurate but are no longer bit-identical to the exact profiles.

The default is native-vector-math when the host is x86-64 and the host compiler is GCC, and native otherwise. To pick one, pass host_profile= to the build, or set $HAWK_HOST_PROFILE; the argument wins. An unknown name is refused, as is native-vector-math on a non-GCC compiler or a non-x86-64 host:

from hawk.compile import toolchain

print("profiles:", toolchain.HOST_PROFILES)
print("bit-identical to scalar:", toolchain.EXACT_HOST_PROFILES)
print("default on this machine:", toolchain.default_host_profile())
print("explicit portable:", toolchain.host_profile("portable"))
profiles: ('native', 'portable', 'native-vector-math')
bit-identical to scalar: ('native', 'portable')
default on this machine: native-vector-math
explicit portable: portable

literal_table=: device literals in one table#

hawk.build and hawk.artifact.build_bundle take literal_table= (default False). On, the device source reads its double literals from one __constant__ table per translation unit instead of embedding each as an immediate; the bits are the same. It pays on architectures that issue a move pair per literal (sm_90). A float32 build ignores it, and with it off the device code is exactly what it was before. It is part of the compile cache’s key, so the two settings never share a slot:

import pathlib, tempfile
import hawk
from hawk import Mutable, Param, Scalar

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

for lt in (False, True):
    art = hawk.build([scale], pathlib.Path(tempfile.mkdtemp()), targets=("host",),
                     literal_table=lt, host_profile="portable")
    print("literal_table =", lt, "->", [a.name for a in art.artifacts])
literal_table = False -> ['scale']
literal_table = True -> ['scale']

NVRTC defines and extra flags#

A build’s defines=("NAME=value", ...) become -DNAME=value on every compile, and CompileOptions.extra flags are appended as given. The NVRTC device compile receives exactly the same macros and flags that nvcc and the host compiler do, so a kernel’s behaviour does not change with which device compiler happens to be available. hawk.compile.nvrtc.options shows the final NVRTC command line:

from hawk.compile import CompileOptions

opts = CompileOptions(target="host", defines=("MY_SCALE=2",), extra=("--use_fast_math",))
print(opts.defines, opts.extra)
from hawk.compile import nvrtc
print([f for f in nvrtc.options("sm_80", extra=("-DMY_SCALE=2", "--use_fast_math")) if "MY_SCALE" in f or "fast" in f])
('MY_SCALE=2',) ('--use_fast_math',)
['-DMY_SCALE=2', '--use_fast_math']

Performance numbers in these docs#

The performance cards record the build flags they were measured with, and opt_level="O3" is the default; "O0"/"O1"/"O2" are for a smaller or faster-to-compile debug build, never for comparing wall time against them.