Merged
feat(exported_custom_op): Add kernel-source introspection and the runtime compile contract #5599
hid22900163Add on Aug 21
feat(exported_custom_op): Add kernel-source introspection and the runtime compile contract #5599
Merged
hid22900163Add on Aug 21
Total: 14 files changed+1281-0
@@ -78,6 +78,8 @@ packages.find.include = [
78 "pypto",78 "pypto",
79 "pypto_pro",79 "pypto_pro",
80 "pypto_pro.*",80 "pypto_pro.*",
81+ "pypto.extensions",
82+ "pypto.extensions.*",
81 "pypto.op",83 "pypto.op",
82 "pypto.include.tilefwk",84 "pypto.include.tilefwk",
83 "pypto.lib",85 "pypto.lib",
@@ -0,0 +1,9 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""pypto extension subpackages (e.g. ``torch_custom_op``) — optional, author/build-time tooling layered on core."""
@@ -0,0 +1,20 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""pypto.extensions.torch_custom_op — pack a pypto kernel into a framework custom-op node.
10+ 
11+This package holds ONLY what concerns the pypto kernel SOURCE: authoring constants (common.authoring),
12+source-manipulation utils (common.source_utils), and the runtime compile contract (common.compile).
13+ 
14+Everything downstream of the kernel source — whole-graph orchestration and the build tooling that turns
15+an exported artifact into a deployable op library — lives with the consuming application, which
16+reconstructs the kernel from the node's embedded snippet. This package describes only the kernel
17+source it packs.
18+"""
19+# Load order matters: common.compile carries no subpackage dependency, so it loads fully first.
20+from .common.compile import * # noqa: F403, I001 - keep the load order described above
@@ -0,0 +1,13 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""Framework-agnostic kernel-source machinery.
10+ 
11+Holds authoring constants (``authoring``), source-manipulation utils (``source_utils``), and the
12+runtime compile contract (``compile``). Nothing here depends on a specific export framework.
13+"""
@@ -0,0 +1,133 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Shared custom-op authoring constants, validation and kernel-form helpers.
12+ 
13+Dependency-free pieces the ``ExportedCustomOp`` authoring path needs: the default ONNX
14+custom-domain coordinates a pypto op exports under, the op_type identifier validation, and the
15+``kernel=`` form helpers (jit-kernel detection, factory-signature classification, kernel-name
16+derivation). Pure ``ast``/``inspect``/``textwrap`` logic; this module stays a leaf.
17+"""
18+import ast
19+import inspect
20+import re
21+import textwrap
22+ 
23+# Default ONNX custom-domain coordinates for a pypto op's node (overridable per op at authoring time).
24+_DEFAULT_DOMAIN = "pypto"
25+_DEFAULT_DOMAIN_OPSET_VERSION = 1
26+ 
27+_OP_TYPE_ID_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
28+ 
29+ 
30+def validate_op_type_identifier(op_type: str) -> None:
31+ """Ensure *op_type* is a safe program identifier (letters, digits, underscore; not digit-leading)."""
32+ if not op_type or not _OP_TYPE_ID_RE.match(op_type):
33+ raise ValueError(
34+ "op_type must be a non-empty identifier (letters, digits, underscore; "
35+ f"must not start with a digit), got {op_type!r}"
36+ )
37+ 
38+ 
39+def _is_jit_kernel(fn) -> bool:
40+ """True if *fn* is a ``@pypto.frontend.jit`` object (the bare-kernel form passed to ``kernel=``).
41+ 
42+ A jit object is a ``JitCallableWrapper`` instance carrying the raw function as
43+ ``_original_func``; a factory is a plain function. Duck-typed to avoid a frontend import.
44+ """
45+ return (not inspect.isfunction(fn)) and hasattr(fn, "_original_func")
46+ 
47+ 
48+def _wrapped_jit_kernel_name(op):
49+ """The name of the function ``@pypto.frontend.jit`` wraps, the default kernel_name for *op*.
50+ 
51+ DIRECT: the jit kernel itself. FACTORY: the inner jit def the factory defines and returns —
52+ found by scanning the factory's source for the first nested def whose decorators include a
53+ ``.jit`` attribute-call, alongside whether any ``return`` carries a value (a factory may bind
54+ then return, branch, or return more than once). The raise below is also the construction-time
55+ gate rejecting a ``kernel=`` plain function that is not a factory: no inner jit def, no value
56+ return, or source that does not parse as a plain function.
57+ """
58+ if op._bare_kernel_fn is not None:
59+ return op._bare_kernel_fn._original_func.__name__
60+ inner_jit_name = None
61+ has_value_return = False
62+ try:
63+ tree = ast.parse(textwrap.dedent(inspect.getsource(op._create_kernel_fn)))
64+ except (OSError, TypeError, SyntaxError):
65+ tree = None
66+ top = tree.body[0] if tree is not None and tree.body else None
67+ if isinstance(top, (ast.FunctionDef, ast.AsyncFunctionDef)):
68+ for node in ast.walk(top):
69+ if node is top:
70+ continue
71+ if isinstance(node, ast.Return) and node.value is not None:
72+ has_value_return = True
73+ if inner_jit_name is None and isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
74+ for dec in node.decorator_list:
75+ call = dec.func if isinstance(dec, ast.Call) else dec
76+ if isinstance(call, ast.Attribute) and call.attr == "jit":
77+ inner_jit_name = node.name
78+ break
79+ if inner_jit_name is None or not has_value_return:
80+ raise ValueError(
81+ "kernel=: could not derive kernel_name from the factory; it must define and return a "
82+ "@pypto.frontend.jit-decorated inner kernel (whose name becomes the op's kernel_name). "
83+ "For a direct kernel, decorate the kernel itself with @pypto.frontend.jit."
84+ )
85+ return inner_jit_name
86+ 
87+ 
88+def _direct_declared_annotations(op):
89+ """Extract author-pinned literal shapes/dtypes from a DIRECT jit kernel's annotations, or ``None``.
90+ 
91+ Reads the cached tensor-defs (``op._bare_kernel_fn._cached_signature[0]``, the inputs-then-output
92+ param list in the order ``CompileEntry._check_declared_mismatches`` zips against) and returns one
93+ ``{"shape": [int]|None, "dtype": "DT_*"|None}`` per param: ``shape`` only when every dim is a
94+ concrete int, ``dtype`` only when one was pinned. ``None`` when no param pins anything.
95+ """
96+ kernel = op._bare_kernel_fn
97+ if kernel is None:
98+ return None
99+ defs = kernel._cached_signature[0]
100+ annotations = []
101+ any_pinned = False
102+ for d in defs:
103+ raw_shape = getattr(d, "shape", None)
104+ if raw_shape is not None and all(isinstance(dim, int) for dim in raw_shape):
105+ shape = [int(dim) for dim in raw_shape]
106+ else:
107+ shape = None
108+ explicit_dtype = getattr(d, "explicit_dtype", None)
109+ dtype = explicit_dtype.name if explicit_dtype is not None else None
110+ if shape is not None or dtype is not None:
111+ any_pinned = True
112+ annotations.append({"shape": shape, "dtype": dtype})
113+ return annotations if any_pinned else None
114+ 
115+ 
116+def _detect_factory_signature(fn) -> str:
117+ """Classify a factory as ``"single"`` / ``"lists"`` / ``"full"`` from its parameter names.
118+ 
119+ Detection is by name, so renaming a factory parameter changes its classification. The three
120+ forms are documented in ``CompileEntry``.
121+ """
122+ params = list(inspect.signature(fn).parameters)
123+ if "attrs" in params:
124+ return "full"
125+ if params and params[0] == "shapes":
126+ return "lists"
127+ if params and params[0] == "shape":
128+ return "single"
129+ raise ValueError(
130+ f"kernel= factory {getattr(fn, '__name__', '?')!r} has an unrecognized signature {params}; "
131+ "it must start with (shape, dtype, ...) [single], (shapes, dtypes, ...) [lists], or "
132+ "(shapes, dtypes, attrs, ...) [full]"
133+ )
@@ -0,0 +1,373 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+"""Custom-op runtime compile entry.
13+ 
14+``CompileEntry`` (constructed with either ``jit_kernel=`` or ``factory=``) satisfies the runtime
15+compile contract: a callable ``(shapes, dtypes, attrs, soc_version) -> path`` that the host runtime
16+invokes by module-attribute name.
17+ 
18+``torch`` and ``pypto`` are resolved through this module's attributes at call time, so the unit
19+tests substitute lightweight fakes without an NPU toolchain (see
20+``python/tests/ut/torch_custom_op/test_op_compile_selftest.py``).
21+"""
22+import inspect
23+import json
24+from typing import Any, Callable, Optional, get_origin
25+import warnings
26+ 
27+import torch
28+ 
29+import pypto
30+ 
31+__all__ = ["CompileEntry"]
32+ 
33+ 
34+# ``str(torch.dtype)`` basename -> the pypto DataType attribute name; mirrors
35+# ``JitCallableWrapper._dtype_dict``. Both sides resolve by getattr at call time (the test seam above).
36+_TORCH_TO_PTO_DTYPE = {
37+ "float16": "DT_FP16",
38+ "float32": "DT_FP32",
39+ "bfloat16": "DT_BF16",
40+ "int8": "DT_INT8",
41+ "int16": "DT_INT16",
42+ "int32": "DT_INT32",
43+ "int64": "DT_INT64",
44+ "uint8": "DT_UINT8",
45+ "bool": "DT_BOOL",
46+}
47+ 
48+ 
49+def _torch_dtype(dtype_str: str):
50+ """``"float16"`` -> ``torch.float16``, restricted to the dtypes the pto mapping covers."""
51+ if dtype_str not in _TORCH_TO_PTO_DTYPE:
52+ raise ValueError(f"Unsupported dtype string '{dtype_str}'")
53+ return getattr(torch, dtype_str)
54+ 
55+ 
56+def _pto_dtype(torch_dtype) -> Any:
57+ """``str(torch.dtype)`` -> ``pypto.DataType``."""
58+ key = str(torch_dtype)
59+ name = _TORCH_TO_PTO_DTYPE.get(key.removeprefix("torch."))
60+ if name is None:
61+ raise ValueError(f"Unsupported dtype for custom op: {key}")
62+ return getattr(pypto, name)
63+ 
64+ 
65+def _as_tuple_of(result, n: int) -> tuple:
66+ """Normalize a hook return (a single shape/dtype, or a sequence of N) to a length-N tuple.
67+ 
68+ A *single* shape is a flat sequence of ints, including the 0-d ``()`` case, or a non-sequence
69+ (e.g. a ``torch.dtype``); a *multi-output* return is a sequence of those.
70+ """
71+ is_seq = isinstance(result, (list, tuple))
72+ looks_single = (not is_seq) or all(isinstance(d, int) for d in result) # () -> single 0-d shape
73+ if is_seq and not looks_single:
74+ out = tuple(result) # sequence of N shapes/dtypes
75+ elif n == 1:
76+ out = (result,) # the single shape/dtype (incl. flat-int shape and 0-d ())
77+ else:
78+ # A single value where n outputs are declared: refusing beats silently splitting a flat
79+ # shape like (8, 64) into n integer "shapes".
80+ raise ValueError(f"inference returned a single value but {n} outputs are declared")
81+ if len(out) != n:
82+ raise ValueError(f"inference returned {len(out)} values, expected {n}")
83+ return out
84+ 
85+ 
86+def _convert_shape_attr(raw, annotation, name: str):
87+ """Convert a stringified attr value to the typed value ``infer_shape`` expects, driven off
88+ the param annotation, the same conversion the kernel factory does (``list[int]`` ->
89+ ``json.loads``, ``int`` -> ``int``) so infer_shape and the factory get identical typed
90+ values. A non-string value (already typed) passes through."""
91+ if not isinstance(raw, str):
92+ return raw
93+ if annotation is list or get_origin(annotation) is list:
94+ return json.loads(raw)
95+ if annotation is int:
96+ return int(raw)
97+ if annotation is str:
98+ return raw
99+ # Unannotated shape-affecting param: accept a JSON-typed value, but never silently hand
100+ # infer_shape an unconverted string.
101+ try:
102+ return json.loads(raw)
103+ except ValueError as exc:
104+ raise ValueError(
105+ f"attr '{name}': cannot convert {raw!r} for infer_shape; annotate the parameter "
106+ f"(int / str / list[int]) or pass a JSON-parseable value"
107+ ) from exc
108+ 
109+ 
110+class CompileEntry:
111+ """Callable runtime kernel-JIT entry: ``op(shapes, dtypes, attrs, soc_version) -> path str``.
112+ 
113+ This is the Python callable the host runtime enters at op-compile time (via the embedded
114+ ``__pypto_compile``): it infers output shapes/dtypes, JIT-builds the pypto kernel for the
115+ runtime shape, and returns the compiled-kernel path (result cached per key). This is the
116+ runtime compile, distinct from any build-time kernel preparation.
117+ 
118+ Pass exactly one of ``jit_kernel=`` (DIRECT: an already-built ``@pypto.frontend.jit`` kernel, no
119+ factory and no synthesis) or ``factory=`` (an existing ``create_*_kernel(shape, dtype,
120+ soc_version) -> jit_obj``), bind the instance to the module attribute name the host runtime
121+ looks the entry up by, and attach optional hooks via ``infer_shape`` / ``infer_dtype``::
122+ 
123+ add_op_compile = CompileEntry(jit_kernel=add_kernel, num_inputs=2, num_outputs=1)
124+ add_op_compile = CompileEntry(factory=create_add_kernel, num_inputs=2)
125+ 
126+ ``num_outputs`` is not derived from the jit wrapper's signature (a ``JitCallableWrapper`` may
127+ not expose a clean one); pass it explicitly for multi-output kernels. ``factory_signature``
128+ names which argument shape the factory takes: ``"single"`` = ``create(shape, dtype, soc)``,
129+ ``"lists"`` = ``create(shapes, dtypes, soc)``, ``"full"`` = ``create(shapes, dtypes, attrs,
130+ soc)``. For a factory taking none of these forms, pass a small adapter lambda.
131+ """
132+ 
133+ def __init__(
134+ self,
135+ *,
136+ num_inputs: int,
137+ num_outputs: int = 1,
138+ factory: Optional[Callable] = None,
139+ jit_kernel: Optional[Callable] = None,
140+ factory_signature: str = "single",
141+ declared_annotations: Optional[list[dict]] = None,
142+ ):
143+ if (factory is None) == (jit_kernel is None):
144+ raise ValueError("Provide exactly one of `factory` or `jit_kernel`")
145+ if factory_signature not in ("single", "lists", "full"):
146+ raise ValueError("factory_signature must be 'single', 'lists', or 'full'")
147+ if num_inputs < 1:
148+ raise ValueError(f"num_inputs must be >= 1, got {num_inputs}")
149+ if num_outputs < 1:
150+ raise ValueError(f"num_outputs must be >= 1, got {num_outputs}")
151+ 
152+ self._num_inputs = num_inputs
153+ self._num_outputs = num_outputs
154+ self._factory = factory
155+ self._jit_kernel = jit_kernel
156+ self._factory_signature = factory_signature
157+ # Author-declared explicit constants (see authoring._direct_declared_annotations); None = no checks.
158+ self._declared_annotations = declared_annotations
159+ self._infer_shape_fn: Optional[Callable] = None
160+ self._infer_dtype_fn: Optional[Callable] = None
161+ self._cache: dict[tuple, str] = {}
162+ 
163+ # The entry's name in every error message: whichever of the two kernel forms was supplied.
164+ entry_target = jit_kernel if jit_kernel is not None else factory
165+ self.__name__ = getattr(entry_target, "__name__", "compile_entry")
166+ 
167+ def __call__(self, shapes, dtypes, attrs, soc_version) -> str:
168+ """Compile for the runtime *shapes*/*dtypes* and return the compiled-kernel path (*soc_version* required)."""
169+ attrs = {} if attrs is None else dict(attrs)
170+ if not soc_version:
171+ raise ValueError(f"{self.__name__}: soc_version is required")
172+ shapes, dtype_strs = self._prepare(shapes, dtypes)
173+ 
174+ # attrs are sorted so the key is order-independent: the same attr dict spelled in any order
175+ # is one cache entry, not several.
176+ key = (shapes, dtype_strs, tuple(sorted(attrs.items())), soc_version)
177+ if key in self._cache:
178+ return self._cache[key]
179+ 
180+ jit_obj, out_shapes, out_torch = self.build_jit(shapes, dtype_strs, soc_version, attrs=attrs)
181+ # The deploy path always validates the hook's output dtypes: _pto_dtype raises for a dtype
182+ # the runtime cannot represent, whether or not the kernel declares annotations.
183+ for dtype in out_torch:
184+ _pto_dtype(dtype)
185+ 
186+ # Dummy values are irrelevant for compilation; torch.empty is dtype-safe across all dtypes.
187+ in_torch = [_torch_dtype(s) for s in dtype_strs]
188+ dummies = [torch.empty(s, dtype=d, device="cpu") for s, d in zip(shapes, in_torch)]
189+ dummies += [torch.empty(s, dtype=d, device="cpu") for s, d in zip(out_shapes, out_torch)]
190+ 
191+ path = str(jit_obj.build_kernel(*dummies))
192+ self._cache[key] = path
193+ return path
194+ 
195+ @property
196+ def infer_shape(self) -> Optional[Callable]:
197+ """The output-shape hook, or ``None`` when the op declares none.
198+ 
199+ *fn* takes one shape (a ``tuple[int]``) per input, plus one trailing parameter per
200+ shape-affecting attr (matched to the attr by name, converted per its annotation), and
201+ returns the output shape, or a sequence of ``num_outputs`` shapes for multi-output ops::
202+ 
203+ def add_infer_shape(a_shape, b_shape):
204+ return a_shape
205+ 
206+ add_op_compile.infer_shape = add_infer_shape
207+ 
208+ Without a hook every output takes ``shapes[0]``.
209+ """
210+ return self._infer_shape_fn
211+ 
212+ @infer_shape.setter
213+ def infer_shape(self, fn: Callable) -> None:
214+ # A non-callable would otherwise surface far from this assignment (deep inside dispatch),
215+ # so reject it here; ``None`` stays valid because a hook-less op legitimately has none.
216+ if fn is not None and not callable(fn):
217+ raise TypeError(f"infer_shape must be callable or None, got {type(fn).__name__}")
218+ self._infer_shape_fn = fn
219+ 
220+ @property
221+ def infer_dtype(self) -> Optional[Callable]:
222+ """The output-dtype hook, or ``None`` when the op declares none.
223+ 
224+ *fn* takes one ``torch.dtype`` per input and returns the output dtype, or a sequence of
225+ ``num_outputs`` dtypes for multi-output ops::
226+ 
227+ def norm_infer_dtype(x_dtype, w_dtype):
228+ return (x_dtype, torch.float32)
229+ 
230+ norm_op_compile.infer_dtype = norm_infer_dtype
231+ 
232+ Without a hook every output takes the first input's dtype.
233+ """
234+ return self._infer_dtype_fn
235+ 
236+ @infer_dtype.setter
237+ def infer_dtype(self, fn: Callable) -> None:
238+ # As with infer_shape: a non-callable is rejected at the assignment rather than deep in
239+ # dispatch, while ``None`` keeps meaning "no hook, every output takes the first input's dtype".
240+ if fn is not None and not callable(fn):
241+ raise TypeError(f"infer_dtype must be callable or None, got {type(fn).__name__}")
242+ self._infer_dtype_fn = fn
243+ 
244+ def _prepare(self, shapes, dtypes):
245+ shapes = tuple(tuple(s) for s in shapes)
246+ dtype_strs = tuple(dtypes)
247+ if len(shapes) != self._num_inputs or len(dtype_strs) != self._num_inputs:
248+ raise ValueError(
249+ f"{self.__name__}: got {len(shapes)} shapes / {len(dtype_strs)} dtypes, "
250+ f"expected num_inputs={self._num_inputs}"
251+ )
252+ return shapes, dtype_strs
253+ 
254+ def infer_outputs(self, shapes, dtypes, attrs=None):
255+ """Return ``(out_shapes, out_torch_dtypes)`` for *shapes*/*dtypes*; inference only, no jit build.
256+ 
257+ Used by the run path to allocate the output tensors when the jit object is produced elsewhere
258+ (the DIRECT-on-NPU re-wrap), so no process-global soc is touched.
259+ """
260+ shapes, dtype_strs = self._prepare(shapes, dtypes)
261+ return self._infer_out_shapes_dtypes(shapes, [_torch_dtype(s) for s in dtype_strs], attrs)
262+ 
263+ def build_jit(self, shapes, dtypes, soc_version=None, run_mode=None, attrs=None):
264+ """Build the pypto jit kernel for *shapes*/*dtypes* and return ``(jit_obj, out_shapes, out_torch_dtypes)``.
265+ 
266+ Layers ``infer_outputs`` with the declared-annotation guard and the jit build (``__call__`` in turn
267+ layers the dummies and ``build_kernel`` on top of this), and returns the live jit object and the
268+ inferred output shapes/dtypes instead of a compiled ``.o`` path; the run path allocates the outputs
269+ from these and invokes the jit kernel directly.
270+ 
271+ *run_mode* (a ``pypto.RunMode``) is forwarded only for the factory form (its inner jit binds it as a
272+ closure param); DIRECT kernels pin run_mode at decoration, so the caller re-wraps for NPU separately.
273+ 
274+ ``soc_version`` is forwarded unchanged on this run path: a ``None`` soc stays ``None`` (pinning a
275+ SIM soc onto an NPU factory build would mis-target it). When ``None`` the factory's inner
276+ ``@jit(codegen_options={"soc_version": None})`` lets ``set_codegen_options`` drop the key so the
277+ framework auto-detects on-device. (The deploy/compile path is ``__call__``, which requires a soc.)
278+ """
279+ attrs = {} if attrs is None else dict(attrs)
280+ shapes, dtype_strs = self._prepare(shapes, dtypes)
281+ in_pto = [_pto_dtype(_torch_dtype(s)) for s in dtype_strs]
282+ out_shapes, out_torch = self.infer_outputs(shapes, dtype_strs, attrs)
283+ if self._declared_annotations:
284+ out_pto = [_pto_dtype(d) for d in out_torch]
285+ self._check_declared_mismatches(shapes, in_pto, out_shapes, out_pto)
286+ if self._jit_kernel is not None:
287+ # The author's jit kernel is used as-is (the dummies drive every tensor's shape and dtype);
288+ # only the process-global soc is pinned. DIRECT mode therefore requires a jit decorator
289+ # that pins no ``soc_version``: pypto's per-wrapper setter would otherwise clobber the
290+ # global at build time and silently mis-target the build.
291+ pypto.set_codegen_options(soc_version=soc_version)
292+ jit_obj = self._jit_kernel
293+ else:
294+ jit_obj = self._build_jit_from_factory(shapes, in_pto, soc_version, attrs, run_mode=run_mode)
295+ return jit_obj, out_shapes, out_torch
296+ 
297+ # ---- internals ----
298+ def _infer_shape_run_args(self, in_shapes, attrs):
299+ """Positional args for an ``infer_shape`` call: the tensor shapes, then any shape-affecting
300+ attr values (the infer_shape params beyond the tensor count ``_num_inputs``), each looked
301+ up in *attrs* by param name and converted from its stringified form. A shape-invariant op
302+ has no trailing infer_shape params, so this returns just the shapes (call is
303+ ``infer_shape(*shapes)``)."""
304+ args = list(in_shapes)
305+ if self._infer_shape_fn is None:
306+ return args
307+ trailing = list(inspect.signature(self._infer_shape_fn).parameters.values())[self._num_inputs:]
308+ if not trailing:
309+ return args
310+ attrs = attrs or {}
311+ for p in trailing:
312+ args.append(_convert_shape_attr(attrs[p.name], p.annotation, p.name))
313+ return args
314+ 
315+ def _infer_out_shapes_dtypes(self, in_shapes, in_torch_dtypes, attrs=None) -> tuple:
316+ """``(out_shapes, out_torch_dtypes)``; without a hook every output takes the first input's value."""
317+ if self._infer_shape_fn is not None: # attrs feed a shape-affecting infer_shape
318+ out_shapes = _as_tuple_of(
319+ self._infer_shape_fn(*self._infer_shape_run_args(in_shapes, attrs)), self._num_outputs
320+ )
321+ else:
322+ out_shapes = tuple(in_shapes[0] for _ in range(self._num_outputs))
323+ if self._infer_dtype_fn is not None:
324+ out_dtypes = _as_tuple_of(self._infer_dtype_fn(*in_torch_dtypes), self._num_outputs)
325+ else:
326+ out_dtypes = tuple(in_torch_dtypes[0] for _ in range(self._num_outputs))
327+ return out_shapes, out_dtypes
328+ 
329+ def _check_declared_mismatches(self, in_shapes, in_pto, out_shapes, out_pto) -> None:
330+ """Enforce author-declared explicit-constant annotations against the runtime values.
331+ 
332+ Only fires for explicit constants (a literal shape / a ``DT_*`` dtype recorded at synthesis);
333+ placeholder and variable annotations recorded ``None`` and are skipped. Policy:
334+ 
335+ * a dtype mismatch raises, since a pinned ``explicit_dtype`` silently overrides the dtype the
336+ runtime hands the op (a genuine correctness hazard), so it is a hard error (input and output);
337+ * a shape mismatch warns, since a pinned shape is informational and the dummy drives the real shape.
338+ """
339+ # declared_annotations has one entry per kernel positional param (inputs then output slots);
340+ # zip against (inputs + inferred outputs). Output-slot entries are always erased
341+ # ({None,None}), so any length divergence only drops non-checkable None entries.
342+ tensors = list(zip(in_shapes, in_pto)) + list(zip(out_shapes, out_pto))
343+ for idx, (decl, (shp, pto)) in enumerate(zip(self._declared_annotations, tensors)):
344+ kind = "input" if idx < self._num_inputs else "output"
345+ j = idx if kind == "input" else idx - self._num_inputs
346+ d_shape = decl.get("shape")
347+ if d_shape is not None and list(d_shape) != list(shp):
348+ warnings.warn(
349+ f"{self.__name__}: declared {kind}[{j}] shape {list(d_shape)} != runtime {list(shp)}",
350+ stacklevel=2,
351+ )
352+ d_dtype = decl.get("dtype")
353+ if d_dtype is not None:
354+ # Resolve the declared "DT_*" token to a pypto.DataType and compare the enums directly
355+ # (the enum stringifies to its int value, so compare objects, not str forms).
356+ resolved = getattr(pypto, d_dtype, None)
357+ if resolved is not None and resolved != pto:
358+ runtime_name = getattr(pto, "name", None) or str(pto)
359+ raise ValueError(
360+ f"{self.__name__}: declared {kind}[{j}] dtype {d_dtype} != runtime {runtime_name}; "
361+ f"a pinned dtype silently overrides the runtime dtype, fix the pinned annotation "
362+ f"or infer_dtype so they agree"
363+ )
364+ 
365+ def _build_jit_from_factory(self, shapes, in_pto, soc_version, attrs, run_mode=None):
366+ # run_mode is forwarded only when explicitly requested (the run path's NPU mode); the factory's
367+ # own default (SIM) stands otherwise.
368+ kw = {} if run_mode is None else {"run_mode": run_mode}
369+ if self._factory_signature == "single": # create(shape, dtype, soc[, run_mode])
370+ return self._factory(shapes[0], in_pto[0], soc_version, **kw)
371+ if self._factory_signature == "full": # create(shapes, dtypes, attrs, soc[, run_mode]); attrs-aware
372+ return self._factory(list(shapes), list(in_pto), dict(attrs), soc_version, **kw)
373+ return self._factory(list(shapes), list(in_pto), soc_version, **kw) # "lists": create(shapes, dtypes, soc)
@@ -0,0 +1,184 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Source-text and function-introspection utils for kernel authoring.
12+ 
13+Capture and reshape a function's source for the embedded compile snippet (strip decorator lines,
14+drop a leading ``@<recv>.kernel`` op-marker), plus the canonical-naming, span-editing and symtable
15+scope-analysis primitives the multi-file kernel tracer uses.
16+"""
17+import ast
18+import re
19+import symtable
20+ 
21+ 
22+def _unwrap_decorated_func_source(source: str) -> str:
23+ """Return the def ... body of a function, stripping decorator lines."""
24+ return source[source.find("def "):]
25+ 
26+ 
27+# ---- identity-based canonical naming ----
28+ 
29+_NON_IDENT_RE = re.compile(r"[^A-Za-z0-9_]")
30+ 
31+ 
32+def _sanitize(s: str) -> str:
33+ """Turn a module/qualname string into a valid Python identifier fragment.
34+ 
35+ ``.`` becomes ``__``; every other non-``[A-Za-z0-9_]`` char becomes a single ``_``.
36+ """
37+ return _NON_IDENT_RE.sub("_", s.replace(".", "__"))
38+ 
39+ 
40+# ---- byte-to-char span editor ----
41+ 
42+def _line_start_offsets(src: str) -> list[int]:
43+ """Absolute char offset at which each 1-based source line begins.
44+ 
45+ Index ``i`` is the start of line ``i+1``, with a trailing entry so a node ending at EOF is
46+ representable.
47+ """
48+ starts = [0]
49+ offset = 0
50+ for line in src.splitlines(keepends=True):
51+ offset += len(line)
52+ starts.append(offset)
53+ return starts
54+ 
55+ 
56+def _byte_col_to_char_col(line: str, byte_col: int) -> int:
57+ """Convert an AST ``col_offset`` (a UTF-8 byte offset into *line*) to a char column.
58+ 
59+ ``ast`` reports columns as byte offsets; a non-ASCII identifier (e.g. a Greek letter) occupies
60+ multiple bytes, so a byte offset must be decoded back to a char index to slice the raw text.
61+ """
62+ if byte_col <= 0:
63+ return 0
64+ return len(line.encode("utf-8")[:byte_col].decode("utf-8", "surrogatepass"))
65+ 
66+ 
67+def _node_char_span(node: ast.AST, line_starts: list[int], lines: list[str]) -> tuple[int, int]:
68+ """Absolute ``(start, end)`` char offsets of *node* within the source, or ``(-1, -1)``.
69+ 
70+ Converts the node's byte ``col_offset``/``end_col_offset`` to char columns against each line's
71+ text. *lines* is ``src.splitlines(keepends=True)``.
72+ """
73+ if node.lineno is None or getattr(node, "end_lineno", None) is None:
74+ return (-1, -1)
75+ start_line = lines[node.lineno - 1] if node.lineno - 1 < len(lines) else ""
76+ end_line = lines[node.end_lineno - 1] if node.end_lineno - 1 < len(lines) else ""
77+ start = line_starts[node.lineno - 1] + _byte_col_to_char_col(start_line, node.col_offset)
78+ end = line_starts[node.end_lineno - 1] + _byte_col_to_char_col(end_line, node.end_col_offset)
79+ return (start, end)
80+ 
81+ 
82+def _stmt_line_span(node: ast.AST, src: str, line_starts: list[int], lines: list[str]) -> tuple[int, int]:
83+ """Whole-line char span of a statement node (incl. the trailing newline), for clean deletion.
84+ 
85+ Extends the node's span to its first line's start and past its last line's end, so a
86+ multi-line statement is removed whole without leaving a stray blank line.
87+ """
88+ node_start, node_end = _node_char_span(node, line_starts, lines)
89+ if node_start < 0:
90+ return (-1, -1)
91+ start = line_starts[node.lineno - 1] # beginning of the statement's first physical line
92+ end_line_idx = getattr(node, "end_lineno", node.lineno) - 1
93+ end = line_starts[end_line_idx + 1] if end_line_idx + 1 < len(line_starts) else len(src)
94+ return (start, end)
95+ 
96+ 
97+def _annotation_delete_spans(
98+ func_def: ast.AST, src: str, line_starts: list[int], lines: list[str]
99+) -> list[tuple[ast.AST, tuple[int, int]]]:
100+ """``(annotation node, delete span)`` per annotated param of *func_def*, then its return annotation.
101+ 
102+ A param span is ``[name_end .. annotation_end]``, covering the ``: Foo`` of ``def f(x: Foo = 3)``:
103+ anchored just past the arg's own identifier (its ``lineno``/``col_offset`` plus the byte-to-char
104+ safe name length), never a backward ``:`` scan, so the ``= 3`` default is preserved and a preceding
105+ param is never touched. The return span is ``[arrow .. returns_end]``, its ``->`` located by a
106+ bounded ``rfind`` so the whitespace between arrow and annotation goes too. A span that cannot be
107+ located is ``(-1, -1)``.
108+ """
109+ args = func_def.args
110+ slots: list[tuple[ast.AST, tuple[int, int]]] = []
111+ for arg in (*args.posonlyargs, *args.args, *args.kwonlyargs):
112+ if arg.annotation is None:
113+ continue
114+ line = lines[arg.lineno - 1] if arg.lineno - 1 < len(lines) else ""
115+ start = line_starts[arg.lineno - 1] + _byte_col_to_char_col(line, arg.col_offset) + len(arg.arg)
116+ slots.append((arg.annotation, (start, _node_char_span(arg.annotation, line_starts, lines)[1])))
117+ returns = getattr(func_def, "returns", None)
118+ if returns is not None:
119+ ret_start, ret_end = _node_char_span(returns, line_starts, lines)
120+ # The last ``->`` before the annotation is the return arrow (the arg list is already closed).
121+ arrow = src.rfind("->", line_starts[func_def.lineno - 1], ret_start) if ret_start >= 0 else -1
122+ slots.append((returns, (arrow, ret_end) if arrow >= 0 else (-1, -1)))
123+ return slots
124+ 
125+ 
126+def _apply_span_replacements(src: str, replacements: list[tuple[int, int, str]]) -> str:
127+ """Apply ``(start, end, text)`` char-offset replacements to *src*, non-overlapping.
128+ 
129+ Candidates are taken in (start, longest-first) order and a span overlapping an already-chosen
130+ one is dropped; edits are applied in descending start order so earlier edits never shift later
131+ spans. Never re-parses, so the comments and formatting the jit parser re-reads survive.
132+ """
133+ chosen: list[tuple[int, int, str]] = []
134+ occupied: list[tuple[int, int]] = []
135+ for start, end, text in sorted(replacements, key=lambda r: (r[0], -(r[1]))):
136+ if start < 0 or end < start:
137+ continue
138+ if any(not (end <= os or start >= oe) for os, oe in occupied):
139+ continue # overlaps an already-chosen span
140+ chosen.append((start, end, text))
141+ occupied.append((start, end))
142+ out = src
143+ for start, end, text in sorted(chosen, key=lambda r: r[0], reverse=True):
144+ out = out[:start] + text + out[end:]
145+ return out
146+ 
147+ 
148+# ---- symtable-based global-load scope analysis ----
149+ 
150+def _scope_classify(src: str) -> tuple[set[str], set[str]]:
151+ """``(global-load names, ambiguous names)`` for *src* via ``symtable``.
152+ 
153+ ``symtable`` is used because it is version-robust: the bytecode ``co_consts``/AST lockstep is
154+ broken on 3.12+, where PEP 709 inlines comprehensions. Every lexical scope is walked (module +
155+ nested function/class/lambda/comprehension). A name is a global load iff in some scope its
156+ symbol ``is_global()`` and is referenced; locals, parameters, comprehension/lambda vars,
157+ assignment targets and ``global``/``nonlocal`` decls are excluded. A name that is a global load
158+ in one scope but locally bound in another (shadow-and-global-use) is ambiguous and comes back
159+ in the second set; the span editor cannot decide those per-occurrence, so callers raise.
160+ """
161+ try:
162+ table = symtable.symtable(src, "<snip>", "exec")
163+ except (SyntaxError, ValueError):
164+ return set(), set()
165+ global_loads: set[str] = set()
166+ locally_bound: set[str] = set()
167+ 
168+ def _visit(scope: symtable.SymbolTable) -> None:
169+ for sym in scope.get_symbols():
170+ name = sym.get_name()
171+ # ``is_global()`` covers implicit module-level frees + explicit ``global`` decls;
172+ # ``is_referenced()`` excludes a store-only ``global x; x = 5``.
173+ if sym.is_global() and sym.is_referenced():
174+ global_loads.add(name)
175+ # A local binding (parameter / assignment target / for-target / comp var) shadows the
176+ # module global in this scope.
177+ if sym.is_local() and not sym.is_global():
178+ locally_bound.add(name)
179+ for child in scope.get_children():
180+ _visit(child)
181+ 
182+ _visit(table)
183+ ambiguous = global_loads & locally_bound
184+ return global_loads, ambiguous
@@ -19,6 +19,8 @@ from enum import IntEnum
19import inspect19import inspect
20import itertools20import itertools
21import os21import os
22+from pathlib import Path
23+import threading
22from typing import Any, Callable, Optional, Union24from typing import Any, Callable, Optional, Union
23 25 
24import torch26import torch
@@ -39,6 +41,10 @@ from pypto.logging import log_debug
39from pypto.pil.compile_pipeline import compile_new_ir41from pypto.pil.compile_pipeline import compile_new_ir
40from pypto.runtime import _pto_verify_datas, setup_verify_data42from pypto.runtime import _pto_verify_datas, setup_verify_data
41 43 
44+# Only one build_kernel() at a time: recording mutates interpreter-wide state (the C++ Program
45+# singleton, the jit_scope stack). Reentrant so a nested call hits the parser's error, not a deadlock.
46+_GLOBAL_BUILD_STATE_LOCK = threading.RLock()
47+ 
42 48 
43def _default_globals() -> dict[str, Any]:49def _default_globals() -> dict[str, Any]:
44 """Get the default global variables for parsing.50 """Get the default global variables for parsing.
@@ -710,6 +716,49 @@ class JitCallableWrapper:
710 self.compile(pto_tensors)716 self.compile(pto_tensors)
711 self._run_with_cpu(pto_tensors, [])717 self._run_with_cpu(pto_tensors, [])
712 718 
719+ def build_kernel(self, *args: Any, **kwargs: Any) -> Path:
720+ """Build this kernel to a device object file and return its path.
721+ 
722+ Parses ``*args``/``**kwargs`` the same way ``__call__`` does and compiles under a ``jit_scope``.
723+ 
724+ Returns
725+ -------
726+ Path
727+ The single object file the backend emitted under ``LogTopFolder()/kernel_aicore``.
728+ 
729+ Raises
730+ ------
731+ RuntimeError
732+ If the emitted-object count is not exactly one.
733+ """
734+ with _GLOBAL_BUILD_STATE_LOCK:
735+ in_tensors, non_tensor_values, input_tensor_defs = self._parse_call_args(
736+ args, kwargs
737+ )
738+ self._get_or_create_kmodule(non_tensor_values)
739+ 
740+ pto_tensors = self._convert_tensors_with_metadata(
741+ in_tensors, input_tensor_defs
742+ )
743+ with pypto.options("jit_scope"):
744+ self._set_config_option()
745+ pypto_impl.DeviceInit()
746+ self.compile(pto_tensors)
747+ 
748+ # Match on the extension only: the stem is a backend-internal magic name.
749+ # The log folder is re-created per recorded function, so this dir only ever holds the
750+ # current build's output.
751+ output_path = Path(pypto_impl.LogTopFolder()) / "kernel_aicore"
752+ matches = list(output_path.glob("*.o"))
753+ if len(matches) != 1:
754+ raise RuntimeError(
755+ f"Expected exactly 1 kernel object (*.o) under {output_path}, found {len(matches)}: "
756+ f"{sorted(m.name for m in matches)}. This deploy entry supports single-object kernels only - "
757+ f"a partitioned (cloud-soc) or control-flow kernel produces several objects and cannot be "
758+ f"deployed through this path."
759+ )
760+ return matches[0]
761+ 
713 def _check_input_defs_match_tensors(self, in_tensors: list, input_tensor_defs: list[pypto.Tensor]) -> None:762 def _check_input_defs_match_tensors(self, in_tensors: list, input_tensor_defs: list[pypto.Tensor]) -> None:
714 """Check if the input tensor definitions match the input tensors."""763 """Check if the input tensor definitions match the input tensors."""
715 764 
@@ -0,0 +1,40 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""DIRECT (``@pypto.frontend.jit``) kernel samples whose parameter annotations drive the
12+declared-annotations extraction: one pinning a literal shape + dtype on every param, one fully erased.
13+ 
14+They live in a real module so ``inspect.getsource`` and pypto's jit parser both see real source on
15+disk. The module is a leaf: it references only ``pypto``, so importing it needs no fixture package.
16+"""
17+ 
18+import pypto
19+ 
20+ 
21+# Pinned DIRECT kernel: literal shape + dtype on every param; drives the declared-annotations extraction.
22+@pypto.frontend.jit(runtime_options={"run_mode": pypto.RunMode.SIM})
23+def direct_add_kernel_pinned(
24+ input0: pypto.Tensor([1, 1, 8, 64], pypto.DT_FP16),
25+ input1: pypto.Tensor([1, 1, 8, 64], pypto.DT_FP16),
26+ output: pypto.Tensor([1, 1, 8, 64], pypto.DT_FP16),
27+):
28+ pypto.set_vec_tile_shapes(1, 4, 1, 64)
29+ output.move(input0 + input1)
30+ 
31+ 
32+# Erased (pinned-free) DIRECT kernel referencing only pypto: no pinned constant, no helper def to pack.
33+@pypto.frontend.jit(runtime_options={"run_mode": pypto.RunMode.SIM})
34+def direct_add_kernel_erased(
35+ input0: pypto.Tensor([...]),
36+ input1: pypto.Tensor([...]),
37+ output: pypto.Tensor([...]),
38+):
39+ pypto.set_vec_tile_shapes(1, 4, 1, 64)
40+ output.move(input0 + input1)
@@ -0,0 +1,45 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Unit tests for the declared-annotations extraction (``_direct_declared_annotations``).
12+ 
13+Extracts author-pinned literal shapes/dtypes from a DIRECT ``@pypto.frontend.jit`` kernel's annotations
14+(reads the cached parsed signature). Building a real ``JitCallableWrapper`` needs the native ``pypto_impl``
15+on the import path; unlike ``test_from_jit_kernel.py`` there is no skip guard, so collection fails without
16+it. The helper reads only ``op._bare_kernel_fn``, so a plain namespace stands in for the ``ExportedCustomOp``.
17+"""
18+import types
19+ 
20+import kernel_compile_samples as samples # sibling fixture module (pytest puts this dir on sys.path)
21+ 
22+from pypto.extensions.torch_custom_op.common.authoring import _direct_declared_annotations
23+ 
24+ 
25+def _op(kernel):
26+ return types.SimpleNamespace(_bare_kernel_fn=kernel)
27+ 
28+ 
29+def test_extract_pinned_returns_full_entry_list():
30+ ann = _direct_declared_annotations(_op(samples.direct_add_kernel_pinned))
31+ # 3 params (input0, input1, output), each pinning shape [1,1,8,64] + DT_FP16
32+ assert ann == [
33+ {"shape": [1, 1, 8, 64], "dtype": "DT_FP16"},
34+ {"shape": [1, 1, 8, 64], "dtype": "DT_FP16"},
35+ {"shape": [1, 1, 8, 64], "dtype": "DT_FP16"},
36+ ]
37+ 
38+ 
39+def test_extract_erased_returns_none():
40+ # Fully-erased kernel (every param [...] with no dtype) -> None so erased demos stay byte-identical.
41+ assert _direct_declared_annotations(_op(samples.direct_add_kernel_erased)) is None
42+ 
43+ 
44+def test_extract_no_bare_kernel_returns_none():
45+ assert _direct_declared_annotations(_op(None)) is None
@@ -0,0 +1,38 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Unit tests for ``pypto.extensions.torch_custom_op.common.source_utils``."""
12+ 
13+import textwrap
14+ 
15+from pypto.extensions.torch_custom_op.common.source_utils import _unwrap_decorated_func_source
16+ 
17+ 
18+def test_unwrap_decorated_func_source_strips_leading_decorator_block():
19+ raw = textwrap.dedent(
20+ '''\
21+ @some_decorator
22+ @another
23+ def foo(a, b):
24+ return a + b
25+ '''
26+ )
27+ out = _unwrap_decorated_func_source(raw)
28+ assert out.startswith("def foo(")
29+ assert "@some_decorator" not in out
30+ assert "return a + b" in out
31+ 
32+ plain = textwrap.dedent(
33+ '''\
34+ def bar():
35+ return 42
36+ '''
37+ )
38+ assert _unwrap_decorated_func_source(plain) == plain # a plain def is returned unchanged
@@ -0,0 +1,51 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Real-backend check for DIRECT mode (``CompileEntry(jit_kernel=...)``): the kernel carries no
12+``soc_version``, so the soc must reach the build through the process-global setter the entry pins.
13+SIM-builds the kernel and asserts a ``.o`` is produced; skips when the SIM backend is unavailable.
14+"""
15+import pytest
16+ 
17+ 
18+def test_from_jit_kernel_real_build_produces_kernel():
19+ pytest.importorskip("pypto")
20+ import pypto
21+ from pypto.extensions.torch_custom_op.common.compile import CompileEntry
22+ 
23+ # DIRECT: a bare @pypto.frontend.jit kernel with erased annotations and no soc_version, so soc
24+ # arrives solely through the entry's process-global set_codegen_options(soc_version=...).
25+ @pypto.frontend.jit(runtime_options={"run_mode": pypto.RunMode.SIM})
26+ def add_kernel(
27+ input0: pypto.Tensor([...]),
28+ input1: pypto.Tensor([...]),
29+ output: pypto.Tensor([...]),
30+ ):
31+ pypto.set_vec_tile_shapes(1, 4, 1, 64)
32+ output.move(input0 + input1)
33+ 
34+ entry = CompileEntry(jit_kernel=add_kernel, num_inputs=2, num_outputs=1)
35+ 
36+ def infer_shape(x_shape, y_shape):
37+ return x_shape
38+ 
39+ def infer_dtype(x_dtype, y_dtype):
40+ return x_dtype
41+ 
42+ entry.infer_shape = infer_shape
43+ entry.infer_dtype = infer_dtype
44+ 
45+ try:
46+ # soc_version passed only as the 4th positional arg, so the entry threads it to the global setter.
47+ path = entry(((1, 8, 1, 64), (1, 8, 1, 64)), ("float16", "float16"), {}, "Kirin9030")
48+ except Exception as e: # noqa: BLE001 - a missing backend has no single statically known raise type
49+ pytest.skip(f"DIRECT build unavailable on this host (backend): {type(e).__name__}: {str(e)[:160]}")
50+ 
51+ assert path and str(path).endswith(".o"), path
@@ -0,0 +1,184 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Unit tests for the factory form of ``CompileEntry``.
12+ 
13+The compile module's ``torch``/``pypto`` attributes are monkeypatched with fakes, so the contract logic
14+runs without the NPU toolchain; importing the module under test still requires pypto on the path.
15+"""
16+import importlib
17+import types
18+ 
19+import pytest
20+ 
21+from pypto.extensions.torch_custom_op.common.compile import CompileEntry, _as_tuple_of
22+ 
23+_cop = importlib.import_module("pypto.extensions.torch_custom_op.common.compile") # to patch its seams
24+ 
25+ 
26+class _FakeTensor:
27+ def __init__(self, shape, dtype):
28+ self.shape, self.dtype = tuple(shape), dtype
29+ 
30+ def __repr__(self):
31+ return f"T{self.shape}:{self.dtype}"
32+ 
33+ 
34+@pytest.fixture
35+def fake_backend(monkeypatch):
36+ """Patch the compile module's torch/pypto seams with toolchain-free fakes."""
37+ fake_torch = types.SimpleNamespace(
38+ float16="torch.float16", float32="torch.float32", int32="torch.int32",
39+ bfloat16="torch.bfloat16",
40+ empty=lambda shape, dtype, device="cpu": _FakeTensor(shape, dtype),
41+ )
42+ monkeypatch.setattr(_cop, "torch", fake_torch)
43+ monkeypatch.setattr(_cop, "_pto_dtype", lambda td: f"pto:{td}")
44+ return fake_torch
45+ 
46+ 
47+def test_as_tuple_of():
48+ # single vs N-tuple disambiguation, incl. the 0-d output case
49+ assert _as_tuple_of((8, 64), 1) == ((8, 64),)
50+ assert _as_tuple_of((), 1) == ((),)
51+ assert _as_tuple_of("torch.float16", 1) == ("torch.float16",)
52+ assert _as_tuple_of(((8, 64), (8,)), 2) == ((8, 64), (8,))
53+ assert _as_tuple_of(("a", "b"), 2) == ("a", "b")
54+ with pytest.raises(ValueError):
55+ _as_tuple_of(((8, 64),), 2) # wrong count
56+ with pytest.raises(ValueError):
57+ _as_tuple_of((8, 64), 2) # a single flat shape must not be split into 2 scalar "shapes"
58+ 
59+ 
60+def test_from_factory_basic_and_caching(fake_backend):
61+ calls = {"factory": [], "build": []}
62+ 
63+ def fake_create_add_kernel(shape, dtype, soc_version):
64+ calls["factory"].append((tuple(shape), dtype, soc_version))
65+ 
66+ class _Jit:
67+ def build_kernel(self, *tensors):
68+ calls["build"].append([(t.shape, t.dtype) for t in tensors])
69+ return f"/tmp/kernel_{tuple(shape)}.o"
70+ return _Jit()
71+ 
72+ add_op_compile = CompileEntry(factory=fake_create_add_kernel, num_inputs=2)
73+ 
74+ p1 = add_op_compile(((8, 64), (8, 64)), ("float16", "float16"), {}, "Kirin9030")
75+ assert p1 == "/tmp/kernel_(8, 64).o", p1
76+ assert calls["factory"] == [((8, 64), "pto:torch.float16", "Kirin9030")], calls["factory"]
77+ # 2 inputs + 1 inferred output
78+ assert calls["build"][-1] == [((8, 64), "torch.float16")] * 3, calls["build"][-1]
79+ 
80+ # an identical key hits the cache; a different shape recompiles
81+ add_op_compile(((8, 64), (8, 64)), ("float16", "float16"), {}, "Kirin9030")
82+ assert len(calls["factory"]) == 1, calls["factory"]
83+ add_op_compile(((256, 64), (256, 64)), ("float16", "float16"), {}, "Kirin9030")
84+ assert len(calls["factory"]) == 2, calls["factory"]
85+ 
86+ # single-input op; soc_version is required (the host always supplies it)
87+ op1 = CompileEntry(
88+ factory=lambda s, d, v: types.SimpleNamespace(build_kernel=lambda *t: f"/tmp/one_{tuple(s)}.o"),
89+ num_inputs=1)
90+ assert op1(((8, 64),), ("float32",), {}, "Kirin9030").endswith("one_(8, 64).o")
91+ with pytest.raises(ValueError, match="soc_version"):
92+ op1(((8, 64),), ("float32",), {}, None)
93+ 
94+ 
95+def test_matmul_lists_factory(fake_backend):
96+ # matmul: different input shapes, heterogeneous input dtypes, out shape != in[0]
97+ mm = {}
98+ 
99+ def fake_mm_factory(shapes, dtypes, soc):
100+ mm["factory"] = ([tuple(s) for s in shapes], list(dtypes), soc)
101+ 
102+ def build_kernel(*tensors):
103+ mm["build"] = [(t.shape, t.dtype) for t in tensors]
104+ return "/tmp/mm.o"
105+ return types.SimpleNamespace(build_kernel=build_kernel)
106+ 
107+ matmul_op = CompileEntry(factory=fake_mm_factory, num_inputs=2, factory_signature="lists")
108+ 
109+ def _mm_infer_shape(a_shape, b_shape):
110+ return (a_shape[0], b_shape[1]) # C[M,N] = A[M,K] @ B[K,N]
111+ 
112+ matmul_op.infer_shape = _mm_infer_shape
113+ 
114+ pmm = matmul_op(((8, 16), (16, 32)), ("float16", "int32"), {}, "Kirin9030")
115+ assert pmm == "/tmp/mm.o"
116+ assert mm["factory"] == ([(8, 16), (16, 32)],
117+ ["pto:torch.float16", "pto:torch.int32"], "Kirin9030"), mm["factory"]
118+ # A(8,16) fp16 + B(16,32) int32 inputs, then the hook-inferred C(8,32) output (dtype of in[0])
119+ assert mm["build"] == [((8, 16), "torch.float16"), ((16, 32), "torch.int32"),
120+ ((8, 32), "torch.float16")], mm["build"]
121+ 
122+ 
123+def test_multi_output_mixed_dtypes(fake_backend):
124+ # norm -> (y, rstd), mixed output dtypes (y=fp16, rstd=fp32)
125+ nm = {}
126+ 
127+ def fake_norm_factory(shapes, dtypes, soc):
128+ def build_kernel(*tensors):
129+ nm["build"] = [(t.shape, t.dtype) for t in tensors]
130+ return "/tmp/norm.o"
131+ return types.SimpleNamespace(build_kernel=build_kernel)
132+ 
133+ norm_op = CompileEntry(
134+ factory=fake_norm_factory, num_inputs=2, num_outputs=2, factory_signature="lists")
135+ 
136+ def _norm_infer_shape(x_shape, w_shape):
137+ return (x_shape, (x_shape[0],)) # y like x; rstd is per-row
138+ 
139+ norm_op.infer_shape = _norm_infer_shape
140+ 
141+ def _norm_infer_dtype(x_dtype, w_dtype):
142+ return (x_dtype, fake_backend.float32) # y keeps dtype; rstd is fp32
143+ 
144+ norm_op.infer_dtype = _norm_infer_dtype
145+ 
146+ pn = norm_op(((8, 64), (64,)), ("float16", "float16"), {}, "Kirin9030")
147+ assert pn == "/tmp/norm.o"
148+ # inputs x(8,64) w(64,); outputs y(8,64) fp16, rstd(8,) fp32
149+ assert nm["build"] == [((8, 64), "torch.float16"), ((64,), "torch.float16"),
150+ ((8, 64), "torch.float16"), ((8,), "torch.float32")], nm["build"]
151+ 
152+ 
153+def test_full_factory_attrs(fake_backend):
154+ # factory_signature="full": attrs forwarded to the factory (e.g. rmsnorm eps)
155+ fl = {}
156+ 
157+ def fake_full_factory(shapes, dtypes, attrs, soc):
158+ fl["call"] = ([tuple(s) for s in shapes], list(dtypes), dict(attrs), soc)
159+ return types.SimpleNamespace(build_kernel=lambda *t: "/tmp/full.o")
160+ 
161+ full_op = CompileEntry(factory=fake_full_factory, num_inputs=2, factory_signature="full")
162+ pf = full_op(((8, 64), (64,)), ("float16", "float16"), {"eps": "1e-6"}, "Kirin9030")
163+ assert pf == "/tmp/full.o"
164+ assert fl["call"] == ([(8, 64), (64,)], ["pto:torch.float16", "pto:torch.float16"],
165+ {"eps": "1e-6"}, "Kirin9030"), fl["call"]
166+ 
167+ 
168+@pytest.mark.parametrize("hook", ["infer_shape", "infer_dtype"])
169+def test_infer_hook_setters_reject_non_callables(hook):
170+ """The hooks are assigned by name (``entry.infer_shape = fn``), so a typo'd non-callable would
171+ otherwise only surface deep inside dispatch. ``None`` stays valid: a hook-less op has none."""
172+ entry = CompileEntry(factory=lambda shape, dtype, soc: None, num_inputs=1)
173+ 
174+ with pytest.raises(TypeError, match=f"{hook} must be callable or None, got int"):
175+ setattr(entry, hook, 42)
176+ 
177+ setattr(entry, hook, None)
178+ assert getattr(entry, hook) is None
179+ 
180+ def _hook(a):
181+ return a
182+ 
183+ setattr(entry, hook, _hook)
184+ assert getattr(entry, hook) is _hook
@@ -0,0 +1,140 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Unit tests for the declared-annotation guard in ``CompileEntry``: a shape mismatch warns, a dtype
12+mismatch raises. The compile module's ``torch``/``pypto`` attributes are monkeypatched with fakes.
13+"""
14+import importlib
15+import types
16+import warnings
17+ 
18+import pytest
19+ 
20+from pypto.extensions.torch_custom_op.common.compile import CompileEntry
21+ 
22+_cop = importlib.import_module("pypto.extensions.torch_custom_op.common.compile")
23+ 
24+ 
25+def _install_mocks(monkeypatch):
26+ class _T:
27+ def __init__(self, shape, dtype):
28+ self.shape, self.dtype = tuple(shape), dtype
29+ 
30+ fake_torch = types.SimpleNamespace(
31+ float16="torch.float16", int32="torch.int32",
32+ empty=lambda shape, dtype, device="cpu": _T(shape, dtype),
33+ )
34+ 
35+ # Stand-in DataType enum: like the real pypto.DataType it stringifies to its int value, not to the
36+ # DT_ token, so the guard has to compare the enum objects rather than their string forms.
37+ class _DT:
38+ def __init__(self, token, val):
39+ self.name, self._val = token, val
40+ 
41+ def __repr__(self):
42+ return str(self._val)
43+ fp16, int32 = _DT("DT_FP16", 6), _DT("DT_INT32", 3)
44+ pto_by_torch_dtype = {"torch.float16": fp16, "torch.int32": int32}
45+ fake_pypto = types.SimpleNamespace(
46+ DT_FP16=fp16, DT_INT32=int32, # top-level DT_* alias -> same obj
47+ set_codegen_options=lambda **_k: None, # a DIRECT jit_kernel pins soc via this global
48+ )
49+ monkeypatch.setattr(_cop, "torch", fake_torch)
50+ monkeypatch.setattr(_cop, "_pto_dtype", lambda td: pto_by_torch_dtype[td])
51+ monkeypatch.setattr(_cop, "pypto", fake_pypto)
52+ 
53+ 
54+def _fake_factory(*_a, **_k):
55+ class _Jit:
56+ def build_kernel(self, *tensors):
57+ return "/tmp/k.o"
58+ return _Jit()
59+ 
60+ 
61+def _entry(declared):
62+ # only the constructor carries declared_annotations on the factory form
63+ return CompileEntry(
64+ factory=_fake_factory, num_inputs=2, num_outputs=1,
65+ factory_signature="lists", declared_annotations=declared,
66+ )
67+ 
68+ 
69+def test_no_warning_when_declared_matches(monkeypatch):
70+ _install_mocks(monkeypatch)
71+ entry = _entry([
72+ {"shape": [8, 64], "dtype": "DT_FP16"},
73+ {"shape": [8, 64], "dtype": "DT_FP16"},
74+ {"shape": None, "dtype": None},
75+ ])
76+ with warnings.catch_warnings():
77+ warnings.simplefilter("error") # any warning -> failure
78+ entry(((8, 64), (8, 64)), ("float16", "float16"), {}, "Kirin9030")
79+ 
80+ 
81+def test_shape_mismatch_warns(monkeypatch):
82+ _install_mocks(monkeypatch)
83+ entry = _entry([
84+ {"shape": [8, 64], "dtype": None},
85+ {"shape": None, "dtype": None},
86+ {"shape": None, "dtype": None},
87+ ])
88+ with warnings.catch_warnings(record=True) as rec:
89+ warnings.simplefilter("always")
90+ entry(((16, 64), (8, 64)), ("float16", "float16"), {}, "Kirin9030")
91+ msgs = [str(w.message) for w in rec]
92+ assert any("input[0] shape [8, 64] != runtime [16, 64]" in m for m in msgs), msgs
93+ 
94+ 
95+def test_dtype_mismatch_raises(monkeypatch):
96+ _install_mocks(monkeypatch)
97+ # input0 declared int32, fed float16 -> raise (a pinned dtype would silently override the runtime one)
98+ entry = _entry([
99+ {"shape": None, "dtype": "DT_INT32"},
100+ {"shape": None, "dtype": None},
101+ {"shape": None, "dtype": None},
102+ ])
103+ with pytest.raises(ValueError, match=r"input\[0\] dtype DT_INT32"):
104+ entry(((8, 64), (8, 64)), ("float16", "float16"), {}, "Kirin9030")
105+ 
106+ 
107+def test_none_declared_skips_checks(monkeypatch):
108+ _install_mocks(monkeypatch)
109+ entry = CompileEntry(
110+ factory=_fake_factory, num_inputs=2, num_outputs=1, factory_signature="lists",
111+ ) # no declared_annotations at all
112+ with warnings.catch_warnings():
113+ warnings.simplefilter("error")
114+ entry(((8, 64), (8, 64)), ("float16", "float16"), {}, "Kirin9030")
115+ 
116+ 
117+class _FakeJit:
118+ __name__ = "attention_kernel"
119+ 
120+ def build_kernel(self, *tensors):
121+ return "/tmp/k.o"
122+ 
123+ 
124+def _jit_entry(declared):
125+ return CompileEntry(
126+ jit_kernel=_FakeJit(), num_inputs=3, num_outputs=1, declared_annotations=declared,
127+ )
128+ 
129+ 
130+# 4 pinned entries (q, k, v, output) mirroring the attention demo
131+_ATTN_DECL = [{"shape": [1, 1, 8, 64], "dtype": "DT_FP16"}] * 4
132+_ATTN_DTYPES = ("float16", "float16", "float16")
133+ 
134+ 
135+def test_jit_kernel_shape_mismatch_warns(monkeypatch):
136+ # DIRECT (jit_kernel=) entries run the same guard as the factory form
137+ _install_mocks(monkeypatch)
138+ entry = _jit_entry(_ATTN_DECL)
139+ with pytest.warns(UserWarning, match=r"input\[0\] shape \[1, 1, 8, 64\] != runtime \[2, 1, 8, 64\]"):
140+ entry(((2, 1, 8, 64), (1, 1, 8, 64), (1, 1, 8, 64)), _ATTN_DTYPES, {}, "Kirin9030")