"""规则自检:给每条规则造一个**必然触发**的最小样本,跑一遍看谁不响。
规则在自己的正样本上都不报 = 哑弹(要么正则写错,要么代码路径根本到不了,
要么扫描的目录/文件类型压根不对)。这类"永远返回 0"的检查比没有检查更危险,
因为它看起来像通过了。
python3 selftest.py # 建夹具、跑全 13 组、报哑弹
"""
from __future__ import annotations
import json
import re
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(tempfile.gettempdir()) / "changwei-code-check-selftest" / "selftest_repo"
OP = "image/grid_unnormal"
OP2 = "activation/celu"
OP4 = "activation/hard_shrink"
OP5 = "index/scatter_min"
OP3 = "array/non_zero_with_value"
KNOWN_CONDITIONAL = {
"G13-multiple-commits": "夹具只有 1 个 commit,量不出多提交",
"G13-mass-deletion": "夹具删除行数远小于阈值",
"G10-tool-version-mismatch": "取决于本机 clang-format 与 CI pinned 是否一致",
"G9-golden-not-runnable": "另有独立负向对照(见 g09 的 _probe_runnable 测试)",
}
def sh(*args: str, cwd: Path | None = None) -> str:
r = subprocess.run(args, cwd=str(cwd) if cwd else None,
capture_output=True, text=True)
return r.stdout
def w(rel: str, content: str) -> None:
p = ROOT / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content, encoding="utf-8")
CANNDEV = ROOT.parent / "selftest_canndev"
_A2_SOC_MATRIX = {
"ascend910b": ["Celu", "GridUnnormal", "NonZeroWithValue"],
"ascend910_93": ["Celu", "GridUnnormal", "NonZeroWithValue"],
"ascend910": ["Celu", "GridUnnormal"],
"ascend310p": ["Celu", "NonZeroWithValue"],
"ascend310b": ["Celu"],
}
def build_canndev() -> None:
def cw(rel: str, content: str) -> None:
p = CANNDEV / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content, encoding="utf-8")
for soc, ops in _A2_SOC_MATRIX.items():
body = []
for op in ops:
body.append(f"[{op}]")
if op == "GridUnnormal":
body += ["input0.name=grid", "input0.dtype=float,float16",
"input1.name=assist", "input1.dtype=float,float16",
"output0.name=diff", "output0.dtype=float,float16", ""]
elif op == "NonZeroWithValue":
body += ["input0.name=self", "input0.dtype=float,float16",
"input0.format=ND,NC1HWC0", "input0.paramType=optional",
"output0.name=index", "output0.dtype=int32,int32",
"output0.format=ND,ND", "output0.paramType=required",
"attr.list=alpha,beta",
"attr_alpha.type=float", "attr_alpha.paramType=optional",
"attr_alpha.defaultValue=1.0",
"attr_beta.type=float", "attr_beta.paramType=optional",
"attr_beta.defaultValue=1.0", ""]
else:
body += ["input0.dtype=float", "output0.dtype=float", ""]
cw(f"ops/built-in/tbe/op_info_cfg/ai_core/{soc}/aic-{soc}-ops-info.ini",
"\n".join(body) + "\n")
cw("ops/built-in/op_proto/inc/fake_ops.h",
"/**\n *@li grid: 4-D Tensor with shape `[batch, height, width, 2]`.\n */\n"
"REG_OP(GridUnnormal)\n .OP_END_FACTORY_REG(GridUnnormal)\n\n"
"/**\n *@li x: 2-D Tensor.\n */\n"
"REG_OP(NonZeroWithValue)\n .OP_END_FACTORY_REG(NonZeroWithValue)\n")
cw("ops/built-in/op_proto/fake_ops.cc",
"IMPLEMT_INFERFUNC(GridUnnormal, GridUnnormalInfer) {\n"
" auto grid_shape = op.GetInputDescByName(\"grid\").GetShape().GetDims();\n"
" auto x_shape = op.GetInputDescByName(\"assist\").GetShape().GetDims();\n"
" if (x_shape.size() != 4 || grid_shape.size() != 4) { return GRAPH_FAILED; }\n"
" if (grid_shape[3] != 2) { return GRAPH_FAILED; }\n"
" return GRAPH_SUCCESS;\n}\n\n"
"IMPLEMT_INFERFUNC(NonZeroWithValue, NonZeroWithValueInfer) {\n"
" auto x_shape = op_desc->MutableInputDesc(0)->GetShape();\n"
" if (x_shape.GetDimNum() != 2) { return GRAPH_FAILED; }\n"
" return GRAPH_SUCCESS;\n}\n")
cw("ops/built-in/tbe/impl/grid_unnormal.py", "# A2 TIK impl\n")
cw("ops/built-in/framework/tf_plugin/non_zero_with_value_plugin.cc", "// A2 tf plugin\n")
def build_fixture() -> None:
if ROOT.exists():
subprocess.run(["rm", "-rf", str(ROOT)])
ROOT.mkdir(parents=True)
sh("git", "init", "-q", cwd=ROOT)
sh("git", "config", "user.email", "selftest@local", cwd=ROOT)
sh("git", "config", "user.name", "selftest", cwd=ROOT)
w(".pre-commit-config.yaml", """repos:
- repo: https://gitcode.com/pre-commit-clang/mirrors-clang-format
rev: v18.1.8
hooks: [{id: clang-format}]
- repo: https://gitcode.com/gh_mirrors/ru/ruff-pre-commit
rev: v0.14.14
hooks: [{id: ruff-check}]
""")
w(".clang-format", "BasedOnStyle: Google\nColumnLimit: 120\n")
w(f"{OP}/op_kernel/grid_unnormal.cpp", "// existing A2-side kernel\nvoid f() {}\n")
w("cmake/func.cmake", "# existing framework file\n")
w("common/inc/op_graph/proto_extend.h", "// shared proto header\n")
w(f"{OP}/tests/ut/op_host/test_grid_unnormal_infershape.cpp",
"// 既有共用 infershape UT(A2 与 A5 共用,A2 门禁在跑)\n"
"TEST_F(GridUnnormalInfer, basic) { EXPECT_EQ(1, 1); }\n")
w(f"{OP}/op_kernel/CMakeLists.txt",
"add_kernel_sources(\n COMPUTE_UNITS ascend910b ascend910_93\n)\n"
"add_kernel_sources(\n KERNEL_SRC arch35/grid_unnormal.cpp\n"
" COMPUTE_UNITS ascend950\n AUTO_SYNC false\n)\n")
w(f"{OP}/tests/ut/op_kernel/test_legacy_untouched.cpp",
"// 既有 kernel UT,本次 PR 未改动。blockDim 恒为 1 → 触发 G17-kernel-ut-single-core-only,\n"
"// 而 g17 是 glob 整个算子目录的,于是锚点落在 diff 之外。\n"
"TEST_F(LegacyUt, single_core) {\n"
" ICPU_RUN_KF(grid_unnormal, 1, x, y, tiling);\n"
" ICPU_RUN_KF(grid_unnormal, 1, x2, y2, tiling);\n}\n")
sh("git", "add", "-A", cwd=ROOT)
sh("git", "commit", "-qm", "base", cwd=ROOT)
base = sh("git", "rev-parse", "HEAD", cwd=ROOT).strip()
w(f"{OP}/op_kernel/grid_unnormal.cpp",
"// existing A2-side kernel, now MODIFIED\nvoid f() { int a = 1; (void)a; }\n")
w(f"{OP}/tests/ut/op_host/test_grid_unnormal_infershape.cpp",
"// 既有共用 infershape UT(A2 与 A5 共用,A2 门禁在跑)\n"
"TEST_F(GridUnnormalInfer, basic) { EXPECT_EQ(1, 1); }\n"
"TEST_F(GridUnnormalInfer, unknown_rank) { EXPECT_EQ(1, 1); } // A5 新增,越界\n")
w(f"{OP}/op_kernel/CMakeLists.txt",
"add_kernel_sources(\n COMPUTE_UNITS ascend910b ascend910_93\n AUTO_SYNC false\n)\n"
"add_kernel_sources(\n KERNEL_SRC arch35/grid_unnormal.cpp\n"
" COMPUTE_UNITS ascend950\n AUTO_SYNC false\n)\n")
w("cmake/func.cmake", "# existing framework file\n# hacked for local build\n")
w("common/inc/op_graph/proto_extend.h", "// shared proto header\n// grid_unnormal migrated out\n")
w(f"{OP}/op_host/grid_unnormal_tiling.cpp", "// top-level tiling\n")
w(f"{OP}/op_host/arch35/grid_unnormal_tiling_arch35.cpp", _tiling_cpp())
w(f"{OP}/op_kernel/arch35/grid_unnormal.h", _kernel_h())
w(f"{OP}/op_host/arch35/grid_unnormal_tiling_arch35.h", _tiling_h())
w(f"{OP}/framework/grid_unnormal_plugin.cpp", _plugin_cpp())
w(f"{OP}/op_graph/grid_unnormal_proto.h",
'/**\n *@li grid: flow field grid, 4-D Tensor with shape `[batch, height, width, 2]`.\n */\n'
'REG_OP(GridUnnormal)\n .ATTR(align_corners, Bool, false)\n'
' .ATTR(only_in_proto, Bool, true)\n .OP_END_FACTORY_REG(GridUnnormal)\n')
w(f"{OP}/op_host/grid_unnormal_def.cpp", _def_cpp())
w(f"{OP}/op_host/grid_unnormal_infershape.cpp",
"auto* p = attrs->GetAttrPointer<float>(0);\nauto* q = attrs->GetAttrPointer<int64_t>(9);\n")
w(f"{OP}/README.md", _readme())
w(f"{OP}/tests/assets/golden.py",
"import numpy as np\n\n\ndef grid_unnormal_golden(grid, assist, scalar):\n"
' """中间统一用 fp32 计算,与 kernel 一致。"""\n'
" scalar_val = scalar.astype('float32').reshape(-1)[0] # int 标量先进 fp32\n"
" scalar_i = scalar_val.astype(out_dtype) # 再转回 int → G14-golden-int-via-fp32\n"
" return [grid, assist]\n")
w(f"{OP}/op_host/big_header.h", _big_header())
w(f"{OP}/op_host/dup_a.cpp", _dup_block("A"))
w(f"{OP}/op_host/dup_b.cpp", _dup_block("B"))
(ROOT / OP / "op_host" / "bad_ws.cpp").write_text("int x = 1; \nint y = 2;", encoding="utf-8")
w(f"{OP}/op_kernel/grid_unnormal_apt.cpp", "// legacy apt entry\n")
w(f"{OP3}/CMakeLists.txt",
"add_modules_sources(HOSTNAME x MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}\n"
" OPTYPE non_zero_with_value COMPUTE_UNIT ascend950 DISABLE_IN_OPP TRUE)\n")
w(f"{OP2}/op_host/celu_impl.cpp", "IMPL_OP(Celu).InferDataType(InferDtypeCelu);\n")
w(f"{OP2}/docs/aclnnCeluV2.md",
"# aclnnCeluV2\n\n第一段接口 aclnnCeluV2GetWorkspaceSize。\n\n错误码:\n<table>\n"
"<tr><td>ACLNN_ERR_PARAM_INVALID</td><td>161002</td>"
"<td>self的数据类型不在支持的范围之内。</td></tr>\n</table>\n")
w(f"{OP2}/op_api/aclnn_celu_v2.cpp",
"aclnnStatus aclnnCeluV2GetWorkspaceSize(const aclTensor* self, aclTensor* out) {\n"
" CHECK_RET(CheckDtypeValid(self, out), ACLNN_ERR_PARAM_INVALID);\n"
" return ACLNN_SUCCESS;\n}\n")
w("docs/zh/op_list.md", "# 算子清单\n\n| 算子 | 说明 |\n|---|---|\n")
w("docs/zh/op_api_list.md", "# aclnn 清单\n\n| 接口 | 说明 |\n|---|---|\n")
w(f"{OP4}/op_host/hard_shrink_def.cpp",
"class HardShrink : public OpDef {\n"
" this->Input(\"x\").DataType({ge::DT_FLOAT});\n"
" this->AICore().AddConfig(\"ascend950\");\n};\n")
w(f"{OP4}/op_host/op_api/aclnn_hard_shrink.cpp", "// aclnn entry, 但 docs/ 下没有 aclnnHardShrink.md\n")
w(f"{OP4}/op_kernel/hard_shrink.cpp", "// kernel\n")
w(f"{OP5}/op_host/scatter_min_def.cpp",
"class ScatterMin : public OpDef {\n"
" this->Input(\"var\").DataType({ge::DT_FLOAT});\n"
" this->AICore().AddConfig(\"ascend950\");\n};\n")
w(f"{OP5}/docs/aclnnScatterMin.md",
"# aclnnScatterMin\n\n<table>\n"
"<tr><th>参数名</th><th>非连续Tensor</th></tr>\n"
"<tr><td>varRef</td><td>√</td></tr>\n</table>\n")
w(f"{OP5}/op_kernel/scatter_min.cpp", "// kernel\n")
w(f"{OP5}/README.md", "# ScatterMin\n\n按 indices 取最小值更新。\n")
w(f"{OP5}/tests/ut/op_host/test_scatter_min_tiling.cpp",
"// DT_FLOAT 用例\nTEST_F(ScatterMinTiling, f32) { EXPECT_EQ(1, 1); }\n")
w(f"{OP5}/tests/ut/op_kernel/test_scatter_min.cpp",
"// kernel UT\nTEST_F(ScatterMinKernel, f32) { EXPECT_EQ(1, 1); }\n")
w(f"{OP}/tests/tmp_output.bin", "x" * 10)
w(f"{OP}/op_host/huge_blob.inc", "x" * (600 * 1024))
w(f"{OP2}/op_host/celu_def.cpp",
"class Celu : public OpDef {\n"
" this->Input(\"x\").DataType({ge::DT_FLOAT16, ge::DT_BF16});\n"
" this->DynamicRankSupportFlag(true);\n"
" this->AICore().AddConfig(\"ascend950\");\n"
" this->DynamicRankSupportFlag(true);\n"
" this->AICore().AddConfig(\"ascend910b\");\n"
"};\n")
w(f"{OP2}/op_host/op_api/aclnn_celu.cpp", "// aclnn entry\n")
w(f"{OP}/docs/aclnnGridUnnormal.md",
"# aclnnGridUnnormal\n\n第一段接口 aclnnGridUnnormalGetWorkspaceSize。\n\n"
"## 返回值\n\n错误码:\n\n<table>\n"
"<tr><td>ACLNN_ERR_PARAM_NULLPTR</td><td>161001</td>"
"<td>传入的self、alpha、out是空指针。</td></tr>\n"
"<tr><td>ACLNN_ERR_PARAM_INVALID</td><td>161002</td>"
"<td>self的数据类型不在支持的范围之内。</td></tr>\n"
"<tr><td></td><td></td><td>self、out的维度大于8。</td></tr>\n"
"</table>\n")
w(f"{OP}/op_api/aclnn_grid_unnormal.cpp",
"aclnnStatus aclnnGridUnnormalGetWorkspaceSize(const aclTensor* grid,\n"
" aclTensor* out, uint64_t* ws) {\n"
" if (grid->IsEmpty()) { return ACLNN_SUCCESS; } // 代码支持空Tensor,"
"而 aclnn 文档只字不提 → G7-empty-tensor-supported-undeclared\n"
" return ACLNN_SUCCESS; // 一个校验都没有 → 组 21 全类缺失\n}\n")
w(f"{OP3}/docs/aclnnNonZeroWithValue.md",
"# aclnnNonZeroWithValue\n\naclnnNonZeroWithValueGetWorkspaceSize 支持空Tensor。\n\n"
"错误码:\n<table>\n<tr><td>ACLNN_ERR_PARAM_INVALID</td><td>161002</td>"
"<td>x的数据类型不在支持的范围之内。</td></tr>\n</table>\n")
w(f"{OP3}/op_api/aclnn_non_zero_with_value.cpp",
"aclnnStatus aclnnNonZeroWithValueGetWorkspaceSize(const aclTensor* x, aclTensor* out) {\n"
" CHECK_RET(SomeOpaqueGuard(x, out), ACLNN_ERR_PARAM_INVALID);\n"
" if (x->IsEmpty()) {\n"
" FillScalar(out, 0, uniqueExecutor.get());\n"
" return ACLNN_SUCCESS;\n }\n"
" return ACLNN_SUCCESS;\n}\n")
w(f"{OP2}/op_kernel/arch35/celu.h",
"// kernel, no tiling header\n"
"RegTensor<float> reg;\n"
"float r = (d == 0) ? 0.0f : a / d;\n")
w("experimental/activation/foo_op/op_host/foo_op_def.cpp", "// contributed op\n")
w("experimental/activation/foo_op/op_kernel/foo_op.cpp", "// kernel, no tiling header at all\n")
w(f"{OP2}/op_host/celu_tiling.h",
"BEGIN_TILING_DATA_DEF(CeluTilingData)\n"
"TILING_DATA_FIELD_DEF(int64_t, legacyField);\n"
"END_TILING_DATA_DEF\n")
w(f"{OP2}/op_kernel/arch35/celu_tiling_data.h",
"// 是 TilingData 头,但字段用了本规则不认识的写法\n"
"struct CeluTilingData {\n USING_UNKNOWN_MACRO(x);\n};\n")
w(f"{OP2}/tests/assets/README.txt", "no golden here\n")
w(f"{OP2}/README.md",
"# Celu\n\n## 功能说明\n\n- 非有限输入 inf / nan 不属于支持域。\n"
"- 支持总元素数为 0 的空 Tensor,空进空出。\n"
"- 支持动态 rank。\n")
w(f"{OP2}/op_host/celu_infershape.cpp",
"graphStatus Infer(gert::InferShapeContext* c) {\n"
" if (a != b) { return ge::GRAPH_FAILED; }\n"
" if (n != 4) { return ge::GRAPH_FAILED; }\n"
" return ge::GRAPH_SUCCESS;\n}\n")
w(f"{OP2}/tests/ut/op_host/test_celu_infershape.cpp",
"TEST_F(CeluInfer, ok) { ExecuteTestCase({{2, 4}}, ge::GRAPH_SUCCESS); }\n")
w(f"{OP2}/op_kernel/celu.cpp",
'#ifndef __CCE_KT_TEST__\nextern "C" __global__ __aicore__ void celu(GM_ADDR x) {}\n#endif\n')
w(f"{OP2}/tests/ut/op_kernel/test_celu.cpp",
"TEST_F(CeluKernel, run) { ICPU_RUN_KF(celu_ut_kernel<float>, 1, x, y); }\n")
w(f"{OP2}/tests/ut/op_kernel/celu_data/gen_data.py",
"import numpy as np\nx = np.random.uniform(-1, 1, (4, 4))\n")
w(f"{OP2}/tests/ut/op_kernel/celu_data/compare_data.py",
"import numpy as np\nnp.allclose(a, b, rtol=atol, atol=atol)\n")
w(f"{OP}/op_host/config/ascend950/grid_unnormal_binary.json", "{not valid json\n")
(ROOT / OP / "op_host" / "dead_link.h").symlink_to("/nonexistent/abs/path.h")
w(f"{OP3}/op_host/non_zero_with_value_infershape.cpp",
"graphStatus Infer(gert::InferShapeContext* c) {\n"
" if (x.GetDimNum() != 4) { return ge::GRAPH_FAILED; }\n"
" return ge::GRAPH_SUCCESS;\n}\n")
w(f"{OP3}/op_kernel/non_zero_with_value.cpp", "// minimal kernel so the dir counts as a real op\n")
w(f"{OP3}/op_host/non_zero_with_value_def.cpp",
"class NonZeroWithValue : public OpDef {\n"
" this->Input(\"x\").ParamType(REQUIRED).DataType({ge::DT_FLOAT})\n"
" .Format({ge::FORMAT_ND});\n"
" this->Output(\"index\").ParamType(REQUIRED).DataType({ge::DT_INT32})\n"
" .Format({ge::FORMAT_ND});\n"
" this->Attr(\"beta\").AttrType(OPTIONAL).Int(2);\n"
" this->AICore().AddConfig(\"ascend950\");\n"
"};\n")
w(f"{OP3}/op_host/config/ascend950/non_zero_with_value_binary.json",
'{"op_type":"NonZeroWithValue","op_list":[{"bin_filename":"NonZeroWithValue_fp32_950",'
'"inputs":[{"name":"x","index":0,"dtype":"float32","format":"ND","paramType":"required","shape":[-2]}],'
'"outputs":[]}]}\n')
sh("git", "add", "-A", cwd=ROOT)
sh("git", "commit", "-qm", "head", cwd=ROOT)
dl = ROOT.parent / "selftest_deliverables" / "GridUnnormal"
subprocess.run(["rm", "-rf", str(dl.parent)])
(dl / "05_test_result" / "generalization").mkdir(parents=True)
(dl / "05_test_result" / "generalization" / "GridUnnormal_generalization.csv").write_text(
"testcase,dtype\ncase1,fp16\n", encoding="utf-8")
(dl / "05_test_result" / "generalization" / "notes.txt").write_text("stray\n", encoding="utf-8")
prec = dl / "05_test_result" / "precision"
prec.mkdir(parents=True, exist_ok=True)
(prec / "whatever.csv").write_text("case,r\nx,PASS\n", encoding="utf-8-sig")
perf = dl / "05_test_result" / "performance"
perf.mkdir(parents=True, exist_ok=True)
(perf / "GridUnnormal_performance.csv").write_text(
"case,dtype,npu_us,gpu_us\n"
"gu_001,float16,452.0,100.0\n"
"gu_002,float16,80.0,100.0\n"
"gu_003,float16,30.0,100.0\n",
encoding="utf-8")
import os as _os, time as _t
old = _t.time() - 3600
(perf / "GridUnnormal_result_stale.csv").write_text("case,r\nx,PASS\n", encoding="utf-8")
_os.utime(perf / "GridUnnormal_result_stale.csv", (old, old))
vend = ROOT.parent / "selftest_vendor"
(vend / "op_kernel").mkdir(parents=True, exist_ok=True)
(vend / "op_kernel" / "grid_unnormal.o").write_text("fake binary\n", encoding="utf-8")
(perf / "GridUnnormal_perf_no_baseline.csv").write_text(
"case,dtype,bin_perf_us\ngu_010,float16,42.0\n", encoding="utf-8")
(dl / "01_requirement.md").write_text(
"# R\n\n## 一\n\n## 3. 910B/910C 支持范围(canndev 权威)\n\n"
"| 名称 | shape |\n|---|---|\n| grid | 任意 shape |\n", encoding="utf-8")
(dl / "02_design.md").write_text("# D\n\n## 一\n", encoding="utf-8")
ip1 = dl / "05_test_result" / "invoke_path"
ip1.mkdir(parents=True, exist_ok=True)
(ip1 / "GridUnnormal_invoke_path.csv").write_text(
"项,内容\n支持通路范围,kernel=✅\n通路,testcase,precision_status\ngeir,c1,PASS\n", encoding="utf-8-sig")
dl2 = ROOT.parent / "selftest_deliverables" / "Celu"
ip2 = dl2 / "05_test_result" / "invoke_path"
ip2.mkdir(parents=True, exist_ok=True)
(ip2 / "Celu_invoke_path.csv").write_text(
"项,内容\n依据,01\n\n通路,testcase,precision_status,xpu_status,xpu_device_us\n"
"geir,c1,PASS,PASS,NA\ngeir,c2,PASS,PASS,\n", encoding="utf-8-sig")
dl3 = ROOT.parent / "selftest_deliverables" / "NonZeroWithValue"
ip3 = dl3 / "05_test_result" / "invoke_path"
ip3.mkdir(parents=True, exist_ok=True)
(ip3 / "NonZeroWithValue_invoke_path.csv").write_text(
"项,内容\n支持通路范围,geir=✅\n\n通路,testcase,precision_status\ngeir,c1,PASS\n", encoding="utf-8-sig")
(ROOT / ".selftest_base").write_text(base)
def _kernel_h() -> str:
return """// A5 kernel for selftest
#include <cstdint>
constexpr int32_t NZV_ALL_CORE_NUM = 72 * 32; // G1-hardcoded-platform-const
struct K {
uint32_t gmOffset_ = 0; // G1-narrow-accumulator (同文件有 int64)
int64_t totalNum_ = 0;
void Run(int64_t row, int64_t col, int64_t denom) {
int64_t numel = row * col; // G1-mul-overflow-unguarded
uint16_t lc = static_cast<uint16_t>(numelCol / 8); // G1-narrowing-cast (shape 溯源)
int32_t v = (int32_t)row; // G1-c-style-narrow-cast / G11-c-style-cast
int64_t q = row / denom; // G14-int-div-by-zero
int32_t mag = abs(v); // G14-ask: 整型极值取负/abs 溢出
__VEC_SCOPE__ { } // 真作用域,供 G2-ar-not-cleared 计数
RegTensor<float> reg; // G2-vf-missing-vec-scope (无 __VEC_SCOPE__)
CompareScalar(mask, reg, 1.0f); // G2-comparescalar-no-mode
pad.rightPadding = numColAlign - numCol; // G2-rightpadding-wrong-base
GatherMask<STORE_REG>(reg); // G2-ar-not-cleared
(void)numel; (void)lc; (void)v; (void)q;
}
// A5 走 regbase,A2 走老路 // G4-team-slang-naming
__aicore__ inline void Process() {
for (int64_t i = 0; i < totalNum_; ++i) { } // G14-no-empty-tensor-guard
}
};
long numelCol = 4096;
long numColAlign = 64, numCol = 50;
"""
def _tiling_cpp() -> str:
body = "\n".join(f" int v{i} = {i} + 1;" for i in range(60))
return ("ge::graphStatus GridUnnormalTilingFunc(gert::TilingContext* context)\n{\n"
+ body + "\n return ge::GRAPH_SUCCESS;\n}\n"
"// G2-fixed-dim-array-no-rank-check: 用了定长维度模板但全目录无 rank 校验\n"
"BroadcastBaseTiling<OpDag> brcBaseTiling(context_, BROADCAST_KERNEL_TYPE::KERNEL_TYPE_NDDMA);\n")
def _tiling_h() -> str:
return ("BEGIN_TILING_DATA_DEF(GridUnnormalTilingData)\n"
"TILING_DATA_FIELD_DEF(int64_t, totalNum);\n"
"TILING_DATA_FIELD_DEF(int64_t, neverReadField);\n"
"END_TILING_DATA_DEF\n")
def _plugin_cpp() -> str:
return ("""ge::graphStatus Parse(Operator& op) {
ge::DataType outputDataType; // G3-uninitialized-var
op.GetAttr("output_type", outputDataType); // G3-getattr-unchecked
if (!ok) {
OP_LOGE(context->GetNodeName(), "dtype of grid is invalid"); // G3-bare-op-loge
return ge::GRAPH_FAILED;
}
const int64_t* p = attrs->GetAttrPointer<int64_t>(0);
int64_t v = *p; // G2-ptr-deref-unchecked
(void)v;
return ge::GRAPH_SUCCESS;
}
""")
def _def_cpp() -> str:
return ("""class GridUnnormal : public OpDef {
explicit GridUnnormal(const char* name) : OpDef(name) {
this->Input("grid").DataType({ge::DT_FLOAT16}) // G5: 比 A2 少 float
.Format({ge::FORMAT_NDC1HWC0, ge::FORMAT_NDC1HWC0}); // G6-format-rank-vs-doc-dims(配 README 0-8维)
this->Attr("align_corners").AttrType(OPTIONAL).Int(0); // G6-attr-type-mismatch (proto 是 Bool)
this->Attr("extra_only_in_def").AttrType(OPTIONAL).Bool(false);
this->AICore().AddConfig("ascend950"); // G9-binary-json-invalid(下方非法 json)
// ⚠️ 这一行是 G4-a2-path-touched 的**前提**,别删:
// "改动会不会污染 A2"的判据是**本仓为哪些 soc 编译**(def 的 AddConfig),
// 不是"存在非 arch35 的 .cpp"。只注册 ascend950 时本仓压根不出 A2 产物,
// 改它的非 arch35 路径碰不到 A2 —— 真算子 NonZeroWithValue 就是这样被误报成红线 R2 的。
// 夹具要有这一行,OP 才真是双代算子,规则才该响。
this->AICore().AddConfig("ascend910b", cfg910b);
}
};
""")
def _readme() -> str:
return """# GridUnnormal
## 产品支持情况
| 产品 | 是否支持 |
| :--- | :---: |
| <term>Ascend 950PR/Ascend 950DT</term> | √ |
| <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | x |
| <term>Atlas 推理系列产品</term> | √ |
## 功能说明
- 计算公式:
$$
GridUnnormal(grid) = grid \\ast (size - 1) / 2
$$
- 算子功能:这是 GridSample 链路的算子。非有限输入 inf / nan 不属于支持域。
说明缩进不对的续行
> 说明:这是一条 editorial 注。
## 约束说明
- 输入支持 0-8 维。
- <term>Ascend 950PR/Ascend 950DT</term>:不支持 BFLOAT16。
- <term>Atlas A2 训练系列产品</term>:支持 BFLOAT16。
## 参数说明
<table><thead><tr><th>参数名</th><th>描述</th></tr></thead>
<tbody><tr><td>x</td><td>表示输入张量,对应公式中的`x`(G12-md-syntax-in-html-table 正样本:HTML 表格内反引号不渲染)。</td></tr></tbody></table>
## 调用说明
| 方式 | 说明 |
| --- | --- |
| PyTorch | 通过 torch 接口调用。 |
"""
def _big_header() -> str:
return "#pragma once\n" + "".join(f"// filler line {i}\nint g{i} = {i};\n" for i in range(300))
def _dup_block(tag: str) -> str:
blk = "\n".join(f" int shared_{i} = {i} * 3 + 7;" for i in range(14))
return f"void func_{tag}() {{\n{blk}\n}}\n"
def main() -> int:
build_fixture()
build_canndev()
base = (ROOT / ".selftest_base").read_text().strip()
fired: set[str] = set()
asks: set[str] = set()
ood_seen: set[str] = set()
data = {"findings": [], "skipped": []}
for extra in ([], ["--local"]):
import os
env = {**os.environ,
"CHANGWEI_DELIVERABLES_ROOT": str(ROOT.parent / "selftest_deliverables"),
"CHANGWEI_CANNDEV": str(CANNDEV)}
r = subprocess.run(
[sys.executable, str(Path(__file__).parent / "check.py"),
"--repo", str(ROOT), "--base", base, "--head", "HEAD", "--json",
"--vendor", str(ROOT.parent / "selftest_vendor"), *extra],
capture_output=True, text=True, env=env)
if r.returncode != 0 or not r.stdout.strip():
print(f"❌ check.py 跑挂了({'local' if extra else 'remote'} 趟):")
print(r.stderr[-2500:])
return 1
d = json.loads(r.stdout)
fired |= {f["rule"] for f in d["findings"]}
asks |= {a["topic"] for a in d.get("judgment_asks", [])}
ood_seen |= {f["rule"] for f in d["findings"] if f.get("out_of_diff")}
if not extra:
data = d
else:
data["skipped"] = [s for s in data["skipped"] if "组 15" not in s and "组 13" not in s]
all_rules = set()
for p in (Path(__file__).parent / "checkers").glob("*.py"):
all_rules |= set(re.findall(r'rule="([^"]+)"', p.read_text(encoding="utf-8")))
silent = sorted(all_rules - fired - set(KNOWN_CONDITIONAL))
conditional = sorted(all_rules & set(KNOWN_CONDITIONAL) - fired)
print(f"规则总数 {len(all_rules)}|夹具触发 {len(fired & all_rules)}|"
f"哑弹 {len(silent)}|条件豁免 {len(conditional)}\n")
if silent:
print("❌ 哑弹(在必然触发的样本上没响,要查):")
for s in silent:
print(f" {s}")
else:
print("✅ 无哑弹")
if conditional:
print("\n○ 条件豁免(已登记原因):")
for s in conditional:
print(f" {s:<38} {KNOWN_CONDITIONAL[s]}")
want_asks = {
"整型除零可达性", "空 Tensor 可达性", "乘法溢出可达性",
"收窄到 uint16_t 的上界", "32 位累加器",
"rightPadding 的对齐基准",
"浮点除法的兜底是不是多余的除零保护",
"公共/框架文件改动", "该算子到底有没有 aclnn 对外接口",
"整型极值取负/abs 溢出", "产品隔离疑似传播",
"grid_unnormal 性能是否达标取决于芯片对",
"grid_unnormal 的 golden 实现是否与 README 计算公式一致",
}
miss_asks = sorted(w for w in want_asks if not any(a.startswith(w[:8]) for a in asks))
print(f"\n判断类待判题 {len(want_asks) - len(miss_asks)}/{len(want_asks)} 类被提出"
+ (" ✅" if not miss_asks else f" ❌ 缺:{'、'.join(miss_asks)}"))
print(f"锚点约束:标出 {len(ood_seen)} 类 diff 外 finding"
+ (" ✅" if ood_seen else " ⚠️ 夹具未覆盖到(新算子夹具全是新增文件),机制未被验证"))
if data["skipped"]:
print("\n⚠️ 夹具上被跳过的组:")
for s in data["skipped"]:
print(f" {s}")
return 1 if (silent or miss_asks) else 0
if __name__ == "__main__":
sys.exit(main())