Merged
fix(codegen): Uniquify the LiteNPU kernel entry name by function hash #5598
hid22900163Add on Aug 21
fix(codegen): Uniquify the LiteNPU kernel entry name by function hash #5598
Merged
hid22900163Add on Aug 21
Total: 5 files changed+326-3
@@ -20,6 +20,7 @@
20#include "codegen_op_litenpu.h"20#include "codegen_op_litenpu.h"
21#include "codegen/utils/codegen_utils.h"21#include "codegen/utils/codegen_utils.h"
22#include "codegen/utils/parallel_execute.h"22#include "codegen/utils/parallel_execute.h"
23+#include "interface/function/function.h"
23 24 
24namespace npu::tile_fwk {25namespace npu::tile_fwk {
25 26 
@@ -135,7 +136,7 @@ void CodeGenLiteNPU::GenCode(Function& topFunc)
135 int blockDim = 1; // NEXTNEXT: currently only support one block dim136 int blockDim = 1; // NEXTNEXT: currently only support one block dim
136 int jsonWorkspaceSize = subFunc->GetStackWorkespaceSize();137 int jsonWorkspaceSize = subFunc->GetStackWorkespaceSize();
137 GenConfigJson(compileInfo.GetJsonAbsPath(), compileInfo.GetCCEAbsPath(), compileInfo.GetBinAbsPath(),138 GenConfigJson(compileInfo.GetJsonAbsPath(), compileInfo.GetCCEAbsPath(), compileInfo.GetBinAbsPath(),
138- topFunc.GetMagicName(), jsonWorkspaceSize, inOutParams, blockDim);139+ topFunc.GetMagicNameWithHash(), jsonWorkspaceSize, inOutParams, blockDim);
139 }140 }
140#endif141#endif
141 UpdateSubFunc(subFuncPair, compileInfo);142 UpdateSubFunc(subFuncPair, compileInfo);
@@ -329,7 +330,7 @@ extern "C" __global__ [aicore] void ${FunctionName}$_main(${GlobalParams}$) {
329 }330 }
330 331 
331 SubstMap substMap = {332 SubstMap substMap = {
332- {"FunctionName", func.GetMagicName()},333+ {"FunctionName", func.GetMagicNameWithHash()},
333 {"ProgramId", std::to_string(subFuncPair.first)},334 {"ProgramId", std::to_string(subFuncPair.first)},
334 {"SubProgCode", subProgramCode},335 {"SubProgCode", subProgramCode},
335 {"GlobalParams", globalParams.substr(0, globalParams.length() - 2)},336 {"GlobalParams", globalParams.substr(0, globalParams.length() - 2)},
@@ -701,6 +701,7 @@ public:
701 bool IsExplicit() const { return explicitArgSlots_.empty(); }701 bool IsExplicit() const { return explicitArgSlots_.empty(); }
702 size_t GetOperationSize() const { return operations_.size(); }702 size_t GetOperationSize() const { return operations_.size(); }
703 const std::string& GetMagicName() const { return funcMagicName_; }703 const std::string& GetMagicName() const { return funcMagicName_; }
704+ std::string GetMagicNameWithHash() const { return GetMagicName() + "_" + GetFunctionHash(); }
704 const std::string& GetRawName() const { return funcRawName_; }705 const std::string& GetRawName() const { return funcRawName_; }
705 std::string GetOriginalRawName() const;706 std::string GetOriginalRawName() const;
706 void AppendCalleeMagicName(const std::string& name) { calleeMagicNameList_.push_back(name); }707 void AppendCalleeMagicName(const std::string& name) { calleeMagicNameList_.push_back(name); }
@@ -13,6 +13,7 @@
13#include "tilefwk/pypto_fwk_log.h"13#include "tilefwk/pypto_fwk_log.h"
14#include "adapter/api/acl_api.h"14#include "adapter/api/acl_api.h"
15#include "adapter/api/runtime_api.h"15#include "adapter/api/runtime_api.h"
16+#include "interface/function/function.h"
16#include "interface/utils/op_info_manager.h"17#include "interface/utils/op_info_manager.h"
17#include "interface/program/program.h"18#include "interface/program/program.h"
18#include "machine/runtime/launcher/device_launcher.h"19#include "machine/runtime/launcher/device_launcher.h"
@@ -214,7 +215,7 @@ void EslModelLauncher::LiteRegisterKernel(Function* function, void*& hdl, int& s
214 stubFunc = 1;215 stubFunc = 1;
215 std::string kernelName = "";216 std::string kernelName = "";
216 for (auto& devRoot : dynAttr->funcGroup.devRootList) {217 for (auto& devRoot : dynAttr->funcGroup.devRootList) {
217- kernelName = dynAttr->rootTileDict[devRoot]->GetMagicName() + "_main";218+ kernelName = dynAttr->rootTileDict[devRoot]->GetMagicNameWithHash() + "_main";
218 }219 }
219 RuntimeFunctionRegister(hdl, &stubFunc, kernelName.c_str(), kernelName.c_str(), 0);220 RuntimeFunctionRegister(hdl, &stubFunc, kernelName.c_str(), kernelName.c_str(), 0);
220}221}
@@ -0,0 +1,119 @@
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+"""Build one Kirin9030 kernel and print the entry name recorded in its JSON sidecar.
13+ 
14+Run as a subprocess by test_kirin9030_kernel_entry_uniqueness.py, which copies this file once per build. The
15+separate interpreter is the point: the function id feeding the magic name comes from a process-global counter,
16+so two builds in one interpreter never share a magic name and could not exercise entry-name uniqueness.
17+ 
18+The kernel is always named add_kernel, so its source name cannot be what separates two builds; the operation
19+comes from argv. The test asserts that both builds collide on the magic name, so drift between the two
20+definitions below fails rather than passing silently.
21+"""
22+ 
23+import glob
24+import json
25+import os
26+import re
27+import sys
28+ 
29+import torch
30+ 
31+import pypto
32+ 
33+_OP = sys.argv[1] if len(sys.argv) > 1 else ""
34+ 
35+if _OP == "add":
36+ 
37+ @pypto.frontend.jit(
38+ codegen_options={"soc_version": "Kirin9030"},
39+ runtime_options={"run_mode": pypto.RunMode.SIM},
40+ )
41+ def add_kernel(
42+ input0: pypto.Tensor([...], pypto.DT_INT32),
43+ input1: pypto.Tensor([...], pypto.DT_INT32),
44+ output: pypto.Tensor([...], pypto.DT_INT32),
45+ ):
46+ pypto.set_vec_tile_shapes(200)
47+ output[:] = pypto.add(input0, input1)
48+ 
49+elif _OP == "sub":
50+ 
51+ @pypto.frontend.jit(
52+ codegen_options={"soc_version": "Kirin9030"},
53+ runtime_options={"run_mode": pypto.RunMode.SIM},
54+ )
55+ def add_kernel(
56+ input0: pypto.Tensor([...], pypto.DT_INT32),
57+ input1: pypto.Tensor([...], pypto.DT_INT32),
58+ output: pypto.Tensor([...], pypto.DT_INT32),
59+ ):
60+ pypto.set_vec_tile_shapes(200)
61+ output[:] = pypto.sub(input0, input1)
62+ 
63+else:
64+ raise SystemExit(f"unknown operation {_OP!r}; expected one of: add, sub")
65+ 
66+ 
67+def main():
68+ shape = (160,)
69+ input0 = torch.randint(-100, 100, shape, dtype=torch.int32)
70+ input1 = torch.randint(-100, 100, shape, dtype=torch.int32)
71+ output = torch.empty(shape, dtype=torch.int32)
72+ 
73+ # The sidecar is written during code generation, which precedes execution. Executing the kernel is merely
74+ # the public way to reach code generation, so a launch-side failure still leaves the artifact to inspect.
75+ try:
76+ add_kernel(input0, input1, output)
77+ except Exception as exc:
78+ print("EXECUTION_FAILED %s: %s" % (type(exc).__name__, exc), file=sys.stderr)
79+ 
80+ # CodeGenCCE::PrepareDefaultOutputPath creates kernel_aicore whenever code generation runs, independently
81+ # of the CANN build that fills it, so an absent directory means code generation never happened -- a
82+ # breakage, not an environment limit. (KEY_FIXED_OUTPUT_PATH / IsFixedCceMode relocate the directory, so
83+ # this driver expects the default output layout.)
84+ sidecar_dir = os.path.join(pypto.pypto_impl.LogTopFolder(), "kernel_aicore")
85+ if not os.path.isdir(sidecar_dir):
86+ print("NO_CODEGEN %s" % sidecar_dir)
87+ return 5
88+ 
89+ names = set()
90+ for path in sorted(glob.glob(os.path.join(sidecar_dir, "*.json"))):
91+ with open(path, encoding="utf-8") as handle:
92+ name = json.load(handle).get("kernelName")
93+ if name:
94+ names.add(name)
95+ 
96+ if not names:
97+ print("NO_SIDECAR %s" % sidecar_dir)
98+ return 3
99+ if len(names) > 1:
100+ print("AMBIGUOUS_SIDECAR %s" % sorted(names))
101+ return 4
102+ 
103+ # The sidecar's kernelName and the symbol in the emitted kernel source are written by two independent
104+ # code paths -- GenConfigJson appends the suffix itself, while the source comes from a template that
105+ # spells it inline -- so agreement between them is a real assertion, not a restatement of one value.
106+ symbols = set()
107+ for path in sorted(glob.glob(os.path.join(sidecar_dir, "*.cpp"))):
108+ with open(path, encoding="utf-8") as handle:
109+ found = re.findall(r'extern\s+"C".*?void\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(', handle.read())
110+ symbols.update(found)
111+ 
112+ print("ENTRY_NAME=%s" % names.pop())
113+ for symbol in sorted(symbols):
114+ print("CCE_SYMBOL=%s" % symbol)
115+ return 0
116+ 
117+ 
118+if __name__ == "__main__":
119+ sys.exit(main())
@@ -0,0 +1,201 @@
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+"""
13+Test LiteNPU kernel entry-name uniqueness for Kirin9030.
14+ 
15+The LiteNPU entry symbol (and the ``kernelName`` field of the JSON sidecar that carries it) is built from the
16+function magic name plus the function content hash. The magic name alone is ``<function name>_<id>``, where the
17+function is the generated top-level device function -- so its name reflects the lowering structure rather than
18+anything the kernel author wrote -- and the id comes from a process-global counter that ``Program::Reset()``
19+rewinds. Kernels of the same structural shape therefore share a magic name whenever they are built in separate
20+processes, which is the regime that matters: each operator of a multi-operator offline model is exported and
21+built by its own process, and the resulting artifacts are only combined afterwards. Colliding entry names make
22+one kernel's binary shadow the other's inside the combined model.
23+ 
24+Two consequences drive the shape of this test:
25+ 
26+* The builds must happen in separate interpreters. Inside one interpreter the id counter keeps advancing, so
27+ two same-named kernels already get distinct magic names and the content hash is not what separates them --
28+ an in-process test would pass whether or not the hash takes part in the entry name.
29+* A control case is required. The content hash must depend on the kernel body only. If it picked up anything
30+ process-varying, the uniqueness assertion would go green for the wrong reason while colliding entry names
31+ stayed possible. Building the identical kernel in two fresh interpreters and demanding an identical entry
32+ name is what rules that out.
33+ 
34+The sidecar is emitted by ``CodeGenLiteNPU::GenConfigJson`` only in a CANN-enabled build with ASCEND_HOME_PATH
35+set, so this is a box test: it skips when no sidecar is produced.
36+"""
37+ 
38+import os
39+from pathlib import Path
40+import re
41+import shutil
42+import subprocess
43+import sys
44+ 
45+import pytest
46+ 
47+# The build driver always names its kernel add_kernel, so the source name cannot be what separates two
48+# builds, and takes the operation to use as its one argument.
49+_DRIVER_PATH = Path(__file__).with_name("kernel_entry_uniqueness_driver.py")
50+ 
51+# Entry names have the form <function name>_<function id>_<content hash>_main. The magic-name part is captured
52+# separately from the hash part so a test can assert on each independently.
53+_ENTRY_NAME = re.compile(r"^(?P<magic>[A-Za-z_][A-Za-z0-9_]*?_\d+)_(?P<hash>\d+)_main$")
54+ 
55+_BUILD_TIMEOUT_SECONDS = 600
56+ 
57+_ENTRY_NAME_PREFIX = "ENTRY_NAME="
58+_CCE_SYMBOL_PREFIX = "CCE_SYMBOL="
59+# Key under which the fixture carries the per-build emitted symbols, kept out of the tag namespace.
60+_SYMBOLS_KEY = "__symbols__"
61+ 
62+ 
63+def _output_tail(stdout, stderr):
64+ """Render the tail of a build's streams for a failure or skip message."""
65+ 
66+ def as_text(stream):
67+ if stream is None:
68+ return ""
69+ return stream.decode(errors="replace") if isinstance(stream, bytes) else stream
70+ 
71+ return f"--- stdout ---\n{as_text(stdout)[-2000:]}\n--- stderr ---\n{as_text(stderr)[-2000:]}"
72+ 
73+ 
74+def _entry_name(base_dir, tag, op):
75+ """Build add_kernel with the given operation in a fresh interpreter and return its emitted entry name."""
76+ # Each build gets its own copy, so the three builds differ in script path as well as body: the control
77+ # case then also shows the content hash ignores where the source was read from.
78+ script = base_dir / f"build_{tag}.py"
79+ shutil.copyfile(_DRIVER_PATH, script)
80+ 
81+ # Each build gets its own framework output directory so the two runs cannot read each other's sidecars.
82+ output_dir = base_dir / f"output_{tag}"
83+ output_dir.mkdir()
84+ env = dict(os.environ)
85+ env["TILE_FWK_OUTPUT_DIR"] = str(output_dir)
86+ 
87+ try:
88+ proc = subprocess.run(
89+ [sys.executable, str(script), op],
90+ cwd=str(base_dir),
91+ env=env,
92+ capture_output=True,
93+ text=True,
94+ timeout=_BUILD_TIMEOUT_SECONDS,
95+ check=False,
96+ )
97+ except subprocess.TimeoutExpired as expired:
98+ raise AssertionError(
99+ f"{tag} build exceeded {_BUILD_TIMEOUT_SECONDS}s\n{_output_tail(expired.stdout, expired.stderr)}"
100+ ) from expired
101+ 
102+ # Exit code 3 is the one environment-limited outcome: code generation ran but the CANN-gated sidecar writer
103+ # produced nothing. Every other non-zero code, including a missing kernel_aicore directory, is a breakage.
104+ if proc.returncode == 3:
105+ pytest.skip(f"no LiteNPU JSON sidecar emitted for the {tag} build\n{_output_tail(proc.stdout, proc.stderr)}")
106+ if proc.returncode != 0:
107+ raise AssertionError(
108+ f"{tag} build failed with exit code {proc.returncode}\n{_output_tail(proc.stdout, proc.stderr)}"
109+ )
110+ 
111+ # Scan for the tagged line rather than taking the last one: pypto's native logging also writes to stdout.
112+ reported = [
113+ line[len(_ENTRY_NAME_PREFIX):].strip()
114+ for line in proc.stdout.splitlines()
115+ if line.startswith(_ENTRY_NAME_PREFIX)
116+ ]
117+ if len(reported) != 1 or not reported[0]:
118+ raise AssertionError(
119+ f"{tag} build did not report exactly one entry name\n{_output_tail(proc.stdout, proc.stderr)}"
120+ )
121+ 
122+ symbols = [
123+ line[len(_CCE_SYMBOL_PREFIX):].strip()
124+ for line in proc.stdout.splitlines()
125+ if line.startswith(_CCE_SYMBOL_PREFIX)
126+ ]
127+ return reported[0], symbols
128+ 
129+ 
130+@pytest.fixture(scope="module")
131+def entry_names(tmp_path_factory):
132+ """Entry names of three separate builds: add_kernel twice, then the same-named kernel with a different body."""
133+ if not os.environ.get("ASCEND_HOME_PATH"):
134+ pytest.skip("ASCEND_HOME_PATH is unset, so no LiteNPU JSON sidecar is emitted")
135+ 
136+ base_dir = tmp_path_factory.mktemp("kernel_entry_uniqueness")
137+ builds = {
138+ "add_first": _entry_name(base_dir, "add_first", "add"),
139+ "add_second": _entry_name(base_dir, "add_second", "add"),
140+ "other_body": _entry_name(base_dir, "other_body", "sub"),
141+ }
142+ return {tag: name for tag, (name, _symbols) in builds.items()} | {
143+ _SYMBOLS_KEY: {tag: symbols for tag, (_name, symbols) in builds.items()}
144+ }
145+ 
146+ 
147+def test_same_kernel_in_two_processes_has_one_entry_name(entry_names):
148+ """Control: an identical kernel body built twice yields one entry name, so the hash is body-determined."""
149+ assert entry_names["add_first"] == entry_names["add_second"], (
150+ f"identical kernel bodies produced different entry names: "
151+ f"{entry_names['add_first']} vs {entry_names['add_second']}"
152+ )
153+ 
154+ 
155+def test_different_kernels_sharing_a_name_get_distinct_entry_names(entry_names):
156+ """Guard: two kernels both named add_kernel but with different bodies get distinct entry names."""
157+ assert entry_names["add_first"] != entry_names["other_body"], (
158+ f"kernels with different bodies share the entry name {entry_names['add_first']}, "
159+ f"so combining their artifacts into one offline model loses one of them"
160+ )
161+ 
162+ 
163+def test_distinct_entry_names_differ_only_in_the_content_hash(entry_names):
164+ """The two kernels of the guard case collide on the magic name and are separated by the content hash alone.
165+ 
166+ Asserting the collision is what gives the guard its force. The magic-name part is what an entry name built
167+ from the magic name alone would consist of, so equality there demonstrates that the hash suffix -- and only
168+ the hash suffix -- is what keeps these two kernels apart.
169+ """
170+ first = _ENTRY_NAME.match(entry_names["add_first"])
171+ other = _ENTRY_NAME.match(entry_names["other_body"])
172+ assert first is not None, f"unexpected entry name format: {entry_names['add_first']}"
173+ assert other is not None, f"unexpected entry name format: {entry_names['other_body']}"
174+ 
175+ assert first.group("magic") == other.group("magic"), (
176+ f"the two kernels do not collide on the magic name ({first.group('magic')} vs {other.group('magic')}), "
177+ f"so this case does not exercise entry-name uniqueness"
178+ )
179+ assert first.group("hash") != other.group("hash"), f"the two kernels share the content hash {first.group('hash')}"
180+ 
181+ 
182+def test_sidecar_entry_name_matches_the_emitted_kernel_symbol(entry_names):
183+ """The sidecar and the generated kernel source name the kernel through two independent code paths.
184+ 
185+ The sidecar writer is handed a name and appends the entry suffix itself; the kernel source gets its symbol
186+ from a template that spells that suffix inline. Nothing compares the two, so a change to either spelling
187+ would ship silently. This is the same class of divergence the shared entry-name helper removes between
188+ codegen and the launch path, on the one seam a test can actually reach.
189+ """
190+ symbols_by_tag = entry_names[_SYMBOLS_KEY]
191+ for tag in ("add_first", "add_second", "other_body"):
192+ symbols = symbols_by_tag[tag]
193+ assert symbols, f"the {tag} build emitted no kernel source symbol to compare against the sidecar"
194+ assert entry_names[tag] in symbols, (
195+ f"{tag}: the sidecar records kernelName {entry_names[tag]!r}, but the emitted kernel source "
196+ f"declares {symbols!r} -- the two spellings of the entry symbol have diverged"
197+ )
198+ 
199+ 
200+if __name__ == "__main__":
201+ pytest.main([__file__, "-v"])