Merged
feat(sanitizer): Optimize memory detection tools #6269
feat(sanitizer): Optimize memory detection tools #6269
Merged
zhengyaoff12Add on Sep 14
Total: 4 files changed+296-330
@@ -516,7 +516,8 @@ StmtPtr SanitizerInstrumenter::CollectMakeTensor(const CallPtr& call)
516 // tensor's shape scaled by its element width. A raw pointer has no516 // tensor's shape scaled by its element width. A raw pointer has no
517 // known bound (-1); the record skips the check then.517 // known bound (-1); the record skips the check then.
518 ExprPtr src_bytes = Int64Const(-1);518 ExprPtr src_bytes = Int64Const(-1);
519- if (auto src_tensor = As<TensorType>(call->args_[0]->GetType())) {519+ auto src_tensor = As<TensorType>(call->args_[0]->GetType());
520+ if (src_tensor != nullptr) {
520 int64_t src_elem = std::max<int64_t>(1, static_cast<int64_t>(src_tensor->dtype_.GetBit()) / 8);521 int64_t src_elem = std::max<int64_t>(1, static_cast<int64_t>(src_tensor->dtype_.GetBit()) / 8);
521 src_bytes = MakeMul(ShapeProduct(src_tensor, call->span_), Int64Const(src_elem), call->span_);522 src_bytes = MakeMul(ShapeProduct(src_tensor, call->span_), Int64Const(src_elem), call->span_);
522 }523 }
@@ -525,6 +526,12 @@ StmtPtr SanitizerInstrumenter::CollectMakeTensor(const CallPtr& call)
525 for (uint32_t i = 0; i < kSanitizerMaxTensorDims; ++i) {526 for (uint32_t i = 0; i < kSanitizerMaxTensorDims; ++i) {
526 fields.push_back(i < shape_tuple->elements_.size() ? shape_tuple->elements_[i] : Int64Const(0));527 fields.push_back(i < shape_tuple->elements_.size() ? shape_tuple->elements_[i] : Int64Const(0));
527 }528 }
529+ // Source dims for the report display; a raw-pointer source pads zeros
530+ // (its records skip the check via src_bytes = -1 anyway).
531+ for (uint32_t i = 0; i < kSanitizerMaxTensorDims; ++i) {
532+ fields.push_back((src_tensor != nullptr && i < src_tensor->shape_.size()) ? src_tensor->shape_[i] :
533+ Int64Const(0));
534+ }
528 fields.push_back(std::move(fp_bytes));535 fields.push_back(std::move(fp_bytes));
529 fields.push_back(std::move(src_bytes));536 fields.push_back(std::move(src_bytes));
530 return MakeLogStmt(static_cast<uint32_t>(SanitizerDetection::ViewShape), std::move(fields), call->span_);537 return MakeLogStmt(static_cast<uint32_t>(SanitizerDetection::ViewShape), std::move(fields), call->span_);
@@ -36,7 +36,6 @@ from pypto.pypto_impl.codegen import CCECodegen
36from pypto.pypto_impl.ir import ConstInt, PtrType, ScalarType, TensorType, TupleType, Var36from pypto.pypto_impl.ir import ConstInt, PtrType, ScalarType, TensorType, TupleType, Var
37from pypto_pro import DataType37from pypto_pro import DataType
38from pypto_pro.runtime.compile_config import KernelTarget, get_jit_compile_config38from pypto_pro.runtime.compile_config import KernelTarget, get_jit_compile_config
39-from pypto_pro.runtime.sanitizer_replay import MAX_RECORD_U32
40 39 
41from .._errors import (40from .._errors import (
42 CommonInner,41 CommonInner,
@@ -68,6 +67,19 @@ using namespace pto;
68# validate tensor args against the kernel signature).67# validate tensor args against the kernel signature).
69_PL_DTYPE_TO_TORCH: dict[str, "torch.dtype"] = {}68_PL_DTYPE_TO_TORCH: dict[str, "torch.dtype"] = {}
70 69 
70+# Sanitizer GM log budget for one launch (~1GB, split across all regions).
71+# Each executing core owns one region laid out as [ctr u32, records...] and is
72+# the region's single writer, so no atomics are needed. The per-region record
73+# capacity is derived from the budget at launch time; with hundreds of
74+# thousands of record slots per core the capacity is effectively unlimited
75+# for debugging use. Allocation stays lazy-cost: only the per-region ctr word
76+# is zeroed and only the written part of each region is copied back to the
77+# host. KSANITIZER_SUB_BLOCKS mirrors the device-side region layout (an A5
78+# vector section addresses each AIV sub-block by its own get_block_idx, so
79+# each gets an independent region).
80+KSANITIZER_LOG_BUDGET_BYTES = 1 * 1024**3
81+KSANITIZER_SUB_BLOCKS = 4
82+ 
71 83 
72def _register_pl_dtype(pl_dtype: DataType, torch_name: str) -> None:84def _register_pl_dtype(pl_dtype: DataType, torch_name: str) -> None:
73 """Map a pl dtype to the torch dtype named ``torch_name``, if this torch build has it."""85 """Map a pl dtype to the torch dtype named ``torch_name``, if this torch build has it."""
@@ -1665,22 +1677,33 @@ def _launch(compiled: "CompiledKernel", args: tuple, block_dim: int, stream):
1665 entry(args, block_dim, stream)1677 entry(args, block_dim, stream)
1666 1678 
1667 1679 
1668-# Per-block record capacity of the sanitizer GM log buffer, and the max1680+def _format_findings(findings) -> str:
1669-# sub-block count per launched block (A5 vector section addresses each AIV1681+ """One block of human-readable findings (or the clean-run marker).
1670-# sub-block by its own get_block_idx, so each gets an independent region —1682+ 
1671-# safe without atomics). Capacity is expressed in u32 words per region; the1683+ Multi-line findings (message + Hint) are indented to the kind column so
1672-# granularity is the largest fixed record (MAX_RECORD_U32 from the replay1684+ the Hint lines up with the leading G of GM_OUT_OF_BOUNDS et al.
1673-# tool's record formats, currently the 11-u32 GM record).1685+ """
1674-ksanitizer_log_slots = 8192 # max records per region (GM record = 16 u32)1686+ if not findings:
1675-ksanitizer_log_capacity_u32 = ksanitizer_log_slots * MAX_RECORD_U321687+ return "PyPTO Sanitizer: no issues detected\n"
1676-ksanitizer_sub_blocks = 41688+ lines = [f"PyPTO Sanitizer: {len(findings)} issue(s) detected\n"]
1689+ for i, finding in enumerate(findings, 1):
1690+ prefix = f"[{i}/{len(findings)}] "
1691+ pad = " " * len(prefix)
1692+ for j, line in enumerate(str(finding).split("\n")):
1693+ lines.append(f"{prefix}{line}\n" if j == 0 else f"{pad}{line}\n")
1694+ return "".join(lines)
1677 1695 
1678 1696 
1679-def _replay_sanitizer(log_buffer, block_dim, args, tensor_names, build_dir, source_file):1697+def _replay_sanitizer(log_buffer, capacity_u32, block_dim, build_dir, kernel_name, source_file):
1680- """Wait for the launch, read the device log buffer back, merge it with the1698+ """Wait for the launch, read the written part of the device log buffer
1681- compile-time metadata into one ``sanitizer_report.bin``, scan that file1699+ back, merge it with the compile-time metadata into one
1682- with the registered detections and raise an aggregated report when1700+ ``sanitizer_report.bin``, scan that file with the registered detections
1683- findings exist.1701+ and raise an aggregated report when findings exist.
1702+ 
1703+ Results go to pypto_sanitizer_report.txt next to sanitizer_report.bin in
1704+ the kernel's build dir (one file per compile instance), appended per
1705+ launch (kernel-tagged). No terminal output; an uncaught
1706+ SanitizerReplayError is the only on-screen signal.
1684 1707 
1685 Replay failures are never swallowed: when the sanitizer is enabled the1708 Replay failures are never swallowed: when the sanitizer is enabled the
1686 developer expects the detection result to be trustworthy, so a broken1709 developer expects the detection result to be trustworthy, so a broken
@@ -1690,30 +1713,28 @@ def _replay_sanitizer(log_buffer, block_dim, args, tensor_names, build_dir, sour
1690 from pypto_pro.runtime.sanitizer_replay import SanitizerReplayError, build_report_file, scan_report_file1713 from pypto_pro.runtime.sanitizer_replay import SanitizerReplayError, build_report_file, scan_report_file
1691 1714 
1692 torch.npu.synchronize()1715 torch.npu.synchronize()
1693- raw = log_buffer.cpu().numpy().tobytes()1716+ words_per_region = capacity_u32 + 1
1694- tensor_args = [a for a in args if isinstance(a, torch.Tensor) and a is not log_buffer]1717+ flat = log_buffer.view(torch.int32)
1695- regions = ksanitizer_sub_blocks * block_dim1718+ # Lazy copy-back stage 1: the per-region write counters only.
1719+ ctrs = flat[::words_per_region].cpu().tolist()
1720+ # Stage 2: for each region copy back just the ctr word and the records
1721+ # actually written (a region that never executed copies one word).
1722+ region_chunks = []
1723+ for region_idx, ctr in enumerate(ctrs):
1724+ written = min(int(ctr), capacity_u32)
1725+ start = region_idx * words_per_region
1726+ region_chunks.append(flat[start:start + 1 + written].cpu().numpy().tobytes())
1696 report_path = os.path.join(build_dir, "sanitizer_report.bin")1727 report_path = os.path.join(build_dir, "sanitizer_report.bin")
1697- build_report_file(1728+ build_report_file(region_chunks, report_path)
1698- raw, regions, ksanitizer_log_capacity_u32,
1699- tensor_names, [tuple(int(d) for d in a.shape) for a in tensor_args],
1700- report_path,
1701- )
1702 findings = scan_report_file(report_path, source_file)1729 findings = scan_report_file(report_path, source_file)
1730+ # Detection result file, appended per launch (kernel-tagged), next to
1731+ # sanitizer_report.bin in the build dir.
1732+ report_file = os.path.join(build_dir, "pypto_sanitizer_report.txt")
1733+ with open(report_file, "a", encoding="utf-8") as f:
1734+ f.write(f"===== kernel '{kernel_name}' ({build_dir}) =====\n")
1735+ f.write(_format_findings(findings))
1736+ f.write("\n")
1703 if findings:1737 if findings:
1704- # Log each finding at a level matching its severity so the report
1705- # survives the default WARNING threshold even when the caller swallows
1706- # the exception (e.g. pytest.raises or a try/except around the launch).
1707- # Levels come from the detection registry (ERROR: definite bounds
1708- # breaches; WARNING: suspicious but possibly deliberate overlap).
1709- for f in findings:
1710- # str(f) already embeds kind + message + location + hint on one
1711- # formatted line, so log it verbatim (single line for greppability).
1712- msg = f"PyPTO Sanitizer: {str(f).replace(chr(10), ' | ')}"
1713- if f.level == "WARNING":
1714- logging.warning(msg)
1715- else:
1716- logging.error(msg)
1717 raise SanitizerReplayError(findings)1738 raise SanitizerReplayError(findings)
1718 1739 
1719 1740 
@@ -1746,21 +1767,21 @@ def _build_sanitizer_entry(compiled: "CompiledKernel", build_dir: str):
1746 Loaded lazily on the first launch via ``compiled.entry``, exactly like the1767 Loaded lazily on the first launch via ``compiled.entry``, exactly like the
1747 non-sanitizer path.1768 non-sanitizer path.
1748 """1769 """
1749- tensor_names = [
1750- s.name for s in compiled.param_specs
1751- if s.kind in (ParamKind.TENSOR, ParamKind.PTR)
1752- and s.name not in ("sanitizer_log", "sanitizer_log_capacity")
1753- ]
1754 base_entry = _build_launch_entry(compiled)1770 base_entry = _build_launch_entry(compiled)
1755 1771 
1756 def entry(args: tuple, block_dim: int, stream):1772 def entry(args: tuple, block_dim: int, stream):
1757 # One region per AIV sub-block, mirroring the device-side buffer layout.1773 # One region per AIV sub-block, mirroring the device-side buffer layout.
1758- regions = ksanitizer_sub_blocks * block_dim1774+ regions = KSANITIZER_SUB_BLOCKS * block_dim
1759- nbytes = (ksanitizer_log_capacity_u32 + 1) * 4 * regions1775+ words_per_region = KSANITIZER_LOG_BUDGET_BYTES // (4 * regions)
1760- log_buffer = torch.zeros(nbytes, dtype=torch.uint8, device="npu")1776+ capacity_u32 = words_per_region - 1 # one u32 per region is the write counter
1761- full_args = (*args, log_buffer, ksanitizer_log_capacity_u32)1777+ nbytes = words_per_region * 4 * regions
1778+ log_buffer = torch.empty(nbytes, dtype=torch.uint8, device="npu")
1779+ # Only the per-region ctr word must start at zero; the record area is
1780+ # write-before-read on the device, so zeroing it would be wasted cost.
1781+ log_buffer.view(torch.int32)[::words_per_region] = 0
1782+ full_args = (*args, log_buffer, capacity_u32)
1762 base_entry(full_args, block_dim, stream)1783 base_entry(full_args, block_dim, stream)
1763- _replay_sanitizer(log_buffer, block_dim, full_args, tensor_names, build_dir, compiled.source_file)1784+ _replay_sanitizer(log_buffer, capacity_u32, block_dim, build_dir, compiled.kernel_name, compiled.source_file)
1764 1785 
1765 return entry1786 return entry
1766 1787 
@@ -8,18 +8,23 @@
8# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.8# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9# See LICENSE in the root of the software repository for the full text of the License.9# See LICENSE in the root of the software repository for the full text of the License.
10 10 
11-"""Host replay for the PyPTO Pro sanitizer (v2).11+"""Host replay for the PyPTO Pro sanitizer.
12 12 
13Scans the single ``sanitizer_report.bin`` file (metadata header + device-side13Scans the single ``sanitizer_report.bin`` file (metadata header + device-side
14log records) produced by a kernel launch and computes the detections:14log records) produced by a kernel launch and computes the detections:
15 15 
16- 1. GM_OUT_OF_BOUNDS - GM access window must fit each tensor dimension.16+ 1. GM_OUT_OF_BOUNDS - GM access window must fit each tensor dimension
17- 2. TILE_OUT_OF_BOUNDS - tile access window must fit the declared tile dims.17+ (linear scalar access included).
18- 3. TILE_OVERLAP - no two tile slots may overlap in address space.18+ 2. TILE_OUT_OF_BOUNDS - tile access window must fit the declared tile
19+ dims (transfers, set_validshape, scalar access).
20+ 3. TILE_OVERLAP - no two tiles may overlap in address space.
19 4. MUTEX_* - mutex lock/unlock pairing per (region, id, pipe).21 4. MUTEX_* - mutex lock/unlock pairing per (region, id, pipe).
22+ 5. GM (declaration) - a ptr.make_tensor view must fit its source.
20 23 
21-Each detection registers its own record format and check logic in24+Record layouts are declared in ``_RECORD_FORMATS`` (the single source both
22-``_DETECTIONS``; see ``/workspace/doc/sanitizer_v2_design.md``.25+the decoder and the size/capacity math derive from); checks are registered
26+in ``_DETECTIONS``. Every check value travels in the records -- the pass
27+never decides, this file does.
23"""28"""
24 29 
25from __future__ import annotations30from __future__ import annotations
Rpython/tests/st/pypto_pro/frontend/sanitizer/test_sanitizer_selflog.py→python/tests/st/pypto_pro/frontend/sanitizer/test_sanitizer.py+22-10
@@ -263,16 +263,16 @@ def test_tile_bounds_combined_check():
263 # 无 offset:窗口超出声明维度263 # 无 offset:窗口超出声明维度
264 hits = _check_tile_bounds([rec(0, 0, 80, 32)], ctx)264 hits = _check_tile_bounds([rec(0, 0, 80, 32)], ctx)
265 assert len(hits) == 1, f"expected 1 finding, got {len(hits)}"265 assert len(hits) == 1, f"expected 1 finding, got {len(hits)}"
266- assert "dim0: offset 0+window 80=80 > declared 64" in hits[0].message266+ assert "dim0: offset 0 + valid_shape 80 = 80 > 64 (over by 16)" in hits[0].message
267 # 有 offset:offset+window 超出声明维度(核心回归场景)267 # 有 offset:offset+window 超出声明维度(核心回归场景)
268 hits = _check_tile_bounds([rec(32, 0, 64, 32)], ctx)268 hits = _check_tile_bounds([rec(32, 0, 64, 32)], ctx)
269 assert len(hits) == 1, f"expected 1 finding, got {len(hits)}"269 assert len(hits) == 1, f"expected 1 finding, got {len(hits)}"
270- assert "dim0: offset 32+window 64=96 > declared 64" in hits[0].message270+ assert "dim0: offset 32 + valid_shape 64 = 96 > 64 (over by 32)" in hits[0].message
271 # 两维都越界271 # 两维都越界
272 hits2 = _check_tile_bounds([rec(32, 16, 64, 64)], ctx)272 hits2 = _check_tile_bounds([rec(32, 16, 64, 64)], ctx)
273 assert len(hits2) == 1, f"expected 1 finding, got {len(hits2)}"273 assert len(hits2) == 1, f"expected 1 finding, got {len(hits2)}"
274- assert "dim0: offset 32+window 64=96 > declared 64" in hits2[0].message274+ assert "dim0: offset 32 + valid_shape 64 = 96 > 64 (over by 32)" in hits2[0].message
275- assert "dim1: offset 16+window 64=80 > declared 64" in hits2[0].message275+ assert "dim1: offset 16 + valid_shape 64 = 80 > 64 (over by 16)" in hits2[0].message
276 # 正样本:offset+window 在声明维度内276 # 正样本:offset+window 在声明维度内
277 hits3 = _check_tile_bounds([rec(16, 0, 32, 32)], ctx)277 hits3 = _check_tile_bounds([rec(16, 0, 32, 32)], ctx)
278 assert len(hits3) == 0, f"expected 0, got {len(hits3)}"278 assert len(hits3) == 0, f"expected 0, got {len(hits3)}"
@@ -1266,7 +1266,7 @@ def test_view_over_source_detected():
1266 with pytest.raises(SanitizerReplayError) as exc_info:1266 with pytest.raises(SanitizerReplayError) as exc_info:
1267 view_over_source_kernel(x, z)1267 view_over_source_kernel(x, z)
1268 torch.npu.synchronize()1268 torch.npu.synchronize()
1269- assert any("exceeds its source" in str(f) for f in exc_info.value.findings)1269+ assert any("source tensor" in str(f) for f in exc_info.value.findings)
1270 logging.info("test_view_over_source_detected OK")1270 logging.info("test_view_over_source_detected OK")
1271 1271 
1272 1272 
@@ -1341,7 +1341,7 @@ def test_wide_stride_view_detected():
1341 with pytest.raises(SanitizerReplayError) as exc_info:1341 with pytest.raises(SanitizerReplayError) as exc_info:
1342 wide_stride_view_kernel(x, z)1342 wide_stride_view_kernel(x, z)
1343 torch.npu.synchronize()1343 torch.npu.synchronize()
1344- assert any("footprint" in str(f) for f in exc_info.value.findings)1344+ assert any("make_tensor view" in str(f) for f in exc_info.value.findings)
1345 logging.info("test_wide_stride_view_detected OK")1345 logging.info("test_wide_stride_view_detected OK")
1346 1346 
1347 1347 
@@ -1444,7 +1444,7 @@ def test_dynamic_view_over_source_detected():
1444 with pytest.raises(SanitizerReplayError) as exc_info:1444 with pytest.raises(SanitizerReplayError) as exc_info:
1445 dynamic_view_over_source_kernel(x, z)1445 dynamic_view_over_source_kernel(x, z)
1446 torch.npu.synchronize()1446 torch.npu.synchronize()
1447- assert any("exceeds its source" in str(f) for f in exc_info.value.findings)1447+ assert any("source tensor" in str(f) for f in exc_info.value.findings)
1448 logging.info("test_dynamic_view_over_source_detected OK")1448 logging.info("test_dynamic_view_over_source_detected OK")
1449 1449 
1450 1450 
@@ -1601,11 +1601,23 @@ if __name__ == "__main__":
1601 """python3 直接执行入口:跑本文件全部 sanitizer 自研日志回放用例。1601 """python3 直接执行入口:跑本文件全部 sanitizer 自研日志回放用例。
1602 1602 
1603 Usage:1603 Usage:
1604- python3 test_sanitizer_selflog.py # 跑全部用例1604+ python3 test_sanitizer.py # 跑全部用例
1605- python3 test_sanitizer_selflog.py -k oob # 只跑名字含 oob 的用例1605+ python3 test_sanitizer.py test_gm_out_of_bounds_detected # 跑指定用例(可多个)
1606+ python3 test_sanitizer.py -k oob # pytest 选项原样透传
1606 """1607 """
1607 logging.basicConfig(level=logging.INFO, format="%(message)s")1608 logging.basicConfig(level=logging.INFO, format="%(message)s")
1608 import sys1609 import sys
1609 1610 
1610- args = [__file__, "-v", "-s", "--tb=short", "--no-header"] + sys.argv[1:]1611+ raw = sys.argv[1:]
1612+ base = ["-v", "-s", "--tb=short", "--no-header"]
1613+ if any(a.startswith("-") for a in raw):
1614+ # Any pytest option (e.g. -k oob / -m mark): pass everything
1615+ # through verbatim -- splitting raw ourselves would break options
1616+ # whose value is a separate argument.
1617+ args = [__file__, *base, *raw]
1618+ elif raw:
1619+ # Bare test names only: address them as this file's nodes.
1620+ args = [*(f"{__file__}::{n}" for n in raw), *base]
1621+ else:
1622+ args = [__file__, *base]
1611 sys.exit(pytest.main(args))1623 sys.exit(pytest.main(args))