Merged
decouple_ops_deliverables_paths #7441
decouple_ops_deliverables_paths #7441
Merged
liuliu876Add on 11 days ago
Total: 7 files changed+1155-32
@@ -18,19 +18,45 @@ import json
18import sys18import sys
19from asc_op_compile_base.asc_op_compiler.op_tiling import _ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT, op_impl_path19from asc_op_compile_base.asc_op_compiler.op_tiling import _ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT, op_impl_path
20from asc_op_compile_base.common.utils.log_utils import LogUtil, AscendCLogLevel20from asc_op_compile_base.common.utils.log_utils import LogUtil, AscendCLogLevel
21+from asc_op_compile_base.common.ops_deliverables_conf import get_existing_deliverable_paths
22+ 
23+ 
24+def _conf_log(msg):
25+ LogUtil.print_compile_log("check_optype_duplicate", msg, AscendCLogLevel.LOG_INFO, LogUtil.Option.NON_SOC)
26+ 
27+ 
28+def _get_ops_info_paths_from_conf(soc_version):
29+ """Query built-in ops-info files from ops deliverables conf.
30+ 
31+ Return None if the conf is not usable (caller falls back to legacy dir scan);
32+ otherwise return the existing ops-info file paths in declaration order.
33+ """
34+ return get_existing_deliverable_paths(
35+ "ops-info",
36+ opp_path=os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT),
37+ soc_version=soc_version,
38+ log_func=_conf_log,
39+ )
21 40 
22 41 
23def check_optype_duplicate(args, ini_optypes):42def check_optype_duplicate(args, ini_optypes):
24- opp_path = os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT)43+ # ops deliverables conf first (compatibility first: no conf, entry not declared, or nothing
25- json_path_base = os.path.join(opp_path, op_impl_path, os.path.join("ai_core", "tbe", "config", args.soc_version))44+ # declared exists on disk all fall back to the legacy hard-coded dir scan)
26- LogUtil.print_compile_log(45+ json_files = _get_ops_info_paths_from_conf(args.soc_version)
27- "check_optype_duplicate",46+ if not json_files:
28- f"json path base is {json_path_base}",47+ # fallback: legacy hard-coded config dir scan, keep original behavior
29- AscendCLogLevel.LOG_DEBUG,48+ opp_path = os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT)
30- LogUtil.Option.NON_SOC,49+ json_path_base = os.path.join(
31- )50+ opp_path, op_impl_path, os.path.join("ai_core", "tbe", "config", args.soc_version)
32- json_pattern = json_path_base + "/*.json"51+ )
33- json_files = glob.glob(json_pattern, recursive=True)52+ LogUtil.print_compile_log(
53+ "check_optype_duplicate",
54+ f"json path base is {json_path_base}",
55+ AscendCLogLevel.LOG_DEBUG,
56+ LogUtil.Option.NON_SOC,
57+ )
58+ json_pattern = json_path_base + "/*.json"
59+ json_files = glob.glob(json_pattern, recursive=True)
34 60 
35 if len(json_files) == 0:61 if len(json_files) == 0:
36 LogUtil.print_compile_log(62 LogUtil.print_compile_log(
@@ -0,0 +1,427 @@
1+#!/usr/bin/python3
2+# coding=utf-8
3+# ----------------------------------------------------------------------------------------------------------
4+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
5+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6+# CANN Open Software License Agreement Version 2.0 (the "License").
7+# Please refer to the License for details. You may not use this file except in compliance with the License.
8+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10+# See LICENSE in the root of the software repository for the full text of the License.
11+# ----------------------------------------------------------------------------------------------------------
12+import argparse
13+import json
14+import os
15+import platform
16+import sys
17+import tempfile
18+import unittest
19+from unittest import mock
20+ 
21+THIS_FILE_NAME = __file__
22+FILE_PATH = os.path.dirname(os.path.realpath(THIS_FILE_NAME))
23+TOP_PATH = os.path.join(FILE_PATH, "../../../")
24+FRAMEWORK_PATH = os.path.join(TOP_PATH, "tools/build/")
25+sys.path.insert(0, FRAMEWORK_PATH)
26+ 
27+import asc_op_compile_base.common.ops_deliverables_conf as ops_deliverables_conf
28+from asc_op_compile_base.asc_op_compiler import op_tiling
29+from asc_op_compile_base.asc_op_compiler import get_op_tiling
30+ 
31+sys.path.insert(0, os.path.join(TOP_PATH, "cmake/asc/fwk_modules/util/"))
32+import ascendc_check_optype_duplicate
33+ 
34+ 
35+VALID_CONF = {
36+ "version": "1.0",
37+ "placeholders": {"socversion": "short soc", "os": "os name", "arch": "arch name"},
38+ "deliverables": [
39+ {
40+ "name": "ophost",
41+ "type": "shared_library",
42+ "paths": [
43+ "{ASCEND_OPP_PATH}/built-in/op_impl/ai_core/tbe/op_host/lib/{os}/{arch}/libophost_cv.so",
44+ "{ASCEND_OPP_PATH}/built-in/op_impl/ai_core/tbe/op_host/lib/{os}/{arch}/libophost_nn.so",
45+ "{ASCEND_OPP_PATH}/built-in/op_impl/ai_core/tbe/op_host/lib/{os}/{arch}/libophost_legacy.so",
46+ ],
47+ },
48+ {
49+ "name": "ops-info",
50+ "type": "json",
51+ "paths": [
52+ "{ASCEND_OPP_PATH}/built-in/op_impl/ai_core/tbe/config/{socversion}/aic-{socversion}-ops-info-nn.json"
53+ ],
54+ },
55+ ],
56+}
57+ 
58+ 
59+def _conf_to_str(conf=VALID_CONF):
60+ return json.dumps(conf)
61+ 
62+ 
63+class TestOpsDeliverablesConf(unittest.TestCase):
64+ def setUp(self):
65+ ops_deliverables_conf.clear_conf_cache()
66+ self._tmp = tempfile.TemporaryDirectory()
67+ self.addCleanup(self._tmp.cleanup)
68+ self.opp_path = self._tmp.name
69+ 
70+ def _write_conf(self, content=_conf_to_str(), file_name="ops_deliverables.json"):
71+ conf_dir = os.path.join(self.opp_path, "conf")
72+ os.makedirs(conf_dir, exist_ok=True)
73+ conf_file = os.path.join(conf_dir, file_name)
74+ with open(conf_file, "w", encoding="utf-8") as f:
75+ f.write(content)
76+ return conf_file
77+ 
78+ def _get_paths(self, **kwargs):
79+ args = {"opp_path": self.opp_path, "os_name": "linux", "arch": "aarch64"}
80+ args.update(kwargs)
81+ return ops_deliverables_conf.get_deliverable_paths("ophost", **args)
82+ 
83+ def test_no_conf_returns_none(self):
84+ self.assertIsNone(self._get_paths())
85+ 
86+ def test_conf_paths_resolved_in_order(self):
87+ self._write_conf()
88+ paths = self._get_paths()
89+ expect_prefix = os.path.join(
90+ self.opp_path, "built-in", "op_impl", "ai_core", "tbe", "op_host", "lib", "linux", "aarch64"
91+ )
92+ self.assertEqual(
93+ paths,
94+ [
95+ os.path.join(expect_prefix, "libophost_cv.so"),
96+ os.path.join(expect_prefix, "libophost_nn.so"),
97+ os.path.join(expect_prefix, "libophost_legacy.so"),
98+ ],
99+ )
100+ 
101+ def test_entry_not_declared_returns_none(self):
102+ self._write_conf()
103+ self.assertIsNone(ops_deliverables_conf.get_deliverable_paths("opgraph", opp_path=self.opp_path))
104+ 
105+ def test_socversion_path_skipped_without_soc_version(self):
106+ self._write_conf()
107+ paths = ops_deliverables_conf.get_deliverable_paths(
108+ "ops-info", opp_path=self.opp_path, os_name="linux", arch="aarch64"
109+ )
110+ self.assertEqual(paths, [])
111+ paths = ops_deliverables_conf.get_deliverable_paths(
112+ "ops-info", opp_path=self.opp_path, soc_version="910B", os_name="linux", arch="aarch64"
113+ )
114+ self.assertEqual(len(paths), 1)
115+ self.assertIn("aic-910b-ops-info-nn.json", paths[0])
116+ 
117+ def test_invalid_json_treated_as_no_conf(self):
118+ self._write_conf(content="{invalid json")
119+ self.assertIsNone(self._get_paths())
120+ 
121+ def test_invalid_structure_treated_as_no_conf(self):
122+ self._write_conf(content=json.dumps({"version": "1.0", "deliverables": "not-a-list"}))
123+ self.assertIsNone(self._get_paths())
124+ 
125+ def test_oversize_conf_treated_as_no_conf(self):
126+ self._write_conf()
127+ with mock.patch.object(ops_deliverables_conf, "MAX_CONF_FILE_SIZE", 10):
128+ self.assertIsNone(self._get_paths())
129+ 
130+ def test_default_conf_file_under_opp_path(self):
131+ # conf_file_path not given: read {opp_path}/conf/ops_deliverables.json by default
132+ self._write_conf()
133+ paths = self._get_paths()
134+ self.assertEqual(len(paths), 3)
135+ self.assertEqual(
136+ paths[0],
137+ os.path.join(
138+ self.opp_path,
139+ "built-in",
140+ "op_impl",
141+ "ai_core",
142+ "tbe",
143+ "op_host",
144+ "lib",
145+ "linux",
146+ "aarch64",
147+ "libophost_cv.so",
148+ ),
149+ )
150+ 
151+ def test_get_existing_paths_filtered_by_disk(self):
152+ lib_dir = os.path.join(
153+ self.opp_path, "built-in", "op_impl", "ai_core", "tbe", "op_host", "lib", "linux", "aarch64"
154+ )
155+ os.makedirs(lib_dir, exist_ok=True)
156+ cv_lib = os.path.join(lib_dir, "libophost_cv.so")
157+ with open(cv_lib, "w", encoding="utf-8") as f:
158+ f.write("")
159+ # VALID_CONF declares cv/nn/legacy, only cv exists on disk
160+ self._write_conf()
161+ paths = ops_deliverables_conf.get_existing_deliverable_paths(
162+ "ophost", opp_path=self.opp_path, os_name="linux", arch="aarch64"
163+ )
164+ self.assertEqual(paths, [cv_lib])
165+ 
166+ def test_get_existing_paths_no_conf_returns_none(self):
167+ logs = []
168+ ret = ops_deliverables_conf.get_existing_deliverable_paths(
169+ "ophost", opp_path=self.opp_path, os_name="linux", arch="aarch64", log_func=logs.append
170+ )
171+ self.assertIsNone(ret)
172+ # fallback cases log, so the compat branch is observable
173+ self.assertTrue(any("fall back" in msg for msg in logs))
174+ 
175+ def test_get_existing_paths_all_missing_returns_none(self):
176+ # compatibility first: entry declared but no declared path exists on disk -> fall back
177+ self._write_conf()
178+ logs = []
179+ ret = ops_deliverables_conf.get_existing_deliverable_paths(
180+ "ophost", opp_path=self.opp_path, os_name="linux", arch="aarch64", log_func=logs.append
181+ )
182+ self.assertIsNone(ret)
183+ self.assertTrue(any("fall back" in msg for msg in logs))
184+ 
185+ def test_get_existing_paths_success_is_silent(self):
186+ lib_dir = os.path.join(
187+ self.opp_path, "built-in", "op_impl", "ai_core", "tbe", "op_host", "lib", "linux", "aarch64"
188+ )
189+ os.makedirs(lib_dir, exist_ok=True)
190+ cv_lib = os.path.join(lib_dir, "libophost_cv.so")
191+ with open(cv_lib, "w", encoding="utf-8") as f:
192+ f.write("")
193+ self._write_conf()
194+ logs = []
195+ paths = ops_deliverables_conf.get_existing_deliverable_paths(
196+ "ophost", opp_path=self.opp_path, os_name="linux", arch="aarch64", log_func=logs.append
197+ )
198+ self.assertEqual(paths, [cv_lib])
199+ # a successful conf hit is silent
200+ self.assertEqual(logs, [])
201+ 
202+ def test_wildcard_expanded_sorted(self):
203+ lib_dir = os.path.join(self.opp_path, "built-in", "op_impl", "ai_core", "tbe", "op_host", "lib")
204+ os.makedirs(lib_dir, exist_ok=True)
205+ for so_name in ("libophost_b.so", "libophost_a.so", "libophost_legacy.so"):
206+ with open(os.path.join(lib_dir, so_name), "w", encoding="utf-8") as f:
207+ f.write("")
208+ wildcard_conf = {
209+ "version": "1.0",
210+ "deliverables": [
211+ {
212+ "name": "ophost",
213+ "type": "shared_library",
214+ "paths": ["{ASCEND_OPP_PATH}/built-in/op_impl/ai_core/tbe/op_host/lib/*"],
215+ }
216+ ],
217+ }
218+ self._write_conf(content=_conf_to_str(wildcard_conf))
219+ paths = self._get_paths()
220+ self.assertEqual(
221+ [os.path.basename(p) for p in paths], ["libophost_a.so", "libophost_b.so", "libophost_legacy.so"]
222+ )
223+ 
224+ def test_parser_copies_byte_identical(self):
225+ common_copy = os.path.join(TOP_PATH, "tools/build/asc_op_compile_base/common/ops_deliverables_conf.py")
226+ adapter_copy = os.path.join(TOP_PATH, "tools/build/asc_op_compile_base/adapter/ops_deliverables_conf.py")
227+ with open(common_copy, "rb") as f:
228+ common_bytes = f.read()
229+ with open(adapter_copy, "rb") as f:
230+ adapter_bytes = f.read()
231+ self.assertEqual(common_bytes, adapter_bytes)
232+ 
233+ 
234+class TestLoadOpHostTilingLibConfSwitch(unittest.TestCase):
235+ def setUp(self):
236+ ops_deliverables_conf.clear_conf_cache()
237+ self._tmp = tempfile.TemporaryDirectory()
238+ self.addCleanup(self._tmp.cleanup)
239+ self.opp_path = self._tmp.name
240+ 
241+ def _fake_libs(self):
242+ # the fallback branch filters libs of the incompatible arch, so the fake lib dir
243+ # must follow the current machine arch to survive the filter on any runner
244+ lib_dir = os.path.join(
245+ self.opp_path, "built-in", "op_impl", "ai_core", "tbe", "op_host", "lib", "linux", platform.machine()
246+ )
247+ os.makedirs(lib_dir, exist_ok=True)
248+ cv_lib = os.path.join(lib_dir, "libophost_cv.so")
249+ legacy_lib = os.path.join(lib_dir, "libophost_legacy.so")
250+ for lib in (cv_lib, legacy_lib):
251+ with open(lib, "w", encoding="utf-8") as f:
252+ f.write("")
253+ return cv_lib, legacy_lib
254+ 
255+ @mock.patch("asc_op_compile_base.asc_op_compiler.get_op_tiling.ctypes.CDLL")
256+ def test_conf_branch_loads_declared_paths(self, mock_cdll):
257+ cv_lib, legacy_lib = self._fake_libs()
258+ with mock.patch.dict(os.environ, {"ASCEND_OPP_PATH": self.opp_path}):
259+ with mock.patch.object(get_op_tiling, "get_existing_deliverable_paths", return_value=[cv_lib, legacy_lib]):
260+ get_op_tiling.load_op_host_tiling_lib()
261+ loaded = [call.args[0] for call in mock_cdll.call_args_list]
262+ self.assertEqual(loaded, [cv_lib, legacy_lib])
263+ 
264+ @mock.patch("asc_op_compile_base.asc_op_compiler.get_op_tiling.ctypes.CDLL")
265+ def test_conf_branch_keeps_legacy_loaded_last(self, mock_cdll):
266+ cv_lib, legacy_lib = self._fake_libs()
267+ with mock.patch.dict(os.environ, {"ASCEND_OPP_PATH": self.opp_path}):
268+ with mock.patch.object(get_op_tiling, "get_existing_deliverable_paths", return_value=[legacy_lib, cv_lib]):
269+ get_op_tiling.load_op_host_tiling_lib()
270+ loaded = [call.args[0] for call in mock_cdll.call_args_list]
271+ self.assertEqual(loaded, [cv_lib, legacy_lib])
272+ 
273+ @mock.patch("asc_op_compile_base.asc_op_compiler.get_op_tiling.glob.glob")
274+ @mock.patch("asc_op_compile_base.asc_op_compiler.get_op_tiling.ctypes.CDLL")
275+ def test_fallback_branch_when_no_conf(self, mock_cdll, mock_glob):
276+ cv_lib, legacy_lib = self._fake_libs()
277+ mock_glob.return_value = [legacy_lib, cv_lib]
278+ with mock.patch.dict(os.environ, {"ASCEND_OPP_PATH": self.opp_path}):
279+ with mock.patch.object(get_op_tiling, "get_existing_deliverable_paths", return_value=None):
280+ get_op_tiling.load_op_host_tiling_lib()
281+ loaded = [call.args[0] for call in mock_cdll.call_args_list]
282+ # legacy lib is sorted last in the fallback branch
283+ self.assertEqual(loaded, [cv_lib, legacy_lib])
284+ 
285+ @mock.patch("asc_op_compile_base.asc_op_compiler.get_op_tiling.glob.glob")
286+ @mock.patch("asc_op_compile_base.asc_op_compiler.get_op_tiling.ctypes.CDLL")
287+ def test_fallback_branch_when_conf_result_empty(self, mock_cdll, mock_glob):
288+ # compatibility first: entry declared but nothing exists (empty result) also falls back
289+ cv_lib, legacy_lib = self._fake_libs()
290+ mock_glob.return_value = [legacy_lib, cv_lib]
291+ with mock.patch.dict(os.environ, {"ASCEND_OPP_PATH": self.opp_path}):
292+ with mock.patch.object(get_op_tiling, "get_existing_deliverable_paths", return_value=[]):
293+ get_op_tiling.load_op_host_tiling_lib()
294+ loaded = [call.args[0] for call in mock_cdll.call_args_list]
295+ self.assertEqual(loaded, [cv_lib, legacy_lib])
296+ 
297+ 
298+class TestGetBuiltinImplDirsConfSwitch(unittest.TestCase):
299+ def setUp(self):
300+ ops_deliverables_conf.clear_conf_cache()
301+ self._tmp = tempfile.TemporaryDirectory()
302+ self.addCleanup(self._tmp.cleanup)
303+ self.opp_path = self._tmp.name
304+ 
305+ def test_conf_impl_dirs_existing_only(self):
306+ impl_dir = os.path.join(self.opp_path, "built-in", "op_impl", "ai_core", "tbe", "impl", "ops-nn", "dynamic")
307+ os.makedirs(impl_dir, exist_ok=True)
308+ drift_dir = os.path.join(self.opp_path, "built-in", "op_impl", "ai_core", "tbe", "impl", "ops-cv", "dynamic")
309+ conf = {
310+ "version": "1.0",
311+ "deliverables": [{"name": "opsrc", "type": "src_file", "paths": [impl_dir, drift_dir]}],
312+ }
313+ conf_file = os.path.join(self.opp_path, "conf", "ops_deliverables.json")
314+ os.makedirs(os.path.dirname(conf_file), exist_ok=True)
315+ with open(conf_file, "w", encoding="utf-8") as f:
316+ f.write(json.dumps(conf))
317+ with mock.patch.dict(os.environ, {"ASCEND_OPP_PATH": self.opp_path}):
318+ dirs = get_op_tiling._get_builtin_impl_dirs_from_conf()
319+ self.assertEqual(dirs, {os.path.normpath(os.path.abspath(impl_dir))})
320+ 
321+ def test_no_conf_returns_none(self):
322+ with mock.patch.dict(os.environ, {"ASCEND_OPP_PATH": self.opp_path}):
323+ self.assertIsNone(get_op_tiling._get_builtin_impl_dirs_from_conf())
324+ 
325+ 
326+class TestOpTilingConfSwitch(unittest.TestCase):
327+ def setUp(self):
328+ ops_deliverables_conf.clear_conf_cache()
329+ self._tmp = tempfile.TemporaryDirectory()
330+ self.addCleanup(self._tmp.cleanup)
331+ self.opp_path = self._tmp.name
332+ 
333+ @mock.patch("asc_op_compile_base.asc_op_compiler.op_tiling.get_existing_deliverable_paths")
334+ def test_ophost_paths_from_conf(self, mock_get):
335+ lib_dir = os.path.join(
336+ self.opp_path, "built-in", "op_impl", "ai_core", "tbe", "op_host", "lib", "linux", "aarch64"
337+ )
338+ os.makedirs(lib_dir, exist_ok=True)
339+ cv_lib = os.path.join(lib_dir, "libophost_cv.so")
340+ with open(cv_lib, "w", encoding="utf-8") as f:
341+ f.write("")
342+ mock_get.return_value = [cv_lib]
343+ with mock.patch.dict(os.environ, {"ASCEND_OPP_PATH": self.opp_path}):
344+ paths = op_tiling._get_ophost_tiling_paths_from_conf()
345+ self.assertEqual(paths, [cv_lib])
346+ 
347+ @mock.patch("asc_op_compile_base.asc_op_compiler.op_tiling.get_existing_deliverable_paths")
348+ def test_ophost_paths_no_conf_returns_none(self, mock_get):
349+ mock_get.return_value = None
350+ with mock.patch.dict(os.environ, {"ASCEND_OPP_PATH": self.opp_path}):
351+ self.assertIsNone(op_tiling._get_ophost_tiling_paths_from_conf())
352+ 
353+ 
354+class TestCheckOptypeDuplicateConfSwitch(unittest.TestCase):
355+ def setUp(self):
356+ ops_deliverables_conf.clear_conf_cache()
357+ self._tmp = tempfile.TemporaryDirectory()
358+ self.addCleanup(self._tmp.cleanup)
359+ self.opp_path = self._tmp.name
360+ 
361+ def _write_ops_info(self, optypes, domain="nn"):
362+ ops_info = {op_type: {} for op_type in optypes}
363+ json_file = os.path.join(self.opp_path, "aic-910b-ops-info-{}.json".format(domain))
364+ with open(json_file, "w", encoding="utf-8") as f:
365+ json.dump(ops_info, f)
366+ return json_file
367+ 
368+ def _check(self, ini_optypes):
369+ args = argparse.Namespace(soc_version="910b")
370+ with mock.patch.dict(os.environ, {"ASCEND_OPP_PATH": self.opp_path}):
371+ return ascendc_check_optype_duplicate.check_optype_duplicate(args, ini_optypes)
372+ 
373+ def test_conf_branch_reads_declared_json(self):
374+ json_file = self._write_ops_info(["Add"])
375+ with mock.patch.object(
376+ ascendc_check_optype_duplicate, "get_existing_deliverable_paths", return_value=[json_file]
377+ ):
378+ with mock.patch.object(ascendc_check_optype_duplicate.glob, "glob") as mock_glob:
379+ ret = self._check(["Add"])
380+ self.assertEqual(ret, 2)
381+ mock_glob.assert_not_called()
382+ 
383+ @mock.patch.object(ascendc_check_optype_duplicate, "get_existing_deliverable_paths", return_value=None)
384+ def test_fallback_when_no_conf(self, mock_get):
385+ json_file = self._write_ops_info(["Add"])
386+ with mock.patch.object(ascendc_check_optype_duplicate.glob, "glob", return_value=[json_file]) as mock_glob:
387+ ret = self._check(["Add"])
388+ self.assertEqual(ret, 2)
389+ legacy_pattern = os.path.normpath(mock_glob.call_args[0][0])
390+ self.assertIn(os.path.join("ai_core", "tbe", "config"), legacy_pattern)
391+ 
392+ @mock.patch.object(ascendc_check_optype_duplicate, "get_existing_deliverable_paths", return_value=[])
393+ def test_fallback_when_conf_result_empty(self, mock_get):
394+ with mock.patch.object(ascendc_check_optype_duplicate.glob, "glob", return_value=[]) as mock_glob:
395+ ret = self._check(["Add"])
396+ self.assertEqual(ret, 0)
397+ mock_glob.assert_called_once()
398+ 
399+ def test_conf_branch_catches_ras_op_when_declared(self):
400+ # P2 regression: the ops-info declaration must cover the RAS (ra5) domain file; once the
401+ # opbase list is synced, the conf branch must catch duplicate RAS built-in ops
402+ nn_json = self._write_ops_info(["Add"])
403+ ra5_json = self._write_ops_info(["MatmulAbftVerify"], domain="ra5")
404+ with mock.patch.object(
405+ ascendc_check_optype_duplicate, "get_existing_deliverable_paths", return_value=[nn_json, ra5_json]
406+ ):
407+ with mock.patch.object(ascendc_check_optype_duplicate.glob, "glob") as mock_glob:
408+ ret = self._check(["MatmulAbftVerify"])
409+ self.assertEqual(ret, 2)
410+ mock_glob.assert_not_called()
411+ 
412+ @mock.patch.object(ascendc_check_optype_duplicate, "get_existing_deliverable_paths", return_value=None)
413+ def test_fallback_mixed_install_catches_ras_op(self, mock_get):
414+ # P2 regression: mixed install without conf must still catch duplicate RAS built-in
415+ # ops via the legacy config dir scan
416+ nn_json = self._write_ops_info(["Add"])
417+ ra5_json = self._write_ops_info(["MatmulAbftVerify"], domain="ra5")
418+ with mock.patch.object(
419+ ascendc_check_optype_duplicate.glob, "glob", return_value=[nn_json, ra5_json]
420+ ) as mock_glob:
421+ ret = self._check(["MatmulAbftVerify"])
422+ self.assertEqual(ret, 2)
423+ mock_glob.assert_called_once()
424+ 
425+ 
426+if __name__ == "__main__":
427+ unittest.main()
@@ -38,6 +38,7 @@ from tbe.common.utils.op_tiling import (
38)38)
39from tbe.tvm.error_mgr import raise_tbe_python_err, TBE_DEFAULT_PYTHON_ERROR_CODE39from tbe.tvm.error_mgr import raise_tbe_python_err, TBE_DEFAULT_PYTHON_ERROR_CODE
40from .log_utils import LogUtil, AscendCLogLevel40from .log_utils import LogUtil, AscendCLogLevel
41+from .ops_deliverables_conf import get_existing_deliverable_paths
41import tbe.common.context.op_context as op_context42import tbe.common.context.op_context as op_context
42from tbe.common.repository_manager.utils.repository_manager_log import LOG_INSTANCE43from tbe.common.repository_manager.utils.repository_manager_log import LOG_INSTANCE
43from .global_storage import global_var_storage44from .global_storage import global_var_storage
@@ -111,14 +112,23 @@ def get_custom_opp_pathlist():
111 return vendor_list112 return vendor_list
112 113 
113 114 
115+def _conf_log(msg):
116+ LogUtil.print_compile_log("", msg, AscendCLogLevel.LOG_INFO)
117+ 
118+ 
119+def _get_ophost_tiling_paths_from_conf():
120+ """Query built-in ophost tiling libs from ops deliverables conf.
121+ 
122+ Return None if the conf is not usable (caller falls back to legacy path scan);
123+ otherwise return the existing lib paths in declaration order.
124+ """
125+ return get_existing_deliverable_paths(
126+ "ophost", opp_path=os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT), log_func=_conf_log
127+ )
128+ 
129+ 
114def load_op_host_tiling_lib():130def load_op_host_tiling_lib():
115 LogUtil.print_compile_log("", "load op host tiling lib.", AscendCLogLevel.LOG_INFO)131 LogUtil.print_compile_log("", "load op host tiling lib.", AscendCLogLevel.LOG_INFO)
116- builtin_op_host_tiling_prefix = (
117- os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT) + "/" + op_impl_path + "/ai_core/tbe/op_host/"
118- )
119- builtin_op_host_tiling_pattern = builtin_op_host_tiling_prefix + "**/*.so"
120- builtin_op_host_tiling_file_path = glob.glob(builtin_op_host_tiling_pattern, recursive=True)
121- builtin_op_host_tiling_file_path.sort(key=lambda x: os.path.basename(x) == "libophost_legacy.so")
122 import platform132 import platform
123 133 
124 archlinux = platform.machine()134 archlinux = platform.machine()
@@ -126,9 +136,28 @@ def load_op_host_tiling_lib():
126 incompatiable_arch_name = "aarch64"136 incompatiable_arch_name = "aarch64"
127 else:137 else:
128 incompatiable_arch_name = "x86_64"138 incompatiable_arch_name = "x86_64"
129- for tiling_path in builtin_op_host_tiling_file_path:139+ tiling_paths = _get_ophost_tiling_paths_from_conf()
130- if incompatiable_arch_name in tiling_path[len(builtin_op_host_tiling_prefix) :]:140+ if not tiling_paths:
131- continue141+ # compatibility first: no conf, entry not declared, or nothing declared exists on disk
142+ # all fall back to the legacy hard-coded op_host path scan, keep original behavior
143+ builtin_op_host_tiling_prefix = (
144+ os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT)
145+ + "/"
146+ + op_impl_path
147+ + "/ai_core/tbe/op_host/"
148+ )
149+ builtin_op_host_tiling_pattern = builtin_op_host_tiling_prefix + "**/*.so"
150+ builtin_op_host_tiling_file_path = glob.glob(builtin_op_host_tiling_pattern, recursive=True)
151+ builtin_op_host_tiling_file_path.sort(key=lambda x: os.path.basename(x) == "libophost_legacy.so")
152+ tiling_paths = [
153+ tiling_path
154+ for tiling_path in builtin_op_host_tiling_file_path
155+ if incompatiable_arch_name not in tiling_path[len(builtin_op_host_tiling_prefix) :]
156+ ]
157+ else:
158+ # make libophost_legacy.so loading lastly even if the conf declaration order changes
159+ tiling_paths.sort(key=lambda x: os.path.basename(x) == "libophost_legacy.so")
160+ for tiling_path in tiling_paths:
132 try:161 try:
133 if os.path.exists(tiling_path):162 if os.path.exists(tiling_path):
134 lib_tiling_builtin = ctypes.CDLL(tiling_path)163 lib_tiling_builtin = ctypes.CDLL(tiling_path)
@@ -1620,6 +1649,24 @@ def get_isolate_tiling_info(op_type, json_file):
1620 return tiling_info1649 return tiling_info
1621 1650 
1622 1651 
1652+def _get_builtin_impl_dirs_from_conf():
1653+ """Query built-in opsrc impl dirs from ops deliverables conf.
1654+ 
1655+ Return None if the conf is not usable; return the existing impl dirs otherwise
1656+ (an empty set means the conf is usable but no declared dir exists on disk).
1657+ """
1658+ paths = get_existing_deliverable_paths(
1659+ "opsrc", opp_path=os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT), log_func=_conf_log
1660+ )
1661+ if paths is None:
1662+ return None
1663+ impl_dirs = set()
1664+ for path in paths:
1665+ if os.path.isdir(path):
1666+ impl_dirs.add(os.path.normpath(os.path.abspath(path)))
1667+ return impl_dirs
1668+ 
1669+ 
1623def get_info_by_traverse_py_stack(op_info: OpInfo, input_tiling_info_dict: dict):1670def get_info_by_traverse_py_stack(op_info: OpInfo, input_tiling_info_dict: dict):
1624 # offline compile python file name, i.e. AddCustom.py1671 # offline compile python file name, i.e. AddCustom.py
1625 offline_op_compile_file = op_info.op_type + ".py"1672 offline_op_compile_file = op_info.op_type + ".py"
@@ -1653,6 +1700,17 @@ def get_info_by_traverse_py_stack(op_info: OpInfo, input_tiling_info_dict: dict)
1653 elif online_op_compile_file == frame_file:1700 elif online_op_compile_file == frame_file:
1654 # online op compile1701 # online op compile
1655 # built-in op1702 # built-in op
1703+ # 1. conf-first: ops deliverables conf opsrc dirs (declared and existing on disk)
1704+ conf_impl_dirs = _get_builtin_impl_dirs_from_conf()
1705+ if conf_impl_dirs:
1706+ normalized_compile_dir = os.path.normpath(op_compile_dir)
1707+ if any(
1708+ normalized_compile_dir == conf_dir or normalized_compile_dir.startswith(conf_dir + os.sep)
1709+ for conf_dir in conf_impl_dirs
1710+ ):
1711+ is_build_in_op = True
1712+ break
1713+ # 2. fallback: legacy hard-coded impl dir check, keep original behavior
1656 build_in_compile_file_dir = os.path.join(op_impl_path, "ai_core", "tbe", "impl")1714 build_in_compile_file_dir = os.path.join(op_impl_path, "ai_core", "tbe", "impl")
1657 if build_in_compile_file_dir in op_compile_dir:1715 if build_in_compile_file_dir in op_compile_dir:
1658 LogUtil.print_compile_log(1716 LogUtil.print_compile_log(
@@ -0,0 +1,268 @@
1+#!/usr/bin/python
2+# -*- coding: utf-8 -*-
3+# ----------------------------------------------------------------------------------------------------------
4+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
5+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6+# CANN Open Software License Agreement Version 2.0 (the "License").
7+# Please refer to the License for details. You may not use this file except in compliance with the License.
8+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10+# See LICENSE in the root of the software repository for the full text of the License.
11+# ----------------------------------------------------------------------------------------------------------
12+"""
13+ops deliverables conf parser
14+ 
15+Parse `{ASCEND_OPP_PATH}/conf/ops_deliverables.json`, which is published by the opbase package with CANN
16+(available since CANN 9.2.0). All consumers of the built-in operator package deliverables should resolve
17+paths through this parser instead of hard-coding paths/names, with the fallback to legacy hard-coded logic
18+when the conf file is unavailable or the required entry is not declared.
19+ 
20+Contract:
21+1. Query an entry by its `name`, and use the declared paths in declaration order.
22+2. Placeholders in paths are replaced by the current environment:
23+ `{ASCEND_OPP_PATH}` -> opp root directory, `{socversion}` -> short soc version (lower-case),
24+ `{os}` -> os name (e.g. linux), `{arch}` -> hardware architecture (e.g. aarch64).
25+3. `*` in a path is a wildcard and is expanded with `glob` in sorted order.
26+4. Paths that do not exist on disk are NOT filtered here; the caller must check existence before use
27+ ("declared means effective only if it exists") to be robust against drift between conf and reality.
28+ 
29+Return value convention of `get_deliverable_paths`:
30+- `None` : conf file missing/invalid, or the entry is not declared. The caller should fall back to
31+ the legacy hard-coded logic.
32+- `list` : declared paths after placeholder replacement (may be empty, meaning declared but not
33+ applicable in the current environment). The caller should filter by existence.
34+ 
35+`get_existing_deliverable_paths` is the compatibility-first wrapper of `get_deliverable_paths`
36+and the recommended entry for consumers: it additionally filters the resolved paths by disk
37+existence, and returns None whenever the conf is unavailable, the entry is not declared, or none
38+of the declared paths exists on disk, so that the caller falls back to the legacy hard-coded
39+logic in all these cases.
40+ 
41+Logging convention: a successful conf hit is silent; diagnostic logs are only emitted on the
42+abnormal (fallback) cases.
43+ 
44+This module is maintained as byte-identical copies for different deployment forms (wheel installed
45+package and tbe deployed package). Keep all copies in sync on any change, and only use python standard
46+library here.
47+"""
48+ 
49+import glob
50+import json
51+import os
52+import platform
53+import threading
54+ 
55+# conf file relative path under the opp root directory
56+CONF_RELATIVE_PATH = os.path.join("conf", "ops_deliverables.json")
57+ENV_OPP_PATH = "ASCEND_OPP_PATH"
58+OPP_PATH_DEFAULT = "/usr/local/Ascend/cann/opp"
59+# size limit of the conf file, oversize conf is treated as no conf for safety
60+MAX_CONF_FILE_SIZE = 1024 * 1024
61+ 
62+PLACEHOLDER_OPP_PATH = "{ASCEND_OPP_PATH}"
63+PLACEHOLDER_SOC_VERSION = "{socversion}"
64+PLACEHOLDER_OS = "{os}"
65+PLACEHOLDER_ARCH = "{arch}"
66+ 
67+_LOG_PREFIX = "[ops deliverables conf] "
68+ 
69+# cache: {abs conf path: ((mtime, size), deliverables_or_None)}
70+_CONF_CACHE = {}
71+_CONF_CACHE_LOCK = threading.Lock()
72+ 
73+ 
74+def _default_log(msg):
75+ print(_LOG_PREFIX + msg, flush=True)
76+ 
77+ 
78+def get_opp_path(opp_path=None):
79+ """
80+ Resolve the opp root directory from the given value, env var or the default install path.
81+ """
82+ if opp_path:
83+ return opp_path
84+ return os.environ.get(ENV_OPP_PATH) or OPP_PATH_DEFAULT
85+ 
86+ 
87+def get_os_name():
88+ """
89+ Os name used in conf paths, e.g. "linux".
90+ """
91+ return platform.system().lower()
92+ 
93+ 
94+def get_arch():
95+ """
96+ Hardware architecture used in conf paths, e.g. "aarch64", "x86_64".
97+ """
98+ machine = platform.machine().lower()
99+ return {"amd64": "x86_64", "x64": "x86_64", "arm64": "aarch64"}.get(machine, machine)
100+ 
101+ 
102+def _load_conf(conf_file_path, log):
103+ """
104+ Load and cache the conf file. Return the `deliverables` list, or None if the conf is
105+ missing, oversize or invalid (bad json / bad structure), in which case callers should
106+ treat the conf as not available.
107+ """
108+ cache_key = os.path.abspath(conf_file_path)
109+ try:
110+ stat_res = os.stat(conf_file_path)
111+ except OSError:
112+ # conf file not exists is a common case (old CANN version), not a warning
113+ return None
114+ if not os.path.isfile(conf_file_path):
115+ return None
116+ if stat_res.st_size > MAX_CONF_FILE_SIZE:
117+ log(
118+ "conf file {} size {} exceeds limit {}, treat as no conf".format(
119+ conf_file_path, stat_res.st_size, MAX_CONF_FILE_SIZE
120+ )
121+ )
122+ return None
123+ 
124+ file_stat = (stat_res.st_mtime, stat_res.st_size)
125+ with _CONF_CACHE_LOCK:
126+ cached = _CONF_CACHE.get(cache_key)
127+ if cached is not None and cached[0] == file_stat:
128+ return cached[1]
129+ try:
130+ with open(conf_file_path, "r", encoding="utf-8") as f:
131+ conf = json.load(f)
132+ except (OSError, ValueError) as e:
133+ log("failed to load conf file {}, treat as no conf, reason: {}".format(conf_file_path, str(e)))
134+ _CONF_CACHE[cache_key] = (file_stat, None)
135+ return None
136+ if not isinstance(conf, dict):
137+ log("invalid conf file {}: top level is not a dict, treat as no conf".format(conf_file_path))
138+ _CONF_CACHE[cache_key] = (file_stat, None)
139+ return None
140+ deliverables = conf.get("deliverables")
141+ if not isinstance(deliverables, list):
142+ log("invalid conf file {}: 'deliverables' is not a list, treat as no conf".format(conf_file_path))
143+ deliverables = None
144+ _CONF_CACHE[cache_key] = (file_stat, deliverables)
145+ return deliverables
146+ 
147+ 
148+def _find_entry_paths(deliverables, name):
149+ """
150+ Find paths of the entry with the given name. Return None if the entry is not declared.
151+ """
152+ for entry in deliverables:
153+ if isinstance(entry, dict) and entry.get("name") == name:
154+ paths = entry.get("paths")
155+ if paths is not None and not isinstance(paths, list):
156+ return None
157+ return paths
158+ return None
159+ 
160+ 
161+def _resolve_path(raw_path, opp_root, placeholder_values, log):
162+ """
163+ Replace placeholders in one raw path. Return the resolved path, or None to skip this
164+ path (placeholder not resolvable in the current environment).
165+ 
166+ :param placeholder_values: (placeholder, value) pairs to substitute; a path containing
167+ a placeholder whose value is not available is skipped.
168+ """
169+ resolved = raw_path.replace(PLACEHOLDER_OPP_PATH, opp_root)
170+ for placeholder, value in placeholder_values:
171+ if placeholder not in resolved:
172+ continue
173+ if not value:
174+ return None
175+ resolved = resolved.replace(placeholder, str(value))
176+ if "{" in resolved and "}" in resolved:
177+ log("path '{}' contains unresolvable placeholder, ignore it".format(raw_path))
178+ return None
179+ return resolved
180+ 
181+ 
182+def get_deliverable_paths(
183+ name, opp_path=None, soc_version=None, os_name=None, arch=None, conf_file_path=None, log_func=None
184+):
185+ """
186+ Query the ordered paths of a deliverable entry by name.
187+ 
188+ :param name: entry name in the conf file, e.g. "ophost", "opsrc", "ops-info".
189+ :param opp_path: opp root directory, default to ASCEND_OPP_PATH env or the default install path.
190+ :param soc_version: short soc version (lower-case), required by paths containing `{socversion}`;
191+ such paths are skipped when it is not provided.
192+ :param os_name: os name, default to the current platform.
193+ :param arch: hardware architecture, default to the current platform.
194+ :param conf_file_path: conf file path, default to `{opp_path}/conf/ops_deliverables.json`.
195+ :param log_func: callable to receive diagnostic messages, default to print.
196+ :return: None if the conf is unavailable or the entry is not declared (caller falls back);
197+ otherwise a list of resolved paths in declaration order (empty list means declared
198+ but not applicable in the current environment). Callers must filter by existence.
199+ """
200+ log = log_func if callable(log_func) else _default_log
201+ opp_root = get_opp_path(opp_path)
202+ conf_file = conf_file_path or os.path.join(opp_root, CONF_RELATIVE_PATH)
203+ deliverables = _load_conf(conf_file, log)
204+ if deliverables is None:
205+ return None
206+ entry_paths = _find_entry_paths(deliverables, name)
207+ if entry_paths is None:
208+ log("entry '{}' is not declared in {}, caller should fall back to legacy logic".format(name, conf_file))
209+ return None
210+ 
211+ placeholder_values = (
212+ (PLACEHOLDER_SOC_VERSION, str(soc_version).lower() if soc_version else None),
213+ (PLACEHOLDER_OS, os_name or get_os_name()),
214+ (PLACEHOLDER_ARCH, arch or get_arch()),
215+ )
216+ paths = []
217+ for raw_path in entry_paths:
218+ if not isinstance(raw_path, str) or not raw_path:
219+ continue
220+ resolved = _resolve_path(raw_path, opp_root, placeholder_values, log)
221+ if resolved is None:
222+ continue
223+ if "*" in resolved:
224+ paths.extend(sorted(glob.glob(resolved)))
225+ else:
226+ paths.append(resolved)
227+ return paths
228+ 
229+ 
230+def get_existing_deliverable_paths(
231+ name, opp_path=None, soc_version=None, os_name=None, arch=None, conf_file_path=None, log_func=None
232+):
233+ """
234+ Compatibility-first query of the ordered paths of a deliverable entry, filtered by
235+ disk existence, which is the recommended entry for consumers.
236+ 
237+ Return None if the conf is unavailable, the entry is not declared, or none of the
238+ declared paths exists on disk; the caller should fall back to the legacy hard-coded
239+ logic in all these cases. Otherwise return the existing paths in declaration order
240+ (non-empty). A successful conf hit is silent; logs are only emitted on the fallback
241+ cases.
242+ """
243+ log = log_func if callable(log_func) else _default_log
244+ paths = get_deliverable_paths(
245+ name,
246+ opp_path=opp_path,
247+ soc_version=soc_version,
248+ os_name=os_name,
249+ arch=arch,
250+ conf_file_path=conf_file_path,
251+ log_func=log_func,
252+ )
253+ if paths is None:
254+ log("deliverables conf unavailable for entry '{}', fall back to legacy logic".format(name))
255+ return None
256+ valid_paths = [path for path in paths if os.path.exists(path)]
257+ if not valid_paths:
258+ log("no declared path of entry '{}' exists on disk, fall back to legacy logic".format(name))
259+ return None
260+ return valid_paths
261+ 
262+ 
263+def clear_conf_cache():
264+ """
265+ Clear the conf cache, for test or when the conf file is known to be refreshed.
266+ """
267+ with _CONF_CACHE_LOCK:
268+ _CONF_CACHE.clear()
@@ -36,6 +36,7 @@ from asc_op_compile_base.asc_op_compiler.op_tiling import (
36)36)
37from asc_op_compile_base.common.error_mgr import raise_tbe_python_err, TBE_DEFAULT_PYTHON_ERROR_CODE37from asc_op_compile_base.common.error_mgr import raise_tbe_python_err, TBE_DEFAULT_PYTHON_ERROR_CODE
38from asc_op_compile_base.common.utils.log_utils import LogUtil, AscendCLogLevel38from asc_op_compile_base.common.utils.log_utils import LogUtil, AscendCLogLevel
39+from asc_op_compile_base.common.ops_deliverables_conf import get_existing_deliverable_paths
39import asc_op_compile_base.common.context.op_context as op_context40import asc_op_compile_base.common.context.op_context as op_context
40from asc_op_compile_base.common.utils import log41from asc_op_compile_base.common.utils import log
41from .global_storage import global_var_storage42from .global_storage import global_var_storage
@@ -110,14 +111,23 @@ def get_custom_opp_pathlist():
110 return vendor_list111 return vendor_list
111 112 
112 113 
114+def _conf_log(msg):
115+ LogUtil.print_compile_log("", msg, AscendCLogLevel.LOG_INFO)
116+ 
117+ 
118+def _get_ophost_tiling_paths_from_conf():
119+ """Query built-in ophost tiling libs from ops deliverables conf.
120+ 
121+ Return None if the conf is not usable (caller falls back to legacy path scan);
122+ otherwise return the existing lib paths in declaration order.
123+ """
124+ return get_existing_deliverable_paths(
125+ "ophost", opp_path=os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT), log_func=_conf_log
126+ )
127+ 
128+ 
113def load_op_host_tiling_lib():129def load_op_host_tiling_lib():
114 LogUtil.print_compile_log("", "load op host tiling lib.", AscendCLogLevel.LOG_INFO)130 LogUtil.print_compile_log("", "load op host tiling lib.", AscendCLogLevel.LOG_INFO)
115- builtin_op_host_tiling_prefix = (
116- os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT) + "/" + op_impl_path + "/ai_core/tbe/op_host/"
117- )
118- builtin_op_host_tiling_pattern = builtin_op_host_tiling_prefix + "**/*.so"
119- builtin_op_host_tiling_file_path = glob.glob(builtin_op_host_tiling_pattern, recursive=True)
120- builtin_op_host_tiling_file_path.sort(key=lambda x: os.path.basename(x) == "libophost_legacy.so")
121 import platform131 import platform
122 132 
123 archlinux = platform.machine()133 archlinux = platform.machine()
@@ -125,9 +135,28 @@ def load_op_host_tiling_lib():
125 incompatiable_arch_name = "aarch64"135 incompatiable_arch_name = "aarch64"
126 else:136 else:
127 incompatiable_arch_name = "x86_64"137 incompatiable_arch_name = "x86_64"
128- for tiling_path in builtin_op_host_tiling_file_path:138+ tiling_paths = _get_ophost_tiling_paths_from_conf()
129- if incompatiable_arch_name in tiling_path[len(builtin_op_host_tiling_prefix) :]:139+ if not tiling_paths:
130- continue140+ # compatibility first: no conf, entry not declared, or nothing declared exists on disk
141+ # all fall back to the legacy hard-coded op_host path scan, keep original behavior
142+ builtin_op_host_tiling_prefix = (
143+ os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT)
144+ + "/"
145+ + op_impl_path
146+ + "/ai_core/tbe/op_host/"
147+ )
148+ builtin_op_host_tiling_pattern = builtin_op_host_tiling_prefix + "**/*.so"
149+ builtin_op_host_tiling_file_path = glob.glob(builtin_op_host_tiling_pattern, recursive=True)
150+ builtin_op_host_tiling_file_path.sort(key=lambda x: os.path.basename(x) == "libophost_legacy.so")
151+ tiling_paths = [
152+ tiling_path
153+ for tiling_path in builtin_op_host_tiling_file_path
154+ if incompatiable_arch_name not in tiling_path[len(builtin_op_host_tiling_prefix) :]
155+ ]
156+ else:
157+ # make libophost_legacy.so loading lastly even if the conf declaration order changes
158+ tiling_paths.sort(key=lambda x: os.path.basename(x) == "libophost_legacy.so")
159+ for tiling_path in tiling_paths:
131 try:160 try:
132 if os.path.exists(tiling_path):161 if os.path.exists(tiling_path):
133 lib_tiling_builtin = ctypes.CDLL(tiling_path)162 lib_tiling_builtin = ctypes.CDLL(tiling_path)
@@ -1615,6 +1644,24 @@ def get_isolate_tiling_info(op_type, json_file):
1615 return tiling_info1644 return tiling_info
1616 1645 
1617 1646 
1647+def _get_builtin_impl_dirs_from_conf():
1648+ """Query built-in opsrc impl dirs from ops deliverables conf.
1649+ 
1650+ Return None if the conf is not usable; return the existing impl dirs otherwise
1651+ (an empty set means the conf is usable but no declared dir exists on disk).
1652+ """
1653+ paths = get_existing_deliverable_paths(
1654+ "opsrc", opp_path=os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT), log_func=_conf_log
1655+ )
1656+ if paths is None:
1657+ return None
1658+ impl_dirs = set()
1659+ for path in paths:
1660+ if os.path.isdir(path):
1661+ impl_dirs.add(os.path.normpath(os.path.abspath(path)))
1662+ return impl_dirs
1663+ 
1664+ 
1618def get_info_by_traverse_py_stack(op_info: OpInfo, input_tiling_info_dict: dict):1665def get_info_by_traverse_py_stack(op_info: OpInfo, input_tiling_info_dict: dict):
1619 # offline compile python file name, i.e. AddCustom.py1666 # offline compile python file name, i.e. AddCustom.py
1620 offline_op_compile_file = op_info.op_type + ".py"1667 offline_op_compile_file = op_info.op_type + ".py"
@@ -1648,6 +1695,17 @@ def get_info_by_traverse_py_stack(op_info: OpInfo, input_tiling_info_dict: dict)
1648 elif online_op_compile_file == frame_file:1695 elif online_op_compile_file == frame_file:
1649 # online op compile1696 # online op compile
1650 # built-in op1697 # built-in op
1698+ # 1. conf-first: ops deliverables conf opsrc dirs (declared and existing on disk)
1699+ conf_impl_dirs = _get_builtin_impl_dirs_from_conf()
1700+ if conf_impl_dirs:
1701+ normalized_compile_dir = os.path.normpath(op_compile_dir)
1702+ if any(
1703+ normalized_compile_dir == conf_dir or normalized_compile_dir.startswith(conf_dir + os.sep)
1704+ for conf_dir in conf_impl_dirs
1705+ ):
1706+ is_build_in_op = True
1707+ break
1708+ # 2. fallback: legacy hard-coded impl dir check, keep original behavior
1651 build_in_compile_file_dir = os.path.join(op_impl_path, "ai_core", "tbe", "impl")1709 build_in_compile_file_dir = os.path.join(op_impl_path, "ai_core", "tbe", "impl")
1652 if build_in_compile_file_dir in op_compile_dir:1710 if build_in_compile_file_dir in op_compile_dir:
1653 LogUtil.print_compile_log(1711 LogUtil.print_compile_log(
@@ -31,6 +31,7 @@ from asc_op_compile_base.common.context.op_info import OpInfo
31from asc_op_compile_base.common.context import op_context31from asc_op_compile_base.common.context import op_context
32from asc_op_compile_base.common.context.op_context import OpContext32from asc_op_compile_base.common.context.op_context import OpContext
33from asc_op_compile_base.common.buildcfg import get_current_build_config33from asc_op_compile_base.common.buildcfg import get_current_build_config
34+from asc_op_compile_base.common.ops_deliverables_conf import get_existing_deliverable_paths
34 35 
35BANK_CACHE = ""36BANK_CACHE = ""
36 37 
@@ -109,6 +110,17 @@ else:
109 _CUSTOM_TILING_PATH_DEFAULT = os.path.join("op_impl", "custom", tiling_cust_path)110 _CUSTOM_TILING_PATH_DEFAULT = os.path.join("op_impl", "custom", tiling_cust_path)
110 111 
111 112 
113+def _get_ophost_tiling_paths_from_conf():
114+ """Query built-in ophost tiling libs from ops deliverables conf.
115+ 
116+ Return None if the conf is not usable (caller falls back to legacy path scan);
117+ otherwise return the existing lib paths in declaration order.
118+ """
119+ return get_existing_deliverable_paths(
120+ "ophost", opp_path=os.environ.get(_ASCEND_OPP_PATH_ENV, _ASCEND_OPP_PATH_DEFAULT), log_func=log.info
121+ )
122+ 
123+ 
112def _get_default_optiling_pathlist():124def _get_default_optiling_pathlist():
113 default_custom_tiling_full_path_list = []125 default_custom_tiling_full_path_list = []
114 vendor_list = []126 vendor_list = []
@@ -261,11 +273,17 @@ def do_op_tiling(optype, compile_info, inputs, outputs, compile_info_hash=None,
261 lib_optiling_builtin = ctypes.CDLL(builtin_optiling_lib_path2)273 lib_optiling_builtin = ctypes.CDLL(builtin_optiling_lib_path2)
262 builtin_optiling_lib_path2_str = str(builtin_optiling_lib_path2)274 builtin_optiling_lib_path2_str = str(builtin_optiling_lib_path2)
263 lib_optiling_builtin.TbeLoadSoAndSaveToRegistry(builtin_optiling_lib_path2_str.encode("utf_8"))275 lib_optiling_builtin.TbeLoadSoAndSaveToRegistry(builtin_optiling_lib_path2_str.encode("utf_8"))
264- elif os.path.exists(builtin_optiling_open_path):276+ else:
265- so_files = glob.glob(os.path.join(builtin_optiling_open_path, "*.so"))277+ # 3.1 ops deliverables conf first: load ophost libs in declaration order
278+ builtin_ophost_libs = _get_ophost_tiling_paths_from_conf()
279+ if not builtin_ophost_libs:
280+ # fallback: legacy hard-coded op_host dir scan, keep original behavior
281+ builtin_ophost_libs = glob.glob(os.path.join(builtin_optiling_open_path, "*.so"))
266 # make libophost_legacy.so loading lastly282 # make libophost_legacy.so loading lastly
267- so_files.sort(key=lambda x: os.path.basename(x) == "libophost_legacy.so")283+ builtin_ophost_libs.sort(key=lambda x: os.path.basename(x) == "libophost_legacy.so")
268- for so_path in so_files:284+ for so_path in builtin_ophost_libs:
285+ if not os.path.exists(so_path):
286+ continue
269 if "libophost_legacy.so" in so_path:287 if "libophost_legacy.so" in so_path:
270 lib_optiling_builtin = ctypes.CDLL(so_path)288 lib_optiling_builtin = ctypes.CDLL(so_path)
271 so_path_str = str(so_path)289 so_path_str = str(so_path)
@@ -0,0 +1,268 @@
1+#!/usr/bin/python
2+# -*- coding: utf-8 -*-
3+# ----------------------------------------------------------------------------------------------------------
4+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
5+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6+# CANN Open Software License Agreement Version 2.0 (the "License").
7+# Please refer to the License for details. You may not use this file except in compliance with the License.
8+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10+# See LICENSE in the root of the software repository for the full text of the License.
11+# ----------------------------------------------------------------------------------------------------------
12+"""
13+ops deliverables conf parser
14+ 
15+Parse `{ASCEND_OPP_PATH}/conf/ops_deliverables.json`, which is published by the opbase package with CANN
16+(available since CANN 9.2.0). All consumers of the built-in operator package deliverables should resolve
17+paths through this parser instead of hard-coding paths/names, with the fallback to legacy hard-coded logic
18+when the conf file is unavailable or the required entry is not declared.
19+ 
20+Contract:
21+1. Query an entry by its `name`, and use the declared paths in declaration order.
22+2. Placeholders in paths are replaced by the current environment:
23+ `{ASCEND_OPP_PATH}` -> opp root directory, `{socversion}` -> short soc version (lower-case),
24+ `{os}` -> os name (e.g. linux), `{arch}` -> hardware architecture (e.g. aarch64).
25+3. `*` in a path is a wildcard and is expanded with `glob` in sorted order.
26+4. Paths that do not exist on disk are NOT filtered here; the caller must check existence before use
27+ ("declared means effective only if it exists") to be robust against drift between conf and reality.
28+ 
29+Return value convention of `get_deliverable_paths`:
30+- `None` : conf file missing/invalid, or the entry is not declared. The caller should fall back to
31+ the legacy hard-coded logic.
32+- `list` : declared paths after placeholder replacement (may be empty, meaning declared but not
33+ applicable in the current environment). The caller should filter by existence.
34+ 
35+`get_existing_deliverable_paths` is the compatibility-first wrapper of `get_deliverable_paths`
36+and the recommended entry for consumers: it additionally filters the resolved paths by disk
37+existence, and returns None whenever the conf is unavailable, the entry is not declared, or none
38+of the declared paths exists on disk, so that the caller falls back to the legacy hard-coded
39+logic in all these cases.
40+ 
41+Logging convention: a successful conf hit is silent; diagnostic logs are only emitted on the
42+abnormal (fallback) cases.
43+ 
44+This module is maintained as byte-identical copies for different deployment forms (wheel installed
45+package and tbe deployed package). Keep all copies in sync on any change, and only use python standard
46+library here.
47+"""
48+ 
49+import glob
50+import json
51+import os
52+import platform
53+import threading
54+ 
55+# conf file relative path under the opp root directory
56+CONF_RELATIVE_PATH = os.path.join("conf", "ops_deliverables.json")
57+ENV_OPP_PATH = "ASCEND_OPP_PATH"
58+OPP_PATH_DEFAULT = "/usr/local/Ascend/cann/opp"
59+# size limit of the conf file, oversize conf is treated as no conf for safety
60+MAX_CONF_FILE_SIZE = 1024 * 1024
61+ 
62+PLACEHOLDER_OPP_PATH = "{ASCEND_OPP_PATH}"
63+PLACEHOLDER_SOC_VERSION = "{socversion}"
64+PLACEHOLDER_OS = "{os}"
65+PLACEHOLDER_ARCH = "{arch}"
66+ 
67+_LOG_PREFIX = "[ops deliverables conf] "
68+ 
69+# cache: {abs conf path: ((mtime, size), deliverables_or_None)}
70+_CONF_CACHE = {}
71+_CONF_CACHE_LOCK = threading.Lock()
72+ 
73+ 
74+def _default_log(msg):
75+ print(_LOG_PREFIX + msg, flush=True)
76+ 
77+ 
78+def get_opp_path(opp_path=None):
79+ """
80+ Resolve the opp root directory from the given value, env var or the default install path.
81+ """
82+ if opp_path:
83+ return opp_path
84+ return os.environ.get(ENV_OPP_PATH) or OPP_PATH_DEFAULT
85+ 
86+ 
87+def get_os_name():
88+ """
89+ Os name used in conf paths, e.g. "linux".
90+ """
91+ return platform.system().lower()
92+ 
93+ 
94+def get_arch():
95+ """
96+ Hardware architecture used in conf paths, e.g. "aarch64", "x86_64".
97+ """
98+ machine = platform.machine().lower()
99+ return {"amd64": "x86_64", "x64": "x86_64", "arm64": "aarch64"}.get(machine, machine)
100+ 
101+ 
102+def _load_conf(conf_file_path, log):
103+ """
104+ Load and cache the conf file. Return the `deliverables` list, or None if the conf is
105+ missing, oversize or invalid (bad json / bad structure), in which case callers should
106+ treat the conf as not available.
107+ """
108+ cache_key = os.path.abspath(conf_file_path)
109+ try:
110+ stat_res = os.stat(conf_file_path)
111+ except OSError:
112+ # conf file not exists is a common case (old CANN version), not a warning
113+ return None
114+ if not os.path.isfile(conf_file_path):
115+ return None
116+ if stat_res.st_size > MAX_CONF_FILE_SIZE:
117+ log(
118+ "conf file {} size {} exceeds limit {}, treat as no conf".format(
119+ conf_file_path, stat_res.st_size, MAX_CONF_FILE_SIZE
120+ )
121+ )
122+ return None
123+ 
124+ file_stat = (stat_res.st_mtime, stat_res.st_size)
125+ with _CONF_CACHE_LOCK:
126+ cached = _CONF_CACHE.get(cache_key)
127+ if cached is not None and cached[0] == file_stat:
128+ return cached[1]
129+ try:
130+ with open(conf_file_path, "r", encoding="utf-8") as f:
131+ conf = json.load(f)
132+ except (OSError, ValueError) as e:
133+ log("failed to load conf file {}, treat as no conf, reason: {}".format(conf_file_path, str(e)))
134+ _CONF_CACHE[cache_key] = (file_stat, None)
135+ return None
136+ if not isinstance(conf, dict):
137+ log("invalid conf file {}: top level is not a dict, treat as no conf".format(conf_file_path))
138+ _CONF_CACHE[cache_key] = (file_stat, None)
139+ return None
140+ deliverables = conf.get("deliverables")
141+ if not isinstance(deliverables, list):
142+ log("invalid conf file {}: 'deliverables' is not a list, treat as no conf".format(conf_file_path))
143+ deliverables = None
144+ _CONF_CACHE[cache_key] = (file_stat, deliverables)
145+ return deliverables
146+ 
147+ 
148+def _find_entry_paths(deliverables, name):
149+ """
150+ Find paths of the entry with the given name. Return None if the entry is not declared.
151+ """
152+ for entry in deliverables:
153+ if isinstance(entry, dict) and entry.get("name") == name:
154+ paths = entry.get("paths")
155+ if paths is not None and not isinstance(paths, list):
156+ return None
157+ return paths
158+ return None
159+ 
160+ 
161+def _resolve_path(raw_path, opp_root, placeholder_values, log):
162+ """
163+ Replace placeholders in one raw path. Return the resolved path, or None to skip this
164+ path (placeholder not resolvable in the current environment).
165+ 
166+ :param placeholder_values: (placeholder, value) pairs to substitute; a path containing
167+ a placeholder whose value is not available is skipped.
168+ """
169+ resolved = raw_path.replace(PLACEHOLDER_OPP_PATH, opp_root)
170+ for placeholder, value in placeholder_values:
171+ if placeholder not in resolved:
172+ continue
173+ if not value:
174+ return None
175+ resolved = resolved.replace(placeholder, str(value))
176+ if "{" in resolved and "}" in resolved:
177+ log("path '{}' contains unresolvable placeholder, ignore it".format(raw_path))
178+ return None
179+ return resolved
180+ 
181+ 
182+def get_deliverable_paths(
183+ name, opp_path=None, soc_version=None, os_name=None, arch=None, conf_file_path=None, log_func=None
184+):
185+ """
186+ Query the ordered paths of a deliverable entry by name.
187+ 
188+ :param name: entry name in the conf file, e.g. "ophost", "opsrc", "ops-info".
189+ :param opp_path: opp root directory, default to ASCEND_OPP_PATH env or the default install path.
190+ :param soc_version: short soc version (lower-case), required by paths containing `{socversion}`;
191+ such paths are skipped when it is not provided.
192+ :param os_name: os name, default to the current platform.
193+ :param arch: hardware architecture, default to the current platform.
194+ :param conf_file_path: conf file path, default to `{opp_path}/conf/ops_deliverables.json`.
195+ :param log_func: callable to receive diagnostic messages, default to print.
196+ :return: None if the conf is unavailable or the entry is not declared (caller falls back);
197+ otherwise a list of resolved paths in declaration order (empty list means declared
198+ but not applicable in the current environment). Callers must filter by existence.
199+ """
200+ log = log_func if callable(log_func) else _default_log
201+ opp_root = get_opp_path(opp_path)
202+ conf_file = conf_file_path or os.path.join(opp_root, CONF_RELATIVE_PATH)
203+ deliverables = _load_conf(conf_file, log)
204+ if deliverables is None:
205+ return None
206+ entry_paths = _find_entry_paths(deliverables, name)
207+ if entry_paths is None:
208+ log("entry '{}' is not declared in {}, caller should fall back to legacy logic".format(name, conf_file))
209+ return None
210+ 
211+ placeholder_values = (
212+ (PLACEHOLDER_SOC_VERSION, str(soc_version).lower() if soc_version else None),
213+ (PLACEHOLDER_OS, os_name or get_os_name()),
214+ (PLACEHOLDER_ARCH, arch or get_arch()),
215+ )
216+ paths = []
217+ for raw_path in entry_paths:
218+ if not isinstance(raw_path, str) or not raw_path:
219+ continue
220+ resolved = _resolve_path(raw_path, opp_root, placeholder_values, log)
221+ if resolved is None:
222+ continue
223+ if "*" in resolved:
224+ paths.extend(sorted(glob.glob(resolved)))
225+ else:
226+ paths.append(resolved)
227+ return paths
228+ 
229+ 
230+def get_existing_deliverable_paths(
231+ name, opp_path=None, soc_version=None, os_name=None, arch=None, conf_file_path=None, log_func=None
232+):
233+ """
234+ Compatibility-first query of the ordered paths of a deliverable entry, filtered by
235+ disk existence, which is the recommended entry for consumers.
236+ 
237+ Return None if the conf is unavailable, the entry is not declared, or none of the
238+ declared paths exists on disk; the caller should fall back to the legacy hard-coded
239+ logic in all these cases. Otherwise return the existing paths in declaration order
240+ (non-empty). A successful conf hit is silent; logs are only emitted on the fallback
241+ cases.
242+ """
243+ log = log_func if callable(log_func) else _default_log
244+ paths = get_deliverable_paths(
245+ name,
246+ opp_path=opp_path,
247+ soc_version=soc_version,
248+ os_name=os_name,
249+ arch=arch,
250+ conf_file_path=conf_file_path,
251+ log_func=log_func,
252+ )
253+ if paths is None:
254+ log("deliverables conf unavailable for entry '{}', fall back to legacy logic".format(name))
255+ return None
256+ valid_paths = [path for path in paths if os.path.exists(path)]
257+ if not valid_paths:
258+ log("no declared path of entry '{}' exists on disk, fall back to legacy logic".format(name))
259+ return None
260+ return valid_paths
261+ 
262+ 
263+def clear_conf_cache():
264+ """
265+ Clear the conf cache, for test or when the conf file is known to be refreshed.
266+ """
267+ with _CONF_CACHE_LOCK:
268+ _CONF_CACHE.clear()