From d0a9c49a3fce73c3716919e3c087b78faf172556 Mon Sep 17 00:00:00 2001 From: Libre <229890576+Libre908@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:02:57 +0800 Subject: [PATCH 1/2] Add operator-verify skill for offline Lean 4 operator verification --- .gitignore | 2 + AGENTS.md | 2 +- README.md | 4 +- README.zh-CN.md | 4 +- docs/project-architecture.md | 2 +- scripts/install.py | 4 +- skills/operator-verify/SKILL.md | 47 +++ .../operator-verify/lean_lib/AscendLean.lean | 3 + .../lean_lib/AscendLean/PipeModel.lean | 299 +++++++++++++++ .../lean_lib/AscendLean/TritonModel.lean | 317 +++++++++++++++ .../lean_lib/AscendLean/UBModel.lean | 166 ++++++++ skills/operator-verify/lean_lib/README.md | 28 ++ .../lean_lib/lake-manifest.json | 6 + skills/operator-verify/lean_lib/lakefile.toml | 6 + .../operator-verify/lean_lib/lean-toolchain | 1 + skills/operator-verify/references/handoff.md | 88 +++++ skills/operator-verify/references/taxonomy.md | 17 + skills/operator-verify/references/tcb.md | 17 + skills/operator-verify/scripts/audit_scan.py | 362 ++++++++++++++++++ skills/operator-verify/scripts/lean_check.py | 321 ++++++++++++++++ skills/operator-verify/scripts/triage.py | 186 +++++++++ tools/README.md | 2 +- 22 files changed, 1875 insertions(+), 9 deletions(-) create mode 100644 skills/operator-verify/SKILL.md create mode 100644 skills/operator-verify/lean_lib/AscendLean.lean create mode 100644 skills/operator-verify/lean_lib/AscendLean/PipeModel.lean create mode 100644 skills/operator-verify/lean_lib/AscendLean/TritonModel.lean create mode 100644 skills/operator-verify/lean_lib/AscendLean/UBModel.lean create mode 100644 skills/operator-verify/lean_lib/README.md create mode 100644 skills/operator-verify/lean_lib/lake-manifest.json create mode 100644 skills/operator-verify/lean_lib/lakefile.toml create mode 100644 skills/operator-verify/lean_lib/lean-toolchain create mode 100644 skills/operator-verify/references/handoff.md create mode 100644 skills/operator-verify/references/taxonomy.md create mode 100644 skills/operator-verify/references/tcb.md create mode 100644 skills/operator-verify/scripts/audit_scan.py create mode 100644 skills/operator-verify/scripts/lean_check.py create mode 100644 skills/operator-verify/scripts/triage.py diff --git a/.gitignore b/.gitignore index c2ef40b..6e96815 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ !/scripts/ /skills/* !/skills/operator-optimize/ +!/skills/operator-verify/ !/skills/framework-adapt/ !/skills/numericbridge/ !/skills/precision-compare/ @@ -26,6 +27,7 @@ /research/ __pycache__/ *.pyc +.lake/ # Historical local deliveries are not part of the results-only publication. /community/site/evidence/deepseek41-*.zip diff --git a/AGENTS.md b/AGENTS.md index 6adc3ca..424382d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Layout -- `skills/numericbridge/` is the entrypoint for the full workflow. It owns stage transitions and handoffs and links to the installable `framework-adapt`, `precision-compare`, `precision-repair` and `operator-optimize` skills for execution methods. Load those methods on demand. Export the suite with `python -B -m scripts install --output NEW_DIRECTORY` to bundle the shared `tools/` once in Compare. Reuse workload execution, verified resources, inputs/state, collectors and results. `skills/operator-optimize/` owns operator optimization after diagnosis: configuration, backend and kernel variants measured against FP64 with paired timing (`scripts/kernel_check.py`). +- `skills/numericbridge/` is the entrypoint for the full workflow. It owns stage transitions and handoffs and links to the installable `framework-adapt`, `precision-compare`, `precision-repair`, `operator-optimize` and `operator-verify` skills for execution methods. Load those methods on demand. Export the suite with `python -B -m scripts install --output NEW_DIRECTORY` to bundle the shared `tools/` once in Compare. Reuse workload execution, verified resources, inputs/state, collectors and results. `skills/operator-optimize/` owns operator optimization after diagnosis: configuration, backend and kernel variants measured against FP64 with paired timing (`scripts/kernel_check.py`). `skills/operator-verify/` owns offline static auditing (`scripts/audit_scan.py`) and Lean 4 formal verification (`scripts/triage.py`, `scripts/lean_check.py`, `lean_lib/AscendLean/`) for discrete operator invariants. - `research/` is retained local RSI research, Git-ignored and excluded from both the public repository and normal Skill installation. Preserve its local code, state and recorded experiments. It owns task/iteration orchestration over existing workflow tools and an external harness. Index successful/incomplete task evidence; keep full traces and datasets private. The independent improver builds candidates. Evaluate exact tool/context/procedure bundles on independent task families before activation; label dataset outcomes at task scope. Pin task versions, preserve raw usage and reuse comparable baseline receipts. Native checks remain task-owned. Agent-weight training and operator search are extension points. diff --git a/README.md b/README.md index 11254a5..bb2ab57 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ skills="numericbridge-skills-$version" shasum -a 256 -c "$archive.sha256" && mkdir "$skills" && unzip "$archive" -d "$skills" ``` -On Linux you can use `sha256sum -c "$archive.sha256"` in place of `shasum -a 256 -c "$archive.sha256"`. Point your agent client at the directory containing the five skills, or copy the five skill folders together into its skills directory. New Skills ZIP builds include the shared tools, but no community records or search index; older releases may include a snapshot. [Updates and checkout-based installation](tools/README.md#portable-skills) +On Linux you can use `sha256sum -c "$archive.sha256"` in place of `shasum -a 256 -c "$archive.sha256"`. Point your agent client at the directory containing the six skills, or copy the six skill folders together into its skills directory. New Skills ZIP builds include the shared tools, but no community records or search index; older releases may include a snapshot. [Updates and checkout-based installation](tools/README.md#portable-skills) **Develop from source.** Use `git clone --depth 1 https://github.com/FreedomIntelligence/NumericBridge.git` for a clean current checkout without the historical catalog objects. Full Git history still contains independently published older revisions. @@ -52,7 +52,7 @@ For your workload, start with the [NumericBridge Skill](skills/numericbridge/SKI ## Workflow and skills -The [workflow](skills/numericbridge/references/workflow.md) loads only the method it needs: [Framework Adapt](skills/framework-adapt/SKILL.md) for native setup, [Precision Compare](skills/precision-compare/SKILL.md) for measurement, [Precision Repair](skills/precision-repair/SKILL.md) for supported-path failures or numerical findings that warrant diagnosis, and [Operator Optimize](skills/operator-optimize/SKILL.md) for operators that diagnosis finds outside their FP64 bound, reporting each variant's precision and speed. Each stage reuses the confirmed request and evidence. +The [workflow](skills/numericbridge/references/workflow.md) loads only the method it needs: [Framework Adapt](skills/framework-adapt/SKILL.md) for native setup, [Precision Compare](skills/precision-compare/SKILL.md) for measurement, [Precision Repair](skills/precision-repair/SKILL.md) for supported-path failures or numerical findings that warrant diagnosis, [Operator Optimize](skills/operator-optimize/SKILL.md) for operators that diagnosis finds outside their FP64 bound, reporting each variant's precision and speed, and [Operator Verify](skills/operator-verify/SKILL.md) for offline Lean 4 formal verification and static auditing of discrete operator invariants (masks, UB capacity, pipeline synchronization, and algebraic/control-flow equivalence). Each stage reuses the confirmed request and evidence. Task recipes: [Inference](skills/precision-compare/references/inference.md) · [SFT](skills/precision-compare/references/sft.md) · [RL](skills/precision-compare/references/rl.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 09f13a2..fcd7b49 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -36,7 +36,7 @@ skills="numericbridge-skills-$version" shasum -a 256 -c "$archive.sha256" && mkdir "$skills" && unzip "$archive" -d "$skills" ``` -在 Linux 上也可以用 `sha256sum -c "$archive.sha256"` 代替 `shasum -a 256 -c "$archive.sha256"`。让 Agent 客户端从解压后的目录加载五个 Skill,或将五个 Skill 文件夹一起复制到客户端的 Skill 目录。新版 Skills ZIP 包含共享工具,但不附带社区记录或检索索引;旧版可能包含快照。[更新与从仓库安装](tools/README.md#portable-skills) +在 Linux 上也可以用 `sha256sum -c "$archive.sha256"` 代替 `shasum -a 256 -c "$archive.sha256"`。让 Agent 客户端从解压后的目录加载六个 Skill,或将六个 Skill 文件夹一起复制到客户端的 Skill 目录。新版 Skills ZIP 包含共享工具,但不附带社区记录或检索索引;旧版可能包含快照。[更新与从仓库安装](tools/README.md#portable-skills) **需要源码时**,用 `git clone --depth 1 https://github.com/FreedomIntelligence/NumericBridge.git` 获取干净的当前版本;完整 Git 历史仍保留以前公开发布过的记录。 @@ -52,7 +52,7 @@ python -B "$skills/precision-compare/examples/compare_gradients.py" ## 工作流与 Skill -[工作流](skills/numericbridge/references/workflow.md)按需加载各阶段的 Skill:[Framework Adapt](skills/framework-adapt/SKILL.md) 准备原生环境,[Precision Compare](skills/precision-compare/SKILL.md) 采集和对比,支持的路径运行失败或发现值得调查的数值差异时,进入 [Precision Repair](skills/precision-repair/SKILL.md);诊断发现算子超出 FP64 误差范围时,进入 [Operator Optimize](skills/operator-optimize/SKILL.md),给出每个方案的精度和速度。每一步沿用已确认的需求和证据。 +[工作流](skills/numericbridge/references/workflow.md)按需加载各阶段的 Skill:[Framework Adapt](skills/framework-adapt/SKILL.md) 准备原生环境,[Precision Compare](skills/precision-compare/SKILL.md) 采集和对比,支持的路径运行失败或发现值得调查的数值差异时,进入 [Precision Repair](skills/precision-repair/SKILL.md);诊断发现算子超出 FP64 误差范围时,进入 [Operator Optimize](skills/operator-optimize/SKILL.md),给出每个方案的精度和速度;涉及离散不变量(掩码越界、UB 容量、流水线同步或控制流/代数等价性)时,可通过 [Operator Verify](skills/operator-verify/SKILL.md) 进行离线静态审计与 Lean 4 形式化验证。每一步沿用已确认的需求和证据。 任务配方:[推理](skills/precision-compare/references/inference.md) · [SFT](skills/precision-compare/references/sft.md) · [RL](skills/precision-compare/references/rl.md)。 diff --git a/docs/project-architecture.md b/docs/project-architecture.md index 6fa54d1..3d3c953 100644 --- a/docs/project-architecture.md +++ b/docs/project-architecture.md @@ -23,7 +23,7 @@ Agent 从 [NumericBridge Skill](../skills/numericbridge/SKILL.md) 进入。[流 | 本地私有 projects/、runs/ | 原生案例、资源配置、原始数组、完整日志与过程记录 | 这些目录按用途分工,不是用户必须理解或依次启动的架构层。 -安装包包含 numericbridge、framework-adapt、precision-compare、precision-repair、operator-optimize。operator-optimize 接在诊断之后,对照 FP64 测量配置、后端和 kernel 方案的精度与速度。 +安装包包含 numericbridge、framework-adapt、precision-compare、precision-repair、operator-optimize、operator-verify。operator-optimize 接在诊断之后,对照 FP64 测量配置、后端和 kernel 方案的精度与速度;operator-verify 提供面向离散算子不变量的离线静态审计与 Lean 4 形式化验证。 ## 工具放置与安装 diff --git a/scripts/install.py b/scripts/install.py index 9940b51..07538d2 100644 --- a/scripts/install.py +++ b/scripts/install.py @@ -9,7 +9,7 @@ import shutil ROOT = Path(__file__).resolve().parents[1] -INSTALLABLE_SKILLS = ('framework-adapt', 'numericbridge', 'operator-optimize', 'precision-compare', 'precision-repair') +INSTALLABLE_SKILLS = ('framework-adapt', 'numericbridge', 'operator-optimize', 'operator-verify', 'precision-compare', 'precision-repair') COMMUNITY_DATA_NAMES = {'community-search.json', 'search-index.json', 'evaluations.json', 'repairs.json', 'relations.json'} @@ -55,7 +55,7 @@ def install_skills(source, destination): raise FileExistsError(destination / folder.name) for folder in folders: shutil.copytree(folder, destination / folder.name, - ignore=shutil.ignore_patterns('__pycache__', '*.pyc'), + ignore=shutil.ignore_patterns('__pycache__', '*.pyc', '.lake'), copy_function=_copy_workflow_file) if folder.name == 'precision-compare': shutil.copytree(ROOT / 'tools', diff --git a/skills/operator-verify/SKILL.md b/skills/operator-verify/SKILL.md new file mode 100644 index 0000000..d1ceb13 --- /dev/null +++ b/skills/operator-verify/SKILL.md @@ -0,0 +1,47 @@ +--- +name: operator-verify +description: Formally verify accelerator operators (Triton-Ascend, Ascend C, Triton, CUDA) without target hardware using Lean 4 to prove index/mask safety, on-chip resource bounds, pipeline sync safety, and discrete semantic equivalence, or produce machine-checked counterexamples. +--- + +# Operator verification + +Run tools from this skill directory. Each tool's `--help` gives its interface. + +| Step | Tool | Output | +|---|---|---| +| Scan upstream kernel files for discrete bug candidates | [audit_scan](scripts/audit_scan.py) | `audit-findings.json` with candidate rule hits, lines, hashes, and categories | +| Classify verification scope and build a request | [triage](scripts/triage.py) | `verify-request.json` with category, eligibility, route, and model modules | +| Type-check Lean 4 proofs and audit `sorry` / axioms | [lean_check](scripts/lean_check.py) | `verify-report.json` with toolchain, hashes, theorem list, audit status, and verdict | + +Read [taxonomy](references/taxonomy.md) for the discrete-verification vs floating-point boundary, [handoff](references/handoff.md) for the input/output JSON contracts, and [TCB](references/tcb.md) for hardware modeling assumptions. + +`operator-verify` pairs with [operator-optimize](../operator-optimize/SKILL.md): `operator-verify` proves discrete structural, memory, synchronization, and algebraic/bit-level properties offline without an accelerator; pure floating-point rounding accuracy and runtime timing remain in [precision-compare](../precision-compare/SKILL.md) and [operator-optimize](../operator-optimize/SKILL.md). + +## Entry + +1. **Standalone mode.** Start from a kernel source file, PR diff, or Lean 4 target. Run `triage.py` to classify the issue into one of the discrete categories (`index_and_mask`, `resource_capacity`, `pipeline_sync`, `semantic_equivalence`) or route `numeric_rounding` back to dynamic precision tools. +2. **NumericBridge companion / pre-gate mode.** Accept an operator handoff (`result/optimize//handoff.json`) or a `diagnosis.json` hypothesis, verify discrete invariants offline, and write `result/verify//verify-report.json` as evidence alongside dynamic checks. +3. **Repository audit mode.** Scan candidate operator files in an upstream repository (e.g., `sgl-kernel-npu`, `vllm-ascend`, `RL-Kernel`) to surface unreported defects, rule out false positives, and document implicit preconditions. Confirmed defects hand off directly to [upstream_status.py](../precision-compare/scripts/upstream_status.py) and [pr_draft.py](../precision-compare/scripts/pr_draft.py) for upstream PR delivery. + +## Verify + +1. **Classify scope.** Run `triage.py` on the operator target or handoff. Stop and route `numeric_rounding` (quantitative FP rounding error) to `precision-compare` or `operator-optimize`; keep qualitative `±inf` / `NaN` propagation and poisoning in `semantic_equivalence`. +2. **Bind to a Lean target.** Map the kernel property to a reusable semantics module in `lean_lib/` (see [lean_lib/README.md](lean_lib/README.md)). Distinguish **refutation** (concrete counterexample proving a buggy kernel fails) from **universal proof** (invariant proved for all symbolic shapes/inputs). `lean_lib/` targets pure Lean 4 core with **no Mathlib** — use core tactics (`let`, `omega`, `decide`, `simp`, `by_cases`, `induction`) rather than Mathlib-only tactics (`set`, `linarith`, `ring`, `by_contra`). +3. **Run machine check.** Run `lean_check.py` against the target `.lean` file and Lake project, e.g. `python3 scripts/lean_check.py TARGET.lean --project lean_lib --source KERNEL.py --claim-kind refutation --output verify-report.json`. It records Lean/Lake versions, source SHA-256 digests, public theorems, `sorry`/`admit`/custom-`axiom` audit counts, compiler status, and verdict. +4. **Disclose TCB, preconditions, and deliver.** Record explicit modeling assumptions per [TCB](references/tcb.md) and any required or discovered `preconditions` in `result/verify//verify-report.json` (or the standalone output directory). + +```xml + + A verdict of `proved` or `refuted` requires zero compiler errors, zero `sorry` + or `admit` tokens, and zero unapproved custom axioms. + Never claim floating-point rounding error bounds from a discrete Lean model; + quantitative precision belongs to `precision-compare` and `kernel_check.py` + (discrete `±inf`/`NaN` abstract-domain propagation is in scope under `semantic_equivalence`). + Always preserve source SHA-256 digests, Lean toolchain identity, discovered + `preconditions`, and explicit TCB assumptions in `verify-report.json`. + When `lake` or `lean` is unavailable on the host, report `toolchain_missing` + and `verdict: "not_run"` rather than fabricating or skipping verification. + Keep experimental corpora, raw benchmarks, and `.lake/` build caches outside + the tracked skill directory. + +``` diff --git a/skills/operator-verify/lean_lib/AscendLean.lean b/skills/operator-verify/lean_lib/AscendLean.lean new file mode 100644 index 0000000..102be46 --- /dev/null +++ b/skills/operator-verify/lean_lib/AscendLean.lean @@ -0,0 +1,3 @@ +import AscendLean.PipeModel +import AscendLean.UBModel +import AscendLean.TritonModel diff --git a/skills/operator-verify/lean_lib/AscendLean/PipeModel.lean b/skills/operator-verify/lean_lib/AscendLean/PipeModel.lean new file mode 100644 index 0000000..3b7763f --- /dev/null +++ b/skills/operator-verify/lean_lib/AscendLean/PipeModel.lean @@ -0,0 +1,299 @@ +/- + AscendLean.PipeModel + Formal execution & synchronization model for Ascend DaVinci AI Core pipelines + (PIPE_MTE2, PIPE_V, PIPE_MTE3, PIPE_S) and FIFO HardEvent synchronization + (SetFlag / WaitFlag) across all 12 directed cross-pipe HardEvents, targeting + UB data-race freedom (RAW / WAR / WAW), deadlock freedom (no wait underflow), + and event balance. +-/ + +namespace AscendLean.PipeModel + +inductive Pipe where + | MTE2 + | V + | MTE3 + | S + deriving DecidableEq, Repr + +inductive HardEvent where + | MTE3_MTE2 + | MTE2_MTE3 + | MTE2_V + | V_MTE2 + | V_MTE3 + | MTE3_V + | S_MTE2 + | MTE2_S + | S_V + | V_S + | S_MTE3 + | MTE3_S + deriving DecidableEq, Repr + +def HardEvent.src : HardEvent → Pipe + | .MTE3_MTE2 => .MTE3 + | .MTE2_MTE3 => .MTE2 + | .MTE2_V => .MTE2 + | .V_MTE2 => .V + | .V_MTE3 => .V + | .MTE3_V => .MTE3 + | .S_MTE2 => .S + | .MTE2_S => .MTE2 + | .S_V => .S + | .V_S => .V + | .S_MTE3 => .S + | .MTE3_S => .MTE3 + +def HardEvent.dst : HardEvent → Pipe + | .MTE3_MTE2 => .MTE2 + | .MTE2_MTE3 => .MTE3 + | .MTE2_V => .V + | .V_MTE2 => .MTE2 + | .V_MTE3 => .MTE3 + | .MTE3_V => .V + | .S_MTE2 => .MTE2 + | .MTE2_S => .S + | .S_V => .V + | .V_S => .S + | .S_MTE3 => .MTE3 + | .MTE3_S => .S + +abbrev BufId := String + +inductive Op where + | write (pipe : Pipe) (buf : BufId) (tag : String) + | read (pipe : Pipe) (buf : BufId) (tag : String) + | setFlag (ev : HardEvent) + | waitFlag (ev : HardEvent) + | pipeBarrierAll + deriving DecidableEq, Repr + +/-- Per-pipe last access timestamp on `targetBuf`. -/ +structure PipeTimes where + mte2 : Nat := 0 + v : Nat := 0 + mte3 : Nat := 0 + s : Nat := 0 + deriving DecidableEq, Repr + +def PipeTimes.get (t : PipeTimes) : Pipe → Nat + | .MTE2 => t.mte2 + | .V => t.v + | .MTE3 => t.mte3 + | .S => t.s + +def PipeTimes.set (t : PipeTimes) (p : Pipe) (val : Nat) : PipeTimes := + match p with + | .MTE2 => { t with mte2 := val } + | .V => { t with v := val } + | .MTE3 => { t with mte3 := val } + | .S => { t with s := val } + +/-- Latest synchronized timestamp from `src` pipe visible to `dst` pipe via each HardEvent. -/ +structure SyncWatermark where + mte3_mte2 : Nat := 0 + mte2_mte3 : Nat := 0 + mte2_v : Nat := 0 + v_mte2 : Nat := 0 + v_mte3 : Nat := 0 + mte3_v : Nat := 0 + s_mte2 : Nat := 0 + mte2_s : Nat := 0 + s_v : Nat := 0 + v_s : Nat := 0 + s_mte3 : Nat := 0 + mte3_s : Nat := 0 + allBarrier : Nat := 0 + deriving DecidableEq, Repr + +def SyncWatermark.knownSafe (w : SyncWatermark) (src dst : Pipe) : Nat := + let direct := + match src, dst with + | .MTE3, .MTE2 => w.mte3_mte2 + | .MTE2, .MTE3 => w.mte2_mte3 + | .MTE2, .V => w.mte2_v + | .V, .MTE2 => w.v_mte2 + | .V, .MTE3 => w.v_mte3 + | .MTE3, .V => w.mte3_v + | .S, .MTE2 => w.s_mte2 + | .MTE2, .S => w.mte2_s + | .S, .V => w.s_v + | .V, .S => w.v_s + | .S, .MTE3 => w.s_mte3 + | .MTE3, .S => w.mte3_s + | _, _ => 0 + max direct w.allBarrier + +def SyncWatermark.advance (w : SyncWatermark) (ev : HardEvent) (val : Nat) : SyncWatermark := + match ev with + | .MTE3_MTE2 => { w with mte3_mte2 := max w.mte3_mte2 val } + | .MTE2_MTE3 => { w with mte2_mte3 := max w.mte2_mte3 val } + | .MTE2_V => { w with mte2_v := max w.mte2_v val } + | .V_MTE2 => { w with v_mte2 := max w.v_mte2 val } + | .V_MTE3 => { w with v_mte3 := max w.v_mte3 val } + | .MTE3_V => { w with mte3_v := max w.mte3_v val } + | .S_MTE2 => { w with s_mte2 := max w.s_mte2 val } + | .MTE2_S => { w with mte2_s := max w.mte2_s val } + | .S_V => { w with s_v := max w.s_v val } + | .V_S => { w with v_s := max w.v_s val } + | .S_MTE3 => { w with s_mte3 := max w.s_mte3 val } + | .MTE3_S => { w with mte3_s := max w.mte3_s val } + +/-- Per-HardEvent FIFO signal queues (models hardware SetFlag/WaitFlag token counters). -/ +structure EventQueues where + mte3_mte2 : List Nat := [] + mte2_mte3 : List Nat := [] + mte2_v : List Nat := [] + v_mte2 : List Nat := [] + v_mte3 : List Nat := [] + mte3_v : List Nat := [] + s_mte2 : List Nat := [] + mte2_s : List Nat := [] + s_v : List Nat := [] + v_s : List Nat := [] + s_mte3 : List Nat := [] + mte3_s : List Nat := [] + deriving DecidableEq, Repr + +def EventQueues.push (q : EventQueues) (ev : HardEvent) (val : Nat) : EventQueues := + match ev with + | .MTE3_MTE2 => { q with mte3_mte2 := q.mte3_mte2 ++ [val] } + | .MTE2_MTE3 => { q with mte2_mte3 := q.mte2_mte3 ++ [val] } + | .MTE2_V => { q with mte2_v := q.mte2_v ++ [val] } + | .V_MTE2 => { q with v_mte2 := q.v_mte2 ++ [val] } + | .V_MTE3 => { q with v_mte3 := q.v_mte3 ++ [val] } + | .MTE3_V => { q with mte3_v := q.mte3_v ++ [val] } + | .S_MTE2 => { q with s_mte2 := q.s_mte2 ++ [val] } + | .MTE2_S => { q with mte2_s := q.mte2_s ++ [val] } + | .S_V => { q with s_v := q.s_v ++ [val] } + | .V_S => { q with v_s := q.v_s ++ [val] } + | .S_MTE3 => { q with s_mte3 := q.s_mte3 ++ [val] } + | .MTE3_S => { q with mte3_s := q.mte3_s ++ [val] } + +def EventQueues.pop (q : EventQueues) (ev : HardEvent) : Option (Nat × EventQueues) := + match ev with + | .MTE3_MTE2 => match q.mte3_mte2 with | [] => none | e :: r => some (e, { q with mte3_mte2 := r }) + | .MTE2_MTE3 => match q.mte2_mte3 with | [] => none | e :: r => some (e, { q with mte2_mte3 := r }) + | .MTE2_V => match q.mte2_v with | [] => none | e :: r => some (e, { q with mte2_v := r }) + | .V_MTE2 => match q.v_mte2 with | [] => none | e :: r => some (e, { q with v_mte2 := r }) + | .V_MTE3 => match q.v_mte3 with | [] => none | e :: r => some (e, { q with v_mte3 := r }) + | .MTE3_V => match q.mte3_v with | [] => none | e :: r => some (e, { q with mte3_v := r }) + | .S_MTE2 => match q.s_mte2 with | [] => none | e :: r => some (e, { q with s_mte2 := r }) + | .MTE2_S => match q.mte2_s with | [] => none | e :: r => some (e, { q with mte2_s := r }) + | .S_V => match q.s_v with | [] => none | e :: r => some (e, { q with s_v := r }) + | .V_S => match q.v_s with | [] => none | e :: r => some (e, { q with v_s := r }) + | .S_MTE3 => match q.s_mte3 with | [] => none | e :: r => some (e, { q with s_mte3 := r }) + | .MTE3_S => match q.mte3_s with | [] => none | e :: r => some (e, { q with mte3_s := r }) + +def EventQueues.allEmpty (q : EventQueues) : Bool := + q.mte3_mte2.isEmpty && q.mte2_mte3.isEmpty && q.mte2_v.isEmpty && q.v_mte2.isEmpty && + q.v_mte3.isEmpty && q.mte3_v.isEmpty && q.s_mte2.isEmpty && q.mte2_s.isEmpty && + q.s_v.isEmpty && q.v_s.isEmpty && q.s_mte3.isEmpty && q.mte3_s.isEmpty + +/-- + Hardware synchronization state tracking all 4 pipes and all 12 directed `HardEvent` + FIFO queues on a target UB buffer `targetBuf`. Detects cross-pipe RAW, WAR, and WAW + hazards, wait underflow (deadlock), and leaked SetFlag tokens. +-/ +structure SyncState where + step : Nat := 0 + lastRead : PipeTimes := {} + lastWrite : PipeTimes := {} + synced : SyncWatermark := {} + queues : EventQueues := {} + raceDetected : Bool := false + underflow : Bool := false + deriving DecidableEq, Repr + +private def allPipes : List Pipe := [.MTE2, .V, .MTE3, .S] + +private def hasRawHazard (st : SyncState) (dst : Pipe) : Bool := + allPipes.any fun src => + src != dst && st.synced.knownSafe src dst < st.lastWrite.get src + +private def hasWarOrWawHazard (st : SyncState) (dst : Pipe) : Bool := + allPipes.any fun src => + src != dst && + (st.synced.knownSafe src dst < st.lastRead.get src || + st.synced.knownSafe src dst < st.lastWrite.get src) + +def stepOp (targetBuf : BufId) (st : SyncState) (op : Op) : SyncState := + let nextStep := st.step + 1 + match op with + | Op.read p b _ => + if b == targetBuf then + let raced := st.raceDetected || hasRawHazard st p + { st with + step := nextStep, + lastRead := st.lastRead.set p nextStep, + raceDetected := raced } + else + { st with step := nextStep } + | Op.write p b _ => + if b == targetBuf then + let raced := st.raceDetected || hasWarOrWawHazard st p + { st with + step := nextStep, + lastWrite := st.lastWrite.set p nextStep, + raceDetected := raced } + else + { st with step := nextStep } + | Op.setFlag ev => + let src := ev.src + let ts := max (st.lastRead.get src) (st.lastWrite.get src) + { st with step := nextStep, queues := st.queues.push ev ts } + | Op.waitFlag ev => + match st.queues.pop ev with + | none => { st with step := nextStep, underflow := true } + | some (e, q') => + { st with + step := nextStep, + synced := st.synced.advance ev e, + queues := q' } + | Op.pipeBarrierAll => + { st with step := nextStep, synced := { st.synced with allBarrier := nextStep } } + +def runOps (targetBuf : BufId) (st : SyncState) (ops : List Op) : SyncState := + ops.foldl (stepOp targetBuf) st + +theorem runOps_nil (targetBuf : BufId) (st : SyncState) : + runOps targetBuf st [] = st := rfl + +theorem runOps_cons (targetBuf : BufId) (st : SyncState) (op : Op) (ops : List Op) : + runOps targetBuf st (op :: ops) = runOps targetBuf (stepOp targetBuf st op) ops := rfl + +theorem runOps_append (targetBuf : BufId) (st : SyncState) (xs ys : List Op) : + runOps targetBuf st (xs ++ ys) = runOps targetBuf (runOps targetBuf st xs) ys := by + simp [runOps, List.foldl_append] + +/-- Kernel is race-free, deadlock-free (no event underflow), and leaves no leaked tokens. -/ +abbrev VerifiedSafe (st : SyncState) : Prop := + st.raceDetected = false ∧ st.underflow = false ∧ st.queues.allEmpty = true + +/-- Sanity theorem: unsynchronized MTE2 write followed by V read on the same UB buffer detects a RAW race. -/ +theorem mte2_v_unsync_race_detected : + (runOps "ub" {} [Op.write .MTE2 "ub" "load", Op.read .V "ub" "compute"]).raceDetected = true := by + decide + +/-- Sanity theorem: properly synchronized MTE2 -> V sequence is verified safe. -/ +theorem mte2_v_synced_safe : + VerifiedSafe (runOps "ub" {} [ + Op.write .MTE2 "ub" "load", + Op.setFlag .MTE2_V, + Op.waitFlag .MTE2_V, + Op.read .V "ub" "compute" + ]) := by + decide + +/-- Sanity theorem: properly synchronized V -> S sequence is verified safe. -/ +theorem v_s_synced_safe : + VerifiedSafe (runOps "ub" {} [ + Op.write .V "ub" "compute", + Op.setFlag .V_S, + Op.waitFlag .V_S, + Op.read .S "ub" "scalar_read" + ]) := by + decide + +end AscendLean.PipeModel diff --git a/skills/operator-verify/lean_lib/AscendLean/TritonModel.lean b/skills/operator-verify/lean_lib/AscendLean/TritonModel.lean new file mode 100644 index 0000000..c82cac5 --- /dev/null +++ b/skills/operator-verify/lean_lib/AscendLean/TritonModel.lean @@ -0,0 +1,317 @@ +/- + AscendLean.TritonModel + Reusable formal semantics for Triton-Ascend kernels: + 1. BitVec 64 bitwise selection (CANN 9.1 int64 select workaround). + 2. Extended values with `-inf` & tiled 1D reduction equivalence. + 3. Online Softmax IEEE-754 abstract domain (`(-inf) - (-inf) = NaN` poisoning). + 4. Masked load padding / uninitialized UB taint & negative-index OOB guard semantics. +-/ + +namespace AscendLean.TritonModel + +/-! ### 1. BitVec 64 Bitwise Select -/ + +def bitMask64 (cond : Bool) : BitVec 64 := + if cond then BitVec.ofInt 64 (-1) else 0#64 + +def bitwiseSelect64 (cond : Bool) (token value : BitVec 64) : BitVec 64 := + let sel := bitMask64 cond + (token &&& sel) ||| (value &&& ~~~sel) + +theorem bitMask64_true_eq_allOnes : BitVec.ofInt 64 (-1) = BitVec.allOnes 64 := by + decide + +theorem bitMask64_not_zero : ~~~(0#64) = BitVec.allOnes 64 := by + decide + +theorem bitwiseSelect64_eq_ite (cond : Bool) (token value : BitVec 64) : + bitwiseSelect64 cond token value = if cond then token else value := by + cases cond + · simp only [bitwiseSelect64, bitMask64, Bool.false_eq_true, ↓reduceIte, + bitMask64_not_zero, BitVec.and_zero, BitVec.and_allOnes, BitVec.zero_or] + · simp only [bitwiseSelect64, bitMask64, ↓reduceIte, + bitMask64_true_eq_allOnes, BitVec.not_allOnes, BitVec.and_allOnes, BitVec.and_zero, BitVec.or_zero] + +/-! ### 2. Extended Order with `-inf` & Tiled Reduction -/ + +inductive ExtInt where + | negInf + | finite (v : Int) + deriving DecidableEq, Repr + +def ExtInt.gt (a b : ExtInt) : Bool := + match a, b with + | .negInf, _ => false + | .finite _, .negInf => true + | .finite x, .finite y => decide (x > y) + +def ExtInt.ge (a b : ExtInt) : Bool := + match a, b with + | .negInf, .negInf => true + | .negInf, .finite _ => false + | .finite _, .negInf => true + | .finite x, .finite y => decide (x >= y) + +def countRange (p : Nat → Bool) : Nat → Nat + | 0 => 0 + | n + 1 => countRange p n + if p n then 1 else 0 + +def sumBlock (f : Nat → Nat) (start : Nat) : Nat → Nat + | 0 => 0 + | k + 1 => sumBlock f start k + f (start + k) + +def sumTiles (f : Nat → Nat) (blockSize : Nat) : Nat → Nat + | 0 => 0 + | b + 1 => sumTiles f blockSize b + sumBlock f (b * blockSize) blockSize + +theorem sumBlock_eq_count (p : Nat → Bool) (start k : Nat) : + sumBlock (fun idx => if p idx then 1 else 0) start k + countRange p start = + countRange p (start + k) := by + induction k with + | zero => simp [sumBlock] + | succ m ih => + simp only [sumBlock] + have hstep : start + (m + 1) = (start + m) + 1 := by omega + rw [hstep, countRange] + omega + +theorem sumTiles_eq_countRange (p : Nat → Bool) (blockSize numBlocks : Nat) : + sumTiles (fun idx => if p idx then 1 else 0) blockSize numBlocks = + countRange p (numBlocks * blockSize) := by + induction numBlocks with + | zero => simp [sumTiles, countRange] + | succ b ih => + simp only [sumTiles, ih] + have h := sumBlock_eq_count p (b * blockSize) blockSize + have hmul : (b + 1) * blockSize = b * blockSize + blockSize := by + rw [Nat.add_mul, Nat.one_mul] + rw [hmul] + omega + +theorem countRange_zero_tail (p : Nat → Bool) (n m : Nat) (hnm : n ≤ m) + (hzero : ∀ j, n ≤ j → j < m → p j = false) : + countRange p m = countRange p n := by + induction m with + | zero => + have : n = 0 := by omega + subst this; rfl + | succ k ih => + by_cases hnk : n ≤ k + · simp only [countRange] + have hf : p k = false := hzero k hnk (by omega) + rw [hf] + simp only [Bool.false_eq_true, ↓reduceIte, Nat.add_zero] + exact ih hnk (fun j hj1 hj2 => hzero j hj1 (by omega)) + · have : n = k + 1 := by omega + subst this; rfl + +/-! ### 3. Online Softmax IEEE-754 Abstract Domain (`(-inf) - (-inf) = NaN`) -/ + +inductive SumVal where + | zero + | pos + | posInf + | nan + deriving DecidableEq, Repr + +inductive MaxVal where + | negInf + | finite + deriving DecidableEq, Repr + +abbrev TileHasFinite := Bool + +def expDiff (a b : MaxVal) : SumVal := + match a, b with + | .negInf, .negInf => .nan + | .negInf, .finite => .zero + | .finite, .finite => .pos + | .finite, .negInf => .posInf + +def sumMul (x y : SumVal) : SumVal := + match x, y with + | .nan, _ => .nan + | _, .nan => .nan + | .zero, .posInf => .nan + | .posInf, .zero => .nan + | .zero, _ => .zero + | _, .zero => .zero + | .posInf, _ => .posInf + | _, .posInf => .posInf + | .pos, .pos => .pos + +def sumAdd (x y : SumVal) : SumVal := + match x, y with + | .nan, _ => .nan + | _, .nan => .nan + | .posInf, _ => .posInf + | _, .posInf => .posInf + | .zero, b => b + | a, .zero => a + | .pos, .pos => .pos + +structure OnlineState where + m : MaxVal := .negInf + s : SumVal := .zero + deriving DecidableEq, Repr + +def onlineStepBuggy (st : OnlineState) (tileFinite : TileHasFinite) : OnlineState := + let chunkMax : MaxVal := if tileFinite then .finite else .negInf + let newM : MaxVal := match st.m, chunkMax with + | .finite, _ => .finite + | _, .finite => .finite + | .negInf, .negInf => .negInf + let scale := expDiff st.m newM + let tileSum := expDiff chunkMax newM + { m := newM, s := sumAdd (sumMul st.s scale) tileSum } + +def onlineStepFixed (st : OnlineState) (tileFinite : TileHasFinite) : OnlineState := + let chunkMax : MaxVal := if tileFinite then .finite else .negInf + let newM : MaxVal := match st.m, chunkMax with + | .finite, _ => .finite + | _, .finite => .finite + | .negInf, .negInf => .negInf + let safeM : MaxVal := .finite + let scale := expDiff st.m safeM + let tileSum := expDiff chunkMax safeM + { m := newM, s := sumAdd (sumMul st.s scale) tileSum } + +def runOnline (step : OnlineState → TileHasFinite → OnlineState) + (st : OnlineState) (tiles : List TileHasFinite) : OnlineState := + tiles.foldl step st + +theorem runOnline_buggy_dense_safe (rest : List TileHasFinite) : + (runOnline onlineStepBuggy {} (true :: rest)).s = .pos := by + have hgen : ∀ (ts : List TileHasFinite) (st : OnlineState), + st.m = .finite → st.s = .pos → (runOnline onlineStepBuggy st ts).s = .pos := by + intro ts + induction ts with + | nil => intro st _ hs; exact hs + | cons b bs ih => + intro st hm hs + cases b + · exact ih _ (by simp [onlineStepBuggy, hm]) (by simp [onlineStepBuggy, hm, hs, expDiff, sumMul, sumAdd]) + · exact ih _ (by simp [onlineStepBuggy, hm]) (by simp [onlineStepBuggy, hm, hs, expDiff, sumMul, sumAdd]) + exact hgen rest (onlineStepBuggy {} true) rfl rfl + +theorem runOnline_fixed_invariant (tiles : List TileHasFinite) (st : OnlineState) + (hinv : (st.m = .negInf ∧ st.s = .zero) ∨ (st.m = .finite ∧ st.s = .pos)) : + let st' := runOnline onlineStepFixed st tiles + (tiles.any id = true → st'.m = .finite ∧ st'.s = .pos) ∧ + (st.m = .finite → st'.m = .finite ∧ st'.s = .pos) := by + induction tiles generalizing st with + | nil => + rcases hinv with ⟨hm, hs⟩ | ⟨hm, hs⟩ + · simp [runOnline, hm] + · simp [runOnline, hm, hs] + | cons b bs ih => + simp only [runOnline, List.foldl_cons, List.any_cons, Bool.or_eq_true, id_eq] + rcases hinv with ⟨hm, hs⟩ | ⟨hm, hs⟩ + · cases b + · have hstep : onlineStepFixed st false = { m := .negInf, s := .zero } := by + simp [onlineStepFixed, hm, hs, expDiff, sumMul, sumAdd] + rw [hstep] + have hrec := ih { m := .negInf, s := .zero } (Or.inl ⟨rfl, rfl⟩) + refine ⟨fun h => ?_, fun h => by simp [hm] at h⟩ + rcases h with hfalse | hany + · cases hfalse + · exact hrec.1 hany + · have hstep : onlineStepFixed st true = { m := .finite, s := .pos } := by + simp [onlineStepFixed, hm, hs, expDiff, sumMul, sumAdd] + rw [hstep] + have hrec := ih { m := .finite, s := .pos } (Or.inr ⟨rfl, rfl⟩) + exact ⟨fun _ => hrec.2 rfl, fun _ => hrec.2 rfl⟩ + · cases b + · have hstep : onlineStepFixed st false = { m := .finite, s := .pos } := by + simp [onlineStepFixed, hm, hs, expDiff, sumMul, sumAdd] + rw [hstep] + have hrec := ih { m := .finite, s := .pos } (Or.inr ⟨rfl, rfl⟩) + exact ⟨fun _ => hrec.2 rfl, fun _ => hrec.2 rfl⟩ + · have hstep : onlineStepFixed st true = { m := .finite, s := .pos } := by + simp [onlineStepFixed, hm, hs, expDiff, sumMul, sumAdd] + rw [hstep] + have hrec := ih { m := .finite, s := .pos } (Or.inr ⟨rfl, rfl⟩) + exact ⟨fun _ => hrec.2 rfl, fun _ => hrec.2 rfl⟩ + +/-! ### 4. Masked Load Padding Taint & Indexed Load Bounds -/ + +/-- Value with explicit uninitialized/undefined UB lane state (Triton `padding_option=""`). -/ +inductive LaneVal where + | val (v : Int) + | undef + deriving DecidableEq, Repr + +def laneMul (a b : LaneVal) : LaneVal := + match a, b with + | .val x, .val y => .val (x * y) + | _, _ => .undef + +def laneAdd (a b : LaneVal) : LaneVal := + match a, b with + | .val x, .val y => .val (x + y) + | _, _ => .undef + +/-- Inner product of length `bk` where lanes `j < k` are valid and `j ≥ k` are padded. -/ +def dotRow (f g : Nat → LaneVal) : Nat → LaneVal + | 0 => .val 0 + | n + 1 => laneAdd (dotRow f g n) (laneMul (f n) (g n)) + +/-- Pure mathematical inner product over valid indices `0 .. k-1`. -/ +def dotSpec (a b : Nat → Int) : Nat → Int + | 0 => 0 + | n + 1 => dotSpec a b n + a n * b n + +theorem dotRow_zero_padded (a b : Nat → Int) (k bk : Nat) (hkb : k ≤ bk) : + dotRow (fun j => if j < k then .val (a j) else .val 0) + (fun j => if j < k then .val (b j) else .val 0) bk = + .val (dotSpec a b k) := by + induction bk with + | zero => + have hk0 : k = 0 := by omega + subst hk0; rfl + | succ m ih => + by_cases hkm : k ≤ m + · simp only [dotRow] + rw [ih hkm] + have hnot : ¬ (m < k) := by omega + simp [hnot, laneMul, laneAdd] + · have hkeq : k = m + 1 := by omega + subst hkeq + simp only [dotRow] + have hprefix : + ∀ n, n ≤ m → + dotRow (fun j => if j < m + 1 then .val (a j) else .val 0) + (fun j => if j < m + 1 then .val (b j) else .val 0) n = + .val (dotSpec a b n) := by + intro n hn + induction n with + | zero => rfl + | succ r ihr => + simp only [dotRow, ihr (by omega)] + have hr : r < m + 1 := by omega + simp [hr, laneMul, laneAdd, dotSpec] + rw [hprefix m (Nat.le_refl m)] + simp [laneMul, laneAdd, dotSpec] + +theorem dotRow_undef_poisons (a b : Nat → Int) (k bk : Nat) (hlt : k < bk) : + dotRow (fun j => if j < k then .val (a j) else .undef) + (fun j => if j < k then .val (b j) else .undef) bk = .undef := by + induction bk with + | zero => omega + | succ m ih => + simp only [dotRow] + by_cases hkm : k < m + · rw [ih hkm] + cases (if m < k then LaneVal.val (a m) else LaneVal.undef) <;> + cases (if m < k then LaneVal.val (b m) else LaneVal.undef) <;> + rfl + · have hnot : ¬ (m < k) := by omega + simp only [hnot, ↓reduceIte, laneMul] + cases dotRow (fun j => if j < k then .val (a j) else .undef) + (fun j => if j < k then .val (b j) else .undef) m <;> rfl + +/-- Memory-access safety predicate for an indexed load `ptr[idx]` gated by `mask`. -/ +def indexedLoadSafe (bufLen : Nat) (idx : Int) (mask : Bool) : Prop := + mask = true → 0 ≤ idx ∧ idx < bufLen + +end AscendLean.TritonModel diff --git a/skills/operator-verify/lean_lib/AscendLean/UBModel.lean b/skills/operator-verify/lean_lib/AscendLean/UBModel.lean new file mode 100644 index 0000000..62dbaee --- /dev/null +++ b/skills/operator-verify/lean_lib/AscendLean/UBModel.lean @@ -0,0 +1,166 @@ +/- + AscendLean.UBModel + Formal Unified Buffer (UB) capacity, tiling, int32/int64 address bounds, + and AscendC packed vector mask model for Ascend A3 (192 KiB) and A5 / 950PR (248 KiB). +-/ + +namespace AscendLean.UBModel + +def A3_UB_BITS : Nat := 192 * 1024 * 8 +def A5_UB_BITS : Nat := 2031616 -- 248 KiB, exact compiler limit on Arch35 (A5) + +def INT32_MAX : Nat := 2147483647 -- 2^31 - 1 +def INT64_MAX : Nat := 9223372036854775807 -- 2^63 - 1 + +def ceilDiv (a b : Nat) : Nat := + if b = 0 then 0 else (a + b - 1) / b + +/-- Universal ceiling-division coverage bound: for any `b > 0`, `a ≤ ceilDiv a b * b`. -/ +theorem le_ceilDiv_mul (a b : Nat) (hb : 0 < b) : a ≤ ceilDiv a b * b := by + unfold ceilDiv + have hne : b ≠ 0 := by omega + simp only [hne, ↓reduceIte] + have hmod := Nat.div_add_mod (a + b - 1) b + have hlt := Nat.mod_lt (a + b - 1) hb + have hcomm : (a + b - 1) / b * b = b * ((a + b - 1) / b) := Nat.mul_comm _ _ + omega + +/-- Unbounded power-of-two ceiling `nextPow2 n`: smallest power of two `≥ n` (with `nextPow2 0 = 1`). -/ +def nextPow2Aux (n acc : Nat) : Nat → Nat + | 0 => acc + | fuel + 1 => if n ≤ acc then acc else nextPow2Aux n (2 * acc) fuel + +def nextPow2 (n : Nat) : Nat := + nextPow2Aux n 1 n + +private theorem mul_two_pow_succ (acc k : Nat) : + 2 * acc * 2 ^ k = acc * 2 ^ (k + 1) := by + rw [Nat.pow_succ, Nat.mul_comm 2 acc, Nat.mul_assoc, Nat.mul_comm 2 (2 ^ k), ← Nat.mul_assoc] + +private theorem nextPow2Aux_ge (n acc fuel : Nat) (h : n ≤ acc * 2 ^ fuel) : + n ≤ nextPow2Aux n acc fuel := by + induction fuel generalizing acc with + | zero => + simp only [nextPow2Aux, Nat.pow_zero, Nat.mul_one] at * + exact h + | succ k ih => + simp only [nextPow2Aux] + by_cases hna : n ≤ acc + · simp only [hna, ↓reduceIte] + · simp only [hna, ↓reduceIte] + apply ih + rw [mul_two_pow_succ] + exact h + +private theorem le_two_pow (n : Nat) : n ≤ 2 ^ n := by + induction n with + | zero => decide + | succ k ih => + rw [Nat.pow_succ] + have hpos : 1 ≤ 2 ^ k := Nat.one_le_two_pow + omega + +/-- Universal guarantee: `nextPow2 n ≥ n` for EVERY `n : Nat` (no silent clamp). -/ +theorem le_nextPow2 (n : Nat) : n ≤ nextPow2 n := by + unfold nextPow2 + apply nextPow2Aux_ge + simpa using le_two_pow n + +private theorem nextPow2Aux_le_pow2 (n acc bound fuel : Nat) + (hn : n ≤ bound) (hacc : acc ≤ bound) (hdbl : ∀ k, acc * 2 ^ k < bound → acc * 2 ^ (k + 1) ≤ bound) : + nextPow2Aux n acc fuel ≤ bound := by + induction fuel generalizing acc with + | zero => exact hacc + | succ k ih => + simp only [nextPow2Aux] + by_cases hna : n ≤ acc + · simp only [hna, ↓reduceIte]; exact hacc + · simp only [hna, ↓reduceIte] + have hlt : acc < bound := by omega + have h2le : 2 * acc ≤ bound := by + have := hdbl 0 (by simpa using hlt) + simpa [Nat.mul_comm] using this + apply ih (2 * acc) h2le + intro m hm + rw [mul_two_pow_succ] at hm + rw [mul_two_pow_succ] + exact hdbl (m + 1) hm + +private theorem pow2_step_le (p k : Nat) (hlt : 2 ^ k < 2 ^ p) : 2 ^ (k + 1) ≤ 2 ^ p := by + by_cases hkp : k < p + · exact Nat.pow_le_pow_right (by decide) hkp + · have hle : p ≤ k := Nat.le_of_not_lt hkp + have hpow : 2 ^ p ≤ 2 ^ k := Nat.pow_le_pow_right (by decide) hle + omega + +theorem nextPow2_le_pow2 (n p : Nat) (h : n ≤ 2 ^ p) : nextPow2 n ≤ 2 ^ p := by + unfold nextPow2 + apply nextPow2Aux_le_pow2 n 1 (2 ^ p) n h Nat.one_le_two_pow + intro k hk + simp only [Nat.one_mul] at hk ⊢ + exact pow2_step_le p k hk + +theorem nextPow2_le_4096 (n : Nat) (h : n ≤ 4096) : nextPow2 n ≤ 4096 := + nextPow2_le_pow2 n 12 h + +theorem nextPow2_le_8192 (n : Nat) (h : n ≤ 8192) : nextPow2 n ≤ 8192 := + nextPow2_le_pow2 n 13 h + +/-- Exact AscendC `UpdateMask(rem)` semantics for one 256-byte vector register. -/ +def updateMask (rem vl : Nat) : Nat × Nat := + let active := min rem vl + (active, rem - active) + +/-- Four consecutive packed stores sharing ONE counter `rem`. -/ +def stepPacked4Shared (rem vl : Nat) : Nat × Nat := + let (w0, r1) := updateMask rem vl + let (w1, r2) := updateMask r1 vl + let (w2, r3) := updateMask r2 vl + let (w3, r4) := updateMask r3 vl + (w0 + w1 + w2 + w3, r4) + +/-- Four consecutive packed stores with FOUR independent counters. -/ +def stepPacked4Indep (r0 r1 r2 r3 vl : Nat) : Nat × (Nat × Nat × Nat × Nat) := + let (w0, r0') := updateMask r0 vl + let (w1, r1') := updateMask r1 vl + let (w2, r2') := updateMask r2 vl + let (w3, r3') := updateMask r3 vl + (w0 + w1 + w2 + w3, (r0', r1', r2', r3')) + +theorem stepPacked4Shared_eq (rem vl : Nat) : + stepPacked4Shared rem vl = (min rem (4 * vl), rem - min rem (4 * vl)) := by + simp only [stepPacked4Shared, updateMask, Prod.mk.injEq] + omega + +def loopPacked4Shared (loops rem vl : Nat) : Nat := + match loops with + | 0 => 0 + | n + 1 => + let (w, rem') := stepPacked4Shared rem vl + w + loopPacked4Shared n rem' vl + +def loopPacked4Indep (loops r0 r1 r2 r3 vl : Nat) : Nat := + match loops with + | 0 => 0 + | n + 1 => + let (w, (r0', r1', r2', r3')) := stepPacked4Indep r0 r1 r2 r3 vl + w + loopPacked4Indep n r0' r1' r2' r3' vl + +theorem loopPacked4Shared_closed (loops rem vl : Nat) : + loopPacked4Shared loops rem vl = min rem (loops * (4 * vl)) := by + induction loops generalizing rem with + | zero => simp [loopPacked4Shared] + | succ n ih => + simp only [loopPacked4Shared, stepPacked4Shared_eq] + rw [ih] + have hmul : (n + 1) * (4 * vl) = 4 * vl + n * (4 * vl) := by + rw [Nat.add_mul, Nat.one_mul, Nat.add_comm] + omega + +theorem loopPacked4Shared_exact (curColNum vl : Nat) (hvl : 0 < vl) : + loopPacked4Shared (ceilDiv curColNum (4 * vl)) curColNum vl = curColNum := by + rw [loopPacked4Shared_closed] + have hge := le_ceilDiv_mul curColNum (4 * vl) (by omega) + omega + +end AscendLean.UBModel diff --git a/skills/operator-verify/lean_lib/README.md b/skills/operator-verify/lean_lib/README.md new file mode 100644 index 0000000..4974940 --- /dev/null +++ b/skills/operator-verify/lean_lib/README.md @@ -0,0 +1,28 @@ +# Formal model library (`lean_lib/`) + +This directory contains the reusable `AscendLean` Lean 4 library for offline accelerator operator verification (`leanprover/lean4:v4.36.0`, zero external dependencies). + +## Modules + +| Module | Scope | Key primitives | +|---|---|---| +| `AscendLean.PipeModel` | `pipeline_sync` | Ascend DaVinci async pipes (`PIPE_MTE2`, `PIPE_V`, `PIPE_MTE3`, `PIPE_S`), all 12 directed FIFO `HardEvent`s (`MTE3_MTE2`, `V_S`, `S_MTE2`, etc.), `runOps`, `VerifiedSafe` | +| `AscendLean.UBModel` | `resource_capacity`, `index_and_mask` | `A3_UB_BITS` (192 KiB), `A5_UB_BITS` (248 KiB = 2,031,616 bits), `INT32_MAX`, `INT64_MAX`, `nextPow2`, `le_ceilDiv_mul`, AscendC `updateMask` / 4-way packed stores | +| `AscendLean.TritonModel` | `semantic_equivalence`, `index_and_mask` | `BitVec 64` bitwise select, `ExtInt` tiled reductions, IEEE-754 online-softmax `(-inf) - (-inf) = NaN` abstract domain, masked-load `LaneVal` padding taint, `indexedLoadSafe` | + +## Build and check + +```bash +cd skills/operator-verify/lean_lib +lake build +``` + +Verify any external `.lean` target against this library via [lean_check.py](../scripts/lean_check.py): + +```bash +python3 skills/operator-verify/scripts/lean_check.py TARGET.lean \ + --project skills/operator-verify/lean_lib \ + --output result/verify//verify-report.json +``` + +Keep `.lake/` build caches untracked (ignored by the repository `.gitignore`). diff --git a/skills/operator-verify/lean_lib/lake-manifest.json b/skills/operator-verify/lean_lib/lake-manifest.json new file mode 100644 index 0000000..359711f --- /dev/null +++ b/skills/operator-verify/lean_lib/lake-manifest.json @@ -0,0 +1,6 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "AscendLean", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/skills/operator-verify/lean_lib/lakefile.toml b/skills/operator-verify/lean_lib/lakefile.toml new file mode 100644 index 0000000..a110587 --- /dev/null +++ b/skills/operator-verify/lean_lib/lakefile.toml @@ -0,0 +1,6 @@ +name = "AscendLean" +version = "0.1.0" +defaultTargets = ["AscendLean"] + +[[lean_lib]] +name = "AscendLean" diff --git a/skills/operator-verify/lean_lib/lean-toolchain b/skills/operator-verify/lean_lib/lean-toolchain new file mode 100644 index 0000000..00f8483 --- /dev/null +++ b/skills/operator-verify/lean_lib/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.36.0 diff --git a/skills/operator-verify/references/handoff.md b/skills/operator-verify/references/handoff.md new file mode 100644 index 0000000..2a03195 --- /dev/null +++ b/skills/operator-verify/references/handoff.md @@ -0,0 +1,88 @@ +# Verification handoff contracts + +`operator-verify` uses explicit JSON files under `result/verify//` (mirroring `result/optimize//` in `operator-optimize`) so standalone runs, source extractors, and NumericBridge workflows stay decoupled. + +## Input: `verify-request.json` + +Written by `triage.py` (standalone) or derived from `result/optimize//handoff.json`. + +| Field | Content | +|---|---| +| `schema_version` | Integer schema version (currently `1`) | +| `mode` | `standalone`, `numericbridge_companion`, or `repo_audit` | +| `target` | Operator name, backend (`triton-ascend`, `ascendc`, `triton`, `cuda`, `unknown`), source path, source SHA-256, and optional `call_site` | +| `category` | `index_and_mask`, `resource_capacity`, `pipeline_sync`, `semantic_equivalence`, or `numeric_rounding` | +| `eligibility` | `lean_only`, `model_calibration`, or `out_of_scope_numeric` | +| `route` | Target skill: `operator-verify` or `precision-compare` | +| `claim_kind` | `refutation` (buggy counterexample), `universal_proof` (fixed invariant), or `equivalence` | +| `upstream_handoff` | Optional path to `result/optimize//handoff.json` | +| `upstream_issue` | Optional upstream issue metadata propagated from `handoff.json` | +| `model_modules` | Recommended Lean library modules (e.g., `AscendLean.UBModel`, `AscendLean.PipeModel`, `AscendLean.TritonModel`) | + +## Static Audit Output: `audit-findings.json` + +Written by `audit_scan.py` in `repo_audit` mode before triaging individual findings into `verify-request.json`. + +| Field | Content | +|---|---| +| `schema_version` | Integer schema version (currently `1`) | +| `scanned_files` | Count of Triton-Ascend (`.py`) and AscendC (`.h`/`.hpp`/`.cpp`/`.cc`/`.asc`) files scanned | +| `finding_count` | Total candidate findings discovered | +| `by_category` | Map of semantic category (`index_and_mask`, `resource_capacity`, `pipeline_sync`, `semantic_equivalence`) to finding count | +| `findings` | List of candidate records `{rule_id, category, backend, file, sha256, line, symbol, summary, model_modules}` | + +## Output: `verify-report.json` + +Written by `lean_check.py` to `result/verify//verify-report.json` (or `--output`). + +| Field | Content | +|---|---| +| `schema_version` | Integer schema version (currently `1`) | +| `status` | `passed`, `failed`, `audit_failed`, or `toolchain_missing` | +| `verdict` | `proved`, `refuted`, `passed_unclassified`, `inconclusive`, or `not_run` | +| `claim_kind` | `universal_proof`, `refutation`, `equivalence`, or `unspecified` | +| `project` | Resolved Lake project directory path (or `null` for standalone `lean`) | +| `toolchain` | Recorded `lean --version`, `lake --version`, and `lean-toolchain` pin when present | +| `sources` | List of `{role, path, sha256}` for the Lean target and optional kernel source files | +| `audit` | Static + compiler check summary: `sorry_count`, `admit_count`, `custom_axioms`, `unsafe_escapes`, `has_theorems`, `compiler_sorry_warning`, `clean` | +| `theorems` | Declared `theorem` / `lemma` names discovered in the verified Lean target (must be non-empty for `passed`) | +| `preconditions` | Explicit or discovered preconditions required for the proved invariant to hold (e.g., `at least one finite logit`, `len >= 1`) | +| `tcb_assumptions` | Explicit hardware/modeling assumptions required to interpret the result | +| `counterexample` | Optional structured witness (`--counterexample`) when `verdict == "refuted"` | +| `command` | Exact command argv, exit code, duration in seconds, and output tails | + +Example `verify-report.json`: + +```json +{ + "schema_version": 1, + "status": "passed", + "verdict": "proved", + "claim_kind": "universal_proof", + "toolchain": { + "lean_version": "Lean (version 4.36.0)", + "lean_toolchain": "leanprover/lean4:v4.36.0" + }, + "sources": [ + {"role": "lean_target", "path": "Case3_TritonUB_Fixed.lean", "sha256": ""} + ], + "audit": { + "sorry_count": 0, + "admit_count": 0, + "custom_axioms": [], + "unsafe_escapes": [], + "has_theorems": true, + "compiler_sorry_warning": false, + "clean": true + }, + "theorems": ["fixed_safe_all_hidden"], + "preconditions": ["1 <= hidden_size <= 8192"], + "tcb_assumptions": ["A5 UB limit = 2031616 bits (248 KiB)"], + "counterexample": null, + "command": { + "argv": ["lake", "env", "lean", "Case3_TritonUB_Fixed.lean"], + "exit_code": 0, + "duration_sec": 0.42 + } +} +``` diff --git a/skills/operator-verify/references/taxonomy.md b/skills/operator-verify/references/taxonomy.md new file mode 100644 index 0000000..e0636ea --- /dev/null +++ b/skills/operator-verify/references/taxonomy.md @@ -0,0 +1,17 @@ +# Verification taxonomy + +Classify each operator issue by **why dynamic numerical testing misses it**, using self-explanatory `snake_case` category labels consistent with NumericBridge diagnosis and optimization records. + +| Category | Typical accelerator mechanism | Why numerical tests miss it | Eligibility | Route | +|---|---|---|---|---| +| `index_and_mask` | Tiling tail out-of-bounds, padding contamination, `int32` overflow/truncation, shared vs independent mask counters | Unit tests mostly cover aligned, divisible, or power-of-2 shapes where tail branches never fire | `lean_only` | `operator-verify` | +| `resource_capacity` | On-chip Unified Buffer / SRAM overflow (including auto multi-buffering doubling), 32B alignment violations | Small and power-of-2 shapes fit; large or non-power-of-2 hidden sizes overflow on-chip memory | `lean_only` | `operator-verify` | +| `pipeline_sync` | Missing `SetFlag`/`WaitFlag` across Cube/Vector/MTE pipes, UB read/write races, deadlocks, leaked event tokens | Timing-dependent, architecture-dependent (passes on A3, fails on A5), or masked by single-head tests | `model_calibration` | `operator-verify` | +| `semantic_equivalence` | Fused kernels, `torch.compile` lowering mismatches, bit-level workarounds (`BitVec 64` select), tiled reductions, qualitative IEEE-754 special-value (`±inf` / `NaN`) propagation & poisoning (e.g., online softmax `(-inf) - (-inf) = NaN`), hidden preconditions | Fusion introduces small FP drift so loose tolerances hide logic bugs; dense random tests (`randn`) never trigger masked `-inf` leading tiles or tie/edge preconditions | `lean_only` | `operator-verify` | +| `numeric_rounding` | Quantitative BF16/FP16 accumulation order, transcendental rounding tolerance (ULP/RMSE), cross-stack FP drift | Directly measurable against FP64 on captured operands | `out_of_scope_numeric` | `precision-compare` / `operator-optimize` | + +## Eligibility states + +- `lean_only`: Self-contained discrete arithmetic, bit-vector, mask, or capacity property requiring no hardware timing calibration. +- `model_calibration`: Requires an explicit hardware execution model (such as DaVinci pipeline FIFO event ordering) documented in [TCB](tcb.md). +- `out_of_scope_numeric`: Pure floating-point rounding accuracy or unformalized numerical behavior; handled by dynamic NumericBridge tracks. diff --git a/skills/operator-verify/references/tcb.md b/skills/operator-verify/references/tcb.md new file mode 100644 index 0000000..9469840 --- /dev/null +++ b/skills/operator-verify/references/tcb.md @@ -0,0 +1,17 @@ +# Trusted Computing Base (TCB) and modeling boundaries + +Every `verify-report.json` must distinguish what is mechanically checked by the Lean 4 kernel from what remains an explicit modeling assumption. + +## Mechanically verified (inside the Lean kernel) + +- Logical soundness of all theorems and counterexample witnesses in the verified `.lean` target, audited for zero `sorry`, zero `admit`, and zero unapproved custom `axiom` declarations. +- Universal quantification over symbolic parameters (e.g., arbitrary `Nat` dimensions, `BitVec 64` inputs, arbitrary loop/chunk counts) within the formalized model. + +## Explicit modeling assumptions (outside the Lean kernel) + +1. **Source-to-Lean abstraction gap.** Until a certified compiler frontend exists, mapping from Triton Python AST or Ascend C C++ source into Lean 4 expressions is part of the TCB. Record the exact source path, SHA-256 digest, and extractor version. +2. **Hardware constants and execution semantics.** + - Unified Buffer limits (e.g., Ascend A3 `192 KiB`, Ascend A5 / 950PR `248 KiB = 2,031,616 bits`) reflect documented compiler limits for the named architecture. + - DaVinci pipeline synchronization models (`PIPE_MTE2`, `PIPE_V`, `PIPE_MTE3`, `HardEvent` FIFO queues) abstract hardware ordering at buffer/event granularity rather than cycle-accurate microarchitecture. + - Vector register widths (e.g., 256-byte register = 64 `float32` lanes) match the targeted AscendC ISA. +3. **Numerical boundary.** Discrete bit-vector, integer, or extended-order models do **not** establish floating-point rounding accuracy; pair with `precision-compare` or `operator-optimize` (`kernel_check.py`) whenever floating-point precision matters. diff --git a/skills/operator-verify/scripts/audit_scan.py b/skills/operator-verify/scripts/audit_scan.py new file mode 100644 index 0000000..d270d5c --- /dev/null +++ b/skills/operator-verify/scripts/audit_scan.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +"""Statically audit Triton-Ascend (.py) and AscendC (.h/.hpp/.cpp/.asc) kernels for discrete verification candidates. + +Call: scan_path(path); CLI: python scripts/audit_scan.py PATH [PATH ...] [--output findings.json] +Input: one or more kernel source files or directories (Triton Python and/or AscendC C++). +Output: schema_version=1 JSON report listing candidate defects mapped to operator-verify categories +(`index_and_mask`, `resource_capacity`, `pipeline_sync`, `semantic_equivalence`) for triage and Lean 4 verification. +Requires: Python standard library only. +""" +__all__ = ['scan_file', 'scan_path', 'RULES'] + +import argparse +import ast +from collections import Counter +import hashlib +import json +from pathlib import Path +import re +import sys + + +RULES = { + 'online_softmax_neginf': { + 'category': 'semantic_equivalence', + 'backend': 'triton-ascend', + 'model_modules': ['AscendLean.TritonModel'], + }, + 'block_ptr_unpadded_load': { + 'category': 'index_and_mask', + 'backend': 'triton-ascend', + 'model_modules': ['AscendLean.TritonModel'], + }, + 'masked_load_missing_other': { + 'category': 'index_and_mask', + 'backend': 'triton-ascend', + 'model_modules': ['AscendLean.TritonModel'], + }, + 'unmasked_mapping_index_load': { + 'category': 'index_and_mask', + 'backend': 'triton-ascend', + 'model_modules': ['AscendLean.TritonModel'], + }, + 'int32_pointer_mul_overflow': { + 'category': 'index_and_mask', + 'backend': 'triton-ascend', + 'model_modules': ['AscendLean.UBModel'], + }, + 'hardcoded_multibuffer_np2': { + 'category': 'resource_capacity', + 'backend': 'triton-ascend', + 'model_modules': ['AscendLean.UBModel'], + }, + 'ascendc_hardevent_imbalance': { + 'category': 'pipeline_sync', + 'backend': 'ascendc', + 'model_modules': ['AscendLean.PipeModel'], + }, +} + +_TRITON_EXTS = {'.py'} +_ASCENDC_EXTS = {'.h', '.hpp', '.cpp', '.cc', '.asc'} +_NEGINF_RE = re.compile(r"(?:float\(\s*['\"]-inf['\"]\s*\)|-\s*float\(\s*['\"]inf['\"]\s*\))") + + +def _sha256(path): + digest = hashlib.sha256() + with Path(path).open('rb') as handle: + for chunk in iter(lambda: handle.read(65536), b''): + digest.update(chunk) + return digest.hexdigest() + + +def _is_triton_jit(fn): + for dec in fn.decorator_list: + target = dec.func if isinstance(dec, ast.Call) else dec + text = ast.unparse(target) + if text == 'jit' or text.endswith('.jit'): + return True + return False + + +def _has_autotune_multibuffer(fn): + for dec in fn.decorator_list: + text = ast.unparse(dec) + if 'autotune' in text and 'multibuffer' in text: + return True + return False + + +def _make_finding(path, file_hash, rule_id, line, symbol, summary): + meta = RULES[rule_id] + return { + 'rule_id': rule_id, + 'category': meta['category'], + 'backend': meta['backend'], + 'file': str(path), + 'sha256': file_hash, + 'line': line, + 'symbol': symbol, + 'summary': summary, + 'model_modules': list(meta['model_modules']), + } + + +def _count_mul_ops(expr): + return sum(1 for n in ast.walk(expr) if isinstance(n, ast.BinOp) and isinstance(n.op, ast.Mult)) + + +def _is_int64_cast(expr): + return ( + isinstance(expr, ast.Call) + and isinstance(expr.func, ast.Attribute) + and expr.func.attr == 'to' + and any('int64' in ast.unparse(a) for a in expr.args) + ) + + +def _is_tl_load(expr): + return isinstance(expr, ast.Call) and ast.unparse(expr.func) == 'tl.load' + + +def _strip_cpp_comments(text): + text = re.sub(r'/\*.*?\*/', lambda m: '\n' * m.group(0).count('\n'), text, flags=re.S) + text = re.sub(r'//[^\n]*', '', text) + return text + + +def _scan_triton_python(path, text, file_hash): + findings = [] + try: + tree = ast.parse(text) + except SyntaxError: + return findings + + jit_fns = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and _is_triton_jit(n)] + if not jit_fns: + return findings + + for fn in jit_fns: + fn_src = ast.unparse(fn) + has_reduction = any(tok in fn_src for tok in ('tl.sum(', 'tl.dot(', 'tl.max(', 'tl.min(')) + + # 1. Online softmax (-inf) - (-inf) = NaN poisoning: + # Track variables explicitly initialized to -inf (not finite sinks or tl.where masked scores). + neginf_vars = set() + for node in ast.walk(fn): + if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): + val_s = ast.unparse(node.value) + if _NEGINF_RE.search(val_s) and 'tl.where(' not in val_s: + neginf_vars.add(node.targets[0].id) + + has_safe_m_guard = False + for node in ast.walk(fn): + if isinstance(node, ast.Call) and ast.unparse(node.func) == 'tl.where' and len(node.args) >= 3: + cond_s = ast.unparse(node.args[0]) + if _NEGINF_RE.search(cond_s) and any(op in cond_s for op in ('>', '!=', '==')): + has_safe_m_guard = True + break + + if neginf_vars and not has_safe_m_guard: + for node in ast.walk(fn): + if isinstance(node, ast.For): + loop_s = ast.unparse(node) + if 'tl.maximum(' not in loop_s or 'tl.exp(' not in loop_s: + continue + flagged_line = None + for call in ast.walk(node): + if isinstance(call, ast.Call) and ast.unparse(call.func) == 'tl.exp' and call.args: + arg_s = ast.unparse(call.args[0]) + if '-' in arg_s and any(re.search(rf'\b{re.escape(v)}\b', arg_s) for v in neginf_vars): + flagged_line = call.lineno + break + if flagged_line is not None: + findings.append(_make_finding( + path, file_hash, 'online_softmax_neginf', flagged_line, fn.name, + 'Online softmax loop initializes running max to -inf and evaluates tl.exp(m - new_m) ' + 'without guarding new_m == -inf; leading all-(-inf) tiles trigger (-inf) - (-inf) = NaN.', + )) + break + + # 2. tl.load(block_ptr, boundary_check=...) without padding_option="zero" + # 3. tl.load(..., mask=...) without other= in a kernel with reductions + # 4. Unmasked indexed load using a request mapping variable (can be -1 in padded graph rows) + mapping_vars = set() + for node in ast.walk(fn): + if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): + val_s = ast.unparse(node.value) + if 'tl.load(' in val_s and 'mapping' in val_s.lower(): + mapping_vars.add(node.targets[0].id) + + for node in ast.walk(fn): + if not (isinstance(node, ast.Call) and ast.unparse(node.func) == 'tl.load'): + continue + kw_names = {kw.arg: ast.unparse(kw.value) for kw in node.keywords if kw.arg} + arg0 = ast.unparse(node.args[0]) if node.args else '' + + if 'boundary_check' in kw_names: + pad_opt = kw_names.get('padding_option', '') + if 'zero' not in pad_opt: + findings.append(_make_finding( + path, file_hash, 'block_ptr_unpadded_load', node.lineno, fn.name, + 'tl.load with boundary_check omits padding_option="zero"; ' + 'out-of-bounds lanes retain undefined UB garbage.', + )) + + has_mask = 'mask' in kw_names or len(node.args) >= 2 + has_other = 'other' in kw_names or len(node.args) >= 3 + if has_mask and not has_other and has_reduction: + findings.append(_make_finding( + path, file_hash, 'masked_load_missing_other', node.lineno, fn.name, + 'Masked tl.load omits explicit `other=` fill value inside a kernel with reductions; ' + 'uninitialized UB padding lanes can contaminate tl.sum/tl.dot.', + )) + + if not has_mask and mapping_vars: + for mv in mapping_vars: + if re.search(rf'\+\s*{re.escape(mv)}\b', arg0): + findings.append(_make_finding( + path, file_hash, 'unmasked_mapping_index_load', node.lineno, fn.name, + f'Unmasked tl.load indexed by mapping variable `{mv}` without `{mv} >= 0` guard; ' + 'padded graph rows with sentinel -1 perform out-of-bounds negative-offset loads.', + )) + break + + # 5. Potential int32 pointer offset overflow: + # (a) `(a * b * c).to(tl.int64)` where widening occurs AFTER int32 multiplications, OR + # (b) multi-factor offset expression (>=3 `*`) with no inner int64 cast. + int64_vars = set() + for node in ast.walk(fn): + if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): + if 'int64' in ast.unparse(node.value): + int64_vars.add(node.targets[0].id) + + for node in ast.walk(fn): + val = None + tgt = None + if isinstance(node, ast.AugAssign) and isinstance(node.op, ast.Add) and isinstance(node.target, ast.Name): + tgt = node.target.id + val = node.value + elif isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): + tgt = node.targets[0].id + val = node.value + if val is None or tgt is None: + continue + + if _is_int64_cast(val) and isinstance(val.func, ast.Attribute): + inner = val.func.value + inner_s = ast.unparse(inner) + if not _is_tl_load(inner) and _count_mul_ops(inner) >= 2 and 'int64' not in inner_s: + if not any(re.search(rf'\b{re.escape(v)}\b', inner_s) for v in int64_vars): + findings.append(_make_finding( + path, file_hash, 'int32_pointer_mul_overflow', node.lineno, fn.name, + f'Offset `{tgt}` widens to int64 AFTER int32 multiplication (`{ast.unparse(val)}`); ' + 'product can overflow signed int32 before .to(tl.int64).', + )) + elif 'offset' in tgt.lower(): + val_s = ast.unparse(val) + if _count_mul_ops(val) >= 3 and 'int64' not in val_s: + if not any(re.search(rf'\b{re.escape(v)}\b', val_s) for v in int64_vars): + findings.append(_make_finding( + path, file_hash, 'int32_pointer_mul_overflow', node.lineno, fn.name, + f'Multi-factor pointer offset `{tgt} = {val_s}` computed without int64 cast; ' + 'can overflow signed int32 (2^31 - 1) on long-context or large-batch workloads.', + )) + + # 6. Hardcoded multibuffer=True with next_power_of_2 and no @triton.autotune + if 'multibuffer=True' in text and 'next_power_of_2' in text: + if not any(_has_autotune_multibuffer(fn) for fn in jit_fns): + line_no = next((i for i, l in enumerate(text.splitlines(), 1) if 'multibuffer=True' in l), 1) + findings.append(_make_finding( + path, file_hash, 'hardcoded_multibuffer_np2', line_no, jit_fns[0].name, + 'Kernel launch hardcodes multibuffer=True with next_power_of_2 tiling and no multibuffer autotune; ' + 'large/non-power-of-2 shapes risk Ascend UB overflow.', + )) + + return findings + + +def _scan_ascendc(path, text, file_hash): + findings = [] + cleaned = _strip_cpp_comments(text) + sets = Counter(re.findall(r'SetFlag<(?:AscendC::)?HardEvent::([A-Z0-9_]+)>', cleaned)) + waits = Counter(re.findall(r'WaitFlag<(?:AscendC::)?HardEvent::([A-Z0-9_]+)>', cleaned)) + for ev in sorted(set(sets) | set(waits)): + if sets[ev] != waits[ev]: + m = re.search(rf'(?:Set|Wait)Flag<(?:AscendC::)?HardEvent::{ev}>', cleaned) + line_no = cleaned[:m.start()].count('\n') + 1 if m else 1 + findings.append(_make_finding( + path, file_hash, 'ascendc_hardevent_imbalance', line_no, ev, + f'Static SetFlag/WaitFlag count mismatch for HardEvent::{ev} ' + f'(SetFlag={sets[ev]}, WaitFlag={waits[ev]}); requires control-flow sync verification.', + )) + return findings + + +def scan_file(path): + """Scan one Triton-Ascend or AscendC source file and return candidate findings.""" + p = Path(path).resolve() + if not p.is_file(): + raise FileNotFoundError(f'source file not found: {path}') + suffix = p.suffix.lower() + if suffix not in _TRITON_EXTS and suffix not in _ASCENDC_EXTS: + return [] + text = p.read_text(encoding='utf-8', errors='replace') + file_hash = _sha256(p) + if suffix in _TRITON_EXTS: + return _scan_triton_python(p, text, file_hash) + return _scan_ascendc(p, text, file_hash) + + +def scan_path(paths): + """Scan one or more files or directories and return a schema_version=1 audit report.""" + findings = [] + scanned_files = 0 + for raw in paths: + p = Path(raw).resolve() + if p.is_file(): + scanned_files += 1 + findings.extend(scan_file(p)) + elif p.is_dir(): + for child in sorted(p.rglob('*')): + if child.is_file() and child.suffix.lower() in (_TRITON_EXTS | _ASCENDC_EXTS): + if '.lake' in child.parts or '__pycache__' in child.parts: + continue + scanned_files += 1 + findings.extend(scan_file(child)) + else: + raise FileNotFoundError(f'path not found: {raw}') + + by_category = Counter(f['category'] for f in findings) + return { + 'schema_version': 1, + 'scanned_files': scanned_files, + 'finding_count': len(findings), + 'by_category': dict(sorted(by_category.items())), + 'findings': findings, + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('paths', nargs='+', type=Path, help='Kernel source files or directories to audit') + parser.add_argument('--output', type=Path, help='Write audit-findings.json to this path (else print JSON)') + args = parser.parse_args(argv) + + try: + report = scan_path(args.paths) + except OSError as exc: + print(f'error: {exc}', file=sys.stderr) + return 2 + + rendered = json.dumps(report, indent=2, ensure_ascii=False) + '\n' + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(rendered, encoding='utf-8') + else: + sys.stdout.write(rendered) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/skills/operator-verify/scripts/lean_check.py b/skills/operator-verify/scripts/lean_check.py new file mode 100644 index 0000000..88866c4 --- /dev/null +++ b/skills/operator-verify/scripts/lean_check.py @@ -0,0 +1,321 @@ +#!/usr/bin/env python3 +"""Type-check a Lean 4 verification file, audit sorry/axioms, and emit verify-report.json. + +Call: check_lean(target, ...); CLI: python scripts/lean_check.py TARGET.lean [--project DIR] [--output verify-report.json] +Input: a Lean 4 target file, optional Lake project root, optional kernel source files for SHA-256 provenance, +claim kind, preconditions, optional counterexample summary, and explicit TCB assumptions. +Output: verify-report.json with toolchain identity, file hashes, theorem list, sorry/admit/axiom/escape audit, +compiler status, and verdict (proved | refuted | passed_unclassified | inconclusive | not_run). +Exit codes: 0=passed, 1=failed or audit_failed, 2=input error, 3=toolchain_missing. +Requires: Python standard library only (invokes host `lake`/`lean` if available). +""" +__all__ = ['audit_lean_source', 'strip_lean_comments', 'check_lean'] + +import argparse +import hashlib +import json +from pathlib import Path +import re +import shutil +import subprocess +import sys +import time + + +_THEOREM_RE = re.compile(r'^\s*(?:(?:protected|noncomputable)\s+)*(?:theorem|lemma)\s+([A-Za-z0-9_.\']+)', re.M) +_AXIOM_RE = re.compile(r'\baxiom\s+([A-Za-z0-9_.\']+)') +_SORRY_RE = re.compile(r'\b(?:sorry|sorryAx)\b') +_ADMIT_RE = re.compile(r'\badmit\b') +_UNSAFE_ESCAPE_RE = re.compile( + r'\b(?:native_decide|unsafe|opaque|implemented_by|extern|ofReduceBool|ofReduceNat|trustCompiler)\b' + r'|@\[[^\]]*\b(?:implemented_by|extern)\b' +) +_COMPILER_SORRY_RE = re.compile(r"declaration uses ['`]?sorry(?:Ax)?['`]?", re.I) + + +def _sha256(path): + digest = hashlib.sha256() + with Path(path).open('rb') as handle: + for chunk in iter(lambda: handle.read(65536), b''): + digest.update(chunk) + return digest.hexdigest() + + +def strip_lean_comments(text): + """Remove Lean 4 line comments (`--`), nested block comments (`/- ... -/`), string literals, and char literals.""" + out = [] + i = 0 + n = len(text) + block_depth = 0 + in_string = False + while i < n: + ch = text[i] + nxt = text[i + 1] if i + 1 < n else '' + if block_depth > 0: + if ch == '/' and nxt == '-': + block_depth += 1 + i += 2 + elif ch == '-' and nxt == '/': + block_depth -= 1 + i += 2 + else: + if ch == '\n': + out.append('\n') + i += 1 + continue + if in_string: + if ch == '\\' and i + 1 < n: + i += 2 + elif ch == '"': + in_string = False + i += 1 + else: + if ch == '\n': + out.append('\n') + i += 1 + continue + if ch == '/' and nxt == '-': + block_depth = 1 + i += 2 + continue + if ch == '-' and nxt == '-': + while i < n and text[i] != '\n': + i += 1 + continue + # Handle Lean char literals like '"' or '\'' so `'"'` never opens a string literal. + # Avoid consuming identifier prime suffixes like `x'` by checking previous char is not ident-part. + if ch == "'": + prev = text[i - 1] if i > 0 else ' ' + if not (prev.isalnum() or prev in ('_', "'")): + if i + 2 < n and text[i + 1] != '\\' and text[i + 1] != '\n' and text[i + 2] == "'": + out.append("''") + i += 3 + continue + if i + 3 < n and text[i + 1] == '\\' and text[i + 3] == "'": + out.append("''") + i += 4 + continue + if ch == '"': + in_string = True + out.append('""') + i += 1 + continue + out.append(ch) + i += 1 + return ''.join(out) + + +def audit_lean_source(text): + """Scan comment-stripped Lean source for theorems, sorry/admit/escape tokens, and custom axioms.""" + cleaned = strip_lean_comments(text) + theorems = _THEOREM_RE.findall(cleaned) + custom_axioms = _AXIOM_RE.findall(cleaned) + sorry_count = len(_SORRY_RE.findall(cleaned)) + admit_count = len(_ADMIT_RE.findall(cleaned)) + unsafe_escapes = sorted(set(_UNSAFE_ESCAPE_RE.findall(cleaned))) + no_theorems = len(theorems) == 0 + clean = ( + sorry_count == 0 + and admit_count == 0 + and not custom_axioms + and not unsafe_escapes + and not no_theorems + ) + return { + 'theorems': theorems, + 'audit': { + 'sorry_count': sorry_count, + 'admit_count': admit_count, + 'custom_axioms': custom_axioms, + 'unsafe_escapes': unsafe_escapes, + 'has_theorems': not no_theorems, + 'compiler_sorry_warning': False, + 'clean': clean, + }, + } + + +def _find_lake_project(target_path, explicit_project=None): + if explicit_project is not None: + return Path(explicit_project).resolve() + for parent in Path(target_path).resolve().parents: + if (parent / 'lakefile.toml').is_file() or (parent / 'lakefile.lean').is_file(): + return parent + return None + + +def _probe_version(binary): + if not binary: + return None + try: + proc = subprocess.run([binary, '--version'], capture_output=True, text=True, timeout=15) + if proc.returncode == 0: + return proc.stdout.strip().splitlines()[0] if proc.stdout.strip() else '' + except (OSError, subprocess.SubprocessError): + return None + return None + + +def check_lean(target, project=None, build_lib=False, kernel_sources=None, + claim_kind='unspecified', preconditions=None, tcb_assumptions=None, + counterexample=None, timeout=120): + """Run static audit and Lean 4 type-checking, returning a schema_version=1 verify-report dict.""" + target_path = Path(target).resolve() + if not target_path.is_file(): + raise FileNotFoundError(f'Lean target not found: {target}') + + text = target_path.read_text(encoding='utf-8') + scan = audit_lean_source(text) + project_dir = _find_lake_project(target_path, project) + + sources = [{'role': 'lean_target', 'path': str(target_path), 'sha256': _sha256(target_path)}] + for src in (kernel_sources or []): + src_path = Path(src).resolve() + if not src_path.is_file(): + raise FileNotFoundError(f'kernel source not found: {src}') + sources.append({'role': 'kernel_source', 'path': str(src_path), 'sha256': _sha256(src_path)}) + + lake_bin = shutil.which('lake') + lean_bin = shutil.which('lean') + toolchain_file = (project_dir / 'lean-toolchain') if project_dir is not None else None + toolchain_pin = ( + toolchain_file.read_text(encoding='utf-8').strip() + if toolchain_file is not None and toolchain_file.is_file() + else None + ) + toolchain = { + 'lean_version': _probe_version(lean_bin), + 'lake_version': _probe_version(lake_bin), + 'lean_toolchain': toolchain_pin, + } + + base_report = { + 'schema_version': 1, + 'claim_kind': claim_kind, + 'project': str(project_dir) if project_dir is not None else None, + 'toolchain': toolchain, + 'sources': sources, + 'audit': dict(scan['audit']), + 'theorems': scan['theorems'], + 'preconditions': list(preconditions or []), + 'tcb_assumptions': list(tcb_assumptions or []), + 'counterexample': counterexample, + } + + use_lake = project_dir is not None + if (use_lake and not lake_bin) or (not use_lake and not lean_bin): + return { + **base_report, + 'status': 'toolchain_missing', + 'verdict': 'not_run', + 'command': None, + } + + t0 = time.monotonic() + cwd = project_dir if project_dir is not None else target_path.parent + if build_lib and use_lake: + build_proc = subprocess.run([lake_bin, 'build'], cwd=cwd, capture_output=True, text=True, timeout=timeout) + if build_proc.returncode != 0: + return { + **base_report, + 'status': 'failed', + 'verdict': 'inconclusive', + 'command': { + 'argv': ['lake', 'build'], + 'exit_code': build_proc.returncode, + 'duration_sec': round(time.monotonic() - t0, 3), + 'stdout_tail': build_proc.stdout.strip()[-2000:], + 'stderr_tail': build_proc.stderr.strip()[-2000:], + }, + } + + cmd = [lake_bin, 'env', 'lean', str(target_path)] if use_lake else [lean_bin, str(target_path)] + display_cmd = ['lake', 'env', 'lean', str(target_path)] if use_lake else ['lean', str(target_path)] + proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout) + duration = round(time.monotonic() - t0, 3) + + combined_output = f'{proc.stdout}\n{proc.stderr}' + compiler_sorry = bool(_COMPILER_SORRY_RE.search(combined_output)) + audit = dict(scan['audit']) + audit['compiler_sorry_warning'] = compiler_sorry + audit['clean'] = audit['clean'] and not compiler_sorry + base_report['audit'] = audit + + if proc.returncode != 0: + status = 'failed' + verdict = 'inconclusive' + elif not audit['clean']: + status = 'audit_failed' + verdict = 'inconclusive' + else: + status = 'passed' + if claim_kind == 'refutation': + verdict = 'refuted' + elif claim_kind in ('universal_proof', 'equivalence'): + verdict = 'proved' + else: + verdict = 'passed_unclassified' + + return { + **base_report, + 'status': status, + 'verdict': verdict, + 'command': { + 'argv': display_cmd, + 'exit_code': proc.returncode, + 'duration_sec': duration, + 'stdout_tail': proc.stdout.strip()[-2000:], + 'stderr_tail': proc.stderr.strip()[-2000:], + }, + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('target', type=Path, help='Path to the Lean 4 (.lean) file to verify') + parser.add_argument('--project', type=Path, help='Lake project directory (auto-detected from ancestors if omitted)') + parser.add_argument('--build-lib', action='store_true', help='Run `lake build` before checking the target file') + parser.add_argument('--source', action='append', default=[], type=Path, + help='Kernel source file to hash for provenance (repeatable)') + parser.add_argument('--claim-kind', default='unspecified', + choices=('universal_proof', 'refutation', 'equivalence', 'unspecified')) + parser.add_argument('--precondition', action='append', default=[], + help='Required or discovered precondition for the proved invariant (repeatable)') + parser.add_argument('--tcb', action='append', default=[], help='Explicit TCB modeling assumption (repeatable)') + parser.add_argument('--counterexample', help='Short witness/counterexample description for refutation claims') + parser.add_argument('--timeout', type=int, default=120, help='Subprocess timeout in seconds (default: 120)') + parser.add_argument('--output', type=Path, help='Write verify-report.json to this path (else print JSON)') + args = parser.parse_args(argv) + + try: + report = check_lean( + target=args.target, + project=args.project, + build_lib=args.build_lib, + kernel_sources=args.source, + claim_kind=args.claim_kind, + preconditions=args.precondition, + tcb_assumptions=args.tcb, + counterexample=args.counterexample, + timeout=args.timeout, + ) + except (OSError, ValueError, subprocess.TimeoutExpired) as exc: + print(f'error: {exc}', file=sys.stderr) + return 2 + + rendered = json.dumps(report, indent=2, ensure_ascii=False) + '\n' + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(rendered, encoding='utf-8') + else: + sys.stdout.write(rendered) + + if report['status'] == 'passed': + return 0 + if report['status'] == 'toolchain_missing': + return 3 + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/skills/operator-verify/scripts/triage.py b/skills/operator-verify/scripts/triage.py new file mode 100644 index 0000000..8e59ad8 --- /dev/null +++ b/skills/operator-verify/scripts/triage.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""Classify an operator verification target and emit verify-request.json. + +Call: triage(...); CLI: python scripts/triage.py --operator NAME --category resource_capacity --output verify-request.json +Input: operator identity (directly or via an operator-optimize handoff.json), semantic category +or free-text description, backend, and optional kernel source path. +Output: verify-request.json recording eligibility, route, and recommended Lean model modules. +Requires: Python standard library only. +""" +__all__ = ['triage', 'CATEGORIES'] + +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys + + +CATEGORIES = { + 'index_and_mask': { + 'eligibility': 'lean_only', + 'route': 'operator-verify', + 'model_modules': ['AscendLean.UBModel', 'AscendLean.TritonModel'], + }, + 'resource_capacity': { + 'eligibility': 'lean_only', + 'route': 'operator-verify', + 'model_modules': ['AscendLean.UBModel'], + }, + 'pipeline_sync': { + 'eligibility': 'model_calibration', + 'route': 'operator-verify', + 'model_modules': ['AscendLean.PipeModel'], + }, + 'semantic_equivalence': { + 'eligibility': 'lean_only', + 'route': 'operator-verify', + 'model_modules': ['AscendLean.TritonModel'], + }, + 'numeric_rounding': { + 'eligibility': 'out_of_scope_numeric', + 'route': 'precision-compare', + 'model_modules': [], + }, +} + +# Word-boundary regex patterns to prevent substring collisions (e.g. "race" in "trace", "tail" in "detail", "192" in "head_dim 192"). +_CATEGORY_PATTERNS = ( + ('pipeline_sync', re.compile( + r'\b(?:setflag|waitflag|hardevent|mte2|mte3|pipe_[a-z0-9]+|data\s+race|race\s+condition|deadlock|pipebarrier|syncall)\b', + re.I, + )), + ('resource_capacity', re.compile( + r'\b(?:unified\s+buffer|ub\s+overflow|ub\s+budget|ub\s+limit|multibuffer|192\s*k(?:i?b)?|248\s*k(?:i?b)?|32b\s*align|sram)\b', + re.I, + )), + ('index_and_mask', re.compile( + r'\b(?:mask|masked\s+load|tail\s+(?:block|tile|lane|padding|slot)|padding_option|tiling|int32\s+overflow|oob|out-of-bounds|updatemask|counter)\b', + re.I, + )), + ('semantic_equivalence', re.compile( + r'(?:-inf\b|\b(?:bitvec|bitwise|torch\.compile|lowering|fusion|megakernel|reduction|equivalence|nan|online\s+softmax|softmax|poison|ldl\^?t)\b)', + re.I, + )), + ('numeric_rounding', re.compile( + r'\b(?:rounding|bf16|fp16|fp64|ulp|rmse|cosine|mantissa|accumulation\s+order)\b', + re.I, + )), +) + + +def _sha256(path): + digest = hashlib.sha256() + with Path(path).open('rb') as handle: + for chunk in iter(lambda: handle.read(65536), b''): + digest.update(chunk) + return digest.hexdigest() + + +def _infer_category(description): + for name, pattern in _CATEGORY_PATTERNS: + if pattern.search(description): + return name + return None + + +def triage(operator=None, category=None, description='', backend='unknown', + source=None, handoff=None, claim_kind='universal_proof', mode='standalone'): + """Build a schema_version=1 verify-request.json payload.""" + handoff_data = None + handoff_path = None + if handoff is not None: + handoff_path = str(handoff) + handoff_data = json.loads(Path(handoff).read_text(encoding='utf-8')) + if not operator: + op_info = handoff_data.get('operator') + if isinstance(op_info, dict): + operator = op_info.get('name') + elif isinstance(op_info, str): + operator = op_info + + if not operator: + raise ValueError('operator name is required (pass --operator or --handoff)') + + resolved_cat = category.lower() if category else _infer_category(description) + if resolved_cat not in CATEGORIES: + choices = ', '.join(CATEGORIES) + raise ValueError(f'unable to classify target; pass --category one of {choices}') + + source_str = None + source_hash = None + if source is not None: + src_path = Path(source).resolve() + if not src_path.is_file(): + raise FileNotFoundError(f'kernel source not found: {source}') + source_str = str(src_path) + source_hash = _sha256(src_path) + + meta = CATEGORIES[resolved_cat] + target = { + 'operator': operator, + 'backend': backend, + 'source': source_str, + 'source_sha256': source_hash, + } + if handoff_data and isinstance(handoff_data.get('operator'), dict): + if handoff_data['operator'].get('call_site'): + target['call_site'] = handoff_data['operator']['call_site'] + + return { + 'schema_version': 1, + 'mode': 'numericbridge_companion' if handoff_path else mode, + 'target': target, + 'category': resolved_cat, + 'eligibility': meta['eligibility'], + 'route': meta['route'], + 'claim_kind': claim_kind, + 'upstream_handoff': handoff_path, + 'upstream_issue': handoff_data.get('issue') if isinstance(handoff_data, dict) else None, + 'model_modules': list(meta['model_modules']), + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('--operator', help='Operator or kernel name') + parser.add_argument('--category', choices=list(CATEGORIES), help='Explicit semantic category') + parser.add_argument('--description', default='', help='Short issue description used when --category is omitted') + parser.add_argument('--backend', default='unknown', + choices=('triton-ascend', 'ascendc', 'triton', 'cuda', 'unknown')) + parser.add_argument('--source', type=Path, help='Optional kernel source file path') + parser.add_argument('--handoff', type=Path, help='Optional operator-optimize handoff.json path') + parser.add_argument('--mode', default='standalone', choices=('standalone', 'repo_audit'), + help='Workflow entry mode (auto-set to numericbridge_companion when --handoff is passed)') + parser.add_argument('--claim-kind', default='universal_proof', + choices=('universal_proof', 'refutation', 'equivalence')) + parser.add_argument('--output', type=Path, help='Write verify-request.json to this path (else print JSON)') + args = parser.parse_args(argv) + + try: + payload = triage( + operator=args.operator, + category=args.category, + description=args.description, + backend=args.backend, + source=args.source, + handoff=args.handoff, + claim_kind=args.claim_kind, + mode=args.mode, + ) + except (OSError, ValueError, json.JSONDecodeError) as exc: + print(f'error: {exc}', file=sys.stderr) + return 2 + + rendered = json.dumps(payload, indent=2, ensure_ascii=False) + '\n' + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(rendered, encoding='utf-8') + else: + sys.stdout.write(rendered) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/README.md b/tools/README.md index 2e22cf7..d6c7359 100644 --- a/tools/README.md +++ b/tools/README.md @@ -24,7 +24,7 @@ imports this package directly. Use the [download and verification steps](../README.md#getting-started) to install without a checkout. For updates, verify and extract the new version into a fresh -directory, then switch the client to it or replace all five installed skill +directory, then switch the client to it or replace all six installed skill folders together. Keep the previous directory if you need to roll back. For an unreleased checkout, export from the repository root: From 8f78fb127e069ab430d53b7802587e9249fe7363 Mon Sep 17 00:00:00 2001 From: Libre <229890576+Libre908@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:22:44 +0800 Subject: [PATCH 2/2] Refine operator-verify to single-operator Lean 4 verification and expand AscendLean models - Narrow operator-verify to standalone and numericbridge_companion single-operator modes (remove heuristic audit_scan.py and repo_audit mode) to mirror operator-optimize - Expand AscendLean.UBModel (alignUp32, ubDisjoint, ubCastSafe) and AscendLean.TritonModel (runOnline_fixed_all_neginf, sumRow lemmas) - Enrich L1-L4 taxonomy and harden triage.py classification priority and input validation - Harden lean_check.py against guillemet-quoted axioms and debug.skipKernelTC, support attributed theorems, and probe toolchain versions in project cwd - Sync top-level docs (AGENTS.md, README*.md, docs/project-architecture.md) and references (tcb.md, handoff.md) --- AGENTS.md | 2 +- README.md | 2 +- README.zh-CN.md | 2 +- docs/project-architecture.md | 2 +- skills/operator-verify/SKILL.md | 6 +- .../lean_lib/AscendLean/TritonModel.lean | 69 +++- .../lean_lib/AscendLean/UBModel.lean | 27 ++ skills/operator-verify/lean_lib/README.md | 4 +- skills/operator-verify/references/handoff.md | 16 +- skills/operator-verify/references/taxonomy.md | 8 +- skills/operator-verify/references/tcb.md | 2 +- skills/operator-verify/scripts/audit_scan.py | 362 ------------------ skills/operator-verify/scripts/lean_check.py | 29 +- skills/operator-verify/scripts/triage.py | 19 +- 14 files changed, 144 insertions(+), 406 deletions(-) delete mode 100644 skills/operator-verify/scripts/audit_scan.py diff --git a/AGENTS.md b/AGENTS.md index 424382d..db8f350 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Layout -- `skills/numericbridge/` is the entrypoint for the full workflow. It owns stage transitions and handoffs and links to the installable `framework-adapt`, `precision-compare`, `precision-repair`, `operator-optimize` and `operator-verify` skills for execution methods. Load those methods on demand. Export the suite with `python -B -m scripts install --output NEW_DIRECTORY` to bundle the shared `tools/` once in Compare. Reuse workload execution, verified resources, inputs/state, collectors and results. `skills/operator-optimize/` owns operator optimization after diagnosis: configuration, backend and kernel variants measured against FP64 with paired timing (`scripts/kernel_check.py`). `skills/operator-verify/` owns offline static auditing (`scripts/audit_scan.py`) and Lean 4 formal verification (`scripts/triage.py`, `scripts/lean_check.py`, `lean_lib/AscendLean/`) for discrete operator invariants. +- `skills/numericbridge/` is the entrypoint for the full workflow. It owns stage transitions and handoffs and links to the installable `framework-adapt`, `precision-compare`, `precision-repair`, `operator-optimize` and `operator-verify` skills for execution methods. Load those methods on demand. Export the suite with `python -B -m scripts install --output NEW_DIRECTORY` to bundle the shared `tools/` once in Compare. Reuse workload execution, verified resources, inputs/state, collectors and results. `skills/operator-optimize/` owns operator optimization after diagnosis: configuration, backend and kernel variants measured against FP64 with paired timing (`scripts/kernel_check.py`). `skills/operator-verify/` owns offline Lean 4 formal verification (`scripts/triage.py`, `scripts/lean_check.py`, `lean_lib/AscendLean/`) for discrete operator invariants. - `research/` is retained local RSI research, Git-ignored and excluded from both the public repository and normal Skill installation. Preserve its local code, state and recorded experiments. It owns task/iteration orchestration over existing workflow tools and an external harness. Index successful/incomplete task evidence; keep full traces and datasets private. The independent improver builds candidates. Evaluate exact tool/context/procedure bundles on independent task families before activation; label dataset outcomes at task scope. Pin task versions, preserve raw usage and reuse comparable baseline receipts. Native checks remain task-owned. Agent-weight training and operator search are extension points. diff --git a/README.md b/README.md index bb2ab57..2c8b41c 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ For your workload, start with the [NumericBridge Skill](skills/numericbridge/SKI ## Workflow and skills -The [workflow](skills/numericbridge/references/workflow.md) loads only the method it needs: [Framework Adapt](skills/framework-adapt/SKILL.md) for native setup, [Precision Compare](skills/precision-compare/SKILL.md) for measurement, [Precision Repair](skills/precision-repair/SKILL.md) for supported-path failures or numerical findings that warrant diagnosis, [Operator Optimize](skills/operator-optimize/SKILL.md) for operators that diagnosis finds outside their FP64 bound, reporting each variant's precision and speed, and [Operator Verify](skills/operator-verify/SKILL.md) for offline Lean 4 formal verification and static auditing of discrete operator invariants (masks, UB capacity, pipeline synchronization, and algebraic/control-flow equivalence). Each stage reuses the confirmed request and evidence. +The [workflow](skills/numericbridge/references/workflow.md) loads only the method it needs: [Framework Adapt](skills/framework-adapt/SKILL.md) for native setup, [Precision Compare](skills/precision-compare/SKILL.md) for measurement, [Precision Repair](skills/precision-repair/SKILL.md) for supported-path failures or numerical findings that warrant diagnosis, [Operator Optimize](skills/operator-optimize/SKILL.md) for operators that diagnosis finds outside their FP64 bound, reporting each variant's precision and speed, and [Operator Verify](skills/operator-verify/SKILL.md) for offline Lean 4 formal verification of discrete operator invariants (masks, UB capacity, pipeline synchronization, and algebraic/control-flow equivalence). Each stage reuses the confirmed request and evidence. Task recipes: [Inference](skills/precision-compare/references/inference.md) · [SFT](skills/precision-compare/references/sft.md) · [RL](skills/precision-compare/references/rl.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index fcd7b49..f685b73 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -52,7 +52,7 @@ python -B "$skills/precision-compare/examples/compare_gradients.py" ## 工作流与 Skill -[工作流](skills/numericbridge/references/workflow.md)按需加载各阶段的 Skill:[Framework Adapt](skills/framework-adapt/SKILL.md) 准备原生环境,[Precision Compare](skills/precision-compare/SKILL.md) 采集和对比,支持的路径运行失败或发现值得调查的数值差异时,进入 [Precision Repair](skills/precision-repair/SKILL.md);诊断发现算子超出 FP64 误差范围时,进入 [Operator Optimize](skills/operator-optimize/SKILL.md),给出每个方案的精度和速度;涉及离散不变量(掩码越界、UB 容量、流水线同步或控制流/代数等价性)时,可通过 [Operator Verify](skills/operator-verify/SKILL.md) 进行离线静态审计与 Lean 4 形式化验证。每一步沿用已确认的需求和证据。 +[工作流](skills/numericbridge/references/workflow.md)按需加载各阶段的 Skill:[Framework Adapt](skills/framework-adapt/SKILL.md) 准备原生环境,[Precision Compare](skills/precision-compare/SKILL.md) 采集和对比,支持的路径运行失败或发现值得调查的数值差异时,进入 [Precision Repair](skills/precision-repair/SKILL.md);诊断发现算子超出 FP64 误差范围时,进入 [Operator Optimize](skills/operator-optimize/SKILL.md),给出每个方案的精度和速度;涉及离散不变量(掩码越界、UB 容量、流水线同步或控制流/代数等价性)时,可通过 [Operator Verify](skills/operator-verify/SKILL.md) 进行离线 Lean 4 形式化验证。每一步沿用已确认的需求和证据。 任务配方:[推理](skills/precision-compare/references/inference.md) · [SFT](skills/precision-compare/references/sft.md) · [RL](skills/precision-compare/references/rl.md)。 diff --git a/docs/project-architecture.md b/docs/project-architecture.md index 3d3c953..fd211b9 100644 --- a/docs/project-architecture.md +++ b/docs/project-architecture.md @@ -23,7 +23,7 @@ Agent 从 [NumericBridge Skill](../skills/numericbridge/SKILL.md) 进入。[流 | 本地私有 projects/、runs/ | 原生案例、资源配置、原始数组、完整日志与过程记录 | 这些目录按用途分工,不是用户必须理解或依次启动的架构层。 -安装包包含 numericbridge、framework-adapt、precision-compare、precision-repair、operator-optimize、operator-verify。operator-optimize 接在诊断之后,对照 FP64 测量配置、后端和 kernel 方案的精度与速度;operator-verify 提供面向离散算子不变量的离线静态审计与 Lean 4 形式化验证。 +安装包包含 numericbridge、framework-adapt、precision-compare、precision-repair、operator-optimize、operator-verify。operator-optimize 接在诊断之后,对照 FP64 测量配置、后端和 kernel 方案的精度与速度;operator-verify 提供面向离散算子不变量的离线 Lean 4 形式化验证。 ## 工具放置与安装 diff --git a/skills/operator-verify/SKILL.md b/skills/operator-verify/SKILL.md index d1ceb13..c1b2b28 100644 --- a/skills/operator-verify/SKILL.md +++ b/skills/operator-verify/SKILL.md @@ -9,19 +9,17 @@ Run tools from this skill directory. Each tool's `--help` gives its interface. | Step | Tool | Output | |---|---|---| -| Scan upstream kernel files for discrete bug candidates | [audit_scan](scripts/audit_scan.py) | `audit-findings.json` with candidate rule hits, lines, hashes, and categories | | Classify verification scope and build a request | [triage](scripts/triage.py) | `verify-request.json` with category, eligibility, route, and model modules | | Type-check Lean 4 proofs and audit `sorry` / axioms | [lean_check](scripts/lean_check.py) | `verify-report.json` with toolchain, hashes, theorem list, audit status, and verdict | Read [taxonomy](references/taxonomy.md) for the discrete-verification vs floating-point boundary, [handoff](references/handoff.md) for the input/output JSON contracts, and [TCB](references/tcb.md) for hardware modeling assumptions. -`operator-verify` pairs with [operator-optimize](../operator-optimize/SKILL.md): `operator-verify` proves discrete structural, memory, synchronization, and algebraic/bit-level properties offline without an accelerator; pure floating-point rounding accuracy and runtime timing remain in [precision-compare](../precision-compare/SKILL.md) and [operator-optimize](../operator-optimize/SKILL.md). +`operator-verify` pairs with [operator-optimize](../operator-optimize/SKILL.md): `operator-verify` proves discrete structural, memory, synchronization, and algebraic/bit-level properties offline for a localized operator without an accelerator; pure floating-point rounding accuracy and runtime timing remain in [precision-compare](../precision-compare/SKILL.md) and [operator-optimize](../operator-optimize/SKILL.md). ## Entry -1. **Standalone mode.** Start from a kernel source file, PR diff, or Lean 4 target. Run `triage.py` to classify the issue into one of the discrete categories (`index_and_mask`, `resource_capacity`, `pipeline_sync`, `semantic_equivalence`) or route `numeric_rounding` back to dynamic precision tools. +1. **Standalone mode.** Start from a single kernel source file, PR diff, or Lean 4 target. Run `triage.py` to classify the issue into one of the discrete categories (`index_and_mask`, `resource_capacity`, `pipeline_sync`, `semantic_equivalence`) or route `numeric_rounding` back to dynamic precision tools. 2. **NumericBridge companion / pre-gate mode.** Accept an operator handoff (`result/optimize//handoff.json`) or a `diagnosis.json` hypothesis, verify discrete invariants offline, and write `result/verify//verify-report.json` as evidence alongside dynamic checks. -3. **Repository audit mode.** Scan candidate operator files in an upstream repository (e.g., `sgl-kernel-npu`, `vllm-ascend`, `RL-Kernel`) to surface unreported defects, rule out false positives, and document implicit preconditions. Confirmed defects hand off directly to [upstream_status.py](../precision-compare/scripts/upstream_status.py) and [pr_draft.py](../precision-compare/scripts/pr_draft.py) for upstream PR delivery. ## Verify diff --git a/skills/operator-verify/lean_lib/AscendLean/TritonModel.lean b/skills/operator-verify/lean_lib/AscendLean/TritonModel.lean index c82cac5..7288016 100644 --- a/skills/operator-verify/lean_lib/AscendLean/TritonModel.lean +++ b/skills/operator-verify/lean_lib/AscendLean/TritonModel.lean @@ -233,7 +233,23 @@ theorem runOnline_fixed_invariant (tiles : List TileHasFinite) (st : OnlineState have hrec := ih { m := .finite, s := .pos } (Or.inr ⟨rfl, rfl⟩) exact ⟨fun _ => hrec.2 rfl, fun _ => hrec.2 rfl⟩ -/-! ### 4. Masked Load Padding Taint & Indexed Load Bounds -/ +theorem runOnline_fixed_all_neginf (tiles : List TileHasFinite) (st : OnlineState) + (h0 : st.m = .negInf ∧ st.s = .zero) (hall : ∀ b ∈ tiles, b = false) : + runOnline onlineStepFixed st tiles = { m := .negInf, s := .zero } := by + induction tiles generalizing st with + | nil => + rcases st with ⟨m, s⟩ + simp only at h0 + simp [runOnline, h0.1, h0.2] + | cons b bs ih => + have hb : b = false := hall b (List.Mem.head _) + subst hb + have hstep : onlineStepFixed st false = { m := .negInf, s := .zero } := by + simp [onlineStepFixed, h0.1, h0.2, expDiff, sumMul, sumAdd] + simp only [runOnline, List.foldl_cons, hstep] + exact ih { m := .negInf, s := .zero } ⟨rfl, rfl⟩ (fun x hx => hall x (List.Mem.tail _ hx)) + +/-! ### 4. Masked Load Padding Taint, Row Reductions & Indexed Load Bounds -/ /-- Value with explicit uninitialized/undefined UB lane state (Triton `padding_option=""`). -/ inductive LaneVal where @@ -251,6 +267,57 @@ def laneAdd (a b : LaneVal) : LaneVal := | .val x, .val y => .val (x + y) | _, _ => .undef +/-- Row reduction `tl.sum` over `bn` lanes with UB taint tracking. -/ +def sumRow (f : Nat → LaneVal) : Nat → LaneVal + | 0 => .val 0 + | n + 1 => laneAdd (sumRow f n) (f n) + +/-- Pure mathematical row sum over valid indices `0 .. n-1`. -/ +def sumSpec (a : Nat → Int) : Nat → Int + | 0 => 0 + | n + 1 => sumSpec a n + a n + +theorem sumRow_zero_padded (a : Nat → Int) (n bn : Nat) (hnb : n ≤ bn) : + sumRow (fun j => if j < n then .val (a j) else .val 0) bn = .val (sumSpec a n) := by + induction bn with + | zero => + have hn0 : n = 0 := by omega + subst hn0; rfl + | succ m ih => + by_cases hnm : n ≤ m + · simp only [sumRow] + rw [ih hnm] + have hnot : ¬ (m < n) := by omega + simp [hnot, laneAdd] + · have hneq : n = m + 1 := by omega + subst hneq + simp only [sumRow] + have hprefix : + ∀ r, r ≤ m → + sumRow (fun j => if j < m + 1 then .val (a j) else .val 0) r = .val (sumSpec a r) := by + intro r hr + induction r with + | zero => rfl + | succ t iht => + simp only [sumRow, iht (by omega)] + have ht : t < m + 1 := by omega + simp [ht, laneAdd, sumSpec] + rw [hprefix m (Nat.le_refl m)] + simp [laneAdd, sumSpec] + +theorem sumRow_undef_poisons (a : Nat → Int) (n bn : Nat) (hlt : n < bn) : + sumRow (fun j => if j < n then .val (a j) else .undef) bn = .undef := by + induction bn with + | zero => omega + | succ m ih => + simp only [sumRow] + by_cases hnm : n < m + · rw [ih hnm] + cases (if m < n then LaneVal.val (a m) else LaneVal.undef) <;> rfl + · have hnot : ¬ (m < n) := by omega + simp only [hnot, ↓reduceIte] + cases sumRow (fun j => if j < n then .val (a j) else .undef) m <;> rfl + /-- Inner product of length `bk` where lanes `j < k` are valid and `j ≥ k` are padded. -/ def dotRow (f g : Nat → LaneVal) : Nat → LaneVal | 0 => .val 0 diff --git a/skills/operator-verify/lean_lib/AscendLean/UBModel.lean b/skills/operator-verify/lean_lib/AscendLean/UBModel.lean index 62dbaee..6189915 100644 --- a/skills/operator-verify/lean_lib/AscendLean/UBModel.lean +++ b/skills/operator-verify/lean_lib/AscendLean/UBModel.lean @@ -163,4 +163,31 @@ theorem loopPacked4Shared_exact (curColNum vl : Nat) (hvl : 0 < vl) : have hge := le_ceilDiv_mul curColNum (4 * vl) (by omega) omega +/-- Round `bytes` up to the nearest 32-byte Ascend UB alignment boundary. -/ +def alignUp32 (bytes : Nat) : Nat := + ceilDiv bytes 32 * 32 + +theorem alignUp32_ge (bytes : Nat) : bytes ≤ alignUp32 bytes := + le_ceilDiv_mul bytes 32 (by decide) + +theorem alignUp32_mod32 (bytes : Nat) : alignUp32 bytes % 32 = 0 := by + unfold alignUp32 + exact Nat.mul_mod_left _ 32 + +/-- Two half-open UB byte intervals `[s1, e1)` and `[s2, e2)` are disjoint. -/ +abbrev ubDisjoint (s1 e1 s2 e2 : Nat) : Prop := + e1 ≤ s2 ∨ e2 ≤ s1 + +/-- Hardware constraint for AscendC `Cast(dst, src, count)` inside a UB buffer of `bufBytes`: + both ranges stay in bounds, are 32-byte aligned, and the source and destination byte ranges + must be strictly disjoint unless `srcWidth = dstWidth` and they start at the exact same offset + (partial overlap is forbidden even for equal-width casts). -/ +abbrev ubCastSafe (bufBytes srcOff dstOff count srcWidth dstWidth : Nat) : Prop := + srcOff % 32 = 0 ∧ + dstOff % 32 = 0 ∧ + srcOff + count * srcWidth ≤ bufBytes ∧ + dstOff + count * dstWidth ≤ bufBytes ∧ + ((srcWidth = dstWidth ∧ srcOff = dstOff) ∨ + ubDisjoint srcOff (srcOff + count * srcWidth) dstOff (dstOff + count * dstWidth)) + end AscendLean.UBModel diff --git a/skills/operator-verify/lean_lib/README.md b/skills/operator-verify/lean_lib/README.md index 4974940..3a0004d 100644 --- a/skills/operator-verify/lean_lib/README.md +++ b/skills/operator-verify/lean_lib/README.md @@ -7,8 +7,8 @@ This directory contains the reusable `AscendLean` Lean 4 library for offline acc | Module | Scope | Key primitives | |---|---|---| | `AscendLean.PipeModel` | `pipeline_sync` | Ascend DaVinci async pipes (`PIPE_MTE2`, `PIPE_V`, `PIPE_MTE3`, `PIPE_S`), all 12 directed FIFO `HardEvent`s (`MTE3_MTE2`, `V_S`, `S_MTE2`, etc.), `runOps`, `VerifiedSafe` | -| `AscendLean.UBModel` | `resource_capacity`, `index_and_mask` | `A3_UB_BITS` (192 KiB), `A5_UB_BITS` (248 KiB = 2,031,616 bits), `INT32_MAX`, `INT64_MAX`, `nextPow2`, `le_ceilDiv_mul`, AscendC `updateMask` / 4-way packed stores | -| `AscendLean.TritonModel` | `semantic_equivalence`, `index_and_mask` | `BitVec 64` bitwise select, `ExtInt` tiled reductions, IEEE-754 online-softmax `(-inf) - (-inf) = NaN` abstract domain, masked-load `LaneVal` padding taint, `indexedLoadSafe` | +| `AscendLean.UBModel` | `resource_capacity`, `index_and_mask` | `A3_UB_BITS` (192 KiB), `A5_UB_BITS` (248 KiB = 2,031,616 bits), `INT32_MAX`, `INT64_MAX`, `nextPow2`, `le_ceilDiv_mul`, `alignUp32`, `ubDisjoint`, `ubCastSafe`, AscendC `updateMask` / 4-way packed stores | +| `AscendLean.TritonModel` | `semantic_equivalence`, `index_and_mask` | `BitVec 64` bitwise select, `ExtInt` tiled reductions, IEEE-754 online-softmax `(-inf) - (-inf) = NaN` abstract domain (`runOnline_fixed_all_neginf`), masked-load `LaneVal` padding taint (`sumRow`, `sumRow_zero_padded`, `sumRow_undef_poisons`), `indexedLoadSafe` | ## Build and check diff --git a/skills/operator-verify/references/handoff.md b/skills/operator-verify/references/handoff.md index 2a03195..5102208 100644 --- a/skills/operator-verify/references/handoff.md +++ b/skills/operator-verify/references/handoff.md @@ -9,7 +9,7 @@ Written by `triage.py` (standalone) or derived from `result/optimize// | Field | Content | |---|---| | `schema_version` | Integer schema version (currently `1`) | -| `mode` | `standalone`, `numericbridge_companion`, or `repo_audit` | +| `mode` | `standalone` or `numericbridge_companion` | | `target` | Operator name, backend (`triton-ascend`, `ascendc`, `triton`, `cuda`, `unknown`), source path, source SHA-256, and optional `call_site` | | `category` | `index_and_mask`, `resource_capacity`, `pipeline_sync`, `semantic_equivalence`, or `numeric_rounding` | | `eligibility` | `lean_only`, `model_calibration`, or `out_of_scope_numeric` | @@ -19,18 +19,6 @@ Written by `triage.py` (standalone) or derived from `result/optimize// | `upstream_issue` | Optional upstream issue metadata propagated from `handoff.json` | | `model_modules` | Recommended Lean library modules (e.g., `AscendLean.UBModel`, `AscendLean.PipeModel`, `AscendLean.TritonModel`) | -## Static Audit Output: `audit-findings.json` - -Written by `audit_scan.py` in `repo_audit` mode before triaging individual findings into `verify-request.json`. - -| Field | Content | -|---|---| -| `schema_version` | Integer schema version (currently `1`) | -| `scanned_files` | Count of Triton-Ascend (`.py`) and AscendC (`.h`/`.hpp`/`.cpp`/`.cc`/`.asc`) files scanned | -| `finding_count` | Total candidate findings discovered | -| `by_category` | Map of semantic category (`index_and_mask`, `resource_capacity`, `pipeline_sync`, `semantic_equivalence`) to finding count | -| `findings` | List of candidate records `{rule_id, category, backend, file, sha256, line, symbol, summary, model_modules}` | - ## Output: `verify-report.json` Written by `lean_check.py` to `result/verify//verify-report.json` (or `--output`). @@ -48,7 +36,7 @@ Written by `lean_check.py` to `result/verify//verify-report.json` (or | `theorems` | Declared `theorem` / `lemma` names discovered in the verified Lean target (must be non-empty for `passed`) | | `preconditions` | Explicit or discovered preconditions required for the proved invariant to hold (e.g., `at least one finite logit`, `len >= 1`) | | `tcb_assumptions` | Explicit hardware/modeling assumptions required to interpret the result | -| `counterexample` | Optional structured witness (`--counterexample`) when `verdict == "refuted"` | +| `counterexample` | Optional counterexample summary string (`--counterexample`) when `verdict == "refuted"` | | `command` | Exact command argv, exit code, duration in seconds, and output tails | Example `verify-report.json`: diff --git a/skills/operator-verify/references/taxonomy.md b/skills/operator-verify/references/taxonomy.md index e0636ea..7fd03d1 100644 --- a/skills/operator-verify/references/taxonomy.md +++ b/skills/operator-verify/references/taxonomy.md @@ -4,10 +4,10 @@ Classify each operator issue by **why dynamic numerical testing misses it**, usi | Category | Typical accelerator mechanism | Why numerical tests miss it | Eligibility | Route | |---|---|---|---|---| -| `index_and_mask` | Tiling tail out-of-bounds, padding contamination, `int32` overflow/truncation, shared vs independent mask counters | Unit tests mostly cover aligned, divisible, or power-of-2 shapes where tail branches never fire | `lean_only` | `operator-verify` | -| `resource_capacity` | On-chip Unified Buffer / SRAM overflow (including auto multi-buffering doubling), 32B alignment violations | Small and power-of-2 shapes fit; large or non-power-of-2 hidden sizes overflow on-chip memory | `lean_only` | `operator-verify` | -| `pipeline_sync` | Missing `SetFlag`/`WaitFlag` across Cube/Vector/MTE pipes, UB read/write races, deadlocks, leaked event tokens | Timing-dependent, architecture-dependent (passes on A3, fails on A5), or masked by single-head tests | `model_calibration` | `operator-verify` | -| `semantic_equivalence` | Fused kernels, `torch.compile` lowering mismatches, bit-level workarounds (`BitVec 64` select), tiled reductions, qualitative IEEE-754 special-value (`±inf` / `NaN`) propagation & poisoning (e.g., online softmax `(-inf) - (-inf) = NaN`), hidden preconditions | Fusion introduces small FP drift so loose tolerances hide logic bugs; dense random tests (`randn`) never trigger masked `-inf` leading tiles or tie/edge preconditions | `lean_only` | `operator-verify` | +| `index_and_mask` | Tiling tail out-of-bounds, padding contamination (`padding_option="zero"` / `other=0.0`), `int32` overflow/truncation, shared vs independent mask counters, wrong `boundary_check` axis, unconditional OOB scatter/store, ignored tensor stride or grid-stride mismatch, indirect load from unpadded masked positions | Unit tests mostly cover aligned, divisible, single-row, or power-of-2 shapes where tail/stride/multi-row branches never fire | `lean_only` | `operator-verify` | +| `resource_capacity` | On-chip Unified Buffer / SRAM overflow (including auto multi-buffering doubling and hardcoded `BLOCK_M` scaling), byte-vs-element UB indexing overrun, 32B alignment violations, mixed-width in-place UB address overlap (`AscendC::Cast` aliasing), silent host-side tile clamping without `RuntimeError` | Small and power-of-2 shapes fit; large, non-power-of-2, or narrowed-dtype shapes overflow or alias on-chip memory | `lean_only` | `operator-verify` | +| `pipeline_sync` | Missing `SetFlag`/`WaitFlag` across Cube/Vector/Scalar/MTE pipes, wrong `HardEvent` pipe pair (e.g., `MTE2_MTE3` guarding `PIPE_S`), inter-core `IBWait`/`IBSet` ring deadlocks on empty segments, UB read/write races, leaked event tokens | Timing-dependent, architecture-dependent (passes on A3, fails on A5), or masked by single-head / non-empty-segment tests | `model_calibration` | `operator-verify` | +| `semantic_equivalence` | Fused kernels, `torch.compile` lowering mismatches, bit-level workarounds (`BitVec 64` select), tiled reductions, qualitative IEEE-754 special-value (`±inf` / `NaN`) propagation & poisoning (e.g., online softmax `(-inf) - (-inf) = NaN`), wrong inverse transpose permutation, wrong Welford online denominator (`step` vs per-lane `cnt`), inverted boolean mask / missing `LOG2E` scaling, uninitialized output quadrant, store dtype truncation, hidden preconditions | Fusion introduces small FP drift so loose tolerances hide logic bugs; dense random tests (`randn`) never trigger masked `-inf` leading tiles, `head_first`, `training=True` multi-step tiles, or boolean/additive masks | `lean_only` | `operator-verify` | | `numeric_rounding` | Quantitative BF16/FP16 accumulation order, transcendental rounding tolerance (ULP/RMSE), cross-stack FP drift | Directly measurable against FP64 on captured operands | `out_of_scope_numeric` | `precision-compare` / `operator-optimize` | ## Eligibility states diff --git a/skills/operator-verify/references/tcb.md b/skills/operator-verify/references/tcb.md index 9469840..fe0c373 100644 --- a/skills/operator-verify/references/tcb.md +++ b/skills/operator-verify/references/tcb.md @@ -12,6 +12,6 @@ Every `verify-report.json` must distinguish what is mechanically checked by the 1. **Source-to-Lean abstraction gap.** Until a certified compiler frontend exists, mapping from Triton Python AST or Ascend C C++ source into Lean 4 expressions is part of the TCB. Record the exact source path, SHA-256 digest, and extractor version. 2. **Hardware constants and execution semantics.** - Unified Buffer limits (e.g., Ascend A3 `192 KiB`, Ascend A5 / 950PR `248 KiB = 2,031,616 bits`) reflect documented compiler limits for the named architecture. - - DaVinci pipeline synchronization models (`PIPE_MTE2`, `PIPE_V`, `PIPE_MTE3`, `HardEvent` FIFO queues) abstract hardware ordering at buffer/event granularity rather than cycle-accurate microarchitecture. + - DaVinci pipeline synchronization models (`PIPE_MTE2`, `PIPE_V`, `PIPE_MTE3`, `PIPE_S`, and all 12 directed `HardEvent` FIFO queues) abstract hardware ordering at buffer/event granularity rather than cycle-accurate microarchitecture; `SyncWatermark` conservatively tracks direct cross-pipe edges without transitive vector-clock propagation (e.g., `MTE2 -> V -> MTE3`). - Vector register widths (e.g., 256-byte register = 64 `float32` lanes) match the targeted AscendC ISA. 3. **Numerical boundary.** Discrete bit-vector, integer, or extended-order models do **not** establish floating-point rounding accuracy; pair with `precision-compare` or `operator-optimize` (`kernel_check.py`) whenever floating-point precision matters. diff --git a/skills/operator-verify/scripts/audit_scan.py b/skills/operator-verify/scripts/audit_scan.py deleted file mode 100644 index d270d5c..0000000 --- a/skills/operator-verify/scripts/audit_scan.py +++ /dev/null @@ -1,362 +0,0 @@ -#!/usr/bin/env python3 -"""Statically audit Triton-Ascend (.py) and AscendC (.h/.hpp/.cpp/.asc) kernels for discrete verification candidates. - -Call: scan_path(path); CLI: python scripts/audit_scan.py PATH [PATH ...] [--output findings.json] -Input: one or more kernel source files or directories (Triton Python and/or AscendC C++). -Output: schema_version=1 JSON report listing candidate defects mapped to operator-verify categories -(`index_and_mask`, `resource_capacity`, `pipeline_sync`, `semantic_equivalence`) for triage and Lean 4 verification. -Requires: Python standard library only. -""" -__all__ = ['scan_file', 'scan_path', 'RULES'] - -import argparse -import ast -from collections import Counter -import hashlib -import json -from pathlib import Path -import re -import sys - - -RULES = { - 'online_softmax_neginf': { - 'category': 'semantic_equivalence', - 'backend': 'triton-ascend', - 'model_modules': ['AscendLean.TritonModel'], - }, - 'block_ptr_unpadded_load': { - 'category': 'index_and_mask', - 'backend': 'triton-ascend', - 'model_modules': ['AscendLean.TritonModel'], - }, - 'masked_load_missing_other': { - 'category': 'index_and_mask', - 'backend': 'triton-ascend', - 'model_modules': ['AscendLean.TritonModel'], - }, - 'unmasked_mapping_index_load': { - 'category': 'index_and_mask', - 'backend': 'triton-ascend', - 'model_modules': ['AscendLean.TritonModel'], - }, - 'int32_pointer_mul_overflow': { - 'category': 'index_and_mask', - 'backend': 'triton-ascend', - 'model_modules': ['AscendLean.UBModel'], - }, - 'hardcoded_multibuffer_np2': { - 'category': 'resource_capacity', - 'backend': 'triton-ascend', - 'model_modules': ['AscendLean.UBModel'], - }, - 'ascendc_hardevent_imbalance': { - 'category': 'pipeline_sync', - 'backend': 'ascendc', - 'model_modules': ['AscendLean.PipeModel'], - }, -} - -_TRITON_EXTS = {'.py'} -_ASCENDC_EXTS = {'.h', '.hpp', '.cpp', '.cc', '.asc'} -_NEGINF_RE = re.compile(r"(?:float\(\s*['\"]-inf['\"]\s*\)|-\s*float\(\s*['\"]inf['\"]\s*\))") - - -def _sha256(path): - digest = hashlib.sha256() - with Path(path).open('rb') as handle: - for chunk in iter(lambda: handle.read(65536), b''): - digest.update(chunk) - return digest.hexdigest() - - -def _is_triton_jit(fn): - for dec in fn.decorator_list: - target = dec.func if isinstance(dec, ast.Call) else dec - text = ast.unparse(target) - if text == 'jit' or text.endswith('.jit'): - return True - return False - - -def _has_autotune_multibuffer(fn): - for dec in fn.decorator_list: - text = ast.unparse(dec) - if 'autotune' in text and 'multibuffer' in text: - return True - return False - - -def _make_finding(path, file_hash, rule_id, line, symbol, summary): - meta = RULES[rule_id] - return { - 'rule_id': rule_id, - 'category': meta['category'], - 'backend': meta['backend'], - 'file': str(path), - 'sha256': file_hash, - 'line': line, - 'symbol': symbol, - 'summary': summary, - 'model_modules': list(meta['model_modules']), - } - - -def _count_mul_ops(expr): - return sum(1 for n in ast.walk(expr) if isinstance(n, ast.BinOp) and isinstance(n.op, ast.Mult)) - - -def _is_int64_cast(expr): - return ( - isinstance(expr, ast.Call) - and isinstance(expr.func, ast.Attribute) - and expr.func.attr == 'to' - and any('int64' in ast.unparse(a) for a in expr.args) - ) - - -def _is_tl_load(expr): - return isinstance(expr, ast.Call) and ast.unparse(expr.func) == 'tl.load' - - -def _strip_cpp_comments(text): - text = re.sub(r'/\*.*?\*/', lambda m: '\n' * m.group(0).count('\n'), text, flags=re.S) - text = re.sub(r'//[^\n]*', '', text) - return text - - -def _scan_triton_python(path, text, file_hash): - findings = [] - try: - tree = ast.parse(text) - except SyntaxError: - return findings - - jit_fns = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and _is_triton_jit(n)] - if not jit_fns: - return findings - - for fn in jit_fns: - fn_src = ast.unparse(fn) - has_reduction = any(tok in fn_src for tok in ('tl.sum(', 'tl.dot(', 'tl.max(', 'tl.min(')) - - # 1. Online softmax (-inf) - (-inf) = NaN poisoning: - # Track variables explicitly initialized to -inf (not finite sinks or tl.where masked scores). - neginf_vars = set() - for node in ast.walk(fn): - if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): - val_s = ast.unparse(node.value) - if _NEGINF_RE.search(val_s) and 'tl.where(' not in val_s: - neginf_vars.add(node.targets[0].id) - - has_safe_m_guard = False - for node in ast.walk(fn): - if isinstance(node, ast.Call) and ast.unparse(node.func) == 'tl.where' and len(node.args) >= 3: - cond_s = ast.unparse(node.args[0]) - if _NEGINF_RE.search(cond_s) and any(op in cond_s for op in ('>', '!=', '==')): - has_safe_m_guard = True - break - - if neginf_vars and not has_safe_m_guard: - for node in ast.walk(fn): - if isinstance(node, ast.For): - loop_s = ast.unparse(node) - if 'tl.maximum(' not in loop_s or 'tl.exp(' not in loop_s: - continue - flagged_line = None - for call in ast.walk(node): - if isinstance(call, ast.Call) and ast.unparse(call.func) == 'tl.exp' and call.args: - arg_s = ast.unparse(call.args[0]) - if '-' in arg_s and any(re.search(rf'\b{re.escape(v)}\b', arg_s) for v in neginf_vars): - flagged_line = call.lineno - break - if flagged_line is not None: - findings.append(_make_finding( - path, file_hash, 'online_softmax_neginf', flagged_line, fn.name, - 'Online softmax loop initializes running max to -inf and evaluates tl.exp(m - new_m) ' - 'without guarding new_m == -inf; leading all-(-inf) tiles trigger (-inf) - (-inf) = NaN.', - )) - break - - # 2. tl.load(block_ptr, boundary_check=...) without padding_option="zero" - # 3. tl.load(..., mask=...) without other= in a kernel with reductions - # 4. Unmasked indexed load using a request mapping variable (can be -1 in padded graph rows) - mapping_vars = set() - for node in ast.walk(fn): - if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): - val_s = ast.unparse(node.value) - if 'tl.load(' in val_s and 'mapping' in val_s.lower(): - mapping_vars.add(node.targets[0].id) - - for node in ast.walk(fn): - if not (isinstance(node, ast.Call) and ast.unparse(node.func) == 'tl.load'): - continue - kw_names = {kw.arg: ast.unparse(kw.value) for kw in node.keywords if kw.arg} - arg0 = ast.unparse(node.args[0]) if node.args else '' - - if 'boundary_check' in kw_names: - pad_opt = kw_names.get('padding_option', '') - if 'zero' not in pad_opt: - findings.append(_make_finding( - path, file_hash, 'block_ptr_unpadded_load', node.lineno, fn.name, - 'tl.load with boundary_check omits padding_option="zero"; ' - 'out-of-bounds lanes retain undefined UB garbage.', - )) - - has_mask = 'mask' in kw_names or len(node.args) >= 2 - has_other = 'other' in kw_names or len(node.args) >= 3 - if has_mask and not has_other and has_reduction: - findings.append(_make_finding( - path, file_hash, 'masked_load_missing_other', node.lineno, fn.name, - 'Masked tl.load omits explicit `other=` fill value inside a kernel with reductions; ' - 'uninitialized UB padding lanes can contaminate tl.sum/tl.dot.', - )) - - if not has_mask and mapping_vars: - for mv in mapping_vars: - if re.search(rf'\+\s*{re.escape(mv)}\b', arg0): - findings.append(_make_finding( - path, file_hash, 'unmasked_mapping_index_load', node.lineno, fn.name, - f'Unmasked tl.load indexed by mapping variable `{mv}` without `{mv} >= 0` guard; ' - 'padded graph rows with sentinel -1 perform out-of-bounds negative-offset loads.', - )) - break - - # 5. Potential int32 pointer offset overflow: - # (a) `(a * b * c).to(tl.int64)` where widening occurs AFTER int32 multiplications, OR - # (b) multi-factor offset expression (>=3 `*`) with no inner int64 cast. - int64_vars = set() - for node in ast.walk(fn): - if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): - if 'int64' in ast.unparse(node.value): - int64_vars.add(node.targets[0].id) - - for node in ast.walk(fn): - val = None - tgt = None - if isinstance(node, ast.AugAssign) and isinstance(node.op, ast.Add) and isinstance(node.target, ast.Name): - tgt = node.target.id - val = node.value - elif isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): - tgt = node.targets[0].id - val = node.value - if val is None or tgt is None: - continue - - if _is_int64_cast(val) and isinstance(val.func, ast.Attribute): - inner = val.func.value - inner_s = ast.unparse(inner) - if not _is_tl_load(inner) and _count_mul_ops(inner) >= 2 and 'int64' not in inner_s: - if not any(re.search(rf'\b{re.escape(v)}\b', inner_s) for v in int64_vars): - findings.append(_make_finding( - path, file_hash, 'int32_pointer_mul_overflow', node.lineno, fn.name, - f'Offset `{tgt}` widens to int64 AFTER int32 multiplication (`{ast.unparse(val)}`); ' - 'product can overflow signed int32 before .to(tl.int64).', - )) - elif 'offset' in tgt.lower(): - val_s = ast.unparse(val) - if _count_mul_ops(val) >= 3 and 'int64' not in val_s: - if not any(re.search(rf'\b{re.escape(v)}\b', val_s) for v in int64_vars): - findings.append(_make_finding( - path, file_hash, 'int32_pointer_mul_overflow', node.lineno, fn.name, - f'Multi-factor pointer offset `{tgt} = {val_s}` computed without int64 cast; ' - 'can overflow signed int32 (2^31 - 1) on long-context or large-batch workloads.', - )) - - # 6. Hardcoded multibuffer=True with next_power_of_2 and no @triton.autotune - if 'multibuffer=True' in text and 'next_power_of_2' in text: - if not any(_has_autotune_multibuffer(fn) for fn in jit_fns): - line_no = next((i for i, l in enumerate(text.splitlines(), 1) if 'multibuffer=True' in l), 1) - findings.append(_make_finding( - path, file_hash, 'hardcoded_multibuffer_np2', line_no, jit_fns[0].name, - 'Kernel launch hardcodes multibuffer=True with next_power_of_2 tiling and no multibuffer autotune; ' - 'large/non-power-of-2 shapes risk Ascend UB overflow.', - )) - - return findings - - -def _scan_ascendc(path, text, file_hash): - findings = [] - cleaned = _strip_cpp_comments(text) - sets = Counter(re.findall(r'SetFlag<(?:AscendC::)?HardEvent::([A-Z0-9_]+)>', cleaned)) - waits = Counter(re.findall(r'WaitFlag<(?:AscendC::)?HardEvent::([A-Z0-9_]+)>', cleaned)) - for ev in sorted(set(sets) | set(waits)): - if sets[ev] != waits[ev]: - m = re.search(rf'(?:Set|Wait)Flag<(?:AscendC::)?HardEvent::{ev}>', cleaned) - line_no = cleaned[:m.start()].count('\n') + 1 if m else 1 - findings.append(_make_finding( - path, file_hash, 'ascendc_hardevent_imbalance', line_no, ev, - f'Static SetFlag/WaitFlag count mismatch for HardEvent::{ev} ' - f'(SetFlag={sets[ev]}, WaitFlag={waits[ev]}); requires control-flow sync verification.', - )) - return findings - - -def scan_file(path): - """Scan one Triton-Ascend or AscendC source file and return candidate findings.""" - p = Path(path).resolve() - if not p.is_file(): - raise FileNotFoundError(f'source file not found: {path}') - suffix = p.suffix.lower() - if suffix not in _TRITON_EXTS and suffix not in _ASCENDC_EXTS: - return [] - text = p.read_text(encoding='utf-8', errors='replace') - file_hash = _sha256(p) - if suffix in _TRITON_EXTS: - return _scan_triton_python(p, text, file_hash) - return _scan_ascendc(p, text, file_hash) - - -def scan_path(paths): - """Scan one or more files or directories and return a schema_version=1 audit report.""" - findings = [] - scanned_files = 0 - for raw in paths: - p = Path(raw).resolve() - if p.is_file(): - scanned_files += 1 - findings.extend(scan_file(p)) - elif p.is_dir(): - for child in sorted(p.rglob('*')): - if child.is_file() and child.suffix.lower() in (_TRITON_EXTS | _ASCENDC_EXTS): - if '.lake' in child.parts or '__pycache__' in child.parts: - continue - scanned_files += 1 - findings.extend(scan_file(child)) - else: - raise FileNotFoundError(f'path not found: {raw}') - - by_category = Counter(f['category'] for f in findings) - return { - 'schema_version': 1, - 'scanned_files': scanned_files, - 'finding_count': len(findings), - 'by_category': dict(sorted(by_category.items())), - 'findings': findings, - } - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument('paths', nargs='+', type=Path, help='Kernel source files or directories to audit') - parser.add_argument('--output', type=Path, help='Write audit-findings.json to this path (else print JSON)') - args = parser.parse_args(argv) - - try: - report = scan_path(args.paths) - except OSError as exc: - print(f'error: {exc}', file=sys.stderr) - return 2 - - rendered = json.dumps(report, indent=2, ensure_ascii=False) + '\n' - if args.output is not None: - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text(rendered, encoding='utf-8') - else: - sys.stdout.write(rendered) - return 0 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/skills/operator-verify/scripts/lean_check.py b/skills/operator-verify/scripts/lean_check.py index 88866c4..be953ae 100644 --- a/skills/operator-verify/scripts/lean_check.py +++ b/skills/operator-verify/scripts/lean_check.py @@ -22,13 +22,15 @@ import time -_THEOREM_RE = re.compile(r'^\s*(?:(?:protected|noncomputable)\s+)*(?:theorem|lemma)\s+([A-Za-z0-9_.\']+)', re.M) -_AXIOM_RE = re.compile(r'\baxiom\s+([A-Za-z0-9_.\']+)') +_THEOREM_RE = re.compile( + r'^\s*(?:@\[[^\]]*\]\s*)*(?:(?:protected|noncomputable)\s+)*(?:theorem|lemma)\s+([A-Za-z0-9_.\']+)', + re.M, +) +_AXIOM_RE = re.compile(r'\baxiom\s+(«[^»]+»|[^\s:({\[]+)') _SORRY_RE = re.compile(r'\b(?:sorry|sorryAx)\b') _ADMIT_RE = re.compile(r'\badmit\b') _UNSAFE_ESCAPE_RE = re.compile( - r'\b(?:native_decide|unsafe|opaque|implemented_by|extern|ofReduceBool|ofReduceNat|trustCompiler)\b' - r'|@\[[^\]]*\b(?:implemented_by|extern)\b' + r'\b(?:native_decide|unsafe|opaque|implemented_by|extern|ofReduceBool|ofReduceNat|trustCompiler|skipKernelTC)\b' ) _COMPILER_SORRY_RE = re.compile(r"declaration uses ['`]?sorry(?:Ax)?['`]?", re.I) @@ -137,18 +139,27 @@ def audit_lean_source(text): def _find_lake_project(target_path, explicit_project=None): if explicit_project is not None: - return Path(explicit_project).resolve() + resolved = Path(explicit_project).resolve() + if not resolved.is_dir(): + raise FileNotFoundError(f'Lake project directory not found: {explicit_project}') + return resolved for parent in Path(target_path).resolve().parents: if (parent / 'lakefile.toml').is_file() or (parent / 'lakefile.lean').is_file(): return parent return None -def _probe_version(binary): +def _probe_version(binary, cwd=None): if not binary: return None try: - proc = subprocess.run([binary, '--version'], capture_output=True, text=True, timeout=15) + proc = subprocess.run( + [binary, '--version'], + cwd=str(cwd) if cwd is not None else None, + capture_output=True, + text=True, + timeout=15, + ) if proc.returncode == 0: return proc.stdout.strip().splitlines()[0] if proc.stdout.strip() else '' except (OSError, subprocess.SubprocessError): @@ -184,8 +195,8 @@ def check_lean(target, project=None, build_lib=False, kernel_sources=None, else None ) toolchain = { - 'lean_version': _probe_version(lean_bin), - 'lake_version': _probe_version(lake_bin), + 'lean_version': _probe_version(lean_bin, cwd=project_dir), + 'lake_version': _probe_version(lake_bin, cwd=project_dir), 'lean_toolchain': toolchain_pin, } diff --git a/skills/operator-verify/scripts/triage.py b/skills/operator-verify/scripts/triage.py index 8e59ad8..19c6f8c 100644 --- a/skills/operator-verify/scripts/triage.py +++ b/skills/operator-verify/scripts/triage.py @@ -48,19 +48,26 @@ # Word-boundary regex patterns to prevent substring collisions (e.g. "race" in "trace", "tail" in "detail", "192" in "head_dim 192"). _CATEGORY_PATTERNS = ( ('pipeline_sync', re.compile( - r'\b(?:setflag|waitflag|hardevent|mte2|mte3|pipe_[a-z0-9]+|data\s+race|race\s+condition|deadlock|pipebarrier|syncall)\b', + r'\b(?:setflag|waitflag|hardevent|ibwait|ibset|mte2|mte3|pipe_[a-z0-9]+|data\s+race|race\s+condition|deadlock|pipebarrier|syncall)\b', re.I, )), ('resource_capacity', re.compile( - r'\b(?:unified\s+buffer|ub\s+overflow|ub\s+budget|ub\s+limit|multibuffer|192\s*k(?:i?b)?|248\s*k(?:i?b)?|32b\s*align|sram)\b', + r'\b(?:unified\s+buffer|ub\s+(?:overflow|overrun|budget|limit|alias\w*)|tbuf|ubcastsafe|' + r'in-place\s+(?:[a-z0-9_:-]+\s+){0,3}(?:cast|alias\w*)|cast\s+in-place|' + r'byte[- ]vs[- ]element|multibuffer|192\s*k(?:i?b)?|248\s*k(?:i?b)?|32b\s*align|sram|silent\s+(?:host-side\s+)?tile\s+clamp\w*)\b', + re.I, + )), + # Specific semantic-equivalence phrases that contain the word "mask" must precede generic index_and_mask `\bmask\b`. + ('semantic_equivalence', re.compile( + r'\b(?:inverted\s+bool(?:ean)?(?:\s+[a-z0-9_]+){0,2}\s+mask|welford|ldl\^?t|log2e)\b', re.I, )), ('index_and_mask', re.compile( - r'\b(?:mask|masked\s+load|tail\s+(?:block|tile|lane|padding|slot)|padding_option|tiling|int32\s+overflow|oob|out-of-bounds|updatemask|counter)\b', + r'\b(?:mask|masked\s+load|boundary_check|tail\s+(?:block|tile|lane|padding|slot)|padding_option|tiling|int32\s+overflow|oob|out-of-bounds|updatemask|counter|unconditional\s+store|stride)\b', re.I, )), ('semantic_equivalence', re.compile( - r'(?:-inf\b|\b(?:bitvec|bitwise|torch\.compile|lowering|fusion|megakernel|reduction|equivalence|nan|online\s+softmax|softmax|poison|ldl\^?t)\b)', + r'(?:-inf\b|\b(?:bitvec|bitwise|torch\.compile|lowering|fusion|megakernel|reduction|equivalence|nan|online\s+softmax|softmax|poison|transpose|inverted\s+bool(?:ean)?|silent\s+truncat\w*)\b)', re.I, )), ('numeric_rounding', re.compile( @@ -93,6 +100,8 @@ def triage(operator=None, category=None, description='', backend='unknown', if handoff is not None: handoff_path = str(handoff) handoff_data = json.loads(Path(handoff).read_text(encoding='utf-8')) + if not isinstance(handoff_data, dict): + raise ValueError(f'handoff file must contain a JSON object: {handoff}') if not operator: op_info = handoff_data.get('operator') if isinstance(op_info, dict): @@ -151,7 +160,7 @@ def main(argv=None): choices=('triton-ascend', 'ascendc', 'triton', 'cuda', 'unknown')) parser.add_argument('--source', type=Path, help='Optional kernel source file path') parser.add_argument('--handoff', type=Path, help='Optional operator-optimize handoff.json path') - parser.add_argument('--mode', default='standalone', choices=('standalone', 'repo_audit'), + parser.add_argument('--mode', default='standalone', choices=('standalone', 'numericbridge_companion'), help='Workflow entry mode (auto-set to numericbridge_companion when --handoff is passed)') parser.add_argument('--claim-kind', default='universal_proof', choices=('universal_proof', 'refutation', 'equivalence'))