已开启
feat(onnx): Integrate validated ONNX input into native PyPTO-Pro #4
feat(onnx): Integrate validated ONNX input into native PyPTO-Pro #4
已开启
hid22900163创建于 22 天前
共 49 个文件变更+13900-4
@@ -120,3 +120,7 @@ cannbot-skills/
120- `examples/` — 可选,随 Skill 分发的可运行样例120- `examples/` — 可选,随 Skill 分发的可运行样例
121 121 
122跨 Skill 引用必须指向本仓实际存在的目录,并使用目标工具可解析的相对路径;Plugin 只声明和安装自身工作流需要的 Skills 与 Agents。122跨 Skill 引用必须指向本仓实际存在的目录,并使用目标工具可解析的相对路径;Plugin 只声明和安装自身工作流需要的 Skills 与 Agents。
123+ 
124+## ONNX input
125+ 
126+[`pypto-pro-onnx-ingest`](ops/pypto-pro-onnx-ingest/SKILL.md) converts supported ONNX graphs into validated references, SPEC and CPU/NPU golden files for the native `pypto-pro-kernel` workflow. ONNX Runtime agreement validates the reference; kernel device acceptance remains a separate step.
@@ -224,3 +224,7 @@ cannbot-skills/
224|------|---------|------|224|------|---------|------|
225| GitCode Issue | Skill bug / 功能缺失 | [提交 Issue](https://gitcode.com/cann/pypto-gym/issues) |225| GitCode Issue | Skill bug / 功能缺失 | [提交 Issue](https://gitcode.com/cann/pypto-gym/issues) |
226| GitCode Discussions | 使用疑问 / 经验交流 / 功能建议 | [参与讨论](https://gitcode.com/cann/pypto-gym/discussions) |226| GitCode Discussions | 使用疑问 / 经验交流 / 功能建议 | [参与讨论](https://gitcode.com/cann/pypto-gym/discussions) |
227+ 
228+## ONNX input
229+ 
230+[`pypto-pro-onnx-ingest`](ops/pypto-pro-onnx-ingest/SKILL.md) converts supported ONNX graphs into validated references, SPEC and CPU/NPU golden files for the native `pypto-pro-kernel` workflow. ONNX Runtime agreement validates the reference; kernel device acceptance remains a separate step.
Mcannbot-skills/ops/pypto-pro-golden-generate/SKILL.md+3-0文件内容审核中,请稍后刷新重试
@@ -1,14 +1,17 @@
1# 既有参考规范化1# 既有参考规范化
2 2 
3-本流程用于选择并规范化 PyTorch/NumPy 参考。确认参考源路径并保持原文件只读,按 [../SKILL.md](../SKILL.md) 生成骨架并填充数学逻辑及等价自验证。若参考源正是任一目标交付文件,先保留独立只读 oracle 副本,再在临时目录生成两份候选;等价验证通过并取得覆盖确认后才按 §5 采用,不能先覆盖原目标或让对照指向替换后的文件。不在此阶段划分 Module 或设计 kernel。3+本流程用于选择并规范化既有参考:PyTorch、NumPy,或由 `pypto-pro-onnx-ingest` 从 ONNX 图恢复的参考模型。确认参考源路径并保持原文件只读,按 [../SKILL.md](../SKILL.md) 生成骨架并填充数学逻辑及等价自验证。若参考源正是任一目标交付文件,先保留独立只读 oracle 副本,再在临时目录生成两份候选;等价验证通过并取得覆盖确认后才按 §5 采用,不能先覆盖原目标或让对照指向替换后的文件。不在此阶段划分 Module 或设计 kernel。
4 4 
5## 1. 选择参考源5## 1. 选择参考源
6 6 
7按以下顺序选择可执行且语义最完整的参考:7按以下顺序选择可执行且语义最完整的参考:
8 8 
9-1. PyTorch forward/backward 参考;9+1. ONNX 图:由 `pypto-pro-onnx-ingest` 恢复为 PyTorch 参考模型,参考源为 `frozen.onnx`,权重经哈希校验;
10-2. NumPy 参考;10+2. PyTorch forward/backward 参考;
11-3. 没有可用参考时,才根据 SPEC 数学公式自行实现。11+3. NumPy 参考;
12+4. 没有可用参考时,才根据 SPEC 数学公式自行实现。
13+ 
14+参考源为 ONNX 图时,按 [native handoff](../../pypto-pro-onnx-ingest/references/native-handoff.md) 核对现有产物并保留图数值策略,不重新生成数学。`manifest.json` 保存来源与哈希;导入期 CPU/ORT 比较只覆盖已声明用例。需要设备数值证据时显式执行 ONNX device helper;普通 `_validate()` 或自验证回执不替代该比较。其余语义与边界覆盖按任务要求核对,不把导入成功当作整个规范化流程或 kernel 验收完成。
12 15 
13仅在 [../SKILL.md](../SKILL.md) 定义的明确缺口成立时,编排模式才在以下仓内范围检索:16仅在 [../SKILL.md](../SKILL.md) 定义的明确缺口成立时,编排模式才在以下仓内范围检索:
14 17 
Mcannbot-skills/ops/pypto-pro-kernel/SKILL.md+1-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-kernel/references/workflows/debugging.md+8-0文件内容审核中,请稍后刷新重试
Acannbot-skills/ops/pypto-pro-onnx-ingest/SKILL.md+68-0文件内容审核中,请稍后刷新重试
Acannbot-skills/ops/pypto-pro-onnx-ingest/references/native-handoff.md+34-0文件内容审核中,请稍后刷新重试
Acannbot-skills/ops/pypto-pro-onnx-ingest/references/onnx-contract.md+46-0文件内容审核中,请稍后刷新重试
@@ -0,0 +1,7 @@
1+# Frozen tensor bundle scope
2+ 
3+`tensor_bundle.py` is a library for the `cannbot.tensor-bundle/1` payload format. The ingest CLI does not call it or emit a weight bundle; generated goldens embed parameters up to `onnx_golden.MAX_WEIGHT_BYTES` (4 MiB).
4+ 
5+Above that limit, inspect `golden_cpu_skipped` and `golden_npu_skipped`: exit zero does not establish preparation success. Extract a smaller graph region or report the packaging limitation. Do not silently replace weights or derive a new golden from SPEC prose.
6+ 
7+The old Scriptor `BOUND_TENSOR_BUNDLE` exporter is not part of the native workflow. This module alone does not bind weights into a native kernel. Follow [native handoff](../references/native-handoff.md) for the public interface and parameter-binding requirements; validate the actual native wrapper on the target runtime before claiming support.
Acannbot-skills/ops/pypto-pro-onnx-ingest/scripts/onnx_ingest.py+1125-0文件内容审核中,请稍后刷新重试
Acannbot-skills/ops/pypto-pro-onnx-ingest/scripts/onnx_spec.py+443-0文件内容审核中,请稍后刷新重试
@@ -0,0 +1,14 @@
1+# Python dependencies of scripts/onnx_to_reference_model.py and its tests.
2+# Keep torch / torchvision aligned with the local Ascend CANN environment; they are
3+# not pinned here. CANN itself is not installed through pip.
4+numpy
5+torch
6+# torchvision is lazy-imported by the converter for the RoiAlign / NMS wrappers;
7+# currently transitive via onnx2torch -- pin here if that breaks.
8+torchvision
9+pytest
10+# Exact pin: the converter reads private attrs on onnx2torch wrapper classes;
11+# a patch-level change could rename them.
12+onnx==1.17.0
13+onnx2torch==1.5.15
14+onnxruntime
@@ -0,0 +1,365 @@
1+# Copyright (c) 2025-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+"""Bound tensor artefacts for one graph: the persistent parameters as files beside the golden.
10+ 
11+A self-contained golden carries its weights base64-encoded in its own source, which is why
12+``onnx_golden.MAX_WEIGHT_BYTES`` exists: past a few MiB the emitted module stops being a source file. This
13+module is the other way of being self-contained -- the parameters are written once as a *bundle* directory
14+beside the golden, and the golden binds them by name, shape, dtype and content hash.
15+ 
16+The bundle is generic: nothing here knows an operator, a model family or a tensor name. It carries exactly
17+what the state dict of the recovered reference model holds, under the names that state dict uses.
18+ 
19+Three tensor roles exist in the pipeline and this bundle holds only the first:
20+ 
21+``persistent_parameter`` bound to the graph, identical on every call, carried by the bundle.
22+``runtime_activation_input`` a SPEC input, generated per P0 case, NEVER in the bundle. A bound parameter
23+ that became an activation input would be regenerated at random on every run,
24+ so the loader refuses a bundle whose binding names collide with them.
25+``temporary_workspace`` allocated by whatever executes the task, never persisted anywhere.
26+ 
27+Relocation: every path in ``BUNDLE.json`` is relative to the bundle directory, and the generated loader
28+resolves the bundle directory from the golden module's own ``__file__``. Copying ``SPEC.md``, the goldens
29+and the bundle directory to any other directory is therefore sufficient to run them; nothing records an
30+absolute path, and ``write_bundle`` refuses to write one.
31+"""
32+ 
33+import hashlib
34+import json
35+import os
36+from pathlib import Path
37+ 
38+from onnx_ingest import IngestError
39+ 
40+SCHEMA = "cannbot.tensor-bundle/1"
41+INDEX_NAME = "BUNDLE.json"
42+DIR_SUFFIX = "_weights"
43+ROLE_PARAMETER = "persistent_parameter"
44+ 
45+ROLE_GLOSSARY = {
46+ ROLE_PARAMETER: "bound to the graph; identical on every call; carried by this bundle",
47+ "runtime_activation_input": "a SPEC input, generated per P0 case; never carried by this bundle",
48+ "temporary_workspace": "allocated by the executing task; never persisted",
49+}
50+ 
51+ 
52+class BundleWriteError(IngestError, RuntimeError):
53+ """A bundle could not be written: an unusable tensor, name or destination.
54+ 
55+ An ``IngestError``, so the CLI reports it as ``error: ...`` with an exit status instead of a traceback.
56+ """
57+ 
58+ exit_code = 11
59+ 
60+ 
61+def bundle_dirname(op: str) -> str:
62+ """The bundle directory's name for operator ``op``, relative to the artefact directory."""
63+ return op + DIR_SUFFIX
64+ 
65+ 
66+def _safe_stem(name: str, index: int) -> str:
67+ """A filename for a binding name that may hold dots, slashes or anything else a state dict allows."""
68+ keep = "".join(ch if (ch.isalnum() or ch in "-_") else "_" for ch in name)
69+ return "t{:04d}_{}".format(index, keep[:80] or "tensor")
70+ 
71+ 
72+def _payload(tensor):
73+ """The tensor's raw little-endian bytes, dtype-agnostic (bfloat16 has no numpy dtype)."""
74+ import torch
75+ 
76+ flat = tensor.detach().cpu().contiguous().reshape(-1)
77+ if flat.numel() == 0:
78+ return b""
79+ return flat.view(torch.uint8).numpy().tobytes()
80+ 
81+ 
82+def write_bundle(
83+ root,
84+ state_dict,
85+ *,
86+ op: str,
87+ activation_inputs,
88+ source_name: str = "",
89+ source_sha256: str = "",
90+ frozen_sha256: str = "",
91+) -> dict:
92+ """Write ``state_dict`` as a bundle under ``root`` and return the index that describes it.
93+ 
94+ ``activation_inputs`` are the SPEC input names. They are recorded so the loader can refuse a bundle
95+ that tries to bind one of them, which is how a weight stays a weight instead of becoming a randomly
96+ regenerated model input.
97+ """
98+ import torch
99+ 
100+ root = Path(root)
101+ if not state_dict:
102+ raise BundleWriteError(
103+ "the reference model has no persistent parameter, so there is no bundle to "
104+ "write; an embedded golden is the right artefact for it"
105+ )
106+ overlap = sorted(set(state_dict) & set(activation_inputs or ()))
107+ if overlap:
108+ raise BundleWriteError(
109+ "binding name(s) {} are also SPEC activation inputs; a bound parameter must never be declared "
110+ "as a model input, or the golden would regenerate it at random".format(", ".join(overlap))
111+ )
112+ root.mkdir(parents=True, exist_ok=True)
113+ entries, total = [], 0
114+ for index, binding in enumerate(sorted(state_dict)):
115+ tensor = state_dict[binding]
116+ if not isinstance(tensor, torch.Tensor):
117+ raise BundleWriteError("state dict entry {!r} is a {}, not a tensor".format(binding, type(tensor).__name__))
118+ dtype = str(tensor.dtype).removeprefix("torch.")
119+ payload = _payload(tensor)
120+ relative = _safe_stem(binding, index) + ".bin"
121+ (root / relative).write_bytes(payload)
122+ entries.append(
123+ {
124+ "binding": binding,
125+ "role": ROLE_PARAMETER,
126+ "path": relative,
127+ "dtype": dtype,
128+ "shape": list(tensor.shape),
129+ "bytes": len(payload),
130+ "sha256": hashlib.sha256(payload).hexdigest(),
131+ }
132+ )
133+ total += len(payload)
134+ index_body = {
135+ "schema": SCHEMA,
136+ "op_name": op,
137+ "graph": {"source_file": source_name, "source_sha256": source_sha256, "frozen_sha256": frozen_sha256},
138+ "roles": dict(ROLE_GLOSSARY),
139+ "runtime_activation_inputs": sorted(activation_inputs or ()),
140+ "tensors": entries,
141+ "tensor_count": len(entries),
142+ "total_bytes": total,
143+ "payload_sha256": payload_digest(entries),
144+ "relocation": {
145+ "path_style": "relative to this file's directory",
146+ "absolute_paths": False,
147+ "resolved_by": "the golden module's own __file__",
148+ "required_copy": "this directory, whole, beside the golden",
149+ },
150+ }
151+ for entry in entries:
152+ if os.path.isabs(entry["path"]) or ".." in entry["path"].split("/"):
153+ raise BundleWriteError("bundle path {!r} is not relative to the bundle directory".format(entry["path"]))
154+ (root / INDEX_NAME).write_text(json.dumps(index_body, indent=2, sort_keys=True) + "\n", encoding="utf-8")
155+ return index_body
156+ 
157+ 
158+def read_index(root) -> dict:
159+ """The bundle index at ``root``, checked for schema. Raises ``BundleWriteError`` if it is not one."""
160+ root = Path(root)
161+ index_path = root / INDEX_NAME
162+ if not index_path.is_file():
163+ raise BundleWriteError("{} is not a tensor bundle: no {}".format(root, INDEX_NAME))
164+ index = json.loads(index_path.read_text(encoding="utf-8"))
165+ if index.get("schema") != SCHEMA:
166+ raise BundleWriteError("bundle index declares schema {!r}, expected {!r}".format(index.get("schema"), SCHEMA))
167+ return index
168+ 
169+ 
170+def load_state_dict(root) -> dict:
171+ """Read a bundle back as a state dict, for loading the *recovered reference model* off the same files.
172+ 
173+ The goldens carry their own inlined loader (they must run with no sibling module); this is the host-side
174+ entry for everything else that needs the same tensors. Every tensor is checked against the index's own
175+ shape, dtype, byte count and digest, and a mismatch raises instead of returning a plausible tensor.
176+ """
177+ import torch
178+ 
179+ root = Path(root)
180+ index = read_index(root)
181+ state = {}
182+ for entry in index["tensors"]:
183+ payload = (root / entry["path"]).read_bytes()
184+ if len(payload) != entry["bytes"]:
185+ raise BundleWriteError(
186+ "bound tensor {!r} is {} byte(s), the index declares {}".format(
187+ entry["binding"], len(payload), entry["bytes"]
188+ )
189+ )
190+ if hashlib.sha256(payload).hexdigest() != entry["sha256"]:
191+ raise BundleWriteError("bound tensor {!r} does not match its recorded sha256".format(entry["binding"]))
192+ dtype = getattr(torch, entry["dtype"])
193+ if not payload:
194+ state[entry["binding"]] = torch.empty(list(entry["shape"]), dtype=dtype)
195+ continue
196+ state[entry["binding"]] = (
197+ torch.frombuffer(bytearray(payload), dtype=dtype).reshape(list(entry["shape"])).clone()
198+ )
199+ return state
200+ 
201+ 
202+def payload_digest(entries) -> str:
203+ """One digest over the ordered (binding, dtype, shape, sha256) tuples: the bundle's content identity."""
204+ joined = "\n".join("{}|{}|{}|{}".format(e["binding"], e["dtype"], list(e["shape"]), e["sha256"]) for e in entries)
205+ return hashlib.sha256(joined.encode("utf-8")).hexdigest()
206+ 
207+ 
208+def binding_table(index) -> list:
209+ """The rows the generated golden bakes in: ``[binding, dtype, shape, sha256, bytes]`` per tensor.
210+ 
211+ Baked into the golden *source*, so it is independent of the bundle's own ``BUNDLE.json``. A bundle
212+ rewritten self-consistently -- new tensor, new metadata, new hash -- still fails against this table.
213+ """
214+ return [[e["binding"], e["dtype"], list(e["shape"]), e["sha256"], e["bytes"]] for e in index["tensors"]]
215+ 
216+ 
217+def manifest_section(index, *, dirname: str, index_sha256: str) -> dict:
218+ """The ``weight_bundle`` section added to the ingest's existing ``manifest.json``."""
219+ return {
220+ "schema": index["schema"],
221+ "dir": dirname,
222+ "index": dirname + "/" + INDEX_NAME,
223+ "index_sha256": index_sha256,
224+ "tensor_count": index["tensor_count"],
225+ "total_bytes": index["total_bytes"],
226+ "payload_sha256": index["payload_sha256"],
227+ "roles": index["roles"],
228+ "runtime_activation_inputs": index["runtime_activation_inputs"],
229+ "relocation": index["relocation"],
230+ "tensors": [
231+ {
232+ "binding": e["binding"],
233+ "role": e["role"],
234+ "path": dirname + "/" + e["path"],
235+ "dtype": e["dtype"],
236+ "shape": e["shape"],
237+ "bytes": e["bytes"],
238+ "sha256": e["sha256"],
239+ }
240+ for e in index["tensors"]
241+ ],
242+ }
243+ 
244+ 
245+_LOADER = '''import hashlib
246+import json
247+import os
248+ 
249+# ---------------------------------------------------------------------------------------------------
250+# Bound tensor artefacts. The persistent parameters are NOT embedded in this file: they live in the
251+# bundle directory named below, beside this module. Binding name, dtype, shape and content hash are
252+# declared HERE, in the golden's own source, so a bundle rewritten with self-consistent metadata is
253+# still rejected -- the binding contract is what is checked, not only the file's own hash.
254+# Relocation: the directory is resolved from this module's __file__, so copying SPEC.md, the goldens
255+# and this directory anywhere is enough. No absolute path is recorded.
256+# ---------------------------------------------------------------------------------------------------
257+_BUNDLE_DIR = "@BUNDLE_DIR@"
258+_BUNDLE_INDEX = "@INDEX_NAME@"
259+_BUNDLE_SCHEMA = "@SCHEMA@"
260+# [binding, dtype, shape, sha256, bytes] -- every one a @ROLE@ of this graph.
261+_BINDINGS = @BINDINGS@
262+# SPEC inputs: generated per P0 case. A binding may never be one of these.
263+_ACTIVATION_INPUTS = @ACTIVATION_INPUTS@
264+ 
265+ 
266+class BundleError(RuntimeError):
267+ """A bound tensor is missing, corrupt, or does not match the binding contract."""
268+ 
269+ 
270+def _bundle_root():
271+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), _BUNDLE_DIR)
272+ 
273+ 
274+def _load_weights():
275+ """The state dict, read from the bundle. Every failure is explicit and fatal: never a silent default."""
276+ root = _bundle_root()
277+ index_path = os.path.join(root, _BUNDLE_INDEX)
278+ if not os.path.isdir(root):
279+ raise BundleError(
280+ "bound tensor bundle {!r} is missing beside this golden (looked in {!r}). This golden embeds no "
281+ "weights, so it cannot run without it: copy the whole bundle directory next to this file."
282+ .format(_BUNDLE_DIR, root))
283+ if not os.path.isfile(index_path):
284+ raise BundleError("bundle {!r} has no {} index; it is not a usable tensor bundle".format(
285+ _BUNDLE_DIR, _BUNDLE_INDEX))
286+ try:
287+ with open(index_path, "r", encoding="utf-8") as handle:
288+ index = json.load(handle)
289+ except ValueError as error:
290+ raise BundleError("bundle index {!r} is not valid JSON: {}".format(index_path, error))
291+ if index.get("schema") != _BUNDLE_SCHEMA:
292+ raise BundleError("bundle index declares schema {!r}, this golden requires {!r}".format(
293+ index.get("schema"), _BUNDLE_SCHEMA))
294+ entries = {}
295+ for entry in index.get("tensors") or []:
296+ entries[entry.get("binding")] = entry
297+ required = [row[0] for row in _BINDINGS]
298+ missing = [name for name in required if name not in entries]
299+ if missing:
300+ raise BundleError("bundle {!r} is missing required bound tensor(s): {}".format(
301+ _BUNDLE_DIR, ", ".join(missing)))
302+ extra = sorted(set(entries) - set(required))
303+ if extra:
304+ raise BundleError("bundle {!r} declares tensor(s) this golden does not bind: {}; the bundle is not "
305+ "the one this golden was generated for".format(_BUNDLE_DIR, ", ".join(extra)))
306+ collision = sorted(set(required) & set(_ACTIVATION_INPUTS))
307+ if collision:
308+ raise BundleError("binding(s) {} are also SPEC activation inputs; a bound parameter must not be a "
309+ "generated model input".format(", ".join(collision)))
310+ state = {}
311+ for binding, dtype, shape, sha256, nbytes in _BINDINGS:
312+ entry = entries[binding]
313+ if entry.get("dtype") != dtype or [int(d) for d in entry.get("shape") or []] != list(shape):
314+ raise BundleError(
315+ "bound tensor {!r} does not match the binding contract: the bundle declares dtype {} shape "
316+ "{}, this golden requires dtype {} shape {}".format(
317+ binding, entry.get("dtype"), entry.get("shape"), dtype, shape))
318+ relative = entry.get("path")
319+ if not isinstance(relative, str) or os.path.isabs(relative) or ".." in relative.split("/"):
320+ raise BundleError("bundle path {!r} for {!r} must be relative to the bundle directory".format(
321+ relative, binding))
322+ path = os.path.join(root, *relative.split("/"))
323+ if not os.path.isfile(path):
324+ raise BundleError("bound tensor {!r} names {!r}, which is not in the bundle".format(
325+ binding, relative))
326+ with open(path, "rb") as handle:
327+ payload = handle.read()
328+ if len(payload) != nbytes:
329+ raise BundleError("bound tensor {!r} is {} byte(s); the binding contract requires {}".format(
330+ binding, len(payload), nbytes))
331+ measured = hashlib.sha256(payload).hexdigest()
332+ if measured != sha256:
333+ raise BundleError("bound tensor {!r} is corrupt: sha256 {} does not match the {} this golden "
334+ "was generated against".format(binding, measured, sha256))
335+ if entry.get("sha256") != sha256:
336+ raise BundleError("bundle index records sha256 {} for {!r}, this golden requires {}".format(
337+ entry.get("sha256"), binding, sha256))
338+ if nbytes == 0:
339+ state[binding] = torch.empty(list(shape), dtype=getattr(torch, dtype))
340+ continue
341+ tensor = torch.frombuffer(bytearray(payload), dtype=getattr(torch, dtype))
342+ state[binding] = tensor.reshape(list(shape)).clone()
343+ return state
344+'''
345+ 
346+ 
347+def loader_source(op: str, index, activation_inputs) -> str:
348+ """The loader text inlined into a generated golden that binds ``op``'s bundle.
349+ 
350+ Token substitution, not ``str.format``: the loader body is full of runtime ``{}`` format strings and
351+ must reach the emitted file untouched.
352+ """
353+ rows = binding_table(index)
354+ rendered = "[\n" + "".join(" {},\n".format(json.dumps(row)) for row in rows) + "]"
355+ text = _LOADER
356+ for token, value in (
357+ ("@BUNDLE_DIR@", bundle_dirname(op)),
358+ ("@INDEX_NAME@", INDEX_NAME),
359+ ("@SCHEMA@", SCHEMA),
360+ ("@ROLE@", ROLE_PARAMETER),
361+ ("@BINDINGS@", rendered),
362+ ("@ACTIVATION_INPUTS@", repr(sorted(activation_inputs or ()))),
363+ ):
364+ text = text.replace(token, value)
365+ return text
Acannbot-skills/ops/pypto-pro-onnx-ingest/scripts/validate_device_goldens.py+269-0文件内容审核中,请稍后刷新重试
@@ -0,0 +1,86 @@
1+# Copyright (c) 2025-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+"""Test scaffolding for scripts/onnx_to_reference_model.py regressions.
10+ 
11+Builds ONNX fixtures lazily on first use via the ``onnx_path_for`` fixture.
12+Each fixture name maps to a builder in ``generate_models.BUILDERS``; the
13+returned ``ModelProto`` is serialized to a session-scoped ``tmp_path_factory``
14+dir and cached, so multiple tests requesting the same fixture pay the build
15+cost only once per session. RNG state is isolated around each build so the
16+test process's seed is preserved.
17+"""
18+ 
19+import importlib
20+import sys
21+from pathlib import Path
22+from typing import Callable
23+ 
24+import numpy as np
25+import pytest
26+import torch
27+ 
28+_TESTS_DIR = Path(__file__).resolve().parent
29+_SKILL_DIR = _TESTS_DIR.parent
30+ 
31+sys.path.insert(0, str(_SKILL_DIR / "scripts"))
32+sys.path.insert(0, str(_TESTS_DIR))
33+ 
34+ 
35+def pytest_sessionstart(session):
36+ """Fail hard when a converter dependency is missing.
37+ 
38+ ``test_conversion`` is gated by ``pytest.importorskip("onnxruntime")``; without ONNX
39+ Runtime the whole suite would skip and report success."""
40+ for module in ("onnx", "onnxruntime", "onnx2torch"):
41+ try:
42+ importlib.import_module(module)
43+ except ImportError as exc:
44+ raise pytest.UsageError(
45+ "{} is required: without it this suite would skip silently ({})".format(module, exc)
46+ ) from exc
47+ 
48+ 
49+@pytest.fixture(scope="session")
50+def _fixture_dir(tmp_path_factory) -> Path:
51+ return tmp_path_factory.mktemp("onnx_ref")
52+ 
53+ 
54+@pytest.fixture(scope="session")
55+def onnx_path_for(_fixture_dir) -> Callable[[str], str]:
56+ """Return a function ``name -> path`` that builds the named ONNX fixture
57+ on first call and caches its serialized form under ``_fixture_dir``."""
58+ from generate_models import BUILDERS
59+ 
60+ cache: dict = {}
61+ 
62+ def _build(name: str) -> str:
63+ if name in cache:
64+ return cache[name]
65+ if name not in BUILDERS:
66+ pytest.fail(
67+ f"unknown fixture: {name!r} (known: {sorted(BUILDERS)})",
68+ )
69+ np_state = np.random.get_state()
70+ torch_state = torch.random.get_rng_state()
71+ np.random.seed(0)
72+ torch.manual_seed(0)
73+ try:
74+ model = BUILDERS[name]()
75+ finally:
76+ np.random.set_state(np_state)
77+ torch.random.set_rng_state(torch_state)
78+ path = _fixture_dir / f"{name}.onnx"
79+ path.write_bytes(model.SerializeToString())
80+ cache[name] = str(path)
81+ return cache[name]
82+ 
83+ return _build
84+ 
85+ 
86+pytest_plugins = ["contract_cases"]
@@ -0,0 +1,43 @@
1+# Copyright (c) 2025-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+"""ONNX-local contracts: typed execution, complete validators and honest evidence."""
10+ 
11+import numpy as np
12+import onnx
13+import onnx_ingest
14+import pytest
15+from onnx import TensorProto as T
16+from onnx import helper as h
17+from onnx import numpy_helper as nh
18+ 
19+ 
20+def emit(tmp_path, model, **kwargs):
21+ path = tmp_path / "model.onnx"
22+ onnx.save(model, path)
23+ out = tmp_path / "op"
24+ summary = onnx_ingest.emit_artifacts(path, out, op_name="probe_op", **kwargs)
25+ return out, summary
26+ 
27+ 
28+@pytest.fixture(scope="module")
29+def simple(tmp_path_factory):
30+ x = h.make_tensor_value_info("x", T.FLOAT, [2])
31+ y = h.make_tensor_value_info("y", T.FLOAT, [2])
32+ model = h.make_model(
33+ h.make_graph(
34+ [h.make_node("Add", ["x", "b"], ["y"])],
35+ "simple",
36+ [x],
37+ [y],
38+ [nh.from_array(np.array([1.0, 2.0], np.float32), "b")],
39+ ),
40+ opset_imports=[h.make_opsetid("", 13)],
41+ )
42+ model.ir_version = 8
43+ return emit(tmp_path_factory.mktemp("hardened"), model)
@@ -0,0 +1,221 @@
1+# Copyright (c) 2025-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+"""Shared helpers for the ingest, SPEC and determinism tests (not a test module)."""
10+ 
11+import hashlib
12+import importlib.util
13+import json
14+import os
15+import subprocess
16+import sys
17+from pathlib import Path
18+ 
19+import numpy as np
20+import onnx
21+import torch
22+ 
23+SKILL_DIR = Path(__file__).resolve().parent.parent
24+TOOL = str(SKILL_DIR / "scripts" / "onnx_to_reference_model.py")
25+ 
26+ 
27+def run_tool(*args, cwd=None, env=None):
28+ """Run the CLI in a fresh process; returns the CompletedProcess (text mode)."""
29+ full_env = dict(os.environ)
30+ full_env["PYTHONDONTWRITEBYTECODE"] = "1"
31+ full_env.update(env or {})
32+ return subprocess.run(
33+ [sys.executable, TOOL, *map(str, args)], capture_output=True, text=True, cwd=cwd, env=full_env
34+ )
35+ 
36+ 
37+def build_model(name):
38+ """The named fixture model, built with the same seeding the shared ``onnx_path_for`` fixture uses."""
39+ from generate_models import BUILDERS, REJECTED_BUILDERS
40+ 
41+ np_state, torch_state = np.random.get_state(), torch.random.get_rng_state()
42+ np.random.seed(0)
43+ torch.manual_seed(0)
44+ try:
45+ return (BUILDERS.get(name) or REJECTED_BUILDERS[name])()
46+ finally:
47+ np.random.set_state(np_state)
48+ torch.random.set_rng_state(torch_state)
49+ 
50+ 
51+def save_model(name, directory, filename=None):
52+ directory = Path(directory)
53+ directory.mkdir(parents=True, exist_ok=True)
54+ path = directory / (filename or name + ".onnx")
55+ onnx.save(build_model(name), str(path))
56+ return path
57+ 
58+ 
59+def save_external(model, directory, filename="model.onnx", data_name="model.weights"):
60+ """Save ``model`` with every initializer in one sibling data file; returns the .onnx path."""
61+ directory = Path(directory)
62+ directory.mkdir(parents=True, exist_ok=True)
63+ path = directory / filename
64+ onnx.save_model(
65+ model, str(path), save_as_external_data=True, all_tensors_to_one_file=True, location=data_name, size_threshold=0
66+ )
67+ return path
68+ 
69+ 
70+def read_manifest(out_dir):
71+ return json.loads((Path(out_dir) / "manifest.json").read_text(encoding="utf-8"))
72+ 
73+ 
74+def independent_digest(tensor):
75+ """The documented initializer hash, recomputed here without importing the tool."""
76+ array = onnx.numpy_helper.to_array(tensor)
77+ prefix = "{}|{}|".format(tensor.data_type, ",".join(str(d) for d in tensor.dims)).encode()
78+ return hashlib.sha256(
79+ prefix + np.ascontiguousarray(array).astype(array.dtype.newbyteorder("<")).tobytes()
80+ ).hexdigest()
81+ 
82+ 
83+def sha256_file(path):
84+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
85+ 
86+ 
87+def tree_hashes(directory):
88+ """``{relative name: sha256}`` for every file under ``directory``."""
89+ directory = Path(directory)
90+ return {str(p.relative_to(directory)): sha256_file(p) for p in sorted(directory.rglob("*")) if p.is_file()}
91+ 
92+ 
93+def load_reference(out_dir):
94+ """Instantiate the emitted runnable reference module from ``out_dir`` (weights loaded)."""
95+ 
96+ out_dir = Path(out_dir)
97+ spec = importlib.util.spec_from_file_location("emitted_reference_" + out_dir.name, out_dir / "reference_model.py")
98+ module = importlib.util.module_from_spec(spec)
99+ spec.loader.exec_module(module)
100+ instance = module.OnnxReferenceModule()
101+ instance.load_state_dict(torch.load(out_dir / "reference_weights.pt", weights_only=True), strict=False)
102+ return instance.eval()
103+ 
104+ 
105+def run_ort(model_or_path, feeds):
106+ import onnxruntime as ort
107+ 
108+ payload = model_or_path.SerializeToString() if hasattr(model_or_path, "SerializeToString") else str(model_or_path)
109+ return ort.InferenceSession(payload, providers=["CPUExecutionProvider"]).run(None, feeds)
110+ 
111+ 
112+# ---------------------------------------------------------------------------
113+# Sibling skills: the real SPEC validator, the golden scaffold and the CPU-golden preflight
114+# ---------------------------------------------------------------------------
115+ 
116+ 
117+def sibling(*parts):
118+ """A path under the ``ops`` tree (or under ``PYPTO_PRO_SKILLS_DIR``); fails, never skips, when absent."""
119+ root = os.environ.get("PYPTO_PRO_SKILLS_DIR")
120+ path = Path(root) if root else SKILL_DIR.parent
121+ path = path.joinpath(*parts)
122+ if not path.exists():
123+ raise AssertionError("required sibling skill file is missing: {} (set PYPTO_PRO_SKILLS_DIR)".format(path))
124+ return path
125+ 
126+ 
127+def validate_spec_script():
128+ return sibling("pypto-pro-kernel", "scripts", "validate_spec.py")
129+ 
130+ 
131+def load_module(name, path):
132+ spec = importlib.util.spec_from_file_location(name, str(path))
133+ module = importlib.util.module_from_spec(spec)
134+ spec.loader.exec_module(module)
135+ return module
136+ 
137+ 
138+def load_validator():
139+ return load_module("spec_validator_for_tests", validate_spec_script())
140+ 
141+ 
142+_ADAPTER = '''
143+import importlib.util
144+import os
145+ 
146+import torch
147+ 
148+_HERE = os.path.dirname(os.path.abspath(__file__))
149+_OUTPUT_DTYPES = {dtypes}
150+ 
151+ 
152+def _reference():
153+ spec = importlib.util.spec_from_file_location("onnx_reference", os.path.join(_HERE, "reference_model.py"))
154+ module = importlib.util.module_from_spec(spec)
155+ spec.loader.exec_module(module)
156+ model = module.OnnxReferenceModule()
157+ model.load_state_dict(torch.load(os.path.join(_HERE, "reference_weights.pt"), weights_only=True), strict=False)
158+ return model.eval()
159+ 
160+ 
161+def {op}_golden_cpu(*args):
162+ """Reference math: the emitted ONNX reference model, rounded once to each SPEC output dtype."""
163+ with torch.no_grad():
164+ result = _reference()(*args)
165+ outputs = result if isinstance(result, (tuple, list)) else (result,)
166+ return tuple(o.to(getattr(torch, d)) for o, d in zip(outputs, _OUTPUT_DTYPES))
167+'''
168+ 
169+ 
170+def write_golden(op_dir):
171+ """Generate ``<op>_golden_cpu.py`` in ``op_dir`` from its SPEC.md.
172+ 
173+ The input factory comes from the real scaffold and the scriptor template; only the reference math is
174+ supplied here, as a thin call into the emitted reference model (test scaffolding, not a shipped emitter).
175+ Returns the validated contract.
176+ """
177+ op_dir = Path(op_dir)
178+ scaffold = load_module(
179+ "golden_scaffold_for_tests", sibling("pypto-pro-golden-generate", "scripts", "gen_golden_scaffold.py")
180+ )
181+ template = sibling("pypto-pro-golden-generate", "templates", "golden_cpu_template.py.tmpl")
182+ contract = load_validator().load_spec_contract(op_dir / "SPEC.md")
183+ op = contract["op_name"]
184+ source = scaffold.generate(str(op_dir / "SPEC.md"), str(template))
185+ source = source.replace("def _make_inputs(device):", "def _make_inputs(device=None):")
186+ adapter = _ADAPTER.format(op=op, dtypes=repr([o["dtype"] for o in contract["outputs"]]))
187+ source = scaffold._replace_block(source, "def {}_golden_cpu(".format(op), adapter)
188+ (op_dir / "{}_golden_cpu.py".format(op)).write_text(source, encoding="utf-8")
189+ return contract
190+ 
191+ 
192+def preflight(op_dir, contract):
193+ """Independently check the generated reference ABI against the native SPEC.
194+ 
195+ This test oracle replaces the deleted Scriptor preflight dependency. Production
196+ reference comparisons run through validate_device_goldens.py, including its CPU-only mode.
197+ """
198+ module = load_module("cpu_abi_probe", Path(op_dir) / (contract["op_name"] + "_golden_cpu.py"))
199+ raw = module._make_inputs(torch.device("cpu"))
200+ if len(contract["p0_cases"]) == 1 and isinstance(raw, tuple) and len(raw) == 2:
201+ raw = [(contract["p0_cases"][0]["name"], *raw)]
202+ assert [item[0] for item in raw] == [case["name"] for case in contract["p0_cases"]]
203+ for (name, args, kwargs), case in zip(raw, contract["p0_cases"]):
204+ assert len(args) == len(contract["inputs"])
205+ for arg, meta in zip(args, contract["inputs"]):
206+ key = meta["name"]
207+ assert list(arg.shape) == case["input_shapes"][key]
208+ assert arg.dtype == getattr(torch, case.get("input_dtypes", {}).get(key, meta["dtype"]))
209+ assert arg.device.type == "cpu" and bool(torch.isfinite(arg).all())
210+ low, high = meta["value_range"]
211+ assert bool(((arg >= low) & (arg <= high)).all()), "generated input violates SPEC value_range"
212+ with torch.no_grad():
213+ result = getattr(module, contract["op_name"] + "_golden_cpu")(*args, **kwargs)
214+ values = result if isinstance(result, (tuple, list)) else (result,)
215+ assert len(values) == len(contract["outputs"])
216+ for value, meta in zip(values, contract["outputs"]):
217+ key = meta["name"]
218+ assert list(value.shape) == case["output_shapes"][key]
219+ assert value.dtype == getattr(torch, case.get("output_dtypes", {}).get(key, meta["dtype"]))
220+ assert value.device.type == "cpu" and bool(torch.isfinite(value).all())
221+ return {"status": "PASS", "cases": len(raw)}
@@ -0,0 +1,13 @@
1+# Copyright (c) 2025-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+ 
10+[pytest]
11+# This file makes the tests directory the pytest rootdir, so the repository-root conftest.py
12+# (which exits unless torch_npu imports) is not loaded: this suite is CPU-only.
13+python_files = test_*.py
@@ -0,0 +1,120 @@
1+# Copyright (c) 2025-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+"""ONNX-local contracts: typed execution, complete validators and honest evidence."""
10+ 
11+import numpy as np
12+import onnx_golden
13+import onnx_ingest
14+import pytest
15+import torch
16+from ingest_helpers import load_module
17+from test_npu_golden import _load_npu
18+ 
19+ 
20+@pytest.mark.parametrize("role", ["cpu", "npu"])
21+@pytest.mark.parametrize("bad", ["count", "shape", "dtype", "nan", "not_tensor", "empty"])
22+def test_generated_validation_rejects_bad_outputs(simple, monkeypatch, role, bad):
23+ out, _ = simple
24+ module = (
25+ load_module("validation_cpu", out / "probe_op_golden_cpu.py")
26+ if role == "cpu"
27+ else _load_npu(out / "probe_op_golden.py", monkeypatch)
28+ )
29+ values = {
30+ "count": (torch.zeros(2), torch.zeros(2)),
31+ "shape": torch.zeros(1, 2),
32+ "dtype": torch.zeros(2, dtype=torch.float64),
33+ "nan": torch.full((2,), float("nan")),
34+ "not_tensor": [0.0, 0.0],
35+ "empty": (),
36+ }
37+ name = "probe_op_golden_cpu" if role == "cpu" else "probe_op_golden"
38+ monkeypatch.setattr(module, name, lambda *a, **k: values[bad])
39+ with pytest.raises((SystemExit, ValueError), match="output"):
40+ module._validate()
41+ 
42+ 
43+@pytest.mark.parametrize("change", ["missing", "duplicate"])
44+def test_generated_validation_rejects_case_coverage(simple, monkeypatch, change):
45+ module = load_module("cases_cpu", simple[0] / "probe_op_golden_cpu.py")
46+ values = module._make_inputs()
47+ monkeypatch.setattr(module, "_make_inputs", lambda device: [] if change == "missing" else values * 2)
48+ with pytest.raises((SystemExit, ValueError), match="case"):
49+ module._validate()
50+ 
51+ 
52+def test_finite_fp64_not_narrowed_by_validator(simple, monkeypatch):
53+ module = load_module("wide_cpu", simple[0] / "probe_op_golden_cpu.py")
54+ module._EXPECTED_OUTPUTS["default"][0][2] = "float64"
55+ monkeypatch.setattr(module, "probe_op_golden_cpu", lambda *a, **k: torch.full((2,), 1e100, dtype=torch.float64))
56+ module._validate()
57+ 
58+ 
59+def test_integer_agreement_is_exact_above_double_integer_precision():
60+ result = onnx_golden._ort_comparison(
61+ torch.tensor([2**53], dtype=torch.int64), [np.array([2**53 + 1], dtype=np.int64)], None, 0, "int64"
62+ )
63+ assert result["ort_mismatch"] is True
64+ 
65+ 
66+def test_nonfinite_pair_never_agrees():
67+ result = onnx_golden._ort_comparison(
68+ torch.tensor([float("nan")]), [np.array([float("nan")], np.float32)], None, 0, "float32"
69+ )
70+ assert result["ort_mismatch"] is True
71+ 
72+ 
73+def test_dtype_mismatch_never_agrees():
74+ result = onnx_golden._ort_comparison(
75+ torch.tensor([1.0], dtype=torch.float32), [np.array([1.0], np.float64)], None, 0, "float32"
76+ )
77+ assert result["ort_mismatch"] is True
78+ 
79+ 
80+def test_npu_fallback_receipt_has_no_device_numerics(simple, monkeypatch, capsys):
81+ module = _load_npu(simple[0] / "probe_op_golden.py", monkeypatch)
82+ module._validate()
83+ output = capsys.readouterr().out
84+ assert "device_numerics=NOT_RUN" in output
85+ assert "cpu_fallback" in output
86+ 
87+ 
88+def test_per_case_shapes_and_dtype_override_are_checked(simple, monkeypatch):
89+ module = load_module("case_shapes_cpu", simple[0] / "probe_op_golden_cpu.py")
90+ # Use a generated validator from two concrete P0 contracts, including an override.
91+ contract = {
92+ "p0_cases": [
93+ {"name": "short", "output_shapes": {"y": [2]}},
94+ {"name": "long", "output_shapes": {"y": [4]}, "output_dtypes": {"y": "float64"}},
95+ ],
96+ "outputs": [{"name": "y", "shape": ["N"], "dtype": "float32"}],
97+ }
98+ exec(onnx_golden._validation_source(contract), module.__dict__)
99+ module._validate_outputs("short", torch.zeros(2))
100+ module._validate_outputs("long", torch.zeros(4, dtype=torch.float64))
101+ with pytest.raises(ValueError, match="shape"):
102+ module._validate_outputs("long", torch.zeros(2, dtype=torch.float64))
103+ with pytest.raises(ValueError, match="dtype"):
104+ module._validate_outputs("long", torch.zeros(4))
105+ 
106+ 
107+def test_incomplete_or_missing_comparison_never_claims_pass():
108+ contract = {"p0_cases": [{"name": "a"}, {"name": "b"}], "outputs": [{"name": "y"}]}
109+ good = {"case": "a", "output": "y", "ort_status": "agrees with ORT", "nonfinite": 0}
110+ assert onnx_ingest._validation_scope(contract, None)["graph_cpu_agreement"] == "UNVERIFIED"
111+ assert onnx_ingest._validation_scope(contract, {"records": [good]})["graph_cpu_agreement"] == "UNVERIFIED"
112+ assert onnx_ingest._validation_scope(contract, {"records": [good, good]})["graph_cpu_agreement"] == "UNVERIFIED"
113+ assert (
114+ onnx_ingest._validation_scope(contract, {"records": [good, {**good, "case": "b"}]})["graph_cpu_agreement"]
115+ == "PASS"
116+ )
117+ assert (
118+ onnx_ingest._validation_scope(contract, {"records": [{**good, "ort_mismatch": True}]})["graph_cpu_agreement"]
119+ == "FAIL"
120+ )
@@ -0,0 +1,471 @@
1+# Copyright (c) 2025-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+"""End-to-end regressions for scripts/onnx_to_reference_model.py.
10+ 
11+Four groups, all parametrized over the fixture builder registry in
12+``generate_models.BUILDERS`` (resolved via the ``onnx_path_for`` fixture
13+defined in this directory's ``conftest.py``):
14+ 
15+* ``test_with_weights`` — runnable mode: invoke the tool's ``--with-weights``
16+ CLI, dynamically import the emitted source, ``load_state_dict`` from the
17+ saved .pt, and assert max-abs-diff against onnxruntime is below the float
18+ tolerance.
19+* ``test_structure_no_unmapped_wrappers`` — structure-only mode: invoke the
20+ library entry point and assert no ``onnx2torch`` wrapper falls through to
21+ the unmapped path. This pins an invariant the runtime comparison can't
22+ see — the original wrapper's ``forward`` keeps working at runtime even
23+ when the rewrite catalog regresses, so a silently-noisier structure
24+ source would not be caught otherwise.
25+* ``test_ort_gate_detects_*`` — negative controls for ``test_with_weights``: the same comparison
26+ must FAIL, on a value mismatch, when one initializer is perturbed or one non-commutative op's
27+ operands are swapped, and PASS on the unmutated model through the identical code path.
28+* ``test_lift_*`` — degraded-mode behavior of ``_lift_to_nn_modules``:
29+ when ``ShapeProp`` raises or a per-node lifter returns False / raises,
30+ the affected node must stay as its functional form while every other
31+ lift in the same model still proceeds.
32+ 
33+Run via: pytest <skill>/tests/
34+"""
35+ 
36+import importlib.util
37+import os
38+import subprocess
39+import sys
40+from pathlib import Path
41+from unittest import mock
42+ 
43+import numpy as np
44+import pytest
45+import torch
46+ 
47+# The converter's own dependencies are optional: the rest of the suite runs on
48+# a machine that never builds an ONNX model.
49+onnx = pytest.importorskip("onnx")
50+ort = pytest.importorskip("onnxruntime")
51+ 
52+import onnx_to_reference_model as otrm
53+from generate_models import BUILDERS
54+ 
55+_SKILL_DIR = Path(__file__).resolve().parent.parent
56+TOOL = str(_SKILL_DIR / "scripts" / "onnx_to_reference_model.py")
57+PYTHON = sys.executable
58+ 
59+ 
60+def _build_dir(tmp_path):
61+ """Per-test build dir: ``ONNX_REF_TEST_BUILD`` when set, else pytest ``tmp_path``."""
62+ out_dir = os.environ.get("ONNX_REF_TEST_BUILD") or str(tmp_path)
63+ os.makedirs(out_dir, exist_ok=True)
64+ return out_dir
65+ 
66+ 
67+_ALL_CASES = sorted(BUILDERS.keys())
68+ 
69+ 
70+def _sample_input_for(onnx_model):
71+ """Build a random sample input matching the ONNX model's input spec.
72+ Seeded locally so the test is reproducible regardless of whatever the
73+ fixture builder did to the global RNG state earlier in the session."""
74+ torch.manual_seed(0)
75+ initializers = {init.name for init in onnx_model.graph.initializer}
76+ inputs = []
77+ for vi in onnx_model.graph.input:
78+ if vi.name in initializers:
79+ continue
80+ tt = vi.type.tensor_type
81+ shape = []
82+ for d in tt.shape.dim:
83+ if d.HasField("dim_value") and d.dim_value > 0:
84+ shape.append(d.dim_value)
85+ else:
86+ shape.append(2)
87+ ot = tt.elem_type
88+ if ot == 7:
89+ t = torch.randint(0, 5, tuple(shape), dtype=torch.int64)
90+ elif ot == 6:
91+ t = torch.randint(0, 5, tuple(shape), dtype=torch.int32)
92+ elif ot == 9:
93+ t = torch.randint(0, 2, tuple(shape), dtype=torch.bool)
94+ elif ot == 10:
95+ t = torch.randn(tuple(shape), dtype=torch.float16)
96+ else:
97+ t = torch.randn(tuple(shape), dtype=torch.float32)
98+ inputs.append(t)
99+ return inputs
100+ 
101+ 
102+def _gen_via_tool(onnx_path, out_py, out_pt):
103+ res = subprocess.run(
104+ [PYTHON, TOOL, onnx_path, "--with-weights", out_pt],
105+ capture_output=True,
106+ text=True,
107+ )
108+ if res.returncode != 0:
109+ raise RuntimeError(f"tool exit {res.returncode}\n--- stderr ---\n{res.stderr}\n--- stdout ---\n{res.stdout}")
110+ with open(out_py, "w") as f:
111+ f.write(res.stdout)
112+ return res.stderr
113+ 
114+ 
115+def _import_module(path, modname):
116+ spec = importlib.util.spec_from_file_location(modname, path)
117+ m = importlib.util.module_from_spec(spec)
118+ spec.loader.exec_module(m)
119+ return m
120+ 
121+ 
122+def _flatten_outputs(out):
123+ if isinstance(out, torch.Tensor):
124+ return (out,)
125+ if isinstance(out, (list, tuple)):
126+ flat = []
127+ for o in out:
128+ flat.extend(_flatten_outputs(o))
129+ return tuple(flat)
130+ raise TypeError(f"Unexpected output type: {type(out)}")
131+ 
132+ 
133+# ORT (oneDNN/MKL kernels) and PyTorch can differ at ~1e-5 on Conv/BN.
134+_ORT_MAX_ABS_DIFF = 1e-3
135+ 
136+ 
137+def _max_abs_diff(a, b):
138+ return (a.float() - b.float()).abs().max().item()
139+ 
140+ 
141+def _ort_outputs(ort_path, onnx_model, inputs):
142+ """ONNX Runtime's outputs for ``ort_path`` fed ``inputs`` (positional, in ``onnx_model``'s input order)."""
143+ sess = ort.InferenceSession(ort_path, providers=["CPUExecutionProvider"])
144+ initializers = {init.name for init in onnx_model.graph.initializer}
145+ input_names = [vi.name for vi in onnx_model.graph.input if vi.name not in initializers]
146+ feed = {name: t.cpu().numpy() for name, t in zip(input_names, inputs)}
147+ return tuple(torch.from_numpy(a) for a in sess.run(None, feed))
148+ 
149+ 
150+def _reference_and_ort_outputs(onnx_path, label, out_dir, ort_path=None):
151+ """Emit the reference model from ``onnx_path`` and run it beside ORT executing ``ort_path``.
152+ 
153+ ``ort_path`` defaults to ``onnx_path``, which is the positive gate: the emitted reference against
154+ ORT on the very model it was recovered from. The negative controls pass a different ``ort_path`` so
155+ that the same code path compares a reference recovered from a mutated model with ORT on the original.
156+ Returns ``(ORT outputs, emitted-reference outputs)``; the comparison is ``_assert_outputs_match``.
157+ """
158+ onnx_model = onnx.load(onnx_path)
159+ out_py = os.path.join(out_dir, f"{label}.py")
160+ out_pt = os.path.join(out_dir, f"{label}.pt")
161+ _gen_via_tool(onnx_path, out_py, out_pt)
162+ 
163+ mod = _import_module(out_py, f"gen_{label}")
164+ inst = mod.OnnxReferenceModule()
165+ sd = torch.load(out_pt, weights_only=True)
166+ inst.load_state_dict(sd, strict=False)
167+ inst.eval()
168+ 
169+ inputs = _sample_input_for(onnx_model)
170+ with torch.no_grad():
171+ out_ref = _ort_outputs(ort_path or onnx_path, onnx_model, inputs)
172+ out_inst = _flatten_outputs(inst(*inputs))
173+ return out_ref, out_inst
174+ 
175+ 
176+def _assert_outputs_match(out_ref, out_inst):
177+ """The numerical gate: same output count, same shapes, max-abs-diff below ``_ORT_MAX_ABS_DIFF``."""
178+ assert len(out_ref) == len(out_inst), f"output count mismatch: ref={len(out_ref)} inst={len(out_inst)}"
179+ for i, (a, b) in enumerate(zip(out_ref, out_inst)):
180+ assert a.shape == b.shape, f"output[{i}] shape mismatch: ref={a.shape} inst={b.shape}"
181+ diff = _max_abs_diff(a, b)
182+ assert diff < _ORT_MAX_ABS_DIFF, f"output[{i}] max_abs_diff {diff} exceeds {_ORT_MAX_ABS_DIFF}"
183+ 
184+ 
185+def _run_one_case(onnx_path, label, out_dir):
186+ out_ref, out_inst = _reference_and_ort_outputs(onnx_path, label, out_dir)
187+ _assert_outputs_match(out_ref, out_inst)
188+ 
189+ 
190+@pytest.mark.parametrize("onnx_name", _ALL_CASES)
191+def test_with_weights(onnx_name, onnx_path_for, tmp_path):
192+ onnx_path = onnx_path_for(onnx_name)
193+ _run_one_case(onnx_path, onnx_name, _build_dir(tmp_path))
194+ 
195+ 
196+@pytest.mark.parametrize("onnx_name", _ALL_CASES)
197+def test_structure_no_unmapped_wrappers(onnx_name, onnx_path_for, caplog):
198+ onnx_path = onnx_path_for(onnx_name)
199+ otrm.onnx_to_reference_source(onnx.load(onnx_path))
200+ stderr = caplog.text
201+ assert "kept as submodule call" not in stderr, (
202+ f"rewrite catalog regression — fixture left an onnx2torch wrapper in the structure source:\n{stderr}"
203+ )
204+ 
205+ 
206+# ---------------------------------------------------------------------------
207+# Negative controls for the ORT gate (``test_with_weights``)
208+#
209+# ``test_with_weights`` is the primary numerical gate, yet on its own it only ever shows the comparison
210+# PASSING. A comparison that cannot fail would pass all of those fixtures too. These tests build the
211+# failures the gate exists to catch and drive them through the very helpers the gate uses
212+# (``_reference_and_ort_outputs`` + ``_assert_outputs_match``), with the reference emitted from a mutated
213+# copy of a fixture and ORT still running the original:
214+#
215+# * one initializer perturbed -> a wrong, dropped or mis-loaded weight;
216+# * one non-commutative op's operands swapped -> a mis-ordered rewrite of Sub / Div / MatMul.
217+#
218+# A control that fails for the wrong reason proves nothing, so each case also requires that
219+# 1. the SAME code path on the UNMUTATED model passes (the failure comes from the mutation alone);
220+# 2. the mutation is real in ONNX itself: ORT on the mutated model differs from ORT on the original;
221+# 3. the mutated reference still emits, loads and runs, and matches ORT on the MUTATED model (the
222+# emitter is faithful; only the comparison target was changed), so nothing but values can differ;
223+# 4. output count and shapes agree and every value is finite (no NaN/inf standing in for a mismatch);
224+# 5. the gate raises its ``max_abs_diff`` assertion specifically, not a count or shape one;
225+# 6. the measured difference clears the tolerance by a wide margin, so it is not a borderline flip.
226+# ---------------------------------------------------------------------------
227+ 
228+# Every mutated difference must exceed the gate's tolerance by at least this factor.
229+_CONTROL_MARGIN = 20.0
230+ 
231+# (id, fixture, float initializer, offset added to every element of it). One per converter path: Conv, the
232+# lifted BatchNorm2d, Gemm, MatMul, an embedding Gather, LayerNormalization, a plain Mul constant, PRelu.
233+_PERTURB_CASES = [
234+ pytest.param("01_vision_2d_cnn", "conv1.weight", 0.5, id="conv_weight"),
235+ pytest.param("01_vision_2d_cnn", "bn1.weight", 1.0, id="batch_norm_scale"),
236+ pytest.param("01_vision_2d_cnn", "fc.weight", 0.5, id="gemm_weight"),
237+ pytest.param("10_attention_like", "q.weight", 0.5, id="attention_matmul_weight"),
238+ pytest.param("04_nlp_embed_norm", "emb.weight", 0.5, id="embedding_table"),
239+ pytest.param("21_layer_norm_v17", "scale_raw", 0.5, id="layer_norm_scale"),
240+ pytest.param("08_math_constants", "scale", 2.0, id="mul_constant"),
241+ pytest.param("35_prelu", "slope", 0.5, id="prelu_slope"),
242+]
243+ 
244+# (id, fixture, the output tensor of the node whose two operands are swapped, its op type). Each swap
245+# keeps every shape valid, so a broken swap cannot masquerade as a shape error.
246+#
247+# 04_nlp_embed_norm's LayerNorm ``Div`` is deliberately NOT used: ORT's default graph optimisation fuses
248+# that Sub/Pow/ReduceMean/Sqrt/Div pattern into one LayerNormalization without checking the Div operand
249+# order, so ORT returns the same outputs for the swapped model (measured difference 0.0; with
250+# optimisations disabled the same swap moves the output by ~24). Such a case fails check 2 below.
251+_SWAP_CASES = [
252+ pytest.param("47_manual_softmax", "centered", "Sub", id="sub"),
253+ pytest.param("47_manual_softmax", "y", "Div", id="div_softmax"),
254+ pytest.param("06_norm_variants", "/lnrm/Div_output_0", "Div", id="div_layer_norm"),
255+ pytest.param("08_math_constants", "/Div_output_0", "Div", id="div_normalise"),
256+ pytest.param("11_clip_pipeline", "matmuled", "MatMul", id="matmul_square"),
257+]
258+ 
259+ 
260+def _copy_model(model):
261+ clone = onnx.ModelProto()
262+ clone.CopyFrom(model)
263+ return clone
264+ 
265+ 
266+def _with_perturbed_initializer(model, name, offset):
267+ """A copy of ``model`` in which exactly the float initializer ``name`` has ``offset`` added everywhere."""
268+ mutated = _copy_model(model)
269+ hits = [init for init in mutated.graph.initializer if init.name == name]
270+ assert len(hits) == 1, f"fixture has no single initializer named {name!r}"
271+ values = onnx.numpy_helper.to_array(hits[0])
272+ assert values.dtype.kind == "f", f"{name!r} is {values.dtype}; only a float initializer is perturbed"
273+ hits[0].CopyFrom(onnx.numpy_helper.from_array(values + np.asarray(offset, dtype=values.dtype), name))
274+ # exactly one initializer differs from the original
275+ before = {i.name: onnx.numpy_helper.to_array(i) for i in model.graph.initializer}
276+ after = {i.name: onnx.numpy_helper.to_array(i) for i in mutated.graph.initializer}
277+ assert before.keys() == after.keys()
278+ assert [k for k in before if not np.array_equal(before[k], after[k])] == [name]
279+ return mutated
280+ 
281+ 
282+def _with_swapped_operands(model, output_name, op_type):
283+ """A copy of ``model`` in which the two operands of the ``op_type`` node producing ``output_name`` swap."""
284+ mutated = _copy_model(model)
285+ hits = [node for node in mutated.graph.node if list(node.output) == [output_name]]
286+ assert len(hits) == 1, f"fixture has no single node producing {output_name!r}"
287+ node = hits[0]
288+ assert node.op_type == op_type and len(node.input) == 2, (node.op_type, list(node.input))
289+ first, second = node.input
290+ assert first != second, "swapping identical operands is a no-op"
291+ node.input[:] = [second, first]
292+ return mutated
293+ 
294+ 
295+def _assert_gate_detects(pristine_path, mutated_model, label, tmp_path):
296+ """Drive one mutated model through the ORT gate and prove the failure is the intended one."""
297+ out_dir = _build_dir(tmp_path)
298+ mutated_path = os.path.join(out_dir, f"{label}_mutated.onnx")
299+ onnx.save(mutated_model, mutated_path)
300+ pristine = onnx.load(pristine_path)
301+ inputs = _sample_input_for(pristine)
302+ 
303+ # 1. Tightness: the SAME helper and arguments on the unmutated model pass the gate.
304+ clean_ref, clean_inst = _reference_and_ort_outputs(pristine_path, f"{label}_clean", out_dir, ort_path=pristine_path)
305+ _assert_outputs_match(clean_ref, clean_inst)
306+ 
307+ # 2. The mutation is real in ONNX itself, independent of the emitter.
308+ ort_mutated = _ort_outputs(mutated_path, mutated_model, inputs)
309+ assert len(ort_mutated) == len(clean_ref)
310+ assert all(torch.isfinite(t.float()).all() for t in ort_mutated + clean_ref), "non-finite ORT output"
311+ assert max(_max_abs_diff(a, b) for a, b in zip(clean_ref, ort_mutated)) > _CONTROL_MARGIN * _ORT_MAX_ABS_DIFF, (
312+ "the mutation does not change the model's outputs by more than the margin; the control is not valid"
313+ )
314+ 
315+ # 3. The reference emitted from the mutated model, against ORT on the ORIGINAL. Emitting, loading and
316+ # running must succeed (an exception here is a different failure, not a detection).
317+ out_ref, out_inst = _reference_and_ort_outputs(mutated_path, f"{label}_mutated", out_dir, ort_path=pristine_path)
318+ _assert_outputs_match(ort_mutated, out_inst) # the emitter reproduces the mutated model faithfully
319+ 
320+ # 4. Only values can differ: same count, same shapes, everything finite.
321+ assert len(out_ref) == len(out_inst)
322+ assert [tuple(t.shape) for t in out_ref] == [tuple(t.shape) for t in out_inst]
323+ assert all(torch.isfinite(t.float()).all() for t in out_ref + out_inst), "non-finite output"
324+ 
325+ # 5. The gate fails on a VALUE mismatch specifically.
326+ with pytest.raises(AssertionError, match=r"output\[\d+\] max_abs_diff \S+ exceeds"):
327+ _assert_outputs_match(out_ref, out_inst)
328+ 
329+ # 6. ...by a wide margin, not a borderline flip.
330+ worst = max(_max_abs_diff(a, b) for a, b in zip(out_ref, out_inst))
331+ assert worst > _CONTROL_MARGIN * _ORT_MAX_ABS_DIFF, worst
332+ 
333+ 
334+@pytest.mark.parametrize("fixture,initializer,offset", _PERTURB_CASES)
335+def test_ort_gate_detects_a_perturbed_initializer(fixture, initializer, offset, onnx_path_for, tmp_path, request):
336+ """V2 control (a): one wrong weight in the emitted reference must trip the ORT gate.
337+ 
338+ Guards the defect where the comparison is vacuous (e.g. both sides read the same weights, or the
339+ tolerance swallows real differences) and a mis-loaded or mis-lifted weight would go unnoticed.
340+ """
341+ pristine_path = onnx_path_for(fixture)
342+ mutated = _with_perturbed_initializer(onnx.load(pristine_path), initializer, offset)
343+ _assert_gate_detects(pristine_path, mutated, "perturb_" + request.node.callspec.id, tmp_path)
344+ 
345+ 
346+@pytest.mark.parametrize("fixture,output_name,op_type", _SWAP_CASES)
347+def test_ort_gate_detects_swapped_operands(fixture, output_name, op_type, onnx_path_for, tmp_path, request):
348+ """V2 control (b): swapped operands of a non-commutative op must trip the ORT gate.
349+ 
350+ Guards the defect where a rewrite that mis-orders Sub / Div / MatMul inputs slips through because the
351+ comparison only checks shapes or counts, or because the fixture is symmetric in the swapped operands.
352+ """
353+ pristine_path = onnx_path_for(fixture)
354+ mutated = _with_swapped_operands(onnx.load(pristine_path), output_name, op_type)
355+ _assert_gate_detects(pristine_path, mutated, "swap_" + request.node.callspec.id, tmp_path)
356+ 
357+ 
358+def test_ort_gate_controls_are_not_vacuous_for_the_helper_itself(onnx_path_for, tmp_path):
359+ """The mutation helpers must change exactly what they claim and refuse to no-op.
360+ 
361+ Guards the defect where a helper silently returns an unmodified model, which would turn every control
362+ above into a comparison of identical files that "detects" nothing yet still looks like a pass of the
363+ clean half.
364+ """
365+ model = onnx.load(onnx_path_for("11_clip_pipeline"))
366+ assert _with_perturbed_initializer(model, "W", 0.5).SerializeToString() != model.SerializeToString()
367+ swapped = _with_swapped_operands(model, "matmuled", "MatMul")
368+ assert swapped.SerializeToString() != model.SerializeToString()
369+ assert list(next(n for n in swapped.graph.node if n.output[0] == "matmuled").input) == ["W", "clipped"]
370+ # the originals are untouched
371+ assert list(next(n for n in model.graph.node if n.output[0] == "matmuled").input) == ["clipped", "W"]
372+ with pytest.raises(AssertionError):
373+ _with_perturbed_initializer(model, "no_such_initializer", 0.5)
374+ with pytest.raises(AssertionError):
375+ _with_swapped_operands(model, "matmuled", "Sub") # wrong op type is refused, not silently swapped
376+ 
377+ 
378+# ---------------------------------------------------------------------------
379+# Lift-pass fallback tests
380+#
381+# Two paths under test (both in ``_lift_to_nn_modules``):
382+# 1. Whole-pass fallback — if ShapeProp.propagate raises, lift returns
383+# immediately and every candidate (BN/IN/LN/PReLU) stays functional.
384+# 2. Per-node fallback — if one lifter returns False or raises for a
385+# particular node, that node stays functional but other candidates
386+# in the same model still lift.
387+#
388+# Fixture: 01_vision_2d_cnn — has two BatchNorm2d ops AND one
389+# GlobalAveragePool. The GAP rewrite runs in pass-1 (independent of
390+# ShapeProp) so it serves as a control: it must keep lifting to
391+# nn.AdaptiveAvgPool2d even when ShapeProp fails.
392+# ---------------------------------------------------------------------------
393+ 
394+_LIFT_FIXTURE_NAME = "01_vision_2d_cnn"
395+ 
396+ 
397+def test_lift_baseline_enabled(onnx_path_for):
398+ """Sanity: with the lift enabled (no patch), source contains both
399+ nn.BatchNorm2d and nn.AdaptiveAvgPool2d. Anchors the negative
400+ assertions in the fallback tests below."""
401+ src = otrm.onnx_to_reference_source(onnx.load(onnx_path_for(_LIFT_FIXTURE_NAME)))
402+ assert "BatchNorm2d" in src, "baseline broken: lift not producing BatchNorm2d"
403+ assert "AdaptiveAvgPool2d" in src, "baseline broken: GAP rewrite missing"
404+ assert "torch.nn.functional.batch_norm" not in src, "baseline broken: F.batch_norm leaked through"
405+ 
406+ 
407+def test_lift_shape_prop_failure_falls_back_to_functional(onnx_path_for, caplog):
408+ """ShapeProp.propagate raising → lift skipped entirely; BN stays as
409+ F.batch_norm; GAP (pass-1, independent of ShapeProp) still lifts."""
410+ model = onnx.load(onnx_path_for(_LIFT_FIXTURE_NAME))
411+ with (
412+ mock.patch(
413+ "torch.fx.passes.shape_prop.ShapeProp.propagate",
414+ side_effect=RuntimeError("forced shape prop failure"),
415+ ),
416+ ):
417+ src = otrm.onnx_to_reference_source(model)
418+ 
419+ assert "torch.nn.functional.batch_norm" in src, (
420+ "expected F.batch_norm fallback in forward source\n--- source ---\n" + src
421+ )
422+ assert "BatchNorm2d" not in src, (
423+ "expected no nn.BatchNorm2d submodule when ShapeProp failed\n--- source ---\n" + src
424+ )
425+ assert "AdaptiveAvgPool2d" in src, "GAP rewrite (pass-1) regressed under ShapeProp failure\n--- source ---\n" + src
426+ diagnostics = caplog.text
427+ assert "shape prop failed" in diagnostics, "expected diagnostic log message about shape prop failure; got: " + repr(
428+ diagnostics
429+ )
430+ 
431+ 
432+def test_lift_per_node_returning_false_keeps_only_that_node_functional(onnx_path_for, caplog):
433+ """_lift_batch_norm returning False for every node → BN stays functional
434+ but other lifts (AdaptiveAvgPool) still happen, the diagnostic log lists the skips."""
435+ model = onnx.load(onnx_path_for(_LIFT_FIXTURE_NAME))
436+ with mock.patch.object(otrm, "_lift_batch_norm", return_value=False):
437+ src = otrm.onnx_to_reference_source(model)
438+ 
439+ assert "torch.nn.functional.batch_norm" in src, (
440+ "expected F.batch_norm fallback for skipped lift\n--- source ---\n" + src
441+ )
442+ assert "BatchNorm2d" not in src, "expected no nn.BatchNorm2d when lifter returned False\n--- source ---\n" + src
443+ assert "AdaptiveAvgPool2d" in src, "non-BN lift (GAP) regressed under BN-only skip\n--- source ---\n" + src
444+ diagnostics = caplog.text
445+ assert "lift skipped" in diagnostics and "batch_norm" in diagnostics, (
446+ "expected diagnostic log to list the skipped batch_norm nodes; got: " + repr(diagnostics)
447+ )
448+ 
449+ 
450+def test_lift_per_node_raising_keeps_only_that_node_functional(onnx_path_for, caplog):
451+ """_lift_batch_norm raising → caught per-node, BN stays functional,
452+ the diagnostic log includes the exception text."""
453+ model = onnx.load(onnx_path_for(_LIFT_FIXTURE_NAME))
454+ with (
455+ mock.patch.object(
456+ otrm,
457+ "_lift_batch_norm",
458+ side_effect=RuntimeError("forced per-node failure"),
459+ ),
460+ ):
461+ src = otrm.onnx_to_reference_source(model)
462+ 
463+ assert "torch.nn.functional.batch_norm" in src, (
464+ "expected F.batch_norm fallback when lifter raised\n--- source ---\n" + src
465+ )
466+ assert "BatchNorm2d" not in src
467+ assert "AdaptiveAvgPool2d" in src
468+ diagnostics = caplog.text
469+ assert "lift skipped" in diagnostics and "forced per-node failure" in diagnostics, (
470+ "expected diagnostic log to surface the exception text; got: " + repr(diagnostics)
471+ )
@@ -0,0 +1,66 @@
1+# Copyright (c) 2025-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+"""CumSum with omitted ``exclusive`` / ``reverse`` attributes must convert at the ONNX-spec default (0).
10+ 
11+onnx2torch 1.5.15 reads a missing ``reverse`` as 1, and exporters omit an attribute at its default, so an
12+exported plain ``torch.cumsum`` used to be emitted as a reverse scan. The ``52_cumsum_zoo`` fixture sets
13+both attributes explicitly on every node and therefore could not see it. Each case below is compared with
14+ONNX Runtime on the same input; the genuine reverse cases pin that the fix does not turn them forward.
15+"""
16+ 
17+import numpy as np
18+import onnx
19+import onnx_to_reference_model as otrm
20+import pytest
21+import torch
22+from onnx import TensorProto, helper, numpy_helper
23+from test_conversion import _assert_outputs_match, _flatten_outputs, _ort_outputs
24+from test_wrapper_rule_controls import _emit, _outputs_of_source
25+ 
26+_CASES = {
27+ "absent": {},
28+ "reverse_explicit_0": {"reverse": 0},
29+ "reverse_explicit_1": {"reverse": 1},
30+ "reverse_absent_exclusive_1": {"exclusive": 1},
31+ "reverse_1_exclusive_1": {"reverse": 1, "exclusive": 1},
32+}
33+ 
34+ 
35+def _model(attrs):
36+ node = helper.make_node("CumSum", ["x", "axis"], ["y"], **attrs)
37+ graph = helper.make_graph(
38+ [node],
39+ "cumsum_defaults",
40+ [helper.make_tensor_value_info("x", TensorProto.FLOAT, [2, 3])],
41+ [helper.make_tensor_value_info("y", TensorProto.FLOAT, [2, 3])],
42+ initializer=[numpy_helper.from_array(np.array(1, dtype=np.int64), "axis")],
43+ )
44+ return helper.make_model(graph, opset_imports=[helper.make_opsetid("", 17)])
45+ 
46+ 
47+@pytest.mark.parametrize("case", sorted(_CASES))
48+def test_cumsum_matches_ort(case, tmp_path):
49+ path = str(tmp_path / "cs.onnx")
50+ model = _model(_CASES[case])
51+ onnx.save(model, path)
52+ inputs = [torch.arange(1.0, 7.0).reshape(2, 3)]
53+ ref = _ort_outputs(path, model, inputs)
54+ source, weights = _emit(path, tmp_path)
55+ got = _outputs_of_source(source, weights, tmp_path, inputs, case)
56+ _assert_outputs_match(ref, got)
57+ if case == "absent":
58+ assert _flatten_outputs(got)[0].tolist() == [[1, 3, 6], [4, 9, 15]]
59+ 
60+ 
61+def test_prepare_writes_defaults_on_a_copy():
62+ model = _model({"reverse": 1})
63+ patched = otrm._prepare_for_onnx2torch(model)
64+ attrs = {a.name: a.i for a in patched.graph.node[0].attribute}
65+ assert attrs == {"reverse": 1, "exclusive": 0}
66+ assert [a.name for a in model.graph.node[0].attribute] == ["reverse"]
@@ -0,0 +1,113 @@
1+# Copyright (c) 2025-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+"""Self-containment: nothing the skill ships (or generates) names the repository it was built from.
10+ 
11+The patterns are assembled from fragments so that this file does not match itself, and the scan covers
12+every file in the skill directory, this one included.
13+"""
14+ 
15+import re
16+import shutil
17+from pathlib import Path
18+ 
19+import onnx
20+import onnx_to_reference_model as otrm
21+import pytest
22+from ingest_helpers import SKILL_DIR, run_tool, save_model
23+ 
24+_SKIPPED_DIRS = {"__pycache__", ".pytest_cache"}
25+PATTERNS = {
26+ "source repository name": re.compile("easy" + "asc", re.IGNORECASE),
27+ "parent-index repository-root discovery": re.compile(r"parents\s*\[\s*-?\d+\s*\]"),
28+ "absolute machine path": re.compile(
29+ r"(?<![\w.:/$-])/(?:"
30+ + "|".join(("ho" + "me", "Us" + "ers", "ro" + "ot", "mn" + "t", "op" + "t", "da" + "ta", "va" + "r"))
31+ + r")/"
32+ ),
33+ "windows drive path": re.compile(r"\b[A-Za-z]:\\"),
34+ "hardcoded temporary path": re.compile(r"(?<![\w.$])/" + "tm" + r"p\b"),
35+}
36+ 
37+ 
38+def scan_tree(root):
39+ """``[(relative path, line number, kind)]`` for every offending line, and the number of files scanned."""
40+ root = Path(root)
41+ findings, scanned = [], 0
42+ for path in sorted(root.rglob("*")):
43+ if not path.is_file() or _SKIPPED_DIRS & set(path.relative_to(root).parts):
44+ continue
45+ scanned += 1
46+ for number, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1):
47+ findings.extend(
48+ (str(path.relative_to(root)), number, kind) for kind, rx in PATTERNS.items() if rx.search(line)
49+ )
50+ return findings, scanned
51+ 
52+ 
53+def test_shipped_skill_files_are_free_of_source_repository_links():
54+ findings, scanned = scan_tree(SKILL_DIR)
55+ assert scanned >= 12, "the scan must have covered the skill, not an empty directory"
56+ names = {p.name for p in SKILL_DIR.rglob("*") if p.is_file()}
57+ assert {
58+ "SKILL.md",
59+ "onnx_to_reference_model.py",
60+ "onnx_ingest.py",
61+ "onnx_spec.py",
62+ "onnx-contract.md",
63+ "test_conversion.py",
64+ "generate_models.py",
65+ "requirements.txt",
66+ } <= names
67+ assert findings == []
68+ 
69+ 
70+@pytest.mark.parametrize(
71+ "sentinel,kind",
72+ [
73+ ("easy" + "asc", "source repository name"),
74+ ("Easy" + "AscV2 reference", "source repository name"),
75+ ("root = Path(__file__).resolve().par" + "ents[3]", "parent-index repository-root discovery"),
76+ ('path = "/' + "ho" + 'me/someone/work"', "absolute machine path"),
77+ ('out = "/' + "tm" + 'p/build"', "hardcoded temporary path"),
78+ ("C:" + "\\" + "Users", "windows drive path"),
79+ ],
80+)
81+def test_control_the_scan_flags_an_injected_sentinel(sentinel, kind, tmp_path):
82+ copy = tmp_path / "skill"
83+ shutil.copytree(SKILL_DIR, copy, ignore=shutil.ignore_patterns(*_SKIPPED_DIRS))
84+ assert scan_tree(copy)[0] == [], "control: the unmodified copy is clean"
85+ with open(copy / "scripts" / "onnx_ingest.py", "a", encoding="utf-8") as handle:
86+ handle.write("\n# {}\n".format(sentinel))
87+ findings, _ = scan_tree(copy)
88+ assert [(path, k) for path, _, k in findings] == [("scripts/onnx_ingest.py", kind)]
89+ 
90+ 
91+def test_environment_variable_overrides_are_kept_and_not_hardcoded_defaults():
92+ text = (SKILL_DIR / "tests" / "test_conversion.py").read_text() + (
93+ SKILL_DIR / "tests" / "generate_models.py"
94+ ).read_text()
95+ assert "ONNX_REF_TEST_BUILD" in text and "ONNX_REF_TEST_OUT" in text
96+ 
97+ 
98+def test_generated_artefacts_and_runtime_messages_carry_no_repository_path(tmp_path, monkeypatch):
99+ source = save_model("10_attention_like", tmp_path / "src")
100+ assert run_tool(source, "--emit-dir", tmp_path / "out").returncode == 0
101+ structure = otrm.onnx_to_reference_source(onnx.load(str(source)))
102+ texts = {p.name: p.read_text() for p in (tmp_path / "out").iterdir() if p.suffix in (".py", ".md", ".json")}
103+ texts["structure banner"] = structure
104+ # the converter's version-pin error is a runtime message that names the tool
105+ monkeypatch.setattr("importlib.metadata.version", lambda _name: "0.0.0")
106+ with pytest.raises(RuntimeError) as raised:
107+ otrm._check_onnx2torch_version()
108+ texts["pin error"] = str(raised.value)
109+ for label, text in texts.items():
110+ hits = [kind for kind, rx in PATTERNS.items() if rx.search(text)]
111+ assert hits == [], (label, hits)
112+ assert "scripts/onnx_to_reference_model.py" in texts["structure banner"]
113+ assert "scripts/onnx_to_reference_model.py" in texts["pin error"]
@@ -0,0 +1,126 @@
1+# Copyright (c) 2025-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+"""Two runs of the whole emission on the same input produce byte-identical artefacts, verified by hashing.
10+ 
11+The two runs are separate processes that differ in everything that is not the input: PYTHONHASHSEED (set and
12+dict ordering), output directory, working directory, temporary directory and wall-clock time.
13+"""
14+ 
15+import time
16+ 
17+import onnx
18+import onnx_ingest
19+import pytest
20+from ingest_helpers import build_model, run_tool, save_external, save_model, tree_hashes
21+from onnx import numpy_helper
22+ 
23+CASES = [
24+ ("10_attention_like", []), # weights, transposes
25+ ("30_global_avg_pool_dyn", []), # dynamic dims, two P0 cases
26+ ("01_vision_2d_cnn", ["--simplify"]), # declared transform
27+ ("48_multi_branch", ["--extract-inputs", "x", "--extract-outputs", "a"]), # extraction
28+]
29+# The five originals must all survive; the goldens' names follow --op-name, so they are derived.
30+FULL_SET = ["SPEC.md", "frozen.onnx", "manifest.json", "reference_model.py", "reference_weights.pt"]
31+ 
32+ 
33+def expected_set(names):
34+ """FULL_SET plus the one emitted ``*_golden_cpu.py`` and the one ``*_golden.py`` (npu role) beside it."""
35+ golden = sorted(n for n in names if n.endswith("_golden_cpu.py"))
36+ assert len(golden) == 1, "exactly one CPU golden is emitted, got {}".format(golden)
37+ npu = sorted(n for n in names if n.endswith("_golden.py"))
38+ assert npu == [golden[0][: -len("_cpu.py")] + ".py"], "exactly one npu golden, named for the same op: {}".format(
39+ npu
40+ )
41+ return sorted(FULL_SET + golden + npu)
42+ 
43+ 
44+def _emit(source, root, label, hash_seed, extra):
45+ work, tmp, out = root / (label + "_cwd"), root / (label + "_tmp"), root / (label + "_out")
46+ work.mkdir()
47+ tmp.mkdir()
48+ result = run_tool(
49+ source, "--emit-dir", out, *extra, cwd=work, env={"PYTHONHASHSEED": str(hash_seed), "TMPDIR": str(tmp)}
50+ )
51+ return result, out
52+ 
53+ 
54+def _emit_twice(source, tmp_path, extra=()):
55+ first, out_a = _emit(source, tmp_path, "a", 1, extra)
56+ time.sleep(1.1)
57+ second, out_b = _emit(source, tmp_path, "b", 4242, extra)
58+ return first, second, out_a, out_b
59+ 
60+ 
61+@pytest.mark.parametrize("name,extra", CASES, ids=[c[0] + ("+" + c[1][0].lstrip("-") if c[1] else "") for c in CASES])
62+def test_two_emissions_are_byte_identical(name, extra, tmp_path):
63+ source = save_model(name, tmp_path / "src")
64+ first, second, out_a, out_b = _emit_twice(source, tmp_path, extra)
65+ assert first.returncode == 0 and second.returncode == 0, first.stderr + second.stderr
66+ hashes_a, hashes_b = tree_hashes(out_a), tree_hashes(out_b)
67+ assert sorted(hashes_a) == expected_set(hashes_a), "every artefact was emitted"
68+ assert set(FULL_SET) <= set(hashes_a), "no original artefact was dropped"
69+ assert hashes_a == hashes_b
70+ 
71+ 
72+def test_refused_emission_is_byte_identical_too(tmp_path):
73+ source = save_external(build_model("48_multi_branch"), tmp_path / "src", "mb.onnx", "mb.weights")
74+ (source.parent / "mb.weights").unlink()
75+ first, second, out_a, out_b = _emit_twice(source, tmp_path)
76+ assert first.returncode == 6 and second.returncode == 6
77+ hashes_a = tree_hashes(out_a)
78+ assert sorted(hashes_a) == ["manifest.json", "reference_model.py"] and hashes_a == tree_hashes(out_b)
79+ 
80+ 
81+def test_weights_and_reference_do_not_depend_on_where_the_source_stored_its_weights(tmp_path):
82+ inline = save_model("48_multi_branch", tmp_path / "inline", "mb.onnx")
83+ external = save_external(build_model("48_multi_branch"), tmp_path / "external", "mb.onnx", "mb.weights")
84+ assert run_tool(inline, "--emit-dir", tmp_path / "out_inline").returncode == 0
85+ assert run_tool(external, "--emit-dir", tmp_path / "out_external").returncode == 0
86+ hashes_inline, hashes_external = tree_hashes(tmp_path / "out_inline"), tree_hashes(tmp_path / "out_external")
87+ # (frozen.onnx may differ byte-wise: a resolved tensor keeps an explicit data_location field)
88+ for name in ("reference_weights.pt", "reference_model.py"):
89+ assert hashes_inline[name] == hashes_external[name], name
90+ 
91+ 
92+def test_the_hash_comparison_can_fail(tmp_path):
93+ """Control: the comparison is sensitive, so identical hashes above are not an artefact of the method."""
94+ model = build_model("10_attention_like")
95+ base = tmp_path / "base"
96+ base.mkdir()
97+ onnx.save(model, str(base / "m.onnx"))
98+ perturbed = onnx.ModelProto()
99+ perturbed.CopyFrom(model)
100+ weight = perturbed.graph.initializer[0]
101+ array = numpy_helper.to_array(weight).copy()
102+ array.flat[0] += 1.0
103+ weight.CopyFrom(numpy_helper.from_array(array, weight.name))
104+ other = tmp_path / "other"
105+ other.mkdir()
106+ onnx.save(perturbed, str(other / "m.onnx"))
107+ 
108+ out_base, out_other, out_again = tmp_path / "o1", tmp_path / "o2", tmp_path / "o3"
109+ for source, out in ((base / "m.onnx", out_base), (other / "m.onnx", out_other), (base / "m.onnx", out_again)):
110+ assert run_tool(source, "--emit-dir", out).returncode == 0
111+ same, different = tree_hashes(out_base), tree_hashes(out_other)
112+ assert same == tree_hashes(out_again)
113+ changed = sorted(n for n in same if same[n] != different[n])
114+ assert {"reference_weights.pt", "frozen.onnx", "manifest.json"} <= set(changed)
115+ # a different op name changes the SPEC and only what records it
116+ renamed = tmp_path / "o4"
117+ assert run_tool(base / "m.onnx", "--emit-dir", renamed, "--op-name", "other_name").returncode == 0
118+ assert tree_hashes(renamed)["SPEC.md"] != same["SPEC.md"]
119+ assert tree_hashes(renamed)["reference_weights.pt"] == same["reference_weights.pt"]
120+ 
121+ 
122+def test_in_process_emission_twice_is_identical(tmp_path):
123+ source = save_model("10_attention_like", tmp_path / "src")
124+ onnx_ingest.emit_artifacts(source, tmp_path / "a")
125+ onnx_ingest.emit_artifacts(source, tmp_path / "b")
126+ assert tree_hashes(tmp_path / "a") == tree_hashes(tmp_path / "b")
@@ -0,0 +1,182 @@
1+# Copyright (c) 2025-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+"""Real ORT checks, refusal controls and host-only device harness tests. No NPU evidence."""
10+ 
11+import json
12+ 
13+import numpy as np
14+import onnx_to_reference_model as converter
15+import onnxruntime as ort
16+import pytest
17+import torch
18+import validate_device_goldens as device
19+from contract_cases import emit
20+from ingest_helpers import load_reference
21+from onnx import TensorProto as T
22+from onnx import helper as h
23+from onnx import numpy_helper as nh
24+from test_graph_policy import mixed_model
25+ 
26+ 
27+def gather_model(axis, indices, intermediate=False, symbolic=False):
28+ shape = ["batch" if symbolic else 2, 3, 4]
29+ positive = axis % 3
30+ out_shape = shape[:positive] + list(indices.shape) + shape[positive + 1 :]
31+ nodes = [h.make_node("Identity", ["x"], ["middle"])] if intermediate else []
32+ nodes.append(h.make_node("Gather", ["middle" if intermediate else "x", "idx"], ["y"], axis=axis))
33+ model = h.make_model(
34+ h.make_graph(
35+ nodes,
36+ "gather",
37+ [h.make_tensor_value_info("x", T.FLOAT, shape)],
38+ [h.make_tensor_value_info("y", T.FLOAT, out_shape)],
39+ [nh.from_array(indices, "idx")],
40+ ),
41+ opset_imports=[h.make_opsetid("", 13)],
42+ )
43+ model.ir_version = 8
44+ return model
45+ 
46+ 
47+@pytest.mark.parametrize("axis", [-1, -2, -3])
48+@pytest.mark.parametrize(
49+ "indices", [np.array(-1, np.int64), np.array([0, -1], np.int64), np.array([[0, -1], [-1, 0]], np.int64)]
50+)
51+@pytest.mark.parametrize("intermediate,symbolic", [(False, False), (True, True)])
52+def test_negative_gather_matches_positive_and_ort(tmp_path, axis, indices, intermediate, symbolic):
53+ x = torch.arange(24).reshape(2, 3, 4).float()
54+ results = []
55+ for suffix, chosen_axis in [("negative", axis), ("positive", axis + 3)]:
56+ dest = tmp_path / suffix
57+ dest.mkdir()
58+ model = gather_model(chosen_axis, indices, intermediate, symbolic)
59+ # Test converter directly: symbolic rank is known without picking dimension values.
60+ path = dest / "reference_weights.pt"
61+ unmapped = []
62+ source = converter.onnx_to_reference_source(model, str(path), unmapped_out=unmapped)
63+ assert not unmapped
64+ (dest / "reference_model.py").write_text(source)
65+ actual = load_reference(dest)(x)
66+ session = ort.InferenceSession(model.SerializeToString(), providers=["CPUExecutionProvider"])
67+ expected = session.run(None, {"x": x.numpy()})[0]
68+ assert np.array_equal(actual.detach().numpy(), expected)
69+ results.append(actual)
70+ assert torch.equal(*results)
71+ 
72+ 
73+def test_unresolved_gather_rank_refused():
74+ model = gather_model(-1, np.array([0], np.int64))
75+ model.graph.input[0].type.tensor_type.ClearField("shape")
76+ unmapped = []
77+ converter.onnx_to_reference_source(model, unmapped_out=unmapped)
78+ assert any("unresolved input rank" in desc for _, desc in unmapped)
79+ 
80+ 
81+@pytest.fixture
82+def emitted(tmp_path):
83+ model = mixed_model()
84+ model.graph.initializer[1].CopyFrom(nh.from_array(np.array([1.0, 2.0], np.float32), "bias"))
85+ return emit(tmp_path, model, samples={"x": torch.tensor([[1.0, 1.5]], dtype=torch.float16)})[0]
86+ 
87+ 
88+def test_real_host_ort_comparison_is_not_device_pass(emitted):
89+ report = {}
90+ device.validate(emitted, report, cpu_only=True)
91+ assert report["status"] == "HOST_ONLY"
92+ assert report["device_numerics"] == "NOT_RUN"
93+ assert len(report["comparisons"]) == 1
94+ assert all(r["status"] == "PASS" for r in report["comparisons"])
95+ 
96+ 
97+def test_missing_device_is_blocked(emitted, tmp_path, monkeypatch):
98+ def unavailable(index):
99+ raise device.DeviceUnavailable("no device in host qualification")
100+ 
101+ monkeypatch.setattr(device, "open_device", unavailable)
102+ report_path = tmp_path / "device_report.json"
103+ assert device.main(["--emit-dir", str(emitted), "--report", str(report_path), "--device", "0"]) == 2
104+ assert json.loads(report_path.read_text())["status"] == "BLOCKED"
105+ 
106+ 
107+def test_cpu_fallback_rejected():
108+ with pytest.raises(ValueError, match="actual npu"):
109+ device.checked_outputs(torch.ones(2), [("y", [2], "float32")], "default", "npu", "npu")
110+ 
111+ 
112+@pytest.mark.parametrize("fault", ["value", "dtype", "shape", "nonfinite"])
113+def test_bad_device_output_controls(fault):
114+ value = {
115+ "value": torch.full((2,), 100.0),
116+ "dtype": torch.ones(2).half(),
117+ "shape": torch.ones(1, 2),
118+ "nonfinite": torch.full((2,), float("nan")),
119+ }[fault]
120+ expected = [("y", [2], "float32")]
121+ if fault == "value":
122+ record = device.compare_outputs([value], [torch.ones(2)], "default", expected, "npu_vs_ort")[0]
123+ assert record["status"] == "FAIL"
124+ else:
125+ with pytest.raises(ValueError):
126+ device.checked_outputs(value, expected, "default", "test", "cpu")
127+ 
128+ 
129+def test_stale_golden_rejected(emitted):
130+ path = emitted / "probe_op_golden.py"
131+ path.write_text(path.read_text() + "\n# changed\n")
132+ with pytest.raises(ValueError, match="stale artifact"):
133+ device.validate(emitted, {}, cpu_only=True)
134+ 
135+ 
136+@pytest.mark.parametrize("fault", ["missing", "duplicate", "mutation", "wrong_value"])
137+def test_executed_cpu_controls(emitted, monkeypatch, fault):
138+ original_load = device.load
139+ 
140+ def altered(path, name):
141+ module = original_load(path, name)
142+ if name != "_onnx_device_cpu":
143+ return module
144+ original_inputs = module._make_inputs
145+ if fault in ("missing", "duplicate"):
146+ module._make_inputs = lambda dev: [] if fault == "missing" else original_inputs(dev) * 2
147+ elif fault == "mutation":
148+ 
149+ def mutate(x, **kw):
150+ x.add_(1)
151+ return x.float()
152+ 
153+ module.probe_op_golden_cpu = mutate
154+ else:
155+ module.probe_op_golden_cpu = lambda x, **kw: x.float() + 100
156+ return module
157+ 
158+ monkeypatch.setattr(device, "load", altered)
159+ report = {}
160+ if fault == "wrong_value":
161+ device.validate(emitted, report, cpu_only=True)
162+ assert report["status"] == "FAIL"
163+ else:
164+ with pytest.raises(ValueError, match="cases|mutated"):
165+ device.validate(emitted, report, cpu_only=True)
166+ 
167+ 
168+def test_integer_exactness_above_float64_precision():
169+ record = device.compare_outputs(
170+ [torch.tensor([2**53])], [torch.tensor([2**53 + 1])], "case", [("y", [1], "int64")], "npu_vs_cpu"
171+ )[0]
172+ assert record["status"] == "FAIL"
173+ 
174+ 
175+def test_strict_scheme_a_failure_not_hidden_by_absolute_ort_guard(tmp_path):
176+ out, summary = emit(tmp_path, mixed_model(), samples={"x": torch.tensor([[1.0, 1.5]], dtype=torch.float16)})
177+ assert summary["validation"]["graph_cpu_agreement"] == "PASS" # existing absolute guard
178+ report = {}
179+ device.validate(out, report, cpu_only=True)
180+ assert report["status"] == "FAIL"
181+ assert report["comparisons"][0]["max_abs_diff"] < report["comparisons"][0]["limit"]
182+ assert report["comparisons"][0]["scheme_a_passed"] is False
Acannbot-skills/ops/pypto-pro-onnx-ingest/tests/test_extract_manifest.py+408-0文件内容审核中,请稍后刷新重试
Acannbot-skills/ops/pypto-pro-onnx-ingest/tests/test_graph_policy.py+114-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/plugins-official/pypto-pro-op-orchestrator/AGENTS.md+4-0文件内容审核中,请稍后刷新重试