Using complete header files instead of stub
Co-authored-by: huangyunlong2022<huangyunlong4@h-partners.com> # message auto-generated for no-merge-commit merge: !45706 merge 2.13head into master Using complete header files instead of stub Created-by: huangyunlong2022 Commit-by: huangyunlong2022 Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [ ] 需求 - [x] 问题单 - [x] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 > 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\ > 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容) 将打包third_party目录下的stub替换为真实的头文件,防止该路径放在-I的前面时由于`#pragma once`被截断导致的报错 其中`#include_next <acl/acl_rt.h>`没有被使用,是因为这种情况下如果-`I third_party`目录后没有真实头文件也会报错 另外该方法会暴露用户使用`#include "third_party/acl/inc/acl/acl_rt.h"`时的错误,这种场景就是torch_npu之前修复的cann和torch_npu中acl头文件混合使用的报错,这种深度路径只能找到torch_npu目录下的acl头文件,但是acl头文件里由于存在`#include "acl/acl_base_rt.h"`这种写法导致只能在-I目录中寻找,可能找到cann中的头文件,如果和torch_npu版本不配套就会报错,这种情况需要用户改脚本成`#include <acl/acl_rt.h>`这种规范写法,torch_npu中这种写法已修复 同时添加测试用例,模拟用户#include cann和torch_npu真实头文件以及配置-I 中torch_npu,third_party,cann include路径的组合情况,目前只测试编译情况,真实的ABI兼容性暂未进行测试 其中用户`#include "third_party/acl/inc/acl/acl_rt.h"`这种使用没有被测试,因为这种是我们认为不合理写法,是会报错的, 另外该测试用例使用环境上真实的torch_npu和cann路径,只能覆盖CI上的真实情况,实际还可以使用不同的cann和torch_npu版本进行兼容性配套测试 # 【资料变更】 > 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及” # 【接口变更】 > 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及” # 【功能验证】 > 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\ > 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!45706
This commit is contained in:
+2
-18
@@ -242,6 +242,8 @@ def copy_hpp():
|
||||
"torch_npu/csrc/inductor/**/*.h",
|
||||
"torch_npu/csrc/distributed/*.h",
|
||||
"torch_npu/csrc/distributed/*.hpp",
|
||||
"third_party/acl/inc/*/*.h",
|
||||
"third_party/acl/inc/*/*/*.h",
|
||||
"third_party/hccl/inc/*/*.h",
|
||||
]
|
||||
glob_header_files = []
|
||||
@@ -270,24 +272,6 @@ def copy_hpp():
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
ret.append((src, dst))
|
||||
|
||||
# Preserve legacy include paths with forwarding headers, not duplicate ACL headers.
|
||||
compatibility_src = os.path.join(
|
||||
BASE_DIR,
|
||||
"build/acl_compat_headers",
|
||||
relative_header,
|
||||
)
|
||||
os.makedirs(os.path.dirname(compatibility_src), exist_ok=True)
|
||||
compatibility_include = relative_header.replace(os.sep, "/")
|
||||
with open(compatibility_src, "w", encoding="utf-8", newline="\n") as compatibility_header:
|
||||
compatibility_header.write(f"#pragma once\n#include <{compatibility_include}>\n")
|
||||
compatibility_dst = os.path.join(
|
||||
BASE_DIR,
|
||||
"libtorch_npu/include/third_party/acl/inc",
|
||||
relative_header,
|
||||
)
|
||||
os.makedirs(os.path.dirname(compatibility_dst), exist_ok=True)
|
||||
ret.append((compatibility_src, compatibility_dst))
|
||||
|
||||
return ret
|
||||
ret = get_src_py_and_dst()
|
||||
for src, dst in ret:
|
||||
|
||||
@@ -483,6 +483,8 @@ def get_src_py_and_dst():
|
||||
"torch_npu/csrc/*/*/*.h",
|
||||
"torch_npu/csrc/*/*/*/*.h",
|
||||
"torch_npu/csrc/*/*/*/*/*.h",
|
||||
"third_party/acl/inc/*/*.h",
|
||||
"third_party/acl/inc/*/*/*.h",
|
||||
"third_party/hccl/inc/*/*.h",
|
||||
"torch_npu/csrc/distributed/HCCLUtils.hpp",
|
||||
"torch_npu/csrc/distributed/ProcessGroupHCCL.hpp"
|
||||
@@ -514,24 +516,6 @@ def get_src_py_and_dst():
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
ret.append((src, dst))
|
||||
|
||||
# Preserve legacy include paths with forwarding headers, not duplicate ACL headers.
|
||||
compatibility_src = os.path.join(
|
||||
BASE_DIR,
|
||||
"build/acl_compat_headers",
|
||||
relative_header,
|
||||
)
|
||||
os.makedirs(os.path.dirname(compatibility_src), exist_ok=True)
|
||||
compatibility_include = relative_header.replace(os.sep, "/")
|
||||
with open(compatibility_src, "w", encoding="utf-8", newline="\n") as compatibility_header:
|
||||
compatibility_header.write(f"#pragma once\n#include <{compatibility_include}>\n")
|
||||
compatibility_dst = os.path.join(
|
||||
BASE_DIR,
|
||||
"build/packages/torch_npu/include/third_party/acl/inc",
|
||||
relative_header,
|
||||
)
|
||||
os.makedirs(os.path.dirname(compatibility_dst), exist_ok=True)
|
||||
ret.append((compatibility_src, compatibility_dst))
|
||||
|
||||
torch_header_files = [
|
||||
"*/*.h",
|
||||
"*/*/*.h",
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"
|
||||
for path in ("",):
|
||||
while path in sys.path:
|
||||
sys.path.remove(path)
|
||||
|
||||
import torch # noqa: F401
|
||||
import torch_npu # noqa: F401
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
# NOTE on coverage -- a real but currently UNCAUGHT failure mode:
|
||||
# A torch_npu header may directly reference a struct/type that only exists in
|
||||
# the NEWEST CANN it was built against. When a customer pairs that torch_npu
|
||||
# with an OLDER system CANN (and CANN is placed in front in -I), the
|
||||
# transitive ACL headers resolve to the older CANN, which lacks that
|
||||
# referenced definition -> compile error. This is the same "version skew"
|
||||
# family as the deep-path CANN mixing, just triggered through a torch_npu
|
||||
# header's own dependency on a new CANN symbol rather than through the deep
|
||||
# path. The current test env does NOT exhibit it (the torch_npu-vs-CANN skew
|
||||
# here happens not to surface in symbols the framework headers directly
|
||||
# reference), but it exists in the wild -- watch for it when the CANN gap
|
||||
# widens or torch_npu starts using newer CANN APIs.
|
||||
#
|
||||
# This runs against the REAL env, so outcomes depend on the current CANN-vs-
|
||||
# torch_npu version relationship (same / CANN-newer / CANN-older):
|
||||
# * stub-truncation failures (T-first, 报错二) are version-INDEPENDENT and
|
||||
# surface under any version relationship;
|
||||
# * version-skew-sensitive failures (deep-path CANN mixing [disabled above],
|
||||
# and the torch_npu-header-depends-on-new-CANN-symbol case) only manifest
|
||||
# under a skewed relationship -- a same-version env MASKS them, a mismatched
|
||||
# one reveals them. Re-run after switching CANN versions to observe how
|
||||
# behavior shifts across version relationships.
|
||||
|
||||
|
||||
def _npu_include():
|
||||
return os.path.join(os.path.dirname(os.path.realpath(torch_npu.__file__)), "include")
|
||||
|
||||
|
||||
def _cann_include():
|
||||
base = os.environ.get("ASCEND_HOME_PATH") or os.environ.get("ASCEND_TOOLKIT_HOME")
|
||||
if not base:
|
||||
return None
|
||||
inc = os.path.join(base, "include")
|
||||
return inc if os.path.isdir(os.path.join(inc, "acl")) else None
|
||||
|
||||
|
||||
def _third_party_dir():
|
||||
return os.path.join(_npu_include(), "third_party", "acl", "inc")
|
||||
|
||||
|
||||
def _torch_dirs():
|
||||
"""Extra -I needed to compile a torch_npu framework header (torch + python)."""
|
||||
torch_inc = os.path.join(os.path.dirname(os.path.realpath(torch.__file__)), "include")
|
||||
import sysconfig
|
||||
py_inc = sysconfig.get_path("include")
|
||||
return [torch_inc, os.path.join(torch_inc, "torch", "csrc", "api", "include"), py_inc]
|
||||
|
||||
|
||||
def _cxx_std():
|
||||
"""C++ standard for the installed torch: 2.14+ requires c++20, earlier c++17.
|
||||
If the toolchain can't deliver it (e.g. GCC 10 tops out below true C++20),
|
||||
framework tests fail loudly with torch's own '#error C++XX required' --
|
||||
a clear toolchain signal, not an ACL bug."""
|
||||
v = torch.__version__.split("+", 1)[0].split(".")
|
||||
major = int(v[0]) if v and v[0].isdigit() else 0
|
||||
minor = int(v[1]) if len(v) > 1 and v[1].isdigit() else 0
|
||||
return "c++20" if (major, minor) >= (2, 14) else "c++17"
|
||||
|
||||
|
||||
def _compile(include_line, i_order, body="aclrtStream s = nullptr;\n"):
|
||||
"""Compile a literal customer source against the REAL CANN + REAL torch_npu.
|
||||
|
||||
No fabrication: real installed versions, real -I order, literal #include lines.
|
||||
Returns (ok, stderr). g++ writes both the -H include tree and the diagnostics
|
||||
to stderr (stdout is empty for -fsyntax-only); stderr is returned separately so
|
||||
callers can grep real 'error:' lines instead of trusting a tail that may be
|
||||
buried under the (huge, for framework style) -H tree.
|
||||
"""
|
||||
src = include_line + "\n" + body
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
cpp = Path(d) / "t.cpp"
|
||||
cpp.write_text(src)
|
||||
args = ["g++", "-std=" + _cxx_std(), "-fsyntax-only", "-H"]
|
||||
args += ["-I" + x for x in i_order]
|
||||
args += [str(cpp)]
|
||||
proc = subprocess.run(args, capture_output=True, text=True)
|
||||
return proc.returncode == 0, (proc.stderr or "")
|
||||
|
||||
|
||||
# Customer include styles (literal, exactly as a customer writes them).
|
||||
# Each value: (include_line, extra_fixed_includes) where extra_fixed_includes are
|
||||
# dirs always appended (e.g. torch/python for framework headers; do not carry acl/).
|
||||
INCLUDES = {
|
||||
"shallow": ("#include <acl/acl_rt.h>", []),
|
||||
# Deep path is INTENTIONALLY DISABLED: torch_npu already migrated its source
|
||||
# to the shallow form (PR 795468cbc / 26.1.1) and the deep path is deprecated.
|
||||
# A customer still using it hits the CANN-mixing error (deep path pins the
|
||||
# first-level header to torch_npu while transitive deps get stolen by a
|
||||
# front-placed CANN) -> it is NOT a "must pass" scenario. Re-enable manually
|
||||
# only to characterize that legacy failure.
|
||||
# "deep": ('#include "third_party/acl/inc/acl/acl_rt.h"', []),
|
||||
"framework": (
|
||||
# Any torch_npu header that transitively pulls ACL works here as the probe
|
||||
# (it exercises torch_npu's own transitive include hygiene). NPUStream.h
|
||||
# is the default representative; swap in e.g. NPUEvent.h / NPUGraph.h /
|
||||
# CalcuOpUtil.h / AclInterface.h / ... as needed.
|
||||
'#include <torch/extension.h>\n#include "torch_npu/csrc/core/npu/NPUStream.h"',
|
||||
None, # lazily resolved to _torch_dirs() per-run
|
||||
),
|
||||
}
|
||||
|
||||
# Realistic customer -I configurations: all subsets+orders of N/T/C.
|
||||
# N = torch_npu/include, T = third_party/acl/inc, C = cann/include.
|
||||
# N and T are both inside the torch_npu package, so they usually appear together;
|
||||
# C (system CANN) is external and most commonly placed either FIRST or LAST
|
||||
# relative to the torch_npu dirs (both orders covered below).
|
||||
CONFIGS = {
|
||||
# single
|
||||
"N": lambda: [_npu_include()],
|
||||
"T": lambda: [_third_party_dir()],
|
||||
"C": lambda: [_cann_include()],
|
||||
# pair
|
||||
"N_T": lambda: [_npu_include(), _third_party_dir()],
|
||||
"T_N": lambda: [_third_party_dir(), _npu_include()],
|
||||
"N_C": lambda: [_npu_include(), _cann_include()],
|
||||
"C_N": lambda: [_cann_include(), _npu_include()],
|
||||
"T_C": lambda: [_third_party_dir(), _cann_include()],
|
||||
"C_T": lambda: [_cann_include(), _third_party_dir()],
|
||||
# triple (C-first and C-last are the common customer patterns)
|
||||
"C_N_T": lambda: [_cann_include(), _npu_include(), _third_party_dir()],
|
||||
"C_T_N": lambda: [_cann_include(), _third_party_dir(), _npu_include()],
|
||||
"N_T_C": lambda: [_npu_include(), _third_party_dir(), _cann_include()],
|
||||
"T_N_C": lambda: [_third_party_dir(), _npu_include(), _cann_include()],
|
||||
"N_C_T": lambda: [_npu_include(), _cann_include(), _third_party_dir()],
|
||||
"T_C_N": lambda: [_third_party_dir(), _cann_include(), _npu_include()],
|
||||
}
|
||||
|
||||
|
||||
class TestAclCustomerScenarios(TestCase):
|
||||
"""Customer real-usage guard.
|
||||
|
||||
Every realistic customer scenario (literal #include style x real -I order)
|
||||
is compiled against the REAL installed CANN and REAL installed torch_npu --
|
||||
no version fabrication, no path swapping. A failure is a real customer
|
||||
breakage: triage whether the usage is reasonable (fix torch_npu) or
|
||||
unreasonable (fix the customer script).
|
||||
"""
|
||||
|
||||
def _run(self, inc_kind, cfg_kind):
|
||||
if "C" in cfg_kind and _cann_include() is None:
|
||||
self.skipTest("CANN not found")
|
||||
# framework needs N (torch_npu/include) to resolve torch_npu headers;
|
||||
# configs without N are meaningless for it.
|
||||
if inc_kind == "framework" and "N" not in cfg_kind:
|
||||
self.skipTest("framework needs N to resolve torch_npu headers")
|
||||
inc_line, extra = INCLUDES[inc_kind]
|
||||
if extra is None: # framework: resolve torch/python dirs lazily
|
||||
extra = _torch_dirs()
|
||||
i_order = CONFIGS[cfg_kind]() + extra
|
||||
ok, err = _compile(inc_line, i_order)
|
||||
if not ok:
|
||||
errs = [ln for ln in err.splitlines()
|
||||
if "error:" in ln or "fatal error:" in ln]
|
||||
if errs:
|
||||
# dedupe by message text (the part after 'error:') so many
|
||||
# identical lines (e.g. 138x 'aclrtStream has not been
|
||||
# declared' across hccl.h params) collapse to one, and each
|
||||
# distinct error type shows once with its first file:line.
|
||||
seen, msgs = [], set()
|
||||
for ln in errs:
|
||||
m = ln.split("error:", 1)[1].strip() if "error:" in ln else ln
|
||||
if m not in msgs:
|
||||
msgs.add(m)
|
||||
seen.append(ln)
|
||||
snippet = "\n".join(seen[:20])
|
||||
if len(errs) > len(seen):
|
||||
snippet += "\n... (共 %d 条 error,去重 %d 种,仅列前 %d 种)" % (
|
||||
len(errs), len(seen), min(len(seen), 20))
|
||||
else:
|
||||
snippet = err[-700:]
|
||||
else:
|
||||
snippet = ""
|
||||
self.assertTrue(
|
||||
ok,
|
||||
msg=(
|
||||
f"\nCustomer scenario FAILED to compile.\n"
|
||||
f" include style : {inc_kind} ({inc_line})\n"
|
||||
f" -I order : {cfg_kind}\n"
|
||||
f" -> a real customer hitting this would see a compile error.\n"
|
||||
f"--- errors ---\n{snippet}"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _make(inc_kind, cfg_kind):
|
||||
def m(self):
|
||||
self._run(inc_kind, cfg_kind)
|
||||
m.__name__ = "test_%s__%s" % (inc_kind, cfg_kind)
|
||||
return m
|
||||
|
||||
|
||||
# Generate one test method per (include style x -I config) -- each reports
|
||||
# independently so every broken customer scenario surfaces for triage.
|
||||
for _inc in INCLUDES:
|
||||
for _cfg in CONFIGS:
|
||||
setattr(TestAclCustomerScenarios,
|
||||
"test_%s__%s" % (_inc, _cfg),
|
||||
_make(_inc, _cfg))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
Reference in New Issue
Block a user