Merged
test(sanitizer): Add memory check tool #5668
test(sanitizer): Add memory check tool #5668
Merged
zhengyaoff12Add on Aug 25
Total: 10 files changed+3096-31
@@ -256,6 +256,19 @@ Pass CreateRootFunctions();
256 * \brief Finalize dynamic functions built from new IR (post create_root_functions).256 * \brief Finalize dynamic functions built from new IR (post create_root_functions).
257 */257 */
258Pass FinalizeDynamicFunction();258Pass FinalizeDynamicFunction();
259+ 
260+/**
261+ * \brief Create a sanitizer instrumentation pass
gaoxiang618

补充资料

likedislike
262+ *
263+ * Injects block.sanitizer_log records and the hidden log-buffer parameters
264+ * into the entry function, accumulating the replay metadata (span table,
265+ * tile table) into \p meta. The caller keeps \p meta alive as long as the
266+ * pass; call the pass once per program (the Cube and Vector programs of one
267+ * kernel share one meta so the tables accumulate over both).
268+ */
269+/// Sanitizer instrumentation pass. Stateless: every check value travels
270+/// in the records; the replay tool supplies the source file for locations.
271+Pass Sanitizer();
259} // namespace pass272} // namespace pass
260 273 
261/**274/**
@@ -44,6 +44,20 @@ CompareAttrs GetCompareAttrs(const ir::CallPtr& op);
44 44 
45namespace cce {45namespace cce {
46 46 
47+/// Positions of the operands of a GM access op (tile <-> tensor transfer:
48+/// block.load / block.store / debug.dump_tile). tensor/tile name the GM-side
49+/// tensor and the tile operand; offsets names the offset-tuple position.
50+/// Scalar-container ops (getval/setval) deliberately stay out: consumers
51+/// like the CCE tensor-declaration collector treat every contract op as a
52+/// tile-tensor transfer.
53+struct AccessArgIndices {
54+ int tensor_arg_idx = -1;
55+ int tile_arg_idx = -1;
56+ int offsets_arg_idx = -1;
57+};
58+ 
59+AccessArgIndices ResolveAccessArgIndices(const std::string& op_name);
60+ 
47bool IsNZTensorType(const ir::TensorTypePtr& tensor_type);61bool IsNZTensorType(const ir::TensorTypePtr& tensor_type);
48/// Whether a block.load is an MX scale load. Such a load declares its own GlobalTensor at the62/// Whether a block.load is an MX scale load. Such a load declares its own GlobalTensor at the
49/// op -- TileShape2D maps rows/cols into layout-specific dims that the shared per-layout63/// op -- TileShape2D maps rows/cols into layout-specific dims that the shared per-layout
@@ -0,0 +1,567 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <string>
12+#include <utility>
13+ 
14+#include "backend/common/backend_utils.h"
15+#include "ir/kind_traits.h"
16+#include "ir/scalar_expr.h"
17+#include "ir/scalar_expr_ops.h"
18+#include "ir/type.h"
19+#include "ir/transforms/base/mutator.h"
20+#include "ir/transforms/base/visitor.h"
21+#include "ir/transforms/passes.h"
22+ 
23+namespace pypto {
24+namespace ir {
25+ 
26+namespace {
27+ 
28+// det_id values on the wire; each owns a distinct record format. Must stay
29+// in sync with the Python DET_* constants in sanitizer_replay.py.
30+enum class SanitizerDetection : uint32_t {
31+ GmAccess = 1, // GM access: tensor_id, ndim, off[5], acc_row, acc_col
32+ TileAccess = 2, // tile access: tile_id, dim0, dim1, off_row, off_col, acc_row, acc_col
33+ MutexAccess = 3, // mutex lock/unlock: mutex_id, pipe, is_lock, span_id
34+ ViewShape = 4, // runtime view shape: tensor_id, dim[5] (exprs), footprint (expr), span
35+ TileScalar = 5, // tile scalar access: dims, linear offset, span
36+ TileDecl = 6, // make_tile declaration: addr, size, space_id, span (overlap scan)
37+};
38+ 
39+/// Max logical tensor rank supported by the GM bounds check.
40+constexpr uint32_t kSanitizerMaxTensorDims = 5;
41+ 
42+// Runtime-evaluated GetValidRow()/GetValidCol() of the tile.
43+ExprPtr TileDim(const ExprPtr& tile, int axis)
44+{
45+ return std::make_shared<Call>("block.tile_valid_shape", std::vector<ExprPtr>{tile},
46+ std::vector<std::pair<std::string, std::any>>{{"axis", axis}},
47+ std::make_shared<ScalarType>(DataType(DataType::UINT32)), Span::Unknown());
48+}
49+ 
50+ExprPtr IndexConst(int64_t v) { return std::make_shared<ConstInt>(v, DataType::INDEX, Span::Unknown()); }
51+ 
52+// ---------------------------------------------------------------------------
53+// SanitizerInstrumenter injects the log records (an IRMutator).
54+//
55+// Two record handlers: RecordBounds (every memory-access op -- GM
56+// loads/stores, tile transfers at an offset, scalar access, set_validshape
57+// windows) and RecordMutex (lock/unlock pairing); the op name picks the
58+// operand layout inside the handler. Records carry values only -- the pass
59+// never decides, the replay computes the detections. Declarations (make_tile,
60+// ptr.make_tensor) get their own declaration records at the AssignStmt hook.
61+// ---------------------------------------------------------------------------
62+ 
63+class SanitizerInstrumenter : public IRMutator {
64+public:
65+ using IRMutator::VisitExpr_;
66+ using IRMutator::VisitStmt_;
67+ 
68+ SanitizerInstrumenter()
69+ {
70+ // Table entries name the check the record serves, not the op spell.
71+ // Same-entry ops differ only in how they collect the operands (that
72+ // part lives inside each builder).
73+ auto tensor_bounds = [this](const CallPtr& c) { return RecordGmAccess(c); };
74+ auto tile_transfer_bounds = [this](const CallPtr& c) {
75+ // move/move_fp (TEXTRACT): the offset is the SOURCE extraction
76+ // start, the window the DESTINATION's valid shape.
77+ ExprPtr src_off_row = IndexConst(0);
78+ ExprPtr src_off_col = IndexConst(0);
79+ if (auto off_tuple = As<MakeTuple>(c->args_.back())) {
80+ if (!off_tuple->elements_.empty())
81+ src_off_row = off_tuple->elements_[0];
82+ if (off_tuple->elements_.size() > 1)
83+ src_off_col = off_tuple->elements_[1];
84+ }
85+ ExprPtr win_row = TileDim(c->args_[0], 0);
86+ ExprPtr win_col = TileDim(c->args_[0], 1);
87+ auto src = RecordTileAccess(c, 1, src_off_row, src_off_col, win_row, win_col);
88+ auto dst = RecordTileAccess(c, 0, IndexConst(0), IndexConst(0), win_row, win_col);
89+ return SeqStmts::Flatten({src, dst}, c->span_);
90+ };
91+ auto tile_insert_bounds = [this](const CallPtr& c) {
92+ // insert (TINSERT): the offset is the DESTINATION write start,
93+ // the window the SOURCE's valid shape.
94+ ExprPtr win_row = TileDim(c->args_[1], 0);
95+ ExprPtr win_col = TileDim(c->args_[1], 1);
96+ auto src = RecordTileAccess(c, 1, IndexConst(0), IndexConst(0), win_row, win_col);
97+ auto dst = RecordTileAccess(c, 0, c->args_[2], c->args_[3], win_row, win_col);
98+ return SeqStmts::Flatten({src, dst}, c->span_);
99+ };
100+ auto scalar_bounds = [this](const CallPtr& c) { return RecordScalarAccess(c); };
@@ -1640,6 +1640,97 @@ REGISTER_BACKEND_OP(BackendCCE, "debug.trap")
1640 return MakeDebugTrapCodegenCCE(op, codegen);1640 return MakeDebugTrapCodegenCCE(op, codegen);
1641 });1641 });
1642 1642 
1643+// ============================================================================
1644+// Sanitizer log record - device-side write of one per-detection variable-size
1645+// record into the GM log buffer passed as the trailing `sanitizer_log`
1646+// parameter. One op covers every detection type: the leading det_id argument
1647+// selects the record layout on the host side (pypto_pro.runtime.
1648+// sanitizer_replay decodes by det_id); the trailing three arguments are the
1649+// hidden log-buffer pointer / capacity and the span id.
1650+// args = [det_id, field..., log_ptr, capacity, span_id]
1651+// record = [det_id, field...] (rec_u32 = args.size() - 3)
1652+// The buffer region per sub-block is [ctr u32, records...], where ctr is the
1653+// region's u32-word offset past itself and the capacity
1654+// (`sanitizer_log_capacity` scalar) is the per-region u32 word budget for
1655+// records.
1656+// ============================================================================
1657+ 
1658+namespace {
1659+ 
1660+void EmitSanitizerLogPrologue(codegen::CCECodegen& codegen, const std::string& log, const std::string& capacity)
1661+{
1662+ // Region addressing. A mixed kernel runs the Cube part on the AICs and
1663+ // the Vector part on the AIVs of the SAME launch, so both parts share
1664+ // one log buffer and their region indices must never overlap (the
1665+ // append counter is a plain read-modify-write; two writers on one
1666+ // region silently drop records). The Vector part is therefore offset by
1667+ // the block count: Cube covers [0, block_num), Vector covers
1668+ // [block_num, block_num + block_num * subblockdim) = at most [N, 3N),
1669+ // which the host allocation of 4 * block_dim regions holds. A
1670+ // vector-only kernel wastes the first block_num regions, which is safe.
1671+ // Sub-block addressing follows the established get_block_idx() backend-op
1672+ // contract: the Vector target computes the global AIV index, so each
1673+ // sub-block gets its own region even when several AIVs run under one
1674+ // AIC block.
1675+ std::string block_idx;
1676+ if (codegen.GetTarget() == ir::SectionKind::Vector) {
1677+ block_idx = "(int32_t)(get_block_num() + get_block_idx() * get_subblockdim() + get_subblockid())";
1678+ } else {
1679+ block_idx = "(int32_t)(get_block_idx())";
1680+ }
1681+ 
1682+ // Append-mode logging, no atomics: each executing sub-block targets its own
1683+ // region (independently addressable via the global block index above), so
1684+ // the leading counter is only written by this single writer. This keeps
1685+ // every loop iteration's record (no overwrite) without relying on a GM
1686+ // atomic instruction. Region layout: [ctr u32, records...], ctr is the
1687+ // u32-word offset of the first free record (read, incremented, written
1688+ // back); buffer size = sub_block_count * (capacity + 1) * 4 bytes.
1689+ codegen.Emit("if (" + log + " != 0) {");
1690+ codegen.Emit(" int32_t __log_block = " + block_idx + ";");
1691+ codegen.Emit(" __gm__ uint32_t* __log_base = reinterpret_cast<__gm__ uint32_t*>(" + log +
1692+ ") + "
1693+ "static_cast<uint64_t>(__log_block) * (static_cast<uint64_t>(" +
1694+ capacity + ") + 1u);");
1695+ codegen.Emit(" uint32_t __log_off = __log_base[0];");
1696+}
1697+ 
1698+} // namespace
1699+ 
1700+static std::string MakeSanitizerLogCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
1701+{
1702+ auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
1703+ // args = [det_id, field..., log_ptr, capacity, span_id] -> at least the
1704+ // det_id, the two hidden buffer parameters and the span id.
1705+ CHECK(op->args_.size() >= 4) << "block.sanitizer_log requires (det_id, field..., log_ptr, capacity, span_id)";
1706+ 
1707+ const size_t n = op->args_.size();
1708+ std::string det_id = codegen.GetExprAsCode(op->args_[0]);
1709+ // Hidden log-buffer parameters: resolve their final (SSA-suffixed) names.
1710+ std::string log = codegen.GetExprAsCode(op->args_[n - 3]);
1711+ std::string capacity = codegen.GetExprAsCode(op->args_[n - 2]);
1712+ std::string span_id = codegen.GetExprAsCode(op->args_[n - 1]);
1713+ // Record size in u32 words: det_id + fields + span_id (fields exclude the
1714+ // hidden log/capacity parameters).
1715+ const uint32_t rec_u32 = static_cast<uint32_t>(n) - 2u;
1716+ 
1717+ EmitSanitizerLogPrologue(codegen, log, capacity);
1718+ codegen.Emit(" if (__log_off + " + std::to_string(rec_u32) + "u <= static_cast<uint32_t>(" + capacity + ")) {");
1719+ codegen.Emit(" __gm__ uint32_t* __log_rec = __log_base + 1u + __log_off;");
1720+ codegen.Emit(" __log_rec[0] = static_cast<uint32_t>(" + det_id + "); // det_id");
1721+ for (size_t i = 1; i + 3 < n; ++i) {
1722+ codegen.Emit(" __log_rec[" + std::to_string(i) + "] = static_cast<int32_t>(" +
1723+ codegen.GetExprAsCode(op->args_[i]) + ");");
1724+ }
1725+ codegen.Emit(" __log_rec[" + std::to_string(rec_u32 - 1u) + "] = static_cast<uint32_t>(" + span_id + ");");
1726+ codegen.Emit(" __log_base[0] = __log_off + " + std::to_string(rec_u32) + "u;");
1727+ codegen.Emit(" }");
1728+ codegen.Emit("}");
1729+ return "";
1730+}
1731+ 
1732+REGISTER_BACKEND_OP(BackendCCE, "block.sanitizer_log").set_pipe(ir::PipeType::S).f_codegen(MakeSanitizerLogCodegenCCE);
1733+ 
1643// ============================================================================1734// ============================================================================
1644// Language operations: get_block_num, get_subblock_idx1735// Language operations: get_block_num, get_subblock_idx
1645// ============================================================================1736// ============================================================================
@@ -61,6 +61,24 @@ CompareAttrs GetCompareAttrs(const ir::CallPtr& op)
61 61 
62namespace cce {62namespace cce {
63 63 
64+AccessArgIndices ResolveAccessArgIndices(const std::string& op_name)
65+{
66+ AccessArgIndices indices;
67+ if (op_name == "block.load") {
68+ indices.tensor_arg_idx = 1;
69+ indices.tile_arg_idx = 0;
70+ indices.offsets_arg_idx = 2;
71+ } else if (op_name == "block.store") {
72+ indices.tensor_arg_idx = 0;
73+ indices.tile_arg_idx = 1;
74+ indices.offsets_arg_idx = 2;
75+ } else if (op_name == "debug.dump_tile") {
76+ indices.tensor_arg_idx = 3;
77+ indices.tile_arg_idx = 0;
78+ }
79+ return indices;
80+}
81+ 
64bool IsNZTensorType(const ir::TensorTypePtr& tensor_type)82bool IsNZTensorType(const ir::TensorTypePtr& tensor_type)
65{83{
66 return tensor_type && tensor_type->tensor_view_.has_value() &&84 return tensor_type && tensor_type->tensor_view_.has_value() &&
@@ -1226,8 +1226,10 @@ void CCECodegen::VisitStmt_(const ir::YieldStmtPtr& op)
1226 1226 
1227void CCECodegen::EmitYieldAssignments(const std::vector<ir::VarPtr>& return_vars)1227void CCECodegen::EmitYieldAssignments(const std::vector<ir::VarPtr>& return_vars)
1228{1228{
1229- if (return_vars.empty() || yield_buffer_.empty())1229+ if (return_vars.empty() || yield_buffer_.empty()) {
1230+ yield_buffer_.clear();
1230 return;1231 return;
1232+ }
1231 CHECK(return_vars.size() == yield_buffer_.size()) << "IfStmt yield values must match its return variables";1233 CHECK(return_vars.size() == yield_buffer_.size()) << "IfStmt yield values must match its return variables";
1232 for (size_t i = 0; i < return_vars.size(); ++i) {1234 for (size_t i = 0; i < return_vars.size(); ++i) {
1233 EmitVariable(return_vars[i], yield_buffer_[i], false);1235 EmitVariable(return_vars[i], yield_buffer_[i], false);
@@ -2406,29 +2408,9 @@ public:
2406 }2408 }
2407};2409};
2408 2410 
2409-struct AccessArgIndices {
2410- int tensor_arg_idx = -1;
2411- int tile_arg_idx = -1;
2412-};
2413- 
2414-AccessArgIndices ResolveAccessArgIndices(const std::string& op_name)
2415-{
2416- AccessArgIndices indices;
2417- if (op_name == "block.load") {
2418- indices.tensor_arg_idx = 1;
2419- indices.tile_arg_idx = 0;
2420- } else if (op_name == "block.store") {
2421- indices.tensor_arg_idx = 0;
2422- indices.tile_arg_idx = 1;
2423- } else if (op_name == "debug.dump_tile") {
2424- indices.tensor_arg_idx = 3;
2425- indices.tile_arg_idx = 0;
2426- }
2427- return indices;
2428-}
2429- 
2430// Access window shape: the tile operand's shape, which is what the access transfers.2411// Access window shape: the tile operand's shape, which is what the access transfers.
2431-std::optional<std::vector<ir::ExprPtr>> ResolveAccessShape(const ir::CallPtr& op, const AccessArgIndices& indices)2412+std::optional<std::vector<ir::ExprPtr>> ResolveAccessShape(const ir::CallPtr& op,
2413+ const backend::cce::AccessArgIndices& indices)
2432{2414{
2433 if (indices.tile_arg_idx >= 0 && indices.tile_arg_idx < static_cast<int>(op->args_.size())) {2415 if (indices.tile_arg_idx >= 0 && indices.tile_arg_idx < static_cast<int>(op->args_.size())) {
2434 const auto& tile_arg = op->args_[indices.tile_arg_idx];2416 const auto& tile_arg = op->args_[indices.tile_arg_idx];
@@ -2444,7 +2426,7 @@ std::optional<std::vector<ir::ExprPtr>> ResolveAccessShape(const ir::CallPtr& op
2444// variants, not one.2426// variants, not one.
2445bool IsColumnAccess(const ir::CallPtr& op)2427bool IsColumnAccess(const ir::CallPtr& op)
2446{2428{
2447- auto shape = ResolveAccessShape(op, ResolveAccessArgIndices(op->name_));2429+ auto shape = ResolveAccessShape(op, backend::cce::ResolveAccessArgIndices(op->name_));
2448 if (!shape || shape->empty()) {2430 if (!shape || shape->empty()) {
2449 return false;2431 return false;
2450 }2432 }
@@ -2483,7 +2465,7 @@ public:
2483 2465 
2484 void VisitExpr_(const ir::CallPtr& op) override2466 void VisitExpr_(const ir::CallPtr& op) override
2485 {2467 {
2486- AccessArgIndices indices = ResolveAccessArgIndices(op->name_);2468+ backend::cce::AccessArgIndices indices = backend::cce::ResolveAccessArgIndices(op->name_);
2487 if (indices.tensor_arg_idx >= 0 && static_cast<int>(op->args_.size()) > indices.tensor_arg_idx) {2469 if (indices.tensor_arg_idx >= 0 && static_cast<int>(op->args_.size()) > indices.tensor_arg_idx) {
2488 auto tensor_var = std::dynamic_pointer_cast<const ir::Var>(op->args_[indices.tensor_arg_idx]);2470 auto tensor_var = std::dynamic_pointer_cast<const ir::Var>(op->args_[indices.tensor_arg_idx]);
2489 RecordTensorDef(op, ResolveTensorAlias(tensor_var), indices);2471 RecordTensorDef(op, ResolveTensorAlias(tensor_var), indices);
@@ -2510,7 +2492,7 @@ private:
2510 // construction. Accesses that disagree land in different variants instead of overwriting2492 // construction. Accesses that disagree land in different variants instead of overwriting
2511 // each other -- which is what used to silently give one of them the wrong layout.2493 // each other -- which is what used to silently give one of them the wrong layout.
2512 void RecordTensorDef(const ir::CallPtr& op, const std::shared_ptr<const ir::Var>& tensor_var,2494 void RecordTensorDef(const ir::CallPtr& op, const std::shared_ptr<const ir::Var>& tensor_var,
2513- const AccessArgIndices& indices)2495+ const backend::cce::AccessArgIndices& indices)
2514 {2496 {
2515 if (!tensor_var) {2497 if (!tensor_var) {
2516 return;2498 return;
@@ -2550,7 +2532,7 @@ std::string TensorLayoutVariantKey(const ir::CallPtr& op)
2550 // Exactly the inputs GenerateGlobalTensorTypeDeclaration reads: two accesses with the same2532 // Exactly the inputs GenerateGlobalTensorTypeDeclaration reads: two accesses with the same
2551 // key produce the same declaration and share it. NZ tensors are always single-variant --2533 // key produce the same declaration and share it. NZ tensors are always single-variant --
2552 // their declaration is driven by the fractal layout, not by these kwargs.2534 // their declaration is driven by the fractal layout, not by these kwargs.
2553- const AccessArgIndices indices = ResolveAccessArgIndices(op->name_);2535+ const backend::cce::AccessArgIndices indices = backend::cce::ResolveAccessArgIndices(op->name_);
2554 if (indices.tensor_arg_idx < 0 || static_cast<int>(op->args_.size()) <= indices.tensor_arg_idx) {2536 if (indices.tensor_arg_idx < 0 || static_cast<int>(op->args_.size()) <= indices.tensor_arg_idx) {
2555 return "";2537 return "";
2556 }2538 }
@@ -36,6 +36,7 @@ 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
39 40 
40KERNEL_HEADER_SINGLE = """\41KERNEL_HEADER_SINGLE = """\
41// Generated by PyPTO Pro JIT.42// Generated by PyPTO Pro JIT.
@@ -125,6 +126,8 @@ class CompiledKernel:
125 # bookkeeping on every launch.126 # bookkeeping on every launch.
126 kernel_name: str = ""127 kernel_name: str = ""
127 build_dir: str = ""128 build_dir: str = ""
129+ # Kernel source path: supplies the report locations (records carry lines).
130+ source_file: str = ""
128 has_cube: bool = False131 has_cube: bool = False
129 has_vector: bool = True132 has_vector: bool = True
130 target: KernelTarget | None = None133 target: KernelTarget | None = None
@@ -180,6 +183,9 @@ class CodegenResult:
180 tiling_headers: dict[str, str] = dataclasses.field(default_factory=dict)183 tiling_headers: dict[str, str] = dataclasses.field(default_factory=dict)
181 has_cube: bool = False184 has_cube: bool = False
182 has_vector: bool = False185 has_vector: bool = False
186+ sanitizer: bool = False
187+ # Kernel source path (report locations; set by _codegen).
188+ source_file: str = ""
183 189 
184 190 
185# Best-effort debug-print detection only. Launcher ABI metadata is derived from IR,191# Best-effort debug-print detection only. Launcher ABI metadata is derived from IR,
@@ -1161,8 +1167,14 @@ def _parse_and_codegen_targets(
1161 arch: str,1167 arch: str,
1162 build_dir: str,1168 build_dir: str,
1163 bound_signature=None,1169 bound_signature=None,
1170+ sanitizer: bool = False,
1164) -> tuple[CodegenResult | None, CodegenResult | None]:1171) -> tuple[CodegenResult | None, CodegenResult | None]:
1165- """Parse both targets, treating a sectionless kernel as shared by both."""1172+ """Parse both targets, treating a sectionless kernel as shared by both.
1173+ 
1174+ With ``sanitizer`` enabled, each parsed target program is instrumented
1175+ (block.sanitizer_log records injected, one per detection type and
1176+ sanitizer_log pointer + capacity scalar appended to the kernel signature);
1177+ the flag is carried on the returned CodegenResults."""
1166 programs = {}1178 programs = {}
1167 matched = {}1179 matched = {}
1168 for target in (ir.SectionKind.Cube, ir.SectionKind.Vector):1180 for target in (ir.SectionKind.Cube, ir.SectionKind.Vector):
@@ -1177,6 +1189,15 @@ def _parse_and_codegen_targets(
1177 ir.SectionKind.Vector: True,1189 ir.SectionKind.Vector: True,
1178 }1190 }
1179 1191 
1192+ if sanitizer:
1193+ from pypto.pypto_impl.ir import Pass as IRPass
1194+ 
1195+ sanitizer_pass = IRPass.sanitizer()
1196+ target_list = [t for t in (ir.SectionKind.Cube, ir.SectionKind.Vector)
1197+ if matched.get(t) and programs.get(t) is not None]
1198+ for target in target_list:
1199+ programs[target] = sanitizer_pass(programs[target])
1200+ 
1180 results = {1201 results = {
1181 target: (1202 target: (
1182 _codegen_target_cce(programs.get(target), arch, build_dir, target=target)1203 _codegen_target_cce(programs.get(target), arch, build_dir, target=target)
@@ -1185,6 +1206,9 @@ def _parse_and_codegen_targets(
1185 )1206 )
1186 for target in (ir.SectionKind.Cube, ir.SectionKind.Vector)1207 for target in (ir.SectionKind.Cube, ir.SectionKind.Vector)
1187 }1208 }
1209+ for target in (ir.SectionKind.Cube, ir.SectionKind.Vector):
1210+ if results[target] is not None:
1211+ results[target].sanitizer = sanitizer
1188 return results[ir.SectionKind.Cube], results[ir.SectionKind.Vector]1212 return results[ir.SectionKind.Cube], results[ir.SectionKind.Vector]
1189 1213 
1190 1214 
@@ -1328,6 +1352,7 @@ def _codegen(
1328 *,1352 *,
1329 bound_signature=None,1353 bound_signature=None,
1330 static_signature: tuple[tuple[int, int, int], ...] = (),1354 static_signature: tuple[tuple[int, int, int], ...] = (),
1355+ sanitizer: bool = False,
1331) -> CodegenResult | None:1356) -> CodegenResult | None:
1332 """Codegen: parse + generate the kernel source for one concrete tilingkey.1357 """Codegen: parse + generate the kernel source for one concrete tilingkey.
1333 1358 
@@ -1351,8 +1376,11 @@ def _codegen(
1351 arch,1376 arch,
1352 out_dir,1377 out_dir,
1353 bound_signature,1378 bound_signature,
1379+ sanitizer,
1354 )1380 )
1355 result = _assemble_cv_source(cube, vector)1381 result = _assemble_cv_source(cube, vector)
1382+ result.sanitizer = (cube is not None and cube.sanitizer) or (vector is not None and vector.sanitizer)
1383+ result.source_file = getattr(source, "_source_file", "")
1356 1384 
1357 result = _add_kernel_header(result)1385 result = _add_kernel_header(result)
1358 _write_codegen_artifacts(result)1386 _write_codegen_artifacts(result)
@@ -1428,6 +1456,58 @@ def _launch(compiled: "CompiledKernel", args: tuple, block_dim: int, stream):
1428 entry(args, block_dim, stream)1456 entry(args, block_dim, stream)
1429 1457 
1430 1458 
1459+# Per-block record capacity of the sanitizer GM log buffer, and the max
1460+# sub-block count per launched block (A5 vector section addresses each AIV
1461+# sub-block by its own get_block_idx, so each gets an independent region —
1462+# safe without atomics). Capacity is expressed in u32 words per region; the
1463+# granularity is the largest fixed record (MAX_RECORD_U32 from the replay
1464+# tool's record formats, currently the 11-u32 GM record).
1465+ksanitizer_log_slots = 8192 # max records per region (GM record = 16 u32)
1466+ksanitizer_log_capacity_u32 = ksanitizer_log_slots * MAX_RECORD_U32
1467+ksanitizer_sub_blocks = 4
1468+ 
1469+ 
1470+def _replay_sanitizer(log_buffer, block_dim, args, tensor_names, build_dir, source_file):
1471+ """Wait for the launch, read the device log buffer back, merge it with the
1472+ compile-time metadata into one ``sanitizer_report.bin``, scan that file
1473+ with the registered detections and raise an aggregated report when
1474+ findings exist.
1475+ 
1476+ Replay failures are never swallowed: when the sanitizer is enabled the
1477+ developer expects the detection result to be trustworthy, so a broken
1478+ decode or check must surface instead of silently producing a "clean"
1479+ result.
1480+ """
1481+ from pypto_pro.runtime.sanitizer_replay import SanitizerReplayError, build_report_file, scan_report_file
1482+ 
1483+ torch.npu.synchronize()
1484+ raw = log_buffer.cpu().numpy().tobytes()
1485+ tensor_args = [a for a in args if isinstance(a, torch.Tensor) and a is not log_buffer]
1486+ regions = ksanitizer_sub_blocks * block_dim
1487+ report_path = os.path.join(build_dir, "sanitizer_report.bin")
1488+ build_report_file(
1489+ raw, regions, ksanitizer_log_capacity_u32,
1490+ tensor_names, [tuple(int(d) for d in a.shape) for a in tensor_args],
1491+ report_path,
1492+ )
1493+ findings = scan_report_file(report_path, source_file)
1494+ if findings:
1495+ # Log each finding at a level matching its severity so the report
1496+ # survives the default WARNING threshold even when the caller swallows
1497+ # the exception (e.g. pytest.raises or a try/except around the launch).
1498+ # Levels come from the detection registry (ERROR: definite bounds
1499+ # breaches; WARNING: suspicious but possibly deliberate overlap).
1500+ for f in findings:
1501+ # str(f) already embeds kind + message + location + hint on one
1502+ # formatted line, so log it verbatim (single line for greppability).
1503+ msg = f"PyPTO Sanitizer: {str(f).replace(chr(10), ' | ')}"
1504+ if f.level == "WARNING":
1505+ logging.warning(msg)
1506+ else:
1507+ logging.error(msg)
1508+ raise SanitizerReplayError(findings)
1509+ 
1510+ 
1431def _validate_block_dim(block_dim):1511def _validate_block_dim(block_dim):
1432 """Validate that block_dim is a positive integer.1512 """Validate that block_dim is a positive integer.
1433 1513 
@@ -1443,6 +1523,39 @@ def _validate_block_dim(block_dim):
1443 )1523 )
1444 1524 
1445 1525 
1526+def _build_sanitizer_entry(compiled: "CompiledKernel", build_dir: str):
1527+ """Wrap the launch entry of an instrumented kernel with the sanitizer glue.
1528+ 
1529+ Keeps the upstream entry mechanism (``_build_launch_entry``) untouched:
1530+ the base entry performs the ABI packing / validation / call, and this
1531+ wrapper only (a) allocates the GM log buffer and appends the two hidden
1532+ ``sanitizer_log``/``sanitizer_log_capacity`` arguments, then (b) reads the
1533+ buffer back, merges it with the compile-time metadata into a single
1534+ ``sanitizer_report.bin`` and scans that file with the registered
1535+ detections.
1536+ 
1537+ Loaded lazily on the first launch via ``compiled.entry``, exactly like the
1538+ non-sanitizer path.
1539+ """
1540+ tensor_names = [
1541+ s.name for s in compiled.param_specs
1542+ if s.kind in (ParamKind.TENSOR, ParamKind.PTR)
1543+ and s.name not in ("sanitizer_log", "sanitizer_log_capacity")
1544+ ]
1545+ base_entry = _build_launch_entry(compiled)
1546+ 
1547+ def entry(args: tuple, block_dim: int, stream):
1548+ # One region per AIV sub-block, mirroring the device-side buffer layout.
1549+ regions = ksanitizer_sub_blocks * block_dim
1550+ nbytes = (ksanitizer_log_capacity_u32 + 1) * 4 * regions
1551+ log_buffer = torch.zeros(nbytes, dtype=torch.uint8, device="npu")
1552+ full_args = (*args, log_buffer, ksanitizer_log_capacity_u32)
1553+ base_entry(full_args, block_dim, stream)
1554+ _replay_sanitizer(log_buffer, block_dim, full_args, tensor_names, build_dir, compiled.source_file)
1555+ 
1556+ return entry
1557+ 
1558+ 
1446def _validate_tilingkey_no_var_conflict(f, tilingkey_schema, closure_vars):1559def _validate_tilingkey_no_var_conflict(f, tilingkey_schema, closure_vars):
1447 tilingkey_names = set(tilingkey_schema.field_names())1560 tilingkey_names = set(tilingkey_schema.field_names())
1448 1561 
@@ -1473,6 +1586,7 @@ def jit(
1473 tiling_key=None,1586 tiling_key=None,
1474 datatype=None,1587 datatype=None,
1475 compile_timeout: int | None = None,1588 compile_timeout: int | None = None,
1589+ sanitizer: bool = False,
1476 **kwargs,1590 **kwargs,
1477):1591):
1478 """Mark a function for JIT compilation.1592 """Mark a function for JIT compilation.
@@ -1541,6 +1655,7 @@ def jit(
1541 tilingkey_schema=tilingkey_schema,1655 tilingkey_schema=tilingkey_schema,
1542 datatype_schema=datatype_schema,1656 datatype_schema=datatype_schema,
1543 compile_timeout=compile_timeout,1657 compile_timeout=compile_timeout,
1658+ sanitizer=sanitizer,
1544 )1659 )
1545 else:1660 else:
1546 # Legacy path: non-Tile function, wrap as pass-through1661 # Legacy path: non-Tile function, wrap as pass-through
@@ -1625,6 +1740,7 @@ class _TileJitKernel:
1625 tilingkey_schema=None,1740 tilingkey_schema=None,
1626 datatype_schema=None,1741 datatype_schema=None,
1627 compile_timeout=None,1742 compile_timeout=None,
1743+ sanitizer=False,
1628 ):1744 ):
1629 self._func = func1745 self._func = func
1630 self._arch = arch1746 self._arch = arch
@@ -1636,6 +1752,7 @@ class _TileJitKernel:
1636 self._tilingkey_schema = tilingkey_schema1752 self._tilingkey_schema = tilingkey_schema
1637 self._datatype_schema = datatype_schema1753 self._datatype_schema = datatype_schema
1638 self._compile_timeout = compile_timeout1754 self._compile_timeout = compile_timeout
1755+ self._sanitizer = sanitizer
1639 from pypto_pro.runtime.shape_policy import KernelSignatureSpec1756 from pypto_pro.runtime.shape_policy import KernelSignatureSpec
1640 1757 
1641 self._shape_signature_spec = KernelSignatureSpec.from_callable(func, closure_vars)1758 self._shape_signature_spec = KernelSignatureSpec.from_callable(func, closure_vars)
@@ -1922,8 +2039,9 @@ class _TileJitKernel:
1922 self.__name__,2039 self.__name__,
1923 static_signature or "<dynamic-only>",2040 static_signature or "<dynamic-only>",
1924 )2041 )
2042+ kernel_def = self.to_kernel_def(concrete_key, datatype_consts=dtype_consts)
1925 cg = _codegen(2043 cg = _codegen(
1926- self.to_kernel_def(concrete_key, datatype_consts=dtype_consts),2044+ kernel_def,
1927 arch,2045 arch,
1928 clean_up=False,2046 clean_up=False,
1929 tilingkey_packed=tilingkey_packed,2047 tilingkey_packed=tilingkey_packed,
@@ -1931,6 +2049,7 @@ class _TileJitKernel:
1931 datatype_metadata=dtype_metadata,2049 datatype_metadata=dtype_metadata,
1932 bound_signature=bound_signature,2050 bound_signature=bound_signature,
1933 static_signature=static_signature,2051 static_signature=static_signature,
2052+ sanitizer=self._sanitizer,
1934 )2053 )
1935 if cg is None:2054 if cg is None:
1936 raise RuntimeError(f"Failed to generate code for kernel '{self.__name__}'")2055 raise RuntimeError(f"Failed to generate code for kernel '{self.__name__}'")
@@ -1961,9 +2080,15 @@ class _TileJitKernel:
1961 lib_path=lib_path, param_specs=cg.param_specs, is_aiv_only=is_aiv_only,2080 lib_path=lib_path, param_specs=cg.param_specs, is_aiv_only=is_aiv_only,
1962 kernel_name=cg.kernel_name, build_dir=cg.build_dir,2081 kernel_name=cg.kernel_name, build_dir=cg.build_dir,
1963 has_cube=cg.has_cube, has_vector=cg.has_vector,2082 has_cube=cg.has_cube, has_vector=cg.has_vector,
1964- target=target,2083+ target=target, source_file=cg.source_file,
1965 needs_print_debug=cg.needs_print_debug,2084 needs_print_debug=cg.needs_print_debug,
1966 )2085 )
2086+ if self._sanitizer:
2087+ # Pre-bind the sanitizer wrapper as the launch entry: it allocates
2088+ # the GM log buffer, appends the hidden sanitizer_log arguments,
2089+ # launches via the upstream entry, builds the single report file
2090+ # and scans it for detections.
2091+ compiled.entry = _build_sanitizer_entry(compiled, cg.build_dir)
1967 self._compiled_by_signature[(static_signature, dtype_hash, tilingkey_packed)] = compiled2092 self._compiled_by_signature[(static_signature, dtype_hash, tilingkey_packed)] = compiled
1968 return compiled2093 return compiled
1969 2094 
@@ -0,0 +1,640 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+ 
11+"""Host replay for the PyPTO Pro sanitizer (v2).
12+ 
13+Scans the single ``sanitizer_report.bin`` file (metadata header + device-side
14+log records) produced by a kernel launch and computes the detections:
15+ 
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.
18+ 3. TILE_OVERLAP - no two tile slots may overlap in address space.
19+ 4. MUTEX_* - mutex lock/unlock pairing per (region, id, pipe).
20+ 
21+Each detection registers its own record format and check logic in
22+``_DETECTIONS``; see ``/workspace/doc/sanitizer_v2_design.md``.
23+"""
24+ 
25+from __future__ import annotations
26+ 
27+import dataclasses
28+import struct
29+from typing import Callable
30+ 
31+# Record detection ids (must match C++ SanitizerDetection enum).
32+DET_GM_ACCESS = 1
33+DET_TILE_ACCESS = 2
34+DET_MUTEX_ACCESS = 3
35+DET_VIEW_SHAPE = 4
36+DET_TILE_SCALAR = 5
37+DET_TILE_DECL = 6
38+ 
39+# Pipe name mapping, mirroring ir::PipeType (MTE1=0 … ALL=7), used for
40+# human-readable pipe names in reports (e.g. "MTE2" instead of "1").
41+_MAX_RECORD_DIMS = 5 # max logical dims per GM record (matches C++)
42+ 
43+_PIPE_NAMES = ["MTE1", "MTE2", "MTE3", "M", "V", "S", "FIX", "ALL"]
44+ 
45+ 
46+def _pipe_name(pipe: int) -> str:
47+ if 0 <= pipe < len(_PIPE_NAMES):
48+ return _PIPE_NAMES[pipe]
49+ return f"PIPE({pipe})"
50+ 
51+# Per-detection record formats (independent, not uniform).
52+# GM (det_id=1, 15 u32 = 60 bytes):
53+# [0] det_id, [1] ndim, [2..6] off[5], [7..11] shape[5] (runtime values,
54+# aligned with the offsets' trailing dims), [12] acc_row, [13] acc_col,
55+# [14] span_id. For ndim = 0 (linear access) acc_row carries the
56+# whole-tensor element count.
57+_GM_RECORD = struct.Struct(
58+ "<"
59+ "II" # det_id, ndim
60+ "iiiii" # off[0..4]
61+ "iiiii" # shape[0..4]
62+ "III" # acc_row, acc_col, span_id
63+)
64+# Tile (det_id=2, 8 u32 = 32 bytes):
65+# [0] det_id, [1] dim_row, [2] dim_col (the access-site declared dims --
66+# the runtime truth of the access), [3] off_row, [4] off_col,
67+# [5] acc_row, [6] acc_col, [7] span_id
68+_TILE_RECORD = struct.Struct(
69+ "<"
70+ "III" # det_id, dim_row, dim_col
71+ "ii" # off_row, off_col (signed)
72+ "III" # acc_row, acc_col, span_id
73+)
74+# Mutex (det_id=3, 5 u32 = 20 bytes):
75+# [0] det_id, [1] mutex_id, [2] pipe, [3] is_lock, [4] span_id
76+_MUTEX_RECORD = struct.Struct(
77+ "<"
78+ "IIIII" # det_id, mutex_id, pipe, is_lock, span_id
79+)
80+# ViewShape (det_id=4, 9 u32 = 36 bytes): declaration-time view-over-source
81+# check, all fields runtime expressions. [0] det_id, [1..5] shape[0..4],
82+# [6] byte footprint sum((dim-1)*stride)+1 scaled by the view dtype width,
83+# [7] source byte capacity (-1 = raw pointer: no known bound, skip),
84+# [8] span_id.
85+_VIEW_SHAPE_RECORD = struct.Struct(
86+ "<"
87+ "I" # det_id
88+ "iiiii" # shape[0..4]
89+ "ii" # fp_bytes, src_bytes
90+ "I" # span_id
91+)
92+# TileScalar (det_id=5, 5 u32 = 20 bytes):
93+# [0] det_id, [1] dim0, [2] dim1, [3] linear offset, [4] span_id.
94+_TILE_SCALAR_RECORD = struct.Struct(
95+ "<"
96+ "III" # det_id, dim0, dim1
97+ "iI" # offset, span_id
98+)
99+# TileDecl (det_id=6, 6 u32 = 24 bytes): a make_tile declaration for the
100+# overlap scan. [0] det_id, [1] addr, [2] size (bytes), [3] memory space
@@ -100,7 +100,9 @@ void BindPasses(py::module_& m)
100 "Simplify symbolic scalars under their enclosing branch condition")100 "Simplify symbolic scalars under their enclosing branch condition")
101 .def_static("create_root_functions", &pass::CreateRootFunctions, "Create root functions from IR")101 .def_static("create_root_functions", &pass::CreateRootFunctions, "Create root functions from IR")
102 .def_static("finalize_dynamic_function", &pass::FinalizeDynamicFunction,102 .def_static("finalize_dynamic_function", &pass::FinalizeDynamicFunction,
103- "Finalize dynamic functions built from new IR");103+ "Finalize dynamic functions built from new IR")
104+ .def_static("sanitizer", &pass::Sanitizer,
105+ "Create a sanitizer instrumentation pass (stateless; every check value travels in the records)");
104 106 
105 py::class_<PassInstrument, std::shared_ptr<PassInstrument>>(m, "PassInstrument",107 py::class_<PassInstrument, std::shared_ptr<PassInstrument>>(m, "PassInstrument",
106 "Abstract base class for pass instrumentation")108 "Abstract base class for pass instrumentation")