Skip to content

T2.1 算子编译诊断 CLI & T2.2 Pass Diff 工具 & T2.5 Adapter 层健壮性 - #55

Open
kong-LrYz wants to merge 14 commits into
RACE-org:mainfrom
kong-LrYz:t2.5-adapter-robustness
Open

T2.1 算子编译诊断 CLI & T2.2 Pass Diff 工具 & T2.5 Adapter 层健壮性#55
kong-LrYz wants to merge 14 commits into
RACE-org:mainfrom
kong-LrYz:t2.5-adapter-robustness

Conversation

@kong-LrYz

Copy link
Copy Markdown
Contributor

No description provided.

skwmw01 and others added 14 commits July 5, 2026 17:06
Implement PassDiagnostic to run TTIR and triton-linalg pipelines pass by
    pass, saving before/after IR snapshots, failure diagnostics, summary.json,
    and best-effort MLIR op/location.

Add triton_anchor.diagnose CLI with file input and --python
    MODULE:FUNCTION runtime TTIR generation, and register triton-anchor-diagnose
    console script in setup.py and pyproject.toml.

Add diagnostics unit tests, user documentation, T2.1 implementation
    reports, and a retained failing inline-asm sample source.
Add python-frontend and input-parse diagnostic handling before pass
    execution. Update CLI output, summaries, tests, runnable failure
    samples, and diagnostics documentation. Remove the superseded T2.1
    analysis document.
Implement PassDiagnostic to run TTIR and triton-linalg pipelines pass by
    pass, saving before/after IR snapshots, failure diagnostics, summary.json,
    and best-effort MLIR op/location.

Add triton_anchor.diagnose CLI with file input and --python
    MODULE:FUNCTION runtime TTIR generation, and register triton-anchor-diagnose
    console script in setup.py and pyproject.toml.

Add diagnostics unit tests, user documentation, T2.1 implementation
    reports, and a retained failing inline-asm sample source.
Add python-frontend and input-parse diagnostic handling before pass
    execution. Update CLI output, summaries, tests, runnable failure
    samples, and diagnostics documentation. Remove the superseded T2.1
    analysis document.
Extend PassDiagnostic to capture per-pass timing, IR size changes, and RSS
sampling when running adapter pipelines (triton-linalg / triton-shared).
All metrics flow into the existing triton-anchor-diagnose CLI and summary.json.

Changes:
- python/triton_anchor/diagnostics.py: add duration_ms/before_ir_bytes/
  after_ir_bytes/ir_delta_bytes/peak_rss_bytes to PassRunRecord; add
  total_duration_ms/input_ir_bytes/output_ir_bytes/peak_rss_bytes/slowest_pass
  to PassDiagnosticResult; wire collection in _diagnose_pipeline loop
- python/triton_anchor/diagnose.py: display metrics in _print_result
- python/triton_anchor/tests/test_diagnostics.py: add 2 tests for metrics
- docs/t2_5_adapter_robustness_review.md: design writeup

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Add t2_5_adapter_observability.md: usage, metrics, changed files,
  test results, implementation details, design decision, task context,
  and follow-up work
- Remove t2_5_adapter_robustness_review.md (content merged above)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add Sophgo PPLIR and external-stage diagnostic coverage, update CLI support, tests, docs, and the PPLIR failure sample. Keep generated diagnostic outputs and build artifacts untracked.
Copilot AI review requested due to automatic review settings July 22, 2026 08:04

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR introduces a pass-level diagnostics framework for Triton Anchor compilation pipelines, adds a dedicated CLI entry point (triton-anchor-diagnose), and documents/validates the workflow via unit tests and example failure kernels.

Changes:

  • Add PassDiagnostic / StageDiagnostic infrastructure to run pipelines pass-by-pass, snapshot IR, capture diagnostics, and write structured summary.json.
  • Add triton-anchor-diagnose CLI supporting file-based MLIR/TTIR inputs and --python MODULE:FUNCTION TTIR generation for TTIR-only diagnostics.
  • Add tests, user-facing docs, and example “bad kernels” to demonstrate/validate failure localization across TTIR, triton-linalg, and Sophgo PPLIR.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 10 comments.

Show a summary per file
File Description
setup.py Registers triton-anchor-diagnose console script entry point.
python/triton_anchor/diagnostics.py Implements pass/stage diagnostic core, stderr capture, MLIR location/op extraction, and summary recording.
python/triton_anchor/diagnose.py Implements CLI argument parsing, input loading / python frontend flow, and human-readable output printing.
python/triton_anchor/tests/test_diagnostics.py Adds unit tests covering pass failure identification, location extraction, CLI behavior, and metrics.
python/triton_anchor/init.py Re-exports PassDiagnostic and StageDiagnostic from the package.
ops-diagnose-cli/test/anchor_diag_bad_pplir_kernel.py Example kernel to trigger Sophgo PPLIR pipeline failure for validation.
ops-diagnose-cli/test/anchor_diag_bad_kernels.py Example kernel to trigger adapter-lowering failure for validation.
ops-diagnose-cli/test/anchor_diag_bad_frontend_kernel.py Example kernel to trigger python-frontend failure for validation.
ops-diagnose-cli/docs/T2.1-implementation-and-test-results.md Implementation/test report for T2.1 workflow and artifacts.
docs/t2_5_adapter_observability.md Documents adapter observability metrics and their interpretation.
docs/diagnostics.md User-facing documentation for diagnostics capabilities, usage, and boundaries.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +785 to +791
def _find_location_match(text: str) -> Optional[re.Match[str]]:
patterns = [
r'loc\("(?P<file>[^"]+)":(?P<line>\d+):(?P<column>\d+)\)',
r'(?P<file>[^\s:"\']+\.m?lir):(?P<line>\d+):(?P<column>\d+)',
r'(?P<file><[^>]+>):(?P<line>\d+):(?P<column>\d+)',
r'(?P<line>\d+):(?P<column>\d+)',
]
Comment on lines +329 to +337
def _constant_key_to_index(key: str, arg_names: list[str]) -> int:
if key.isdigit():
return int(key)
if key in arg_names:
return arg_names.index(key)
raise ValueError(
f"constant key '{key}' is not an argument name or index; "
f"available args: {', '.join(arg_names) if arg_names else '<unknown>'}"
)

## 提供的指标

指标的采集范围是 **Adapter 层**:从 TTIR 进入 Adapter 开始,到 Linalg IR 输出为止(即 `--pipeline triton-linalg` 的 15 个 pass)。不包含 TTIR 优化阶段、PPLIR 及后续编译阶段。

**这是使用这些指标时最需要注意的一点。**

指标采集**不调用** adapter 的 `convert()`(它内部把 15 个 pass 塞进一个 `pass_manager` 一次 `pm.run()` 跑完,是黑盒,中间插不进埋点)。诊断路径走的是 `build_triton_linalg_pass_descriptors()`——它把 adapter 那条流水线**逐 pass 手抄成了一份独立的 descriptor 列表**,诊断时按这份列表逐个 pass 单独跑并埋点。
| --- | --- |
| `python/triton_anchor/__init__.py` | 导出诊断相关能力,使 `triton_anchor` 包对外暴露新增诊断模块。 |
| `setup.py` | 注册 `console_scripts`,安装后生成 `triton-anchor-diagnose` 命令;同时保留原有 adapter entry point。 |
| `pyproject.toml` | 同步注册 `[project.scripts]`,避免不同安装方式下 CLI 命令未生成。 |
Comment on lines +504 to +512
`pyproject.toml` 中新增:

```toml
[project.scripts]
triton-anchor-diagnose = "triton_anchor.diagnose:main"
```

由于仓库同时存在 `setup.py` 和 PEP 621 `[project]` 元数据,两个位置都注册可以避免安装方式差异导致命令没有生成。

Comment on lines +719 to +739
def _run_with_stderr_capture(pm: Any, mod: Any) -> str:
saved_stderr_fd = os.dup(2)
original: Optional[Exception] = None
with tempfile.TemporaryFile(mode="w+b") as captured:
try:
os.dup2(captured.fileno(), 2)
try:
pm.run(mod)
except Exception as exc:
original = exc
finally:
os.dup2(saved_stderr_fd, 2)
finally:
os.close(saved_stderr_fd)

captured.seek(0)
diagnostic_text = captured.read().decode("utf-8", errors="replace")

if original is not None:
raise _CapturedPassError(original, diagnostic_text) from original
return diagnostic_text
Comment on lines +370 to +391
def _capture_stderr(fn):
saved_stderr_fd = os.dup(2)
original: Exception | None = None
result = None
with tempfile.TemporaryFile(mode="w+b") as captured:
try:
os.dup2(captured.fileno(), 2)
try:
result = fn()
except Exception as exc:
original = exc
finally:
os.dup2(saved_stderr_fd, 2)
finally:
os.close(saved_stderr_fd)

captured.seek(0)
diagnostic_text = captured.read().decode("utf-8", errors="replace")

if original is not None:
raise _CapturedInputError(original, diagnostic_text) from original
return result, diagnostic_text
Comment on lines +90 to +96
OK: pipeline triton-linalg completed, 9/9 passes executed.
total duration: 342.56 ms
input IR: 1523 bytes
output IR: 2847 bytes
peak RSS: 87.34 MB
slowest pass: #7 triton_to_linalg (189.23 ms)
summary: ./out/summary.json
Comment on lines +101 to +109
FAILED: pipeline triton-linalg failed at pass 4/9: pointer_strength_reduction
pass duration: 23.45 ms
before IR: 1523 bytes
total duration (up to failure): 98.76 ms
peak RSS: 65.21 MB
location: kernel.py:12:8
operation: tt.load
summary: ./out/summary.json
```
@github-advanced-security

Copy link
Copy Markdown

You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool.

What Enabling Code Scanning Means:

  • The 'Security' tab will display more code scanning analysis results (e.g., for the default branch).
  • Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results.
  • You will be able to see the analysis results for the pull request's branch on this overview once the scans have completed and the checks have passed.

For more information about GitHub Code Scanning, check out the documentation.

@github-actions

Copy link
Copy Markdown

Codex AI 自动审查

Codex AI 自动审查仅供参考且不阻塞合入;本地确定性 CI 检查结果才是合入门禁。

审查摘要

  • Codex AI 审查结论:警告
  • 本地确定性 CI 检查:已通过;Codex AI 自动审查只提供补充意见,不改变门禁结果。
  • 合入建议:修复两个 MEDIUM finding 后再合入,并复测并发 stderr 捕获与实际 Sophgo JIT 自动错误路径;修正文档 pass 计数。本地确定性 CI 检查门禁仍应作为最终合入条件。

本次变更新增逐 pass 编译诊断 CLI、结构化结果和 Adapter 指标,且当前 14-pass triton-linalg descriptor 与 adapter 实现一致。本地确定性 CI 检查在合并提交上完成 fresh wheel 构建、Sophgo CModel JIT smoke、FlagGems 样本及性能比较,但未覆盖新增诊断的真实失败集成。审查确认一个会破坏并发进程 stderr 的实现缺陷,以及自动 JIT hook 文档与实际仓库变更不一致。

贡献者目标与实现情况

  • 判断:部分实现
  • 贡献者目标:提供算子编译诊断 CLI、Pass Diff 工具及 Adapter 层健壮性/可观测性能力。
  • 预期效果:用户可通过 CLI 定位编译失败 pass,并获得 Adapter 指标;标题同时声明应提供 Pass Diff 工具和 Adapter 健壮性能力。
  • 当前实现情况:已实现 CLI、TTIR/triton-linalg/Sophgo PPLIR 的逐 pass 诊断、结构化结果和 Adapter 指标,且 Adapter descriptor 与当前真实 pass 序列一致。T2.2 Pass Diff 未实现;文档中自动 JIT hook 与外部阶段接入的声明超出本仓库实际 diff。
  • 判断依据:
    • 实际 diff 新增诊断 CLI、逐 pass descriptor、诊断结果与 Adapter 指标字段,并注册 console script。
    • PR 标题包含 T2.2 Pass Diff,但 CLI 参数、模块和文档均未提供两个 pass/IR 结果的差异比较功能。
    • 文档宣称 Sophgo JIT 自动 hook 以及外部编译、运行时和结果错误诊断已接入,但本次仓库变更中只有诊断记录类,没有这些阶段的调用点。

需要处理的问题

1. [中风险] 并发诊断会破坏进程 stderr 路由

  • 问题类型:并发错误
  • 代码定位:python/triton_anchor/diagnostics.py:724
  • 这段代码负责:将 MLIR pass 执行期间的 stderr 重定向到临时文件
  • 核心证据:该函数使用 os.dup2 修改进程级 fd 2,未使用任何同步。定向并发复现两个 _capture_stderr 调用交错后,/proc/self/fd/2 输出为“/tmp/... (deleted)”,证明后完成的调用恢复了另一调用已关闭的临时 stderr,而非原始 stderr。diagnose.py 的同类 _capture_stderr 也采用相同模式。
  • 影响:并发 JIT 编译或多个诊断请求交错时,后续进程 stderr 可能永久写入已删除临时文件,导致编译诊断和应用日志丢失。
  • 建议:避免进程级 fd 重定向,优先使用 MLIR/Python 可用的局部诊断捕获接口;若必须重定向,使用覆盖完整重定向与恢复区间的进程级锁,并为并发调用增加回归测试。

2. [中风险] 自动 JIT 诊断覆盖仅有文档声明,缺少仓库内调用集成

  • 问题类型:正确性错误
  • 代码定位:ops-diagnose-cli/docs/T2.1-implementation-and-test-results.md:25
  • 这段代码负责:声明已覆盖 Sophgo JIT 自动诊断及外部失败阶段
  • 核心证据:文档称环境变量自动 hook 已覆盖 TTIR、triton-linalg、PPLIR、ppl-compile、CMake/.so、runtime 和结果 mismatch;但本次受信 diff 仅新增 PassDiagnostic/StageDiagnostic 记录类。搜索本仓库实际代码,除文档和样例外没有 TRITON_ANCHOR_DIAGNOSE_ON_ERROR、StageDiagnostic.record_failure 或外部阶段 hook 调用点,且文档所列 backend 文件不在本次变更清单。
  • 影响:用户按文档设置环境变量后不会在本仓库实际代码路径中获得承诺的自动诊断,ppl-compile、CMake、runtime 和结果错误的覆盖声明也不可达。
  • 建议:将相应 Sophgo backend、driver 与测试 hook 纳入同一变更并增加端到端失败验证,或删改文档为仅提供可由调用方集成的诊断库与 CLI。

3. [低风险] Adapter 指标文档中的 pass 总数和示例与实现不一致

  • 问题类型:正确性错误
  • 代码定位:docs/t2_5_adapter_observability.md:66-101
  • 这段代码负责:展示 triton-linalg 成功和失败时的 CLI pass 计数
  • 核心证据:实现的 build_triton_linalg_pass_descriptors 返回 14 个 descriptor,未修改的 TritonLinalgAdapter._add_passes 也实际添加 14 个 pass;文档却声明该 pipeline 为 15 个 pass,并给出 9/9 和 4/9 示例。
  • 影响:用户会将正常的 14/14 输出误判为不完整执行,或依据错误序号定位失败 pass。
  • 建议:将范围说明和成功/失败示例统一为当前 14 个 pass,或在实现确实新增 pass 后同步更新 descriptor、adapter 与测试。

可点击代码定位

链接固定到本次测试提交,便于提交者修复和审核者核对代码功能;已验证行号的问题链接到具体行,仅能确认文件的问题链接到文件并标注行号待核对。

验证情况

  • 验证内容与结果:
    • 本地确定性 CI 检查针对合并提交完成 fresh wheel 构建、安装、frontend smoke、Sophgo CModel JIT smoke、FlagGems 6 个样本和性能比较,结果均通过。
    • 诊断单元测试 13 项通过,覆盖逐 pass 成功/失败、CLI pre-pass 诊断、位置提取、PPLIR 结果和 Adapter 指标数据。
    • 新增 Python 文件与故障样例通过 py_compile,模块 CLI 帮助可在源码环境加载。
    • 定向并发复现确认 stderr 捕获会将 fd 2 留在已删除临时文件,支持并发 finding。
    • Codex 执行的验证或诊断命令执行失败,现有记录尚不足以完成稳定性或根因归因。
    • 验证新增 Python 文件可解析执行成功。
    • 定向验证新增诊断核心与 CLI 行为执行成功。
    • 验证 CLI 模块入口不依赖 libtriton 即可加载执行成功。
    • 定向反证 stderr 捕获在并发下可安全恢复的假设执行成功。
  • 限制与未覆盖:
    • 失败记录尚不足以完成稳定性或根因归因。
    • 现有验证尚未覆盖本次变更的全部风险。
    • 尚未执行:在两个线程中同时触发 PassDiagnostic 与 CLI 输入诊断,断言调用结束后 fd 2 仍指向原始 stderr,并验证两份诊断文本各自完整。
    • 尚未执行:在实际 Sophgo backend 中注入一个可控的 TTIR、triton-linalg、ppl-compile 和 runtime 失败,设置 TRITON_ANCHOR_DIAGNOSE_ON_ERROR=1 后断言对应 summary.json 与 diagnostic 文件生成。
    • 尚未执行:用真实 TTIR 输入运行 triton-anchor-diagnose --pipeline triton-linalg,断言 summary.json 的 records 数为 14、指标字段存在且 CLI 文档示例一致。

剩余风险

  • 真实 Sophgo PPLIR pass、外部编译失败和 runtime 失败未在本轮运行;现有单元测试以 fake libtriton/Sophgo pass 验证诊断结果结构。
  • 本地确定性 CI 检查的 pass-profile 产物显示四个 kernel 的 events 均为 0,因此不能作为新增逐 pass Adapter 指标实际输出的验证证据。

变更文件

查看变更文件
文件 类型 改动说明 影响
docs/diagnostics.md 新增 新增诊断工具使用说明、输出格式、样例及边界说明。 向用户公布诊断 CLI、IR pipeline 和自动诊断能力;其中自动 hook 范围需与实际集成代码保持一致。
docs/t2_5_adapter_observability.md 新增 新增 Adapter 可观测性指标字段、示例输出和与真实 adapter pass 列表同步的说明。 定义 Adapter 指标的用户预期和验证方法;示例 pass 数不准确会误导使用者判断执行结果。
ops-diagnose-cli/docs/T2.1-implementation-and-test-results.md 新增 新增 T2.1 实现说明、测试记录和故障样例说明。 作为实现与测试说明,影响用户对自动 JIT 诊断和外部失败阶段覆盖范围的判断。
ops-diagnose-cli/test/anchor_diag_bad_frontend_kernel.py 新增 新增使用不存在 Triton builtin 触发 python-frontend 失败的 kernel 样例。 提供 Python/Triton 前端失败的手工诊断样例。
ops-diagnose-cli/test/anchor_diag_bad_kernels.py 新增 新增 inline asm lowering 失败样例及按环境变量运行诊断的入口。 提供 triton-linalg lowering 失败的手工诊断样例。
ops-diagnose-cli/test/anchor_diag_bad_pplir_kernel.py 新增 新增 2D 到 3D broadcast 的 PPLIR 失败样例及诊断入口。 提供 Sophgo PPLIR lowering 失败的手工诊断样例。
python/triton_anchor/__init__.py 修改 新增两个诊断类的包级 re-export。 将 PassDiagnostic 与 StageDiagnostic 作为 triton_anchor 包级公共导出,增加但不替换既有 API。
python/triton_anchor/diagnose.py 新增 新增 argparse CLI、TTIR 生成、MLIR 加载、输入诊断写入和结果打印。 提供文件输入和 Python kernel 输入的诊断 CLI,定义退出码、输出产物和预处理错误契约。
python/triton_anchor/diagnostics.py 新增 新增 PassDiagnostic、StageDiagnostic、TTIR/triton-linalg/Sophgo descriptor、summary JSON 和指标采集。 实现逐 pass 诊断、IR 快照、位置提取、PPLIR descriptor、外部阶段记录及 Adapter 指标;stderr 捕获会影响同进程并发调用。
python/triton_anchor/tests/test_diagnostics.py 新增 新增 13 个诊断单元测试。 为新增诊断核心提供 fake libtriton/Sophgo 单元覆盖,包括成功、失败、位置和指标场景。
setup.py 修改 新增 console_scripts 注册。 安装 wheel 后生成 triton-anchor-diagnose 命令,同时保留 triton.adapters entry point。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants