Merged
fix(pypto_pro): Fix pro_repro support singlecommit #6240
fix(pypto_pro): Fix pro_repro support singlecommit #6240
Merged
liulufang_gitcodeAdd on Sep 14
Total: 6 files changed+875-120
@@ -15,13 +15,15 @@
15#include <cstring>15#include <cstring>
16#include <dlfcn.h>16#include <dlfcn.h>
17#include <string>17#include <string>
18+#include <unistd.h>
18#include <vector>19#include <vector>
19 20 
20#include "core/logging.h"21#include "core/logging.h"
21 22 
22static constexpr int32_t MAX_KERNEL_BUF_LEN = 1024;23static constexpr int32_t MAX_KERNEL_BUF_LEN = 1024;
23static constexpr int32_t MAX_TENSOR_NUM = 128;24static constexpr int32_t MAX_TENSOR_NUM = 128;
24-static constexpr int32_t MAX_DEBUG_CMD_LEN = 8192;25+static constexpr int32_t MAX_DEBUG_CMD_LEN = 65536;
26+static constexpr int32_t MAX_LAUNCH_META_LEN = 32768;
25 27 
26enum class AdxTensorType : int32_t { INPUT, OUTPUT, WORKSPACE };28enum class AdxTensorType : int32_t { INPUT, OUTPUT, WORKSPACE };
27enum class AdxAddressType : int32_t { TRADITIONAL, NOTILING, RAW };29enum class AdxAddressType : int32_t { TRADITIONAL, NOTILING, RAW };
@@ -63,6 +65,7 @@ using AdumpRegExceptionDumpCallBack = int32_t (*)(AdumpExceptionDumpCallback);
63static std::vector<AdxTensorInfo> g_cachedTensors;65static std::vector<AdxTensorInfo> g_cachedTensors;
64static char g_kernelName[MAX_KERNEL_BUF_LEN] = {0};66static char g_kernelName[MAX_KERNEL_BUF_LEN] = {0};
65static char g_debugCmd[MAX_DEBUG_CMD_LEN] = {0};67static char g_debugCmd[MAX_DEBUG_CMD_LEN] = {0};
68+static char g_launchMeta[MAX_LAUNCH_META_LEN] = {0};
66static bool g_debugCmdExecuted = false;69static bool g_debugCmdExecuted = false;
67static bool g_registered = false;70static bool g_registered = false;
68static void* g_adumpHandle = nullptr;71static void* g_adumpHandle = nullptr;
@@ -93,6 +96,36 @@ static AdumpRegExceptionDumpCallBack LoadAdumpRegFunc()
93 return g_regFunc;96 return g_regFunc;
94}97}
95 98 
99+static void WriteLaunchMetaFile()
100+{
101+ if (g_launchMeta[0] == '\0') {
102+ return;
103+ }
104+ // ASCEND_WORK_PATH may be unset; fall back to the process cwd so the
105+ // launch meta lands next to CANN's own dump data files (which use the
106+ // same default).
107+ char cwdBuf[4096] = {0};
108+ const char* workPath = std::getenv("ASCEND_WORK_PATH");
109+ if (workPath == nullptr || workPath[0] == '\0') {
110+ if (getcwd(cwdBuf, sizeof(cwdBuf)) == nullptr) {
111+ IR_LOGW() << "ProExceptionDumpCallback: getcwd failed, launch meta skipped";
112+ return;
113+ }
114+ workPath = cwdBuf;
115+ }
116+ const char* deviceId = std::getenv("TILE_FWK_DEVICE_ID");
117+ std::string devId = (deviceId != nullptr && deviceId[0] != '\0') ? deviceId : "0";
118+ std::string dumpDir = std::string(workPath) + "/extra-info/data-dump/" + devId;
119+ std::string metaPath = dumpDir + "/" + g_kernelName + "_launch_args.json";
120+ FILE* file = std::fopen(metaPath.c_str(), "w");
121+ if (file == nullptr) {
122+ IR_LOGW() << "ProExceptionDumpCallback: write launch meta failed: " << metaPath;
123+ return;
124+ }
125+ std::fwrite(g_launchMeta, 1, std::strlen(g_launchMeta), file);
126+ std::fclose(file);
127+}
128+ 
96static int32_t ProExceptionDumpCallback(void* exceptionInfo, AdxExceptionDumpInfo* exceptionDumpInfo,129static int32_t ProExceptionDumpCallback(void* exceptionInfo, AdxExceptionDumpInfo* exceptionDumpInfo,
97 uint32_t exceptionDumpSize, uint32_t* exceptionDumpRealSize,130 uint32_t exceptionDumpSize, uint32_t* exceptionDumpRealSize,
98 AdxExceptionDumpMode* mode)131 AdxExceptionDumpMode* mode)
@@ -126,6 +159,8 @@ static int32_t ProExceptionDumpCallback(void* exceptionInfo, AdxExceptionDumpInf
126 159 
127 *exceptionDumpRealSize = exceptionDumpSize;160 *exceptionDumpRealSize = exceptionDumpSize;
128 161 
162+ WriteLaunchMetaFile();
163+ 
129 if (g_debugCmd[0] != '\0' && !g_debugCmdExecuted) {164 if (g_debugCmd[0] != '\0' && !g_debugCmdExecuted) {
130 g_debugCmdExecuted = true;165 g_debugCmdExecuted = true;
131 int ret = std::system(g_debugCmd);166 int ret = std::system(g_debugCmd);
@@ -188,6 +223,7 @@ void pro_clear_dump_info()
188 g_cachedTensors.clear();223 g_cachedTensors.clear();
189 g_kernelName[0] = '\0';224 g_kernelName[0] = '\0';
190 g_debugCmd[0] = '\0';225 g_debugCmd[0] = '\0';
226+ g_launchMeta[0] = '\0';
191 g_debugCmdExecuted = false;227 g_debugCmdExecuted = false;
192}228}
193 229 
@@ -201,6 +237,18 @@ void pro_set_debug_cmd(const char* cmd)
201 g_debugCmdExecuted = false;237 g_debugCmdExecuted = false;
202}238}
203 239 
240+void pro_set_launch_meta(const char* json)
241+{
242+ if (json == nullptr || json[0] == '\0') {
243+ g_launchMeta[0] = '\0';
244+ return;
245+ }
246+ int written = std::snprintf(g_launchMeta, MAX_LAUNCH_META_LEN, "%s", json);
247+ if (written < 0 || static_cast<size_t>(written) >= MAX_LAUNCH_META_LEN) {
248+ IR_LOGW() << "pro_set_launch_meta: launch meta truncated (" << written << " >= " << MAX_LAUNCH_META_LEN << ")";
249+ }
250+}
251+ 
204#ifdef ENABLE_TESTS252#ifdef ENABLE_TESTS
205extern "C" int32_t pro_test_exception_dump_callback(uint32_t dumpSize, uint32_t* realSize, uint32_t* mode,253extern "C" int32_t pro_test_exception_dump_callback(uint32_t dumpSize, uint32_t* realSize, uint32_t* mode,
206 char* outKernelName, uint32_t kernelNameBufSize,254 char* outKernelName, uint32_t kernelNameBufSize,
@@ -11,7 +11,12 @@
11 11 
12#include <gtest/gtest.h>12#include <gtest/gtest.h>
13#include <cstdint>13#include <cstdint>
14+#include <cstdio>
15+#include <cstdlib>
14#include <cstring>16#include <cstring>
17+#include <cerrno>
18+#include <string>
19+#include <sys/stat.h>
15#include <vector>20#include <vector>
16 21 
17extern "C" {22extern "C" {
@@ -21,6 +26,7 @@ void pro_set_dump_info(const char* kernelName, int32_t numTensors, const int32_t
21 const int32_t* shapeCounts, int32_t maxDims);26 const int32_t* shapeCounts, int32_t maxDims);
22void pro_clear_dump_info();27void pro_clear_dump_info();
23void pro_set_debug_cmd(const char* cmd);28void pro_set_debug_cmd(const char* cmd);
29+void pro_set_launch_meta(const char* json);
24int32_t pro_test_exception_dump_callback(uint32_t dumpSize, uint32_t* realSize, uint32_t* mode, char* outKernelName,30int32_t pro_test_exception_dump_callback(uint32_t dumpSize, uint32_t* realSize, uint32_t* mode, char* outKernelName,
25 uint32_t kernelNameBufSize, uint32_t* outExtraTensorNum);31 uint32_t kernelNameBufSize, uint32_t* outExtraTensorNum);
26int32_t pro_test_exception_dump_callback_nullptr();32int32_t pro_test_exception_dump_callback_nullptr();
@@ -99,6 +105,61 @@ TEST_F(ExceptionDumpCallbackTest, SetDebugCmdOverwritesPreviousCmd)
99 pro_set_debug_cmd("echo second");105 pro_set_debug_cmd("echo second");
100}106}
101 107 
108+TEST_F(ExceptionDumpCallbackTest, SetLaunchMetaWithNullJson) { pro_set_launch_meta(nullptr); }
109+ 
110+TEST_F(ExceptionDumpCallbackTest, SetLaunchMetaWithEmptyJson) { pro_set_launch_meta(""); }
111+ 
112+TEST_F(ExceptionDumpCallbackTest, SetLaunchMetaWithValidJson) { pro_set_launch_meta("{\"block_dim\":16}"); }
113+ 
114+TEST_F(ExceptionDumpCallbackTest, SetLaunchMetaOverwritesPreviousJson)
115+{
116+ pro_set_launch_meta("{\"block_dim\":1}");
117+ pro_set_launch_meta("{\"block_dim\":16,\"abi\":[]}");
118+}
119+ 
120+TEST_F(ExceptionDumpCallbackTest, ClearDumpInfoClearsLaunchMeta)
121+{
122+ pro_set_launch_meta("{\"block_dim\":16}");
123+ pro_clear_dump_info();
124+}
125+ 
126+TEST_F(ExceptionDumpCallbackTest, CallbackWritesLaunchMetaFile)
127+{
128+ std::string workPath = testing::TempDir();
129+ ASSERT_NE(::setenv("ASCEND_WORK_PATH", workPath.c_str(), 1), -1);
130+ ASSERT_NE(::setenv("TILE_FWK_DEVICE_ID", "0", 1), -1);
131+ 
132+ // 测试上下文不经 CANN,目录需手动创建(逐级,容忍已存在)
133+ std::string dumpDir = std::string(workPath) + "/extra-info/data-dump/0";
134+ for (const std::string& dir :
135+ {std::string(workPath) + "/extra-info", std::string(workPath) + "/extra-info/data-dump", dumpDir}) {
136+ ASSERT_TRUE(::mkdir(dir.c_str(), 0755) == 0 || errno == EEXIST) << "mkdir failed: " << dir;
137+ }
138+ 
139+ pro_set_dump_info("meta_kernel", 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 8);
140+ pro_set_launch_meta(
141+ "{\"kernel_name\":\"meta_kernel\",\"block_dim\":16,\"abi\":[{\"kind\":\"scalar\",\"value\":256}]}");
142+ 
143+ uint32_t realSize = 0;
144+ uint32_t mode = 0;
145+ char kernelName[1024] = {0};
146+ uint32_t extraTensorNum = 0;
147+ int32_t ret = pro_test_exception_dump_callback(1, &realSize, &mode, kernelName, sizeof(kernelName),
148+ &extraTensorNum);
149+ EXPECT_EQ(ret, 0);
150+ 
151+ std::string metaPath = std::string(workPath) + "/extra-info/data-dump/0/meta_kernel_launch_args.json";
152+ FILE* file = std::fopen(metaPath.c_str(), "rb");
153+ ASSERT_NE(file, nullptr);
154+ char buf[512] = {0};
155+ size_t n = std::fread(buf, 1, sizeof(buf) - 1, file);
156+ std::fclose(file);
157+ EXPECT_EQ(std::string(buf, n),
158+ "{\"kernel_name\":\"meta_kernel\",\"block_dim\":16,\"abi\":[{\"kind\":\"scalar\",\"value\":256}]}");
159+ ::unsetenv("ASCEND_WORK_PATH");
160+ ::unsetenv("TILE_FWK_DEVICE_ID");
161+}
162+ 
102TEST_F(ExceptionDumpCallbackTest, RegisterCallbackReturnsResultCode)163TEST_F(ExceptionDumpCallbackTest, RegisterCallbackReturnsResultCode)
103{164{
104 int32_t ret = pro_register_exception_dump_callback();165 int32_t ret = pro_register_exception_dump_callback();
@@ -36,6 +36,7 @@ from __future__ import annotations
36 36 
37import ctypes37import ctypes
38import glob38import glob
39+import json
39import logging40import logging
40import os41import os
41from pathlib import Path42from pathlib import Path
@@ -108,6 +109,9 @@ def _ensure_lib() -> ctypes.CDLL:
108 109 
109 _lib.pro_set_debug_cmd.restype = None110 _lib.pro_set_debug_cmd.restype = None
110 _lib.pro_set_debug_cmd.argtypes = [ctypes.c_char_p]111 _lib.pro_set_debug_cmd.argtypes = [ctypes.c_char_p]
112+ 
113+ _lib.pro_set_launch_meta.restype = None
114+ _lib.pro_set_launch_meta.argtypes = [ctypes.c_char_p]
111 return _lib115 return _lib
112 116 
113 117 
@@ -130,6 +134,17 @@ def register_callback() -> bool:
130 return _registered134 return _registered
131 135 
132 136 
137+def _dump_dir_path() -> str:
138+ """CANN brief_dump writes to ASCEND_WORK_PATH/extra-info/data-dump/<device_id>.
139+ 
140+ Falls back to current working directory when ASCEND_WORK_PATH is not set,
141+ matching CANN's own default behavior.
142+ """
143+ work_path = os.environ.get("ASCEND_WORK_PATH", "") or os.getcwd()
144+ device_id = os.environ.get("TILE_FWK_DEVICE_ID", "0")
145+ return os.path.join(work_path, "extra-info", "data-dump", device_id)
146+ 
147+ 
133def _build_debug_compile_cmd(compiled: "CompiledKernel") -> str:148def _build_debug_compile_cmd(compiled: "CompiledKernel") -> str:
134 """Pre-construct the shell command for the C++ callback to execute.149 """Pre-construct the shell command for the C++ callback to execute.
135 150 
@@ -161,12 +176,7 @@ def _build_debug_compile_cmd(compiled: "CompiledKernel") -> str:
161 if not os.path.isfile(caller_cpp):176 if not os.path.isfile(caller_cpp):
162 return ""177 return ""
163 178 
164- work_path = os.environ.get("ASCEND_WORK_PATH", "")179+ dump_dir = _dump_dir_path()
165- if not work_path:
166- return ""
167- 
168- device_id = os.environ.get("TILE_FWK_DEVICE_ID", "0")
169- dump_dir = os.path.join(work_path, "extra-info", "data-dump", device_id)
170 so_path = os.path.join(dump_dir, f"{kernel_name}_call_kernel.so")180 so_path = os.path.join(dump_dir, f"{kernel_name}_call_kernel.so")
171 181 
172 ascend_home = os.environ.get("ASCEND_HOME_PATH", "")182 ascend_home = os.environ.get("ASCEND_HOME_PATH", "")
@@ -213,9 +223,15 @@ def _build_debug_compile_cmd(compiled: "CompiledKernel") -> str:
213 # Copy the kernel sources next to the .so so the dump directory is fully223 # Copy the kernel sources next to the .so so the dump directory is fully
214 # self-contained: the repro tool and the user never need the (ephemeral)224 # self-contained: the repro tool and the user never need the (ephemeral)
215 # build directory to read the source lines the Error PC resolves to.225 # build directory to read the source lines the Error PC resolves to.
216- cpp_sources = sorted(glob.glob(os.path.join(build_dir, "*.cpp")))226+ # *.h matters as much as *.cpp here: kernels with a tiling struct include
217- if cpp_sources:227+ # <Tiling>_tiling.h from kernel.cpp, so without it the -g rebuild cannot
218- cmd += " && cp " + " ".join(shlex.quote(f) for f in cpp_sources) + f" {shlex.quote(dump_dir)}/"228+ # be replayed from the dump directory alone.
229+ src_artifacts = sorted(
230+ glob.glob(os.path.join(build_dir, "*.cpp"))
231+ + glob.glob(os.path.join(build_dir, "*.h"))
232+ )
233+ if src_artifacts:
234+ cmd += " && cp " + " ".join(shlex.quote(f) for f in src_artifacts) + f" {shlex.quote(dump_dir)}/"
219 235 
220 # Preserve the original JIT-launched library (call_kernel_<digest>.so) as236 # Preserve the original JIT-launched library (call_kernel_<digest>.so) as
221 # well: the -g rebuild is verified bit-identical in .text, but keeping the237 # well: the -g rebuild is verified bit-identical in .text, but keeping the
@@ -227,12 +243,56 @@ def _build_debug_compile_cmd(compiled: "CompiledKernel") -> str:
227 return cmd243 return cmd
228 244 
229 245 
230-def set_dump_info(compiled: "CompiledKernel", args: tuple) -> None:246+def _record_launch_meta(compiled: "CompiledKernel", args: tuple, block_dim: int | None) -> None:
247+ """Cache the launch ABI (ptr/scalar/tiling args + block_dim) in the C++ shim.
248+ 
249+ Same pattern as the tensor info (``pro_set_dump_info``): the meta is held
250+ in the shim and only persisted to
251+ ``<dump_dir>/<kernel>_launch_args.json`` when the exception-dump callback
252+ fires (``WriteLaunchMetaFile``), so nothing touches the dump directory at
253+ launch time. The CANN dump data file only carries tensor payloads;
254+ standalone scalar args (e.g. int64 m/k/n) and the launch block_dim cannot
255+ be recovered from the call_kernel.cpp signature (which only exposes
256+ shape-derived dyn args), so the ABI is recorded here, in signature order,
257+ for the offline repro tool to rebuild the exact call.
258+ """
259+ if not getattr(compiled, "kernel_name", ""):
260+ return
261+ 
262+ abi = []
263+ for spec, arg in zip(getattr(compiled, "param_specs", None) or [], args):
264+ kind = spec.kind.name
265+ if kind in ("TENSOR", "PTR", "TILING"):
266+ if isinstance(arg, torch.Tensor):
267+ abi.append({
268+ "name": spec.name,
269+ "kind": "ptr",
270+ "dtype": str(spec.dtype) if spec.dtype else "uint8",
271+ "addr": arg.data_ptr(),
272+ "size": arg.numel() * arg.element_size(),
273+ "shape": list(arg.shape),
274+ })
275+ else:
276+ abi.append({"name": spec.name, "kind": "ptr", "dtype": "uint8", "addr": 0, "size": 0, "shape": []})
277+ elif kind == "SCALAR":
278+ value = arg if isinstance(arg, (int, float, bool)) else str(arg)
279+ abi.append({"name": spec.name, "kind": "scalar", "value": value})
280+ 
281+ meta = {"kernel_name": compiled.kernel_name, "block_dim": block_dim, "abi": abi}
282+ _ensure_lib().pro_set_launch_meta(json.dumps(meta).encode("utf-8"))
283+ 
284+ 
285+def set_dump_info(compiled: "CompiledKernel", args: tuple, block_dim: int | None = None) -> None:
231 """Cache tensor info from runtime args before kernel launch.286 """Cache tensor info from runtime args before kernel launch.
232 287 
233 Everything the exception-dump callback needs about the kernel's identity288 Everything the exception-dump callback needs about the kernel's identity
234 and artifacts (name, build dir, arch mix, launched .so) is read from the289 and artifacts (name, build dir, arch mix, launched .so) is read from the
235- CompiledKernel; ``args`` is the only per-launch input.290+ CompiledKernel; ``args`` is the only per-launch input. ``block_dim`` and
291+ the scalar members of ``args`` are cached in the C++ shim via
292+ :func:`_record_launch_meta` and only persisted to ``launch_args.json``
293+ when the exception-dump callback fires (``WriteLaunchMetaFile``), so
294+ nothing touches the dump directory at launch time. The offline repro tool
295+ reads the sidecar to rebuild the exact launch ABI.
236 """296 """
237 if not compiled.build_dir or not os.path.isdir(compiled.build_dir):297 if not compiled.build_dir or not os.path.isdir(compiled.build_dir):
238 logging.warning("exception dump skipped: not a jit scenario (build_dir unavailable)")298 logging.warning("exception dump skipped: not a jit scenario (build_dir unavailable)")
@@ -279,6 +339,8 @@ def set_dump_info(compiled: "CompiledKernel", args: tuple) -> None:
279 339 
280 lib = _ensure_lib()340 lib = _ensure_lib()
281 341 
342+ _record_launch_meta(compiled, args, block_dim)
343+ 
282 lib.pro_set_debug_cmd(_build_debug_compile_cmd(compiled).encode("utf-8"))344 lib.pro_set_debug_cmd(_build_debug_compile_cmd(compiled).encode("utf-8"))
283 345 
284 if num_tensors == 0:346 if num_tensors == 0:
@@ -796,7 +796,7 @@ def _build_launch_entry(compiled: "CompiledKernel"):
796 # native query will further reduce it to this stream's actual resources.796 # native query will further reduce it to this stream's actual resources.
797 if block_dim > 0xFFFFFFFF:797 if block_dim > 0xFFFFFFFF:
798 block_dim = 0xFFFFFFFF798 block_dim = 0xFFFFFFFF
799- _set_dump_info(compiled, args)799+ _set_dump_info(compiled, args, block_dim)
800 # Resolve limits and launch in one C call, avoiding two torch_npu C-extension800 # Resolve limits and launch in one C call, avoiding two torch_npu C-extension
801 # calls and Python dict/loop work. Errors return before any device launch.801 # calls and Python dict/loop work. Errors return before any device launch.
802 actual_block_dim = call_kernel(block_dim, stream._as_parameter_, *abi_args)802 actual_block_dim = call_kernel(block_dim, stream._as_parameter_, *abi_args)
@@ -26,6 +26,9 @@ debug_aicore_error_pro_repro.py 离线复现工具的端到端流程:
263. test_cube_dump_and_repro:纯 cube kernel(dav-c310-cube)matmul 后263. test_cube_dump_and_repro:纯 cube kernel(dav-c310-cube)matmul 后
27 fixpipe(Acc->GM)越界写出的异常,与前两个用例的 MTE2 读 / MTE3 写27 fixpipe(Acc->GM)越界写出的异常,与前两个用例的 MTE2 读 / MTE3 写
28 构成不同管线错误,交叉验证定位正确性。28 构成不同管线错误,交叉验证定位正确性。
29+4. test_ptr_scalar_dump_and_repro:纯 pl.Ptr + scalar 入参的 kernel
30+ (make_tensor 在函数体内构造形状),覆盖无 shape 签名的 ABI 恢复
31+ 路径——scalar 值与 PTR addr/size 均依赖 launch-args sidecar。
29 32 
30注意:33注意:
31 - 不要设置 NPU_COLLECT_PATH,否则 dump 模式变为 norm_dump,不生成 dump 文件。34 - 不要设置 NPU_COLLECT_PATH,否则 dump 模式变为 norm_dump,不生成 dump 文件。
@@ -438,6 +441,82 @@ def test_cube_dump_and_repro():
438 _assert_dump_and_repro(str(work_dir))441 _assert_dump_and_repro(str(work_dir))
439 442 
440 443 
444+# ---------------------------------------------------------------------------
445+# 4. pl.Ptr + scalar 入参的 kernel 异常(子进程隔离)
446+# ---------------------------------------------------------------------------
447+ 
448+_PTR_SCALAR_OOB_TRIGGER = """\
449+#!/usr/bin/env python3
450+from __future__ import annotations
451+import os, sys, logging
452+import torch
453+import pypto_pro.language as pl
454+ 
455+logging.basicConfig(level=logging.INFO, format="%(message)s")
456+ 
457+ 
458+@pl.jit(auto_mutex=True)
459+def ptr_oob_store_kernel(
460+ a_ptr: pl.Ptr[pl.DT_UINT8],
461+ out_ptr: pl.Ptr[pl.DT_UINT8],
462+ m_valid: pl.DT_INT64,
463+ n_valid: pl.DT_INT64,
464+):
465+ \"\"\"PTR + scalar 入参:make_tensor 构造后 vec store_tile 越界写。\"\"\"
466+ io_dtype = pl.DT_FP16
467+ a = pl.make_tensor(a_ptr, [m_valid, n_valid], [n_valid, 1], dtype=io_dtype)
468+ out = pl.make_tensor(out_ptr, [m_valid, n_valid], [n_valid, 1], dtype=io_dtype)
469+ 
470+ tt_vec = pl.TileType(shape=[64, 64], dtype=io_dtype, target_memory=pl.MemorySpace.Vec)
471+ vec = pl.make_tile_group(type=tt_vec, addrs=0x0000, mutex_ids=[0])
472+ 
473+ with pl.section_vector():
474+ cur_vec = vec.current()
475+ pl.load_tile(cur_vec, a, [0, 0])
476+ pl.store_tile(out, cur_vec, [65535, 0])
477+ 
478+ 
479+dev = f"npu:{os.environ.get('TILE_FWK_DEVICE_ID', '0')}"
480+torch.npu.set_device(dev)
481+a = torch.rand(64, 64, device=dev, dtype=torch.float16)
482+out = torch.zeros(64, 64, device=dev, dtype=torch.float16)
483+ 
484+ptr_oob_store_kernel(a, out, 64, 64)
485+try:
486+ torch.npu.synchronize()
487+ print("ERROR: No AICORE error raised")
488+ sys.exit(1)
489+except Exception as e:
490+ print(f"AICORE error raised: {e}")
491+ 
492+print("DONE")
493+"""
494+ 
495+ 
496+@pytest.mark.soc("950")
497+def test_ptr_scalar_dump_and_repro():
498+ """pl.Ptr + scalar 入参 kernel 的越界异常:上抛 + dump + 离线复现 + 定位。
499+ 
500+ 覆盖纯 pl.Ptr(无 shape)与独立 scalar(int64 m/n)入参样式的 ABI
501+ 恢复路径——与 pl.Tensor(shape 随签名走 dyn 参数)不同,这类 kernel
502+ 的形状完全由 scalar 描述,复现工具必须依赖 launch-args sidecar 中的
503+ scalar 值与 PTR 的 addr/size 才能重建调用,不依赖 dump 文件的 dyn
504+ 推导。触发方式为 vec store_tile 越界写(MTE3 路径)。
505+ """
506+ _check_npu()
507+ logging.info("------------test_ptr_scalar_dump_and_repro--------------")
508+ 
509+ work_dir = _make_work_dir("ptr_scalar_dump_and_repro")
510+ trigger = work_dir / "trigger_ptr_scalar_oob.py"
511+ trigger.write_text(_PTR_SCALAR_OOB_TRIGGER)
512+ 
513+ result = _run_subprocess(trigger, str(work_dir))
514+ assert result.returncode == 0, f"Trigger failed:\nstdout: {result.stdout}\nstderr: {result.stderr}"
515+ assert "DONE" in result.stdout, f"trigger script not completed:\n{result.stdout}"
516+ 
517+ _assert_dump_and_repro(str(work_dir))
518+ 
519+ 
441if __name__ == "__main__":520if __name__ == "__main__":
442 logging.basicConfig(level=logging.INFO, format="%(message)s")521 logging.basicConfig(level=logging.INFO, format="%(message)s")
443 pytest.main([__file__, "-v", "-s"])522 pytest.main([__file__, "-v", "-s"])