From 2c89d33ef371307e6519e3b3b4658c10ccd543c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Tue, 19 May 2026 12:24:21 +0000 Subject: [PATCH 1/4] nix-builder: add a hook to detect incorrect op registrations --- docs/source/builder/writing-kernels.md | 41 +++++++++ nix-builder/lib/extension/torch/arch.nix | 2 + nix-builder/lib/extension/torch/no-arch.nix | 2 + nix-builder/lib/extension/tvm-ffi/arch.nix | 2 + nix-builder/overlay.nix | 2 + nix-builder/pkgs/torch-ops-check/default.nix | 9 ++ .../torch-ops-check/torch-ops-check-hook.py | 90 +++++++++++++++++++ .../torch-ops-check/torch-ops-check-hook.sh | 14 +++ 8 files changed, 162 insertions(+) create mode 100644 nix-builder/pkgs/torch-ops-check/default.nix create mode 100644 nix-builder/pkgs/torch-ops-check/torch-ops-check-hook.py create mode 100644 nix-builder/pkgs/torch-ops-check/torch-ops-check-hook.sh diff --git a/docs/source/builder/writing-kernels.md b/docs/source/builder/writing-kernels.md index 9f9309e08..328bf667a 100644 --- a/docs/source/builder/writing-kernels.md +++ b/docs/source/builder/writing-kernels.md @@ -345,6 +345,47 @@ def mykernel(x: torch.Tensor, out: Optional[torch.Tensor] = None) -> torch.Tenso return out ``` +## Registering Torch operators + +You may want to register Torch ops from your kernel's Python code or +register fake ops for `torch.compile` support. It is important register +such ops in the namespace that kernel-builder makes for your kernel +build. This is required for compliant kernels to ensure that multiple +versions of the same kernel can be loaded at the same time without +namespace conflicts. + +You can use the `add_op_namespace_prefix` to prefix an op name with the +correct prefix. So for instance, replace + +```python +@torch.library.register_fake("relu::relu_fwd") +def relu_fwd_fake(input: torch.Tensor) -> torch.Tensor: + return torch.empty_like(input) +``` + +by + +```python +from ._ops import add_op_namespace_prefix + +@torch.library.register_fake(add_op_namespace_prefix("relu_fwd")) +def relu_fwd_fake(input: torch.Tensor) -> torch.Tensor: + return torch.empty_like(input) +``` + +As mentioned in the above, the `_ops` module is generated by kernel-builder. + +kernel-builder uses a hook to reject incorrect uses Torch op registration +functions. However, it can only catch direct use of certain `torch.library` +decorators. For instance, the hook would not reject the following decorator, +so it should be seen as a last-resort check if human review failed: + +```python +@some_indirection_for_register_fake("relu::relu_fwd") +def relu_fwd_fake(input: torch.Tensor) -> torch.Tensor: + return torch.empty_like(input) +``` + ## Kernel tests Kernel tests are stored in the `tests` directory. Since running all diff --git a/nix-builder/lib/extension/torch/arch.nix b/nix-builder/lib/extension/torch/arch.nix index cbc259ee9..eca46a6c8 100644 --- a/nix-builder/lib/extension/torch/arch.nix +++ b/nix-builder/lib/extension/torch/arch.nix @@ -16,6 +16,7 @@ get-kernel-check, kernel-abi-check, kernel-layout-check, + torch-ops-check, ninja, python3, remove-bytecode-hook, @@ -163,6 +164,7 @@ stdenv.mkDerivation (prevAttrs: { kernel-abi-check kernel-layout-check remove-bytecode-hook + torch-ops-check ] ++ lib.optionals doGetKernelCheck [ (get-kernel-check.override { python3 = python3.withPackages (ps: dependencies); }) diff --git a/nix-builder/lib/extension/torch/no-arch.nix b/nix-builder/lib/extension/torch/no-arch.nix index 2e58c8bd1..4abb2f2d7 100644 --- a/nix-builder/lib/extension/torch/no-arch.nix +++ b/nix-builder/lib/extension/torch/no-arch.nix @@ -12,6 +12,7 @@ kernel-layout-check, python3, remove-bytecode-hook, + torch-ops-check, writeText, torch, @@ -90,6 +91,7 @@ stdenv.mkDerivation (prevAttrs: { kernel-builder kernel-layout-check remove-bytecode-hook + torch-ops-check ] ++ lib.optionals doGetKernelCheck [ (get-kernel-check.override { diff --git a/nix-builder/lib/extension/tvm-ffi/arch.nix b/nix-builder/lib/extension/tvm-ffi/arch.nix index 00eff3b8c..7c3b7fe95 100644 --- a/nix-builder/lib/extension/tvm-ffi/arch.nix +++ b/nix-builder/lib/extension/tvm-ffi/arch.nix @@ -20,6 +20,7 @@ python3, remove-bytecode-hook, rewrite-nix-paths-macho, + torch-ops-check, writeScriptBin, # Framework packages @@ -163,6 +164,7 @@ stdenv.mkDerivation (prevAttrs: { kernel-abi-check kernel-layout-check remove-bytecode-hook + torch-ops-check ] ++ lib.optionals doGetKernelCheck [ (get-kernel-check.override { python3 = python3.withPackages (ps: dependencies); }) diff --git a/nix-builder/overlay.nix b/nix-builder/overlay.nix index 389b1c7a8..6ef6e9692 100644 --- a/nix-builder/overlay.nix +++ b/nix-builder/overlay.nix @@ -26,6 +26,8 @@ in remove-bytecode-hook = final.callPackage ./pkgs/remove-bytecode-hook { }; + torch-ops-check = final.callPackage ./pkgs/torch-ops-check { }; + ruff = prev.ruff.overrideAttrs ( finalAttrs: prevAttrs: { version = "0.15.10"; diff --git a/nix-builder/pkgs/torch-ops-check/default.nix b/nix-builder/pkgs/torch-ops-check/default.nix new file mode 100644 index 000000000..982143cc3 --- /dev/null +++ b/nix-builder/pkgs/torch-ops-check/default.nix @@ -0,0 +1,9 @@ +{ makeSetupHook, python3 }: + +makeSetupHook { + name = "torch-ops-check-hook"; + substitutions = { + inherit python3; + hook = ./torch-ops-check-hook.py; + }; +} ./torch-ops-check-hook.sh diff --git a/nix-builder/pkgs/torch-ops-check/torch-ops-check-hook.py b/nix-builder/pkgs/torch-ops-check/torch-ops-check-hook.py new file mode 100644 index 000000000..709fd29b1 --- /dev/null +++ b/nix-builder/pkgs/torch-ops-check/torch-ops-check-hook.py @@ -0,0 +1,90 @@ +import argparse +import ast +import sys +from pathlib import Path + +TORCH_LIBRARY_DECORATORS = frozenset( + { + "custom_op", + "triton_op", + "register_kernel", + "register_fake", + "register_vmap", + "register_torch_dispatch", + } +) + + +def get_func_name(node: ast.Call) -> str | None: + """Return the the function name of a call.""" + # myfunc(...) + if isinstance(node.func, ast.Name): + return node.func.id + # somelib.myfunc(...) + if isinstance(node.func, ast.Attribute): + return node.func.attr + return None + + +def is_torch_library_decorator(node: ast.expr) -> bool: + """Check if a decorator call is one of the known torch.library decorators.""" + return ( + isinstance(node, ast.Call) + and len(node.args) > 0 + and get_func_name(node) in TORCH_LIBRARY_DECORATORS + ) + + +def is_add_namespace_prefix(node: ast.expr) -> bool: + """Check if a node is a call to add_op_namespace_prefix (bare or attribute).""" + return ( + isinstance(node, ast.Call) and get_func_name(node) == "add_op_namespace_prefix" + ) + + +NODE_TYPES: dict[type, str] = { + ast.FunctionDef: "function", + ast.AsyncFunctionDef: "async function", + ast.ClassDef: "class", +} + + +def find_violations(filename: str, tree: ast.Module) -> list[str]: + violations = [] + for node in ast.iter_child_nodes(tree): + if type(node) in NODE_TYPES: + for decorator in node.decorator_list: + if is_torch_library_decorator( + decorator + ) and not is_add_namespace_prefix(decorator.args[0]): + node_type = NODE_TYPES[type(node)] + violations.append( + f"{filename}:{node.lineno} {node_type} {node.name}" + ) + return violations + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Check that Torch library decorators use add_op_namespace_prefix." + ) + parser.add_argument("directory", help="Directory to recursively check") + args = parser.parse_args() + + violations = [] + for path in sorted(Path(args.directory).rglob("*.py")): + source = path.read_text() + tree = ast.parse(source, filename=str(path)) + violations.extend(find_violations(str(path), tree)) + + if violations: + print( + "Found Torch library registrations that do not use `add_op_namespace_prefix`:" + ) + for v in violations: + print(v) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/nix-builder/pkgs/torch-ops-check/torch-ops-check-hook.sh b/nix-builder/pkgs/torch-ops-check/torch-ops-check-hook.sh new file mode 100644 index 000000000..af52e1af2 --- /dev/null +++ b/nix-builder/pkgs/torch-ops-check/torch-ops-check-hook.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +echo "Sourcing torch-ops-check-hook.sh" + + +pythonOpsCheckHook() { + echo "Checking kernel layout" + + @python3@/bin/python @hook@ source +} + +if [ -z "${dontCheckPythonOps-}" ]; then + postUnpackHooks+=(pythonOpsCheckHook) +fi From eb271caeaaeb9dbd9929699dea2c4e10986a2e14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Tue, 19 May 2026 12:40:44 +0000 Subject: [PATCH 2/4] ci: test that the hook fails on incorrect registrations --- .../silu-and-mul-bad-registration/CARD.md | 56 +++++++++++++++++++ .../silu-and-mul-bad-registration/build.toml | 18 ++++++ .../silu-and-mul-bad-registration/flake.nix | 17 ++++++ .../silu_and_mul_bad_registration/__init__.py | 12 ++++ .../silu_and_mul_bad_registration/layers.py | 20 +++++++ .../silu_and_mul_bad_registration/op.py | 33 +++++++++++ nix-builder/lib/checks.nix | 16 +++++- 7 files changed, 171 insertions(+), 1 deletion(-) create mode 100644 examples/kernels/silu-and-mul-bad-registration/CARD.md create mode 100644 examples/kernels/silu-and-mul-bad-registration/build.toml create mode 100644 examples/kernels/silu-and-mul-bad-registration/flake.nix create mode 100644 examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/__init__.py create mode 100644 examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/layers.py create mode 100644 examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/op.py diff --git a/examples/kernels/silu-and-mul-bad-registration/CARD.md b/examples/kernels/silu-and-mul-bad-registration/CARD.md new file mode 100644 index 000000000..c7c707151 --- /dev/null +++ b/examples/kernels/silu-and-mul-bad-registration/CARD.md @@ -0,0 +1,56 @@ +--- +library_name: kernels +{% if license %}license: {{ license }} +{% endif %}--- + +This is the repository card of {{ repo_id }} that has been pushed on the Hub. It was built to be used with the [`kernels` library](https://github.com/huggingface/kernels). This card was automatically generated. + +## How to use +{% if functions %} + +```python +# make sure `kernels` is installed: `pip install -U kernels` +from kernels import get_kernel + +kernel_module = get_kernel("{{ repo_id }}", version={{ version }}) +{{ functions[0] }} = kernel_module.{{ functions[0] }} + +{{ functions[0] }}(...) +``` +{% else %} + +Usage example not available. +{% endif %} + +## Available functions +{% if functions %} +{% for func in functions %} +- `{{ func }}` +{% endfor %} +{% else %} + +Function list not available. +{% endif %} +{% if layers %} + +## Available layers +{% for layer in layers %} +- `{{ layer }}` +{% endfor %} +{% endif %} + +## Benchmarks +{% if has_benchmark %} + +Benchmarking script is available for this kernel. Run `kernels benchmark {{ repo_id }} --version {{ version }}`. +{% else %} + +No benchmark available yet. +{% endif %} +{% if upstream %} + +## Source code + +Source code of this kernel originally comes from {{ upstream }} and it was repurposed for compatibility with `kernels`. +{% endif %} + diff --git a/examples/kernels/silu-and-mul-bad-registration/build.toml b/examples/kernels/silu-and-mul-bad-registration/build.toml new file mode 100644 index 000000000..247407397 --- /dev/null +++ b/examples/kernels/silu-and-mul-bad-registration/build.toml @@ -0,0 +1,18 @@ +[general] +name = "silu-and-mul-bad-registration" +version = 1 +license = "apache-2.0" +backends = [ + "cpu", + "cuda", + "metal", + "rocm", + "xpu", +] + +[general.hub] +repo-id = "kernels-test/silu-and-mul-bad-registration" + +[torch-noarch] + +[kernel] diff --git a/examples/kernels/silu-and-mul-bad-registration/flake.nix b/examples/kernels/silu-and-mul-bad-registration/flake.nix new file mode 100644 index 000000000..29c0cc8f8 --- /dev/null +++ b/examples/kernels/silu-and-mul-bad-registration/flake.nix @@ -0,0 +1,17 @@ +{ + description = "Flake for kernels tests"; + + inputs = { + kernel-builder.url = "path:../../.."; + }; + + outputs = + { + self, + kernel-builder, + }: + kernel-builder.lib.genKernelFlakeOutputs { + inherit self; + path = ./.; + }; +} diff --git a/examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/__init__.py b/examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/__init__.py new file mode 100644 index 000000000..a7102ebe1 --- /dev/null +++ b/examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/__init__.py @@ -0,0 +1,12 @@ +import torch + +from ._ops import ops +from .op import _silu_and_mul +from . import layers + + +def silu_and_mul(x: torch.Tensor) -> torch.Tensor: + return ops.silu_and_mul(x) + + +__all__ = ["layers", "silu_and_mul"] diff --git a/examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/layers.py b/examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/layers.py new file mode 100644 index 000000000..996f64157 --- /dev/null +++ b/examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/layers.py @@ -0,0 +1,20 @@ +import torch +import torch.nn as nn + +from ._ops import ops + + +class SiluAndMul(nn.Module): + """ + Apply SiLU to one half of the array and use it as a multiplicative + gate for the other half. + + Shapes: + x: (num_tokens, 2 * d) or (batch_size, seq_len, 2 * d) + return: (num_tokens, d) or (batch_size, seq_len, d) + """ + + can_torch_compile: bool = True + + def forward(self, x: torch.Tensor): + return ops.silu_and_mul(x) diff --git a/examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/op.py b/examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/op.py new file mode 100644 index 000000000..3b708ec30 --- /dev/null +++ b/examples/kernels/silu-and-mul-bad-registration/torch-ext/silu_and_mul_bad_registration/op.py @@ -0,0 +1,33 @@ +import torch +import torch.nn.functional as F + + +@torch.library.custom_op("myns::silu_and_mul", mutates_args=()) +def _silu_and_mul(x: torch.Tensor) -> torch.Tensor: + d = x.shape[-1] // 2 + return F.silu(x[..., :d]) * x[..., d:] + + +def backward(ctx, grad_output): + x = ctx.saved_tensors[0] + d = x.shape[-1] // 2 + x1, x2 = x[..., :d], x[..., d:] + sigmoid_x1 = torch.sigmoid(x1) + silu_x1 = F.silu(x1) + dsilu_dx1 = sigmoid_x1 + silu_x1 * (1 - sigmoid_x1) + dx1 = grad_output * x2 * dsilu_dx1 + dx2 = grad_output * silu_x1 + return torch.cat([dx1, dx2], dim=-1) + + +def setup_context(ctx, inputs, output): + (x,) = inputs + ctx.save_for_backward(x) + + +_silu_and_mul.register_autograd(backward, setup_context=setup_context) + + +@_silu_and_mul.register_fake +def _(x: torch.Tensor) -> torch.Tensor: + return x.new_empty(x.shape[0], x.shape[1] // 2) diff --git a/nix-builder/lib/checks.nix b/nix-builder/lib/checks.nix index 71cbce27f..d07af79a4 100644 --- a/nix-builder/lib/checks.nix +++ b/nix-builder/lib/checks.nix @@ -1,6 +1,8 @@ { lib, runCommand, + testers, + python3, build, buildSets, @@ -11,11 +13,23 @@ let inherit buildSets; path = ../../examples/kernels/relu-torch-bounds; }; + + badRegistrationCheck = testers.testBuildFailure' { + drv = runCommand "check-bad-registration" { buildInputs = [ python3 ]; } '' + python3 ${../pkgs/torch-ops-check/torch-ops-check-hook.py} \ + ${../../examples/kernels/silu-and-mul-bad-registration} + touch $out + ''; + expectedBuilderExitCode = 1; + expectedBuilderLogEntries = [ + "Found Torch library registrations that do not use `add_op_namespace_prefix`:" + ]; + }; in assert lib.assertMsg (builtins.all (buildSet: buildSet.torch.version == "2.10.0") kernelBuildSets) '' Torch minver/maxver filtering does not work. ''; -runCommand "builder-nix-checks" { } '' +runCommand "builder-nix-checks" { buildInputs = [ badRegistrationCheck ]; } '' touch $out '' From fcfd89884c590761b1620fb39afda10b6928d0c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Tue, 19 May 2026 15:35:21 +0200 Subject: [PATCH 3/4] doc fixes Co-authored-by: Sayak Paul --- docs/source/builder/writing-kernels.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/source/builder/writing-kernels.md b/docs/source/builder/writing-kernels.md index 328bf667a..01627743f 100644 --- a/docs/source/builder/writing-kernels.md +++ b/docs/source/builder/writing-kernels.md @@ -348,7 +348,7 @@ def mykernel(x: torch.Tensor, out: Optional[torch.Tensor] = None) -> torch.Tenso ## Registering Torch operators You may want to register Torch ops from your kernel's Python code or -register fake ops for `torch.compile` support. It is important register +register fake ops for `torch.compile` support. It is important to register such ops in the namespace that kernel-builder makes for your kernel build. This is required for compliant kernels to ensure that multiple versions of the same kernel can be loaded at the same time without @@ -375,7 +375,7 @@ def relu_fwd_fake(input: torch.Tensor) -> torch.Tensor: As mentioned in the above, the `_ops` module is generated by kernel-builder. -kernel-builder uses a hook to reject incorrect uses Torch op registration +kernel-builder uses a hook to reject incorrect usage of Torch op registration functions. However, it can only catch direct use of certain `torch.library` decorators. For instance, the hook would not reject the following decorator, so it should be seen as a last-resort check if human review failed: From 29c5d4149c123848953a730ac97f757a13b46ecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Tue, 19 May 2026 13:59:50 +0000 Subject: [PATCH 4/4] Use full kernel build for torch-ops-check-hook --- flake.nix | 3 ++- nix-builder/lib/checks.nix | 13 ++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/flake.nix b/flake.nix index 098d8bd84..de60f41bc 100644 --- a/flake.nix +++ b/flake.nix @@ -201,7 +201,8 @@ in rec { checks.default = pkgs.callPackage ./nix-builder/lib/checks.nix { - inherit buildSets; + inherit buildSets self; + inherit (self.lib) genKernelFlakeOutputs; build = buildPerSystem.${system}; }; diff --git a/nix-builder/lib/checks.nix b/nix-builder/lib/checks.nix index d07af79a4..0af2cb998 100644 --- a/nix-builder/lib/checks.nix +++ b/nix-builder/lib/checks.nix @@ -1,11 +1,14 @@ { + self, lib, runCommand, testers, python3, + stdenv, build, buildSets, + genKernelFlakeOutputs, }: let @@ -15,11 +18,11 @@ let }; badRegistrationCheck = testers.testBuildFailure' { - drv = runCommand "check-bad-registration" { buildInputs = [ python3 ]; } '' - python3 ${../pkgs/torch-ops-check/torch-ops-check-hook.py} \ - ${../../examples/kernels/silu-and-mul-bad-registration} - touch $out - ''; + drv = + (genKernelFlakeOutputs { + inherit self; + path = ../../examples/kernels/silu-and-mul-bad-registration; + }).packages.${stdenv.hostPlatform.system}.redistributable.torch-cuda; expectedBuilderExitCode = 1; expectedBuilderLogEntries = [ "Found Torch library registrations that do not use `add_op_namespace_prefix`:"