JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat: add skill ascend-moe-optimizer-trace-analyzer
openJiuwen-bot6005eb32b845
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/SKILL.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/SKILL.mdnew file mode 100644index 0000000000..503d13c549--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/SKILL.md@@ -0,0 +1,217 @@+---+name: ascend-moe-optimizer-trace-analyzer+description: 在用户提供 Chrome/Perfetto trace.json、或排查 Ascend 上 MoE/FusedDeepMoe 等算子性能时使用。按 phase、category、core group、tid 统计耗时、overlap、bubble,输出 CSV、Markdown 报告与确定性诊断;可选外部 LLM 扩写分析。默认 phase 映射面向 UMDK FusedDeepMoe,其它 trace 需替换或扩展 config/phase_map.yaml。+---++# Ascend MoE 性能 Trace 分析++分析 Chrome/Perfetto 风格的 `trace.json`,把原始 trace event 转换为结构化统计表、图表和 Markdown 报告,用于替代人工在 Perfetto 中做第一轮耗时分布和瓶颈定位。本 skill 的内置名称为 `ascend-moe-optimizer-trace-analyzer`;当前目录为 `ascend-moe-optimizer-trace-analyzer`。++## 何时使用++- 用户需要分析 **算子或 runtime 打点** 导出的 **Chrome/Perfetto `trace.json`**,关注 **phase 分布、category、Ascend core group、线程 tid、overlap、bubble**。+- 调优 **Ascend 上 MoE / FusedDeepMoe(如 `fused_deep_moe`)** 或需沿用本仓库默认 `config/phase_map.yaml` 的场景。+- 需要 **确定性自动诊断**,或可选的 **`--llm-analysis`** 二次解读。++## 脚本位置++- 用户安装后的 skill 根目录:`<ASCEND_MOE_OPTIMIZER_SKILL>` = `~/.jiuwenclaw/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer`+- 入口:`<ASCEND_MOE_OPTIMIZER_SKILL>/app.py`+- 从本仓库资源运行时,将上述路径换为 `jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer`(相对仓库根目录)。++执行命令前请先 `cd` 到 `<ASCEND_MOE_OPTIMIZER_SKILL>`,或使用下文绝对路径形式的 `python3 .../app.py`。++## 能力概览++本 skill 面向的核心对象是 `trace.json`,不是某一个固定算子。它本身负责:+- 解析 trace 中的完整区间事件。+- 将原始 trace name 映射为可稳定统计的 phase。+- 按 phase、category、core group、tid、raw name 聚合耗时。+- 计算 phase overlap 和外层阶段 bubble。+- 生成统计图、文字化统计摘要和 Markdown 报告。+- 生成稳定、可复现的自动诊断。+- 可选调用外部 LLM,把统计上下文扩写成专家分析段落。++当前仓库默认携带的 `config/phase_map.yaml` 和部分诊断规则来自 UMDK FusedDeepMoe trace 的实践经验。因此,默认配置对 FusedDeepMoe 最友好;如果要分析其他来源的 trace,应替换或扩展 phase/category 映射配置,并逐步沉淀对应领域的诊断规则。++## Agent 执行原则+执行本 skill 时,agent 不应把文档中的示例路径当成固定输入。应先从用户请求或当前工作区中确认以下上下文,并把它们替换到命令中:++- `TRACE_JSON`:必需,用户要分析的 trace 文件。+- `OUTPUT_DIR`:必需或由 agent 选择,建议按本次任务命名,例如 `output/<case_name>`。+- `PHASE_MAP`:可选,phase/category 映射配置。若用户指定算子或已有对应配置,应使用对应配置;否则使用默认 `config/phase_map.yaml`。+- `SOURCE_ROOT`:可选,算子源码工程目录,例如某个 UMDK 工程。当前 CLI 尚未消费该参数,但 agent 可以用它阅读源码、理解打点语义和辅助维护 phase map。+- `OPERATOR`:可选,用户指定的算子名,例如 `fused_deep_moe`。当前 CLI 尚未消费该参数,但 agent 应用它选择或维护对应的 phase/category 规则和诊断上下文。++如果用户只提供 `trace.json`,按 trace-only 模式分析。如果用户同时提供源码目录和算子名,agent 应先阅读相关源码打点,再决定是否需要补充或调整 `PHASE_MAP`。++## 执行命令++在 `<ASCEND_MOE_OPTIMIZER_SKILL>` 目录下执行(以下 `<ASCEND_MOE_OPTIMIZER_SKILL>` 含义见「脚本位置」):++基础命令模板:++```bash+cd <ASCEND_MOE_OPTIMIZER_SKILL>+python3 app.py \+ --trace <TRACE_JSON> \+ --phase-map <PHASE_MAP> \+ --output-dir <OUTPUT_DIR>+```++常用参数:+- `--trace PATH`:输入 trace JSON,必填。+- `--phase-map PATH`:phase/category 映射配置,默认 `config/phase_map.yaml`。+- `--output-dir DIR`:输出目录,默认 `output`。+- `--top-n 20`:控制 `report.md` 中各表展示的行数。+- `--llm-analysis`:启用 LLM Analysis 章节。+- `--llm-command "<cmd>"`:外部 LLM 命令,命令从 stdin 读取 prompt,并把分析文本写到 stdout。+- `--llm-timeout 120`:LLM 命令超时时间,单位秒。++如果使用默认 phase map,可以省略 `--phase-map`:++```bash+cd <ASCEND_MOE_OPTIMIZER_SKILL>+python3 app.py \+ --trace <TRACE_JSON> \+ --output-dir <OUTPUT_DIR>+```++如果本机安装了 `matplotlib`,运行时会默认生成统计分析总图 `analysis_charts.png`,并嵌入 `report.md`。未安装时会跳过图表,其他输出不受影响。++LLM 命令也可以用环境变量配置:++```bash+export TRACE_ANALYSIS_LLM_CMD="<your-llm-cli>"+cd <ASCEND_MOE_OPTIMIZER_SKILL>+python3 app.py \+ --trace <TRACE_JSON> \+ --phase-map <PHASE_MAP> \+ --output-dir <OUTPUT_DIR> \+ --llm-analysis+```++如果未启用 `--llm-analysis`,仍会生成 `llm_prompt.md`,方便后续手动交给 Codex 或其他模型复核。++## 输入要求+支持两种 trace 文件外层格式:+- `{ "traceEvents": [...] }`+- 直接以事件数组 `[...]` 作为文件内容++支持的事件类型:+- `ph == "X"`:完整区间事件,直接使用 `ts + dur` 得到结束时间。+- `ph == "B" / "E"`:按 `(pid, tid, name)` 栈式配对为完整区间。++每个可分析事件至少应包含:+- `name`:事件名称。+- `ts`:开始时间或 B/E 时间戳。+- `dur`:仅 `X` 事件需要。+- `pid` / `tid`:进程和线程维度,建议保留。+- `args`:可选,若包含 `core_type/core_id/rank_id/extra_id/event_id` 等字段,报告会一并保留。++不匹配 `--phase-map` 的事件当前不会进入 phase 统计表。分析非默认 trace 时,最重要的适配工作就是维护一份能覆盖目标 trace name 的 phase mapping。++分析时会同时保留:+- `name`:原始 trace name。+- `normalized_name`:去掉 `[extra:x] #seq` 后的归一化名称,便于把同一类事件合并统计。++## Phase 和 Category++本 skill 通过 `--phase-map` 指定的 YAML 配置把原始 trace name 映射到稳定 phase。配置包含两类信息:+- `phases`:phase 到正则 pattern 列表的映射。+- `phase_categories`:phase 到 category 的归因。++正则命中多个 phase 时,优先选择 pattern 字符串最长的更具体规则。++默认 category 包括:+- `container`+- `wait`+- `sync`+- `compute`+- `epilogue`+- `communication`+- `quant`+- `init`+- `cleanup`+- `other`++对于 UMDK FusedDeepMoe,默认配置已经覆盖 `processing`、`dispatch_gmm1`、`gmm2_combine` 及其子阶段。对于其他 trace,可以保留这套统计框架,只替换 phase/category 映射。++## Core Group++本 skill 会尽量为每个已映射事件补充:+- `core_type`+- `core_group`+- `core_kind`+- `core_id`++当前内置的核组解释来自 UMDK 1C2V trace:+- `type0 -> cube`+- `type1 -> vector_recv`+- `type2 -> vector_send`++如果 trace event args 中没有 `core_type/core_id`,本 skill 会尝试从 `tid` 推断,例如 `type1_core003 -> vector_recv/core_id=3`。++对于其他来源的 trace,如果没有这类 `core_type` 约定,事件会落到 `unknown` 核组。后续若要支持更多硬件或 runtime,可以把 core group 规则从当前内置逻辑中抽成配置。++## 指标口径+- `total_us`:同类事件时长直接求和,会重复累计并行 tid/core。+- `union_us`:同类事件时间区间并集长度,更接近 wall time 覆盖。+- `ratio_to_total_wall = union_us / trace_wall_time`。+- `ratio_to_core_group_wall = union_us / 当前 core_group 的 union_us`,用于判断某类耗时在该核组内部的覆盖比例。+- `ratio_to_core_group_wall` 是覆盖率,不是互斥占比;不同 category/phase 可以在同一时间重叠,因此同一核组下的百分比不要求加和为 100%。+- `overlap_summary.csv` 的 overlap 基于 phase 区间并集两两求交,避免逐事件重复累计。+- `bubble_summary.csv` 表示外层阶段中未被已知子阶段覆盖的时间空洞。这是“未归因时间”,不一定代表硬件空闲。++## 输出文件+- `phase_instances.csv`:每个已映射区间事件,包含 phase/category/name/core_group/core_id/timing。+- `phase_summary.csv`:按 phase 聚合。+- `category_summary.csv`:按 category 聚合。+- `core_group_summary.csv`:按 core group 聚合。+- `phase_core_group_summary.csv`:按 `(core_group, phase)` 聚合。+- `category_core_group_summary.csv`:按 `(core_group, category)` 聚合。+- `name_summary.csv`:按原始 trace name 聚合。+- `phase_tid_summary.csv`:按 `(phase, pid, tid)` 聚合,用于看单线程或单核长尾。+- `overlap_summary.csv`:phase 两两 overlap。+- `bubble_summary.csv`:外层阶段内部 bubble。+- `summary.json`:整体概览。+- `diagnosis.json`:确定性自动诊断结果。+- `statistical_summary.md`:确定性统计摘要,文字化说明图表和关键统计信号。+- `llm_prompt.md`:交给 LLM 的完整统计上下文,总是生成。+- `llm_analysis_meta.json`:LLM 调用状态、命令和错误信息,总是生成。+- `llm_analysis.md`:启用 LLM 且命令成功时生成。+- `report.md`:可读报告,包含 Overview、Visualizations、Statistical Highlights、Automatic Diagnosis、可选 LLM Analysis 和各类汇总表。+- `analysis_charts.png`:安装 `matplotlib` 时默认生成。单图包含 core group wall 覆盖、非 container category 的 `total_us` 饼图和 top phase。完整 trace 时间线建议继续使用 Perfetto UI 查看。++## 诊断策略+报告优先回答:+1. 哪些 phase 覆盖 wall time 最多。+2. 耗时类型更偏 wait、sync、compute、epilogue、communication 还是 quant。+3. 耗时主要落在哪些 core group 或 tid。+4. 关键 phase 之间的 overlap 是否不足。+5. 外层阶段内部是否存在明显未归因 bubble。+6. top raw names 中哪些原始事件应优先回查。++当前确定性诊断仍包含一部分 UMDK FusedDeepMoe 经验规则,例如 `dispatch_gmm1` 与 `gmm2_combine` 的 overlap 判断。分析其他 trace 时,这些规则可能只具备参考价值;通用统计表和图表仍然是主要输出。++## 依赖和验证+默认运行只使用 Python 标准库,不需要安装第三方包。++可选能力:+- `matplotlib`:用于自动生成 `analysis_charts.png`。+- 外部 LLM CLI:用于 `--llm-analysis`,协议是 stdin 输入 prompt、stdout 输出分析文本。++基础验证:++```bash+cd <ASCEND_MOE_OPTIMIZER_SKILL>+python3 app.py --trace <TRACE_JSON> --phase-map <PHASE_MAP> --output-dir <OUTPUT_DIR> --top-n 20+```++## 当前限制+- 默认只分析单个 trace 文件,不做多 trace 对比。+- 当前没有显式 `--profile` 机制;不同 trace 来源主要通过 `--phase-map` 适配。+- 未映射到 phase 的事件会被过滤,通用 fallback 统计仍有改进空间。+- core group 规则目前仍以内置 UMDK 1C2V 约定为主,尚未完全配置化。+- 部分自动诊断规则仍偏 FusedDeepMoe,需要继续拆分为通用规则和领域规则。+- LLM Analysis 是可选外部命令,不内置具体模型、API key 或网络调用。diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/__init__.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/diagnosis.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/diagnosis.pynew file mode 100644index 0000000000..245f71a6b8--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/diagnosis.py@@ -0,0 +1,250 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Dict, List, Optional+++@dataclass+class AutoDiagnosisInput:+ overview: dict+ phase_summary: List[dict]+ category_summary: List[dict]+ core_group_summary: List[dict]+ phase_core_group_summary: List[dict]+ category_core_group_summary: List[dict]+ name_summary: List[dict]+ overlap_summary: List[dict]+ bubble_summary: List[dict]+++def _num(value: Any) -> float:+ try:+ return float(value)+ except (TypeError, ValueError):+ return 0.0+++def _find_row(rows: List[dict], key: str, value: str) -> Optional[dict]:+ for row in rows:+ if row.get(key) == value:+ return row+ return None+++def _top_non_container_phase(phase_summary: List[dict]) -> Optional[dict]:+ top = None+ for row in phase_summary:+ if row.get("category") != "container" and row.get("phase") != "processing":+ top = row+ break+ if top is None:+ return None++ for row in phase_summary:+ if row.get("category") == "wait" and _num(row.get("union_us")) >= _num(top.get("union_us")) * 0.8:+ return row+ return top+++def _top_category(category_summary: List[dict]) -> Optional[dict]:+ wait_row = _find_row(category_summary, "category", "wait")+ if wait_row and _num(wait_row.get("ratio_to_total_wall")) >= 0.2:+ return wait_row++ for row in category_summary:+ if row.get("category") not in {"container", "other"}:+ return row+ return None+++def _pair_overlap(overlap_summary: List[dict], phase_a: str, phase_b: str) -> Optional[dict]:+ for row in overlap_summary:+ pair = {row.get("phase_a"), row.get("phase_b")}+ if pair == {phase_a, phase_b}:+ return row+ return None+++def _top_names_by_category(name_summary: List[dict], category: str, limit: int = 3) -> List[dict]:+ return [row for row in name_summary if row.get("category") == category][:limit]+++def _top_rows_by_category_core_group(rows: List[dict], category: str, limit: int = 3) -> List[dict]:+ matched = [row for row in rows if row.get("category") == category]+ matched.sort(key=lambda row: (_num(row.get("union_us")), _num(row.get("total_us"))), reverse=True)+ return matched[:limit]+++def _fmt_us(value: Any) -> str:+ return f"{_num(value):.3f} us"+++def _fmt_ratio(value: Any) -> str:+ return f"{_num(value) * 100:.1f}%"+++def build_auto_diagnosis(inp: AutoDiagnosisInput) -> dict:+ overview = inp.overview+ phase_summary = inp.phase_summary+ category_summary = inp.category_summary+ core_group_summary = inp.core_group_summary+ category_core_group_summary = inp.category_core_group_summary+ name_summary = inp.name_summary+ overlap_summary = inp.overlap_summary+ bubble_summary = inp.bubble_summary+ total_wall = _num(overview.get("total_wall_us"))+ findings: List[Dict[str, str]] = []++ top_phase = _top_non_container_phase(phase_summary)+ if top_phase:+ findings.append(+ {+ "severity": "high" if _num(top_phase.get("ratio_to_total_wall")) >= 0.5 else "medium",+ "title": f"主耗时阶段是 {top_phase.get('phase')}",+ "detail": (+ f"union={_fmt_us(top_phase.get('union_us'))}, "+ f"占 wall time {_fmt_ratio(top_phase.get('ratio_to_total_wall'))}, "+ f"category={top_phase.get('category')}."+ ),+ "recommendation": "优先检查该阶段内部的 top raw names 和同 category 的等待/计算子阶段。",+ }+ )++ top_category = _top_category(category_summary)+ if top_category:+ category = top_category.get("category")+ finding = {+ "severity": "high" if _num(top_category.get("ratio_to_total_wall")) >= 0.5 else "medium",+ "title": f"瓶颈类型倾向于 {category}",+ "detail": (+ f"{category} union={_fmt_us(top_category.get('union_us'))}, "+ f"占 wall time {_fmt_ratio(top_category.get('ratio_to_total_wall'))}."+ ),+ "recommendation": "若该类型是 wait/sync,优先看跨核信号与通信;若是 compute/epilogue,优先看矩阵维度、分块和核间负载。",+ }+ findings.append(finding)++ wait_category = _find_row(category_summary, "category", "wait")+ if wait_category and _num(wait_category.get("ratio_to_total_wall")) >= 0.1:+ top_wait_names = _top_names_by_category(name_summary, "wait", 3)+ wait_names = ", ".join(str(row.get("normalized_name") or row.get("name")) for row in top_wait_names)+ findings.append(+ {+ "severity": "high" if _num(wait_category.get("ratio_to_total_wall")) >= 0.4 else "medium",+ "title": "存在显著等待开销",+ "detail": (+ f"wait union={_fmt_us(wait_category.get('union_us'))}, "+ f"占 wall time {_fmt_ratio(wait_category.get('ratio_to_total_wall'))}; "+ f"top wait={wait_names or 'N/A'}."+ ),+ "recommendation": "重点排查 token ready、combine status、shared expert 同步和 AIC/AIV pipeline 依赖。",+ }+ )++ wait_by_core = _top_rows_by_category_core_group(category_core_group_summary, "wait", 3)+ if wait_by_core:+ top_wait_core = wait_by_core[0]+ details = ", ".join(+ f"{row.get('core_group')}={_fmt_us(row.get('union_us'))}"+ for row in wait_by_core+ )+ findings.append(+ {+ "severity": "high" if _num(top_wait_core.get("ratio_to_total_wall")) >= 0.4 else "medium",+ "title": f"等待主要出现在 {top_wait_core.get('core_group')} 核组",+ "detail": (+ f"{details}; "+ f"{top_wait_core.get('core_group')} 内 wait 覆盖该核组 "+ f"{_fmt_ratio(top_wait_core.get('ratio_to_core_group_wall'))}."+ ),+ "recommendation": (+ "分别查看 phase_core_group_summary.csv,确认是 cube 等 token,"+ "还是 vector_recv/vector_send 在等待 combine/status。"+ ),+ }+ )++ observed_groups = {+ row.get("core_group") for row in core_group_summary+ if row.get("core_group") not in {None, "", "unknown"}+ }+ if observed_groups and int(overview.get("num_tids", 0)) >= 24:+ for core_group in ("cube", "vector_recv", "vector_send"):+ group_row = _find_row(core_group_summary, "core_group", core_group)+ if group_row is None:+ findings.append(+ {+ "severity": "medium",+ "title": f"未观察到 {core_group} 核组事件",+ "detail": f"trace 中没有 {core_group} 对应的已映射 phase instance。",+ "recommendation": "确认 trace_collector 是否按 1C2V 模式拆分,或者 profiling tensor 是否缺少该核组数据。",+ }+ )++ dispatch_gmm2 = _pair_overlap(overlap_summary, "dispatch_gmm1", "gmm2_combine")+ if dispatch_gmm2:+ overlap_min = _num(dispatch_gmm2.get("overlap_ratio_min"))+ if overlap_min < 0.2:+ severity = "high"+ title = "dispatch_gmm1 与 gmm2_combine 基本串行"+ action = "检查是否缺少跨阶段流水覆盖,或 gmm2 是否被 gmm1 的 token/quant 输出长时间阻塞。"+ elif overlap_min < 0.5:+ severity = "medium"+ title = "dispatch_gmm1 与 gmm2_combine 流水覆盖偏弱"+ action = "优先检查 gmm2 wait quant、combine wait status、gmm1 quant/sync 是否限制后半段启动。"+ else:+ severity = "info"+ title = "dispatch_gmm1 与 gmm2_combine 有一定流水覆盖"+ action = "继续看各自内部 wait 和 epilogue 是否占主导。"+ findings.append(+ {+ "severity": severity,+ "title": title,+ "detail": (+ f"overlap={_fmt_us(dispatch_gmm2.get('overlap_us'))}, "+ f"相对较短阶段覆盖 {_fmt_ratio(overlap_min)}."+ ),+ "recommendation": action,+ }+ )++ if bubble_summary:+ top_bubble = bubble_summary[0]+ if _num(top_bubble.get("bubble_ratio")) >= 0.05:+ findings.append(+ {+ "severity": "medium",+ "title": f"{top_bubble.get('parent_phase')} 内存在未被子阶段覆盖的空洞",+ "detail": (+ f"bubble={_fmt_us(top_bubble.get('bubble_us'))}, "+ f"占 parent {_fmt_ratio(top_bubble.get('bubble_ratio'))}, "+ f"max_gap={_fmt_us(top_bubble.get('max_gap_us'))}."+ ),+ "recommendation": "结合低层 leaf trace 查看这段空洞是否来自未打点代码、跨核等待,还是 trace depth 过滤后的可见性缺口。",+ }+ )++ if not findings:+ findings.append(+ {+ "severity": "info",+ "title": "未发现明显单点瓶颈",+ "detail": f"已解析 {overview.get('num_instances', 0)} 个 phase instance,total wall={_fmt_us(total_wall)}.",+ "recommendation": "继续结合 phase_tid_summary.csv 检查不同 core 的长尾差异。",+ }+ )++ high_or_medium = [finding for finding in findings if finding.get("severity") in {"high", "medium"}]+ headline = ";".join(finding["title"] for finding in high_or_medium[:2])+ if not headline:+ headline = findings[0]["title"]++ return {+ "headline": headline,+ "total_wall_us": total_wall,+ "bottleneck_phase": top_phase,+ "bottleneck_category": top_category,+ "core_groups": core_group_summary,+ "wait_by_core_group": wait_by_core,+ "findings": findings[:6],+ }diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/llm_analysis.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/llm_analysis.pynew file mode 100644index 0000000000..5f97ca94aa--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/llm_analysis.py@@ -0,0 +1,250 @@+from __future__ import annotations++import os+import shlex+import subprocess+from dataclasses import dataclass+from typing import Any, List, Optional+++@dataclass+class LLMPromptInput:+ overview: dict+ diagnosis: dict+ phase_summary: List[dict]+ category_summary: List[dict]+ core_group_summary: List[dict]+ phase_core_group_summary: List[dict]+ category_core_group_summary: List[dict]+ name_summary: List[dict]+ overlap_summary: List[dict]+ bubble_summary: List[dict]+ top_n: int = 12+++def _fmt(value: Any) -> str:+ if value is None:+ return ""+ if isinstance(value, float):+ if abs(value) >= 100:+ return f"{value:.3f}".rstrip("0").rstrip(".")+ return f"{value:.6f}".rstrip("0").rstrip(".")+ if isinstance(value, list):+ return ", ".join(str(item) for item in value)+ return str(value)+++def _table(rows: List[dict], columns: List[str], limit: int = 12) -> str:+ if not rows:+ return "No data."+ selected = rows[:limit]+ header = "| " + " | ".join(columns) + " |"+ sep = "| " + " | ".join("---" for _ in columns) + " |"+ body = [+ "| " + " | ".join(_fmt(row.get(column)) for column in columns) + " |"+ for row in selected+ ]+ return "\n".join([header, sep] + body)+++def build_llm_prompt(inp: LLMPromptInput) -> str:+ overview = inp.overview+ diagnosis = inp.diagnosis+ phase_summary = inp.phase_summary+ category_summary = inp.category_summary+ core_group_summary = inp.core_group_summary+ phase_core_group_summary = inp.phase_core_group_summary+ category_core_group_summary = inp.category_core_group_summary+ name_summary = inp.name_summary+ overlap_summary = inp.overlap_summary+ bubble_summary = inp.bubble_summary+ top_n = inp.top_n+ findings = diagnosis.get("findings", [])+ finding_lines = []+ for finding in findings:+ finding_lines.append(+ f"- [{finding.get('severity')}] {finding.get('title')}: "+ f"{finding.get('detail')} Action: {finding.get('recommendation')}"+ )++ return "\n\n".join(+ [+ "# Task",+ (+ "你是算子 trace 性能分析专家。请基于下面统计表写一段 LLM Analysis,"+ "用于追加到 report.md。请不要复述所有表格,重点给出 3-5 条有证据的判断和下一步排查建议。"+ ),+ "# Rules",+ "\n".join(+ [+ "- 只能依据给出的统计数据,不要虚构 trace 中没有的信息。",+ "- 明确区分 union_us 和 total_us:union_us 更接近 wall time 覆盖,total_us 会重复累计并行核。",+ "- 关注 core group、tid、phase、category 和 raw name 的分布;如果出现 cube/vector_recv/vector_send,请按核组解释。",+ "- 如果 phase/category 语义明显依赖某个算子配置,请说明适用边界。",+ "- 如果结论不确定,请写“可能”并说明需要继续看哪张表或哪部分源码。",+ "- 输出中文,使用简洁小标题和项目符号。",+ ]+ ),+ "# Overview",+ _table(+ [overview],+ [+ "num_instances",+ "num_phases",+ "num_names",+ "num_pids",+ "num_tids",+ "num_core_groups",+ "core_groups",+ "total_wall_us",+ ],+ 1,+ ),+ "# Deterministic Findings",+ "\n".join(finding_lines) if finding_lines else "No deterministic findings.",+ "# Core Group Summary",+ _table(+ core_group_summary,+ ["core_group", "observed_core_count", "union_us", "ratio_to_total_wall", "total_us"],+ top_n,+ ),+ "# Category By Core Group",+ _table(+ category_core_group_summary,+ [+ "core_group",+ "category",+ "union_us",+ "ratio_to_core_group_wall",+ "ratio_to_total_wall",+ "total_us",+ ],+ top_n * 3,+ ),+ "# Phase By Core Group",+ _table(+ phase_core_group_summary,+ [+ "core_group",+ "phase",+ "category",+ "union_us",+ "ratio_to_core_group_wall",+ "total_us",+ ],+ top_n * 3,+ ),+ "# Phase Summary",+ _table(+ phase_summary,+ ["phase", "category", "count", "union_us", "ratio_to_total_wall", "total_us"],+ top_n,+ ),+ "# Category Summary",+ _table(+ category_summary,+ ["category", "count", "union_us", "ratio_to_total_wall", "total_us"],+ top_n,+ ),+ "# Top Raw Names",+ _table(+ name_summary,+ ["name", "phase", "category", "count", "total_us", "union_us", "tid_nunique"],+ top_n,+ ),+ "# High Overlap Pairs",+ _table(+ overlap_summary,+ ["phase_a", "phase_b", "overlap_us", "overlap_ratio_a", "overlap_ratio_b"],+ top_n,+ ),+ "# Bubble Summary",+ _table(+ bubble_summary,+ ["parent_phase", "bubble_us", "bubble_ratio", "gap_count", "max_gap_us"],+ top_n,+ ),+ ]+ )+++def run_llm_command(prompt: str, command: str, timeout_s: int = 120) -> dict:+ try:+ argv = shlex.split(command)+ except ValueError as exc:+ return {+ "status": "error",+ "analysis": "",+ "error": f"Invalid LLM command: {exc}",+ }++ if not argv:+ return {+ "status": "not_configured",+ "analysis": "",+ "error": "Empty LLM command.",+ }++ try:+ result = subprocess.run(+ argv,+ input=prompt,+ text=True,+ capture_output=True,+ timeout=timeout_s,+ check=False,+ )+ except FileNotFoundError as exc:+ return {+ "status": "error",+ "analysis": "",+ "error": f"LLM command not found: {exc}",+ }+ except subprocess.TimeoutExpired:+ return {+ "status": "timeout",+ "analysis": "",+ "error": f"LLM command timed out after {timeout_s}s.",+ }++ if result.returncode != 0:+ return {+ "status": "error",+ "analysis": "",+ "error": result.stderr.strip() or f"LLM command failed with code {result.returncode}.",+ }++ return {+ "status": "ok",+ "analysis": result.stdout.strip(),+ "error": "",+ }+++def generate_llm_analysis(+ prompt: str,+ enabled: bool = False,+ command: Optional[str] = None,+ timeout_s: int = 120,+) -> dict:+ command = command or os.environ.get("TRACE_ANALYSIS_LLM_CMD")+ if not enabled:+ return {+ "enabled": False,+ "status": "disabled",+ "analysis": "",+ "error": "",+ }++ if not command:+ return {+ "enabled": True,+ "status": "not_configured",+ "analysis": "",+ "error": "Set --llm-command or TRACE_ANALYSIS_LLM_CMD to enable LLM analysis.",+ }++ result = run_llm_command(prompt, command, timeout_s=timeout_s)+ result["enabled"] = True+ result["command"] = command+ return resultdiff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/metrics.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/metrics.pynew file mode 100644index 0000000000..55a26a96dc--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/metrics.py@@ -0,0 +1,595 @@+from __future__ import annotations++import re+from collections import Counter, defaultdict+from typing import Any, Dict, Iterable, List, Optional, Tuple+++Row = Dict[str, Any]+Table = List[Row]+Interval = Tuple[float, float]++_EXTRA_RE = re.compile(r"\s+\[extra:[^\]]+\]")+_SEQ_RE = re.compile(r"\s+#-?\d+$")+_TID_CORE_RE = re.compile(r"type(\d+)_core(\d+)")+_CORE_GROUPS = {+ "0": ("cube", "cube"),+ "1": ("vector_recv", "vector"),+ "2": ("vector_send", "vector"),+}+_CORE_GROUP_ORDER = {+ "cube": 0,+ "vector_recv": 1,+ "vector_send": 2,+ "unknown": 99,+}+++def normalize_event_name(name: str) -> str:+ """+ Strip trace_collector suffixes so labels match source TRACE_POINT names.+ Example: "gmm2-combine wait quant [extra:0] #3" -> "gmm2-combine wait quant".+ """+ normalized = _SEQ_RE.sub("", name)+ normalized = _EXTRA_RE.sub("", normalized)+ return normalized.strip()+++def _safe_sort_value(value: Any) -> Tuple[int, str]:+ if value is None:+ return (1, "")+ return (0, str(value))+++def _float(value: Any, default: float = 0.0) -> float:+ try:+ return float(value)+ except (TypeError, ValueError):+ return default+++def _normalize_core_type(value: Any, tid: Any = None) -> Optional[str]:+ if value is not None and value != "":+ return str(value)++ if tid is None:+ return None+ match = _TID_CORE_RE.search(str(tid))+ if match:+ return match.group(1)+ return None+++def _normalize_core_id(value: Any, tid: Any = None) -> Optional[int]:+ if value is not None and value != "":+ try:+ return int(value)+ except (TypeError, ValueError):+ return None++ if tid is None:+ return None+ match = _TID_CORE_RE.search(str(tid))+ if match:+ return int(match.group(2))+ return None+++def _core_group(core_type: Any) -> str:+ group, _ = _CORE_GROUPS.get(str(core_type), ("unknown", "unknown"))+ return group+++def _core_kind(core_type: Any) -> str:+ _, kind = _CORE_GROUPS.get(str(core_type), ("unknown", "unknown"))+ return kind+++def _phase_category(phase: str, name: str, mapper: Any = None) -> str:+ configured = getattr(mapper, "phase_categories", {}).get(phase) if mapper is not None else None+ if configured:+ return configured++ text = normalize_event_name(name).lower()+ phase_text = phase.lower()++ if text in {"processing", "dispatch-gmm1", "gmm2-combine"}:+ return "container"+ if "wait" in text or "waiting" in text or "sleep" in text:+ return "wait"+ if "sync" in text or "barrier" in text:+ return "sync"+ if "init" in text:+ return "init"+ if "clean" in text or "update" in text:+ return "cleanup"+ if "quant" in text or "swiglu" in text:+ return "quant"+ if "block-epilogue" in text:+ return "epilogue"+ _comm_tokens = ("send", "recv", "combine", "dispatch", "local-copy")+ if any(tok in text for tok in _comm_tokens):+ return "communication"+ if "aic" in text or "aiv" in text or "compcorefunc" in text:+ return "compute"+ if "moe-process" in text:+ return "compute"+ if "gmm" in phase_text or "gmm" in text:+ return "compute"+ return "other"+++def build_phase_instances(events: List[dict], mapper: Any) -> Table:+ """+ Convert parser output into interval rows.+ Each row is one matched full interval event.+ """+ rows: Table = []+ for e in events:+ name = e.get("name")+ if not name:+ continue++ phase = mapper.map_event_name(name)+ if phase is None:+ continue++ args = e.get("args") or {}+ tid = e.get("tid")+ core_type = _normalize_core_type(args.get("core_type"), tid)+ core_id = _normalize_core_id(args.get("core_id"), tid)++ row = {+ "phase": phase,+ "category": _phase_category(phase, name, mapper),+ "name": name,+ "normalized_name": normalize_event_name(name),+ "ts_start": _float(e.get("ts_start")),+ "ts_end": _float(e.get("ts_end")),+ "dur": _float(e.get("dur")),+ "pid": e.get("pid"),+ "tid": tid,+ "rank_id": args.get("rank_id"),+ "core_type": core_type,+ "core_group": _core_group(core_type),+ "core_kind": _core_kind(core_type),+ "core_id": core_id,+ "extra_id": args.get("extra_id"),+ "event_id": args.get("event_id"),+ "cat": e.get("cat"),+ "ph": e.get("ph"),+ }+ rows.append(row)++ rows.sort(+ key=lambda r: (+ _safe_sort_value(r.get("pid")),+ _safe_sort_value(r.get("tid")),+ _float(r.get("ts_start")),+ _float(r.get("ts_end")),+ str(r.get("name", "")),+ )+ )+ return rows+++def _merge_intervals(intervals: Iterable[Interval]) -> List[Interval]:+ valid = sorted((float(s), float(e)) for s, e in intervals if e >= s)+ if not valid:+ return []++ merged: List[List[float]] = [[valid[0][0], valid[0][1]]]+ for s, e in valid[1:]:+ if s <= merged[-1][1]:+ merged[-1][1] = max(merged[-1][1], e)+ else:+ merged.append([s, e])++ return [(float(s), float(e)) for s, e in merged]+++def _interval_union_length(intervals: Iterable[Interval]) -> float:+ return float(sum(e - s for s, e in _merge_intervals(intervals)))+++def _interval_overlap_length(intervals_a: Iterable[Interval], intervals_b: Iterable[Interval]) -> float:+ a = _merge_intervals(intervals_a)+ b = _merge_intervals(intervals_b)++ i = 0+ j = 0+ overlap = 0.0++ while i < len(a) and j < len(b):+ sa, ea = a[i]+ sb, eb = b[j]++ left = max(sa, sb)+ right = min(ea, eb)+ if right > left:+ overlap += right - left++ if ea <= eb:+ i += 1+ else:+ j += 1++ return float(overlap)+++def _intersect_intervals(intervals_a: Iterable[Interval], intervals_b: Iterable[Interval]) -> List[Interval]:+ a = _merge_intervals(intervals_a)+ b = _merge_intervals(intervals_b)+ result: List[Interval] = []+ i = 0+ j = 0++ while i < len(a) and j < len(b):+ sa, ea = a[i]+ sb, eb = b[j]+ left = max(sa, sb)+ right = min(ea, eb)+ if right > left:+ result.append((left, right))+ if ea <= eb:+ i += 1+ else:+ j += 1++ return result+++def _subtract_intervals(parents: Iterable[Interval], children: Iterable[Interval]) -> List[Interval]:+ child_merged = _merge_intervals(children)+ gaps: List[Interval] = []++ for ps, pe in _merge_intervals(parents):+ cursor = ps+ for cs, ce in child_merged:+ if ce <= cursor:+ continue+ if cs >= pe:+ break+ if cs > cursor:+ gaps.append((cursor, min(cs, pe)))+ cursor = max(cursor, ce)+ if cursor >= pe:+ break+ if cursor < pe:+ gaps.append((cursor, pe))++ return gaps+++def _intervals(rows: Table) -> List[Interval]:+ return [(_float(r.get("ts_start")), _float(r.get("ts_end"))) for r in rows]+++def _group_by(rows: Table, key: str) -> Dict[Any, Table]:+ grouped: Dict[Any, Table] = defaultdict(list)+ for row in rows:+ grouped[row.get(key)].append(row)+ return dict(grouped)+++def _main_category(rows: Table) -> Optional[str]:+ categories = Counter(r.get("category") for r in rows if r.get("category"))+ return categories.most_common(1)[0][0] if categories else None+++def _nunique(rows: Table, key: str) -> int:+ return len({r.get(key) for r in rows if r.get(key) is not None})+++def _first_non_none(rows: Table, key: str) -> Any:+ for row in rows:+ value = row.get(key)+ if value is not None and value != "":+ return value+ return None+++def _summarize_rows(group_name: str, group_value: Any, rows: Table, total_wall: float) -> Row:+ durations = [_float(r.get("dur")) for r in rows]+ union_us = _interval_union_length(_intervals(rows))+ total_us = float(sum(durations))+ count = len(rows)++ row = {+ group_name: group_value,+ "count": count,+ "total_us": total_us,+ "avg_us": total_us / count if count else 0.0,+ "max_us": max(durations) if durations else 0.0,+ "min_us": min(durations) if durations else 0.0,+ "union_us": union_us,+ "ratio_to_total_wall": union_us / total_wall if total_wall > 0 else 0.0,+ "first_ts": min((_float(r.get("ts_start")) for r in rows), default=0.0),+ "last_ts": max((_float(r.get("ts_end")) for r in rows), default=0.0),+ "pid_nunique": _nunique(rows, "pid"),+ "tid_nunique": _nunique(rows, "tid"),+ }+ if group_name != "category":+ row["category"] = _main_category(rows)+ return row+++def _total_wall(instances: Table) -> float:+ if not instances:+ return 0.0+ return max(_float(r.get("ts_end")) for r in instances) - min(_float(r.get("ts_start")) for r in instances)+++def build_phase_summary(instances: Table) -> Table:+ if not instances:+ return []++ total_wall = _total_wall(instances)+ rows = [+ _summarize_rows("phase", phase, group, total_wall)+ for phase, group in _group_by(instances, "phase").items()+ ]+ rows.sort(+ key=lambda r: (_float(r.get("union_us")), _float(r.get("total_us"))),+ reverse=True,+ )+ return rows+++def build_category_summary(instances: Table) -> Table:+ if not instances:+ return []++ total_wall = _total_wall(instances)+ rows = []+ for category, group in _group_by(instances, "category").items():+ row = _summarize_rows("category", category, group, total_wall)+ rows.append(row)+ rows.sort(key=lambda r: (_float(r.get("union_us")), _float(r.get("total_us"))), reverse=True)+ return rows+++def build_core_group_summary(instances: Table) -> Table:+ if not instances:+ return []++ total_wall = _total_wall(instances)+ rows: Table = []+ for core_group, group in _group_by(instances, "core_group").items():+ row = _summarize_rows("core_group", core_group, group, total_wall)+ row["core_kind"] = _first_non_none(group, "core_kind")+ row["core_type"] = _first_non_none(group, "core_type")+ row["observed_core_count"] = _nunique(group, "tid")+ rows.append(row)++ rows.sort(key=lambda r: (_CORE_GROUP_ORDER.get(str(r.get("core_group")), 99), -_float(r.get("union_us"))))+ return rows+++def _build_summary_by_core_group(instances: Table, key: str) -> Table:+ if not instances:+ return []++ total_wall = _total_wall(instances)+ core_groups = _group_by(instances, "core_group")+ core_group_union = {+ core_group: _interval_union_length(_intervals(group))+ for core_group, group in core_groups.items()+ }++ grouped: Dict[Tuple[Any, Any], Table] = defaultdict(list)+ for row in instances:+ grouped[(row.get("core_group"), row.get(key))].append(row)++ rows: Table = []+ for (core_group, value), group in grouped.items():+ summary = _summarize_rows(key, value, group, total_wall)+ summary["core_group"] = core_group+ summary["core_kind"] = _first_non_none(group, "core_kind")+ summary["core_type"] = _first_non_none(group, "core_type")+ summary["observed_core_count"] = _nunique(group, "tid")+ summary["core_group_union_us"] = core_group_union.get(core_group, 0.0)+ summary["ratio_to_core_group_wall"] = (+ summary["union_us"] / summary["core_group_union_us"]+ if summary["core_group_union_us"] > 0 else 0.0+ )+ rows.append(summary)++ rows.sort(+ key=lambda r: (+ _CORE_GROUP_ORDER.get(str(r.get("core_group")), 99),+ -_float(r.get("union_us")),+ str(r.get(key)),+ )+ )+ return rows+++def build_phase_core_group_summary(instances: Table) -> Table:+ return _build_summary_by_core_group(instances, "phase")+++def build_category_core_group_summary(instances: Table) -> Table:+ return _build_summary_by_core_group(instances, "category")+++def build_name_summary(instances: Table) -> Table:+ if not instances:+ return []++ total_wall = _total_wall(instances)+ rows: Table = []+ for name, group in _group_by(instances, "name").items():+ row = _summarize_rows("name", name, group, total_wall)+ phase_counts = Counter(r.get("phase") for r in group if r.get("phase"))+ row["phase"] = phase_counts.most_common(1)[0][0] if phase_counts else None+ row["normalized_name"] = normalize_event_name(str(name))+ rows.append(row)++ rows.sort(+ key=lambda r: (+ _float(r.get("total_us")),+ _float(r.get("union_us")),+ int(r.get("count", 0)),+ ),+ reverse=True,+ )+ return rows+++def build_phase_tid_summary(instances: Table) -> Table:+ if not instances:+ return []++ total_wall = _total_wall(instances)+ grouped: Dict[Tuple[Any, Any, Any], Table] = defaultdict(list)+ for row in instances:+ grouped[(row.get("phase"), row.get("pid"), row.get("tid"))].append(row)++ rows: Table = []+ for (phase, pid, tid), group in grouped.items():+ summary = _summarize_rows("phase", phase, group, total_wall)+ summary["pid"] = pid+ summary["tid"] = tid+ rows.append(summary)++ rows.sort(key=lambda r: (str(r.get("phase")), -_float(r.get("union_us")), str(r.get("tid"))))+ return rows+++def build_overlap_summary(instances: Table) -> Table:+ if not instances:+ return []++ phase_to_intervals: Dict[str, List[Interval]] = {}+ phase_to_union: Dict[str, float] = {}+ for phase, group in _group_by(instances, "phase").items():+ intervals = _intervals(group)+ phase_to_intervals[phase] = intervals+ phase_to_union[phase] = _interval_union_length(intervals)++ phases = list(phase_to_intervals.keys())+ rows: Table = []++ for i, phase_a in enumerate(phases):+ for phase_b in phases[i + 1:]:+ overlap_us = _interval_overlap_length(phase_to_intervals[phase_a], phase_to_intervals[phase_b])+ union_a = phase_to_union[phase_a]+ union_b = phase_to_union[phase_b]+ min_union = min(union_a, union_b)+ max_union = max(union_a, union_b)+ rows.append(+ {+ "phase_a": phase_a,+ "phase_b": phase_b,+ "overlap_us": overlap_us,+ "overlap_ratio_a": overlap_us / union_a if union_a > 0 else 0.0,+ "overlap_ratio_b": overlap_us / union_b if union_b > 0 else 0.0,+ "overlap_ratio_min": overlap_us / min_union if min_union > 0 else 0.0,+ "overlap_ratio_max": overlap_us / max_union if max_union > 0 else 0.0,+ "union_us_a": union_a,+ "union_us_b": union_b,+ "non_overlap_a_us": max(union_a - overlap_us, 0.0),+ "non_overlap_b_us": max(union_b - overlap_us, 0.0),+ }+ )++ rows.sort(+ key=lambda r: (+ _float(r.get("overlap_us")),+ _float(r.get("overlap_ratio_a")),+ _float(r.get("overlap_ratio_b")),+ ),+ reverse=True,+ )+ return rows+++def _child_intervals_for_parent(instances: Table, parent_phase: str) -> List[Interval]:+ children: Table = []+ for row in instances:+ phase = str(row.get("phase") or "")+ if phase == parent_phase:+ continue+ if parent_phase == "processing":+ if phase.startswith(("dispatch", "gmm2_combine", "combine")):+ children.append(row)+ elif parent_phase == "dispatch_gmm1":+ if phase.startswith("dispatch_gmm1_") or phase.startswith("dispatch_"):+ children.append(row)+ elif parent_phase == "gmm2_combine":+ if phase.startswith("gmm2_combine_") or phase.startswith("combine_"):+ children.append(row)+ return _intervals(children)+++def build_bubble_summary(instances: Table) -> Table:+ if not instances:+ return []++ phase_groups = _group_by(instances, "phase")+ rows: Table = []++ for parent_phase in ("processing", "dispatch_gmm1", "gmm2_combine"):+ parent_rows = phase_groups.get(parent_phase)+ if not parent_rows:+ continue++ parent_intervals = _merge_intervals(_intervals(parent_rows))+ parent_union = _interval_union_length(parent_intervals)+ child_intervals = _child_intervals_for_parent(instances, parent_phase)+ child_inside_parent = _intersect_intervals(parent_intervals, child_intervals)+ child_covered = _interval_union_length(child_inside_parent)+ bubble_intervals = _subtract_intervals(parent_intervals, child_inside_parent)+ bubble_us = _interval_union_length(bubble_intervals)+ max_gap = max((e - s for s, e in bubble_intervals), default=0.0)++ rows.append(+ {+ "parent_phase": parent_phase,+ "parent_union_us": parent_union,+ "child_covered_us": child_covered,+ "bubble_us": bubble_us,+ "bubble_ratio": bubble_us / parent_union if parent_union > 0 else 0.0,+ "gap_count": len(bubble_intervals),+ "max_gap_us": max_gap,+ }+ )++ rows.sort(key=lambda r: (_float(r.get("bubble_us")), _float(r.get("bubble_ratio"))), reverse=True)+ return rows+++def build_trace_overview(instances: Table) -> dict:+ if not instances:+ return {+ "num_instances": 0,+ "num_phases": 0,+ "num_names": 0,+ "num_pids": 0,+ "num_tids": 0,+ "num_core_groups": 0,+ "core_groups": [],+ "trace_start": None,+ "trace_end": None,+ "total_wall_us": 0.0,+ }++ trace_start = min(_float(r.get("ts_start")) for r in instances)+ trace_end = max(_float(r.get("ts_end")) for r in instances)++ return {+ "num_instances": len(instances),+ "num_phases": _nunique(instances, "phase"),+ "num_names": _nunique(instances, "name"),+ "num_pids": _nunique(instances, "pid"),+ "num_tids": _nunique(instances, "tid"),+ "num_core_groups": _nunique(instances, "core_group"),+ "core_groups": sorted(+ {r.get("core_group") for r in instances if r.get("core_group")},+ key=lambda value: _CORE_GROUP_ORDER.get(str(value), 99),+ ),+ "trace_start": trace_start,+ "trace_end": trace_end,+ "total_wall_us": trace_end - trace_start,+ }diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/parser.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/parser.pynew file mode 100644index 0000000000..4b1d332921--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/parser.py@@ -0,0 +1,173 @@+from __future__ import annotations++import json+from dataclasses import dataclass, asdict+from typing import Any, Dict, List, Optional, Tuple+++@dataclass+class Event:+ name: str+ ts_start: float+ ts_end: float+ dur: float+ pid: Optional[int] = None+ tid: Optional[int] = None+ cat: Optional[str] = None+ ph: Optional[str] = None+ args: Optional[Dict[str, Any]] = None+++def _safe_float(value: Any) -> Optional[float]:+ if value is None:+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _load_raw_events(trace_path: str) -> List[Dict[str, Any]]:+ with open(trace_path, "r", encoding="utf-8") as f:+ data = json.load(f)++ if isinstance(data, dict):+ raw_events = data.get("traceEvents", [])+ if isinstance(raw_events, list):+ return raw_events+ return []++ if isinstance(data, list):+ return data++ return []+++def _parse_complete_event(item: Dict[str, Any]) -> Optional[Event]:+ """+ 处理 ph == 'X' 的完整事件+ """+ name = item.get("name")+ ts = _safe_float(item.get("ts"))+ dur = _safe_float(item.get("dur"))++ if not name or ts is None or dur is None:+ return None++ return Event(+ name=name,+ ts_start=ts,+ ts_end=ts + dur,+ dur=dur,+ pid=item.get("pid"),+ tid=item.get("tid"),+ cat=item.get("cat"),+ ph="X",+ args=item.get("args", {}),+ )+++def _pair_begin_end_events(raw_events: List[Dict[str, Any]]) -> List[Event]:+ """+ 将 B/E 事件配对成完整 Event。++ 配对策略:+ - 按 (pid, tid, name) 维护栈+ - 遇到 B 入栈+ - 遇到 E 出栈并生成 Event++ 注意:+ - 若 E 找不到对应 B,则忽略+ - 若 B 最终未匹配到 E,则忽略+ """+ stacks: Dict[Tuple[Any, Any, str], List[Dict[str, Any]]] = {}+ paired_events: List[Event] = []++ for item in raw_events:+ ph = item.get("ph")+ if ph not in ("B", "E"):+ continue++ name = item.get("name")+ ts = _safe_float(item.get("ts"))+ pid = item.get("pid")+ tid = item.get("tid")++ if not name or ts is None:+ continue++ key = (pid, tid, name)++ if ph == "B":+ stacks.setdefault(key, []).append(item)+ continue++ # ph == "E"+ stack = stacks.get(key)+ if not stack:+ # 孤立的 E,直接跳过+ continue++ begin_item = stack.pop()+ ts_begin = _safe_float(begin_item.get("ts"))+ if ts_begin is None:+ continue++ if ts < ts_begin:+ # 时间反常,跳过+ continue++ begin_args = begin_item.get("args", {}) or {}+ end_args = item.get("args", {}) or {}++ merged_args = {}+ merged_args.update(begin_args)+ merged_args.update(end_args)++ paired_events.append(+ Event(+ name=name,+ ts_start=ts_begin,+ ts_end=ts,+ dur=ts - ts_begin,+ pid=pid,+ tid=tid,+ cat=begin_item.get("cat") or item.get("cat"),+ ph="BE",+ args=merged_args,+ )+ )++ return paired_events+++def parse_trace_json(trace_path: str) -> List[Event]:+ """+ V1 parser:+ - 支持 ph == 'X'+ - 支持 ph == 'B' / 'E' 配对+ - 返回统一的完整事件列表+ """+ raw_events = _load_raw_events(trace_path)++ parsed_events: List[Event] = []++ # 1. 先解析 X 事件+ for item in raw_events:+ ph = item.get("ph")+ if ph == "X":+ event = _parse_complete_event(item)+ if event is not None:+ parsed_events.append(event)++ # 2. 再解析 B/E 配对事件+ be_events = _pair_begin_end_events(raw_events)+ parsed_events.extend(be_events)++ # 3. 按时间排序+ parsed_events.sort(key=lambda e: (e.ts_start, e.ts_end, e.name))+ return parsed_events+++def events_to_dicts(events: List[Event]) -> List[Dict[str, Any]]:+ return [asdict(e) for e in events]\ No newline at end of filediff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/phase_mapper.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/phase_mapper.pynew file mode 100644index 0000000000..0f39d39454--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/phase_mapper.py@@ -0,0 +1,110 @@+from __future__ import annotations++import re+from typing import Dict, List, Optional, Tuple+++def _strip_quotes(value: str) -> str:+ value = value.strip()+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):+ return value[1:-1]+ return value+++def _load_simple_yaml(config_path: str) -> dict:+ """+ Small YAML subset parser used when PyYAML is unavailable.++ The skill config intentionally uses only:+ - top-level sections+ - section -> key -> list[str]+ - section -> list[str]+ - section -> key -> scalar+ """+ config: dict = {}+ current_section: Optional[str] = None+ current_key: Optional[str] = None++ with open(config_path, "r", encoding="utf-8") as f:+ for raw_line in f:+ line = raw_line.split("#", 1)[0].rstrip()+ if not line.strip():+ continue++ indent = len(line) - len(line.lstrip(" "))+ text = line.strip()++ if indent == 0 and text.endswith(":"):+ current_section = text[:-1].strip()+ current_key = None+ config[current_section] = {}+ continue++ if current_section is None:+ continue++ if indent == 2 and text.startswith("- "):+ if not isinstance(config.get(current_section), list):+ config[current_section] = []+ config[current_section].append(_strip_quotes(text[2:]))+ continue++ if indent == 2 and ":" in text:+ key, value = text.split(":", 1)+ current_key = key.strip()+ value = value.strip()+ if value:+ config[current_section][current_key] = _strip_quotes(value)+ else:+ config[current_section][current_key] = []+ continue++ if indent == 4 and text.startswith("- ") and current_key is not None:+ values = config[current_section].setdefault(current_key, [])+ if isinstance(values, list):+ values.append(_strip_quotes(text[2:]))++ return config+++def _load_config(config_path: str) -> dict:+ try:+ import yaml # type: ignore+ except ModuleNotFoundError:+ return _load_simple_yaml(config_path)++ with open(config_path, "r", encoding="utf-8") as f:+ loaded = yaml.safe_load(f)+ return loaded or {}+++class PhaseMapper:+ def __init__(self, config_path: str):+ config = _load_config(config_path)++ self.phase_patterns: Dict[str, List[str]] = config.get("phases", {})+ self.focus_phases: List[str] = config.get("focus_phases", [])+ self.phase_categories: Dict[str, str] = config.get("phase_categories", {})++ self._compiled: List[Tuple[str, str, re.Pattern]] = []+ for phase, patterns in self.phase_patterns.items():+ for pattern in patterns:+ self._compiled.append((phase, pattern, re.compile(pattern)))++ def map_event_name(self, event_name: str) -> Optional[str]:+ """+ 选择最具体的匹配:+ - 所有命中的规则里,优先选择 pattern 字符串更长的+ - 若长度相同,保留先出现的+ """+ best_phase = None+ best_pattern_len = -1++ for phase, pattern_str, pattern in self._compiled:+ if pattern.search(event_name):+ score = len(pattern_str)+ if score > best_pattern_len:+ best_phase = phase+ best_pattern_len = score++ return best_phasediff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/plots.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/plots.pynew file mode 100644index 0000000000..459e61c349--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/plots.py@@ -0,0 +1,188 @@+from __future__ import annotations++import os+import tempfile+from typing import Any, List+++_CATEGORY_ORDER = [+ "container",+ "wait",+ "sync",+ "compute",+ "epilogue",+ "communication",+ "quant",+ "init",+ "cleanup",+ "other",+]+_CORE_GROUP_ORDER = ["cube", "vector_recv", "vector_send", "unknown"]+_CATEGORY_COLORS = {+ "container": "#8a8f98",+ "wait": "#d64f45",+ "sync": "#c58a2c",+ "compute": "#2f7ebc",+ "epilogue": "#7b61b3",+ "communication": "#25966f",+ "quant": "#b85c9e",+ "init": "#6b9f3f",+ "cleanup": "#6d6d6d",+ "other": "#9a9a9a",+}+++def _load_pyplot():+ os.environ.setdefault("MPLCONFIGDIR", os.path.join(tempfile.gettempdir(), "trace_analysis_matplotlib"))+ import matplotlib++ matplotlib.use("Agg", force=True)+ import matplotlib.pyplot as plt++ return plt+++def _float(value: Any, default: float = 0.0) -> float:+ try:+ return float(value)+ except (TypeError, ValueError):+ return default+++def _short_label(value: Any, width: int = 42) -> str:+ text = str(value)+ if len(text) <= width:+ return text+ return text[: max(0, width - 3)] + "..."+++def _show_no_data(ax: Any, title: str) -> None:+ ax.text(0.5, 0.5, "No data", ha="center", va="center", transform=ax.transAxes)+ ax.set_title(title)+ ax.set_axis_off()+++def _draw_core_group(ax: Any, rows: List[dict]) -> None:+ title = "Core Group Wall Coverage"+ if not rows:+ _show_no_data(ax, title)+ return++ ordered = sorted(+ rows,+ key=lambda row: (+ _CORE_GROUP_ORDER.index(row.get("core_group"))+ if row.get("core_group") in _CORE_GROUP_ORDER+ else 99,+ -_float(row.get("union_us")),+ ),+ )+ labels = [str(row.get("core_group")) for row in ordered]+ values = [_float(row.get("union_us")) for row in ordered]+ ratios = [_float(row.get("ratio_to_total_wall")) for row in ordered]++ bars = ax.barh(labels, values, color=["#5e8fd6", "#4aa877", "#d48750", "#999999"][: len(labels)])+ ax.invert_yaxis()+ ax.set_xlabel("Union time (us)")+ ax.set_title(title)+ ax.grid(True, axis="x", linestyle="--", alpha=0.35)+ for bar, ratio in zip(bars, ratios):+ ax.text(bar.get_width(), bar.get_y() + bar.get_height() / 2, f" {ratio * 100:.1f}%", va="center", fontsize=8)+++def _draw_category_pie(ax: Any, rows: List[dict]) -> None:+ title = "Non-container Category Event-Time Share\nUses total_us; slices sum to 100%"+ if not rows:+ _show_no_data(ax, title)+ return++ selected: List[dict] = []+ for row in rows:+ if row.get("category") in {None, "", "container"}:+ continue+ if _float(row.get("total_us")) <= 0:+ continue+ selected.append(row)+ if not selected:+ _show_no_data(ax, title)+ return++ selected = sorted(selected, key=lambda row: _float(row.get("total_us")), reverse=True)+ labels = [str(row.get("category")) for row in selected]+ values = [_float(row.get("total_us")) for row in selected]+ colors = [_CATEGORY_COLORS.get(label, _CATEGORY_COLORS["other"]) for label in labels]++ wedges, _, autotexts = ax.pie(+ values,+ colors=colors,+ startangle=90,+ counterclock=False,+ autopct=lambda pct: f"{pct:.1f}%" if pct >= 2.0 else "",+ pctdistance=0.75,+ wedgeprops={"linewidth": 1, "edgecolor": "white"},+ )+ ax.set_title(title)+ for text in autotexts:+ text.set_fontsize(8)+ text.set_color("#222222")+ ax.legend(wedges, labels, loc="center left", bbox_to_anchor=(1.0, 0.5), fontsize=8)+++def _draw_top_phases(ax: Any, rows: List[dict], top_n: int) -> None:+ title = "Top Phases By Union Time"+ if not rows:+ _show_no_data(ax, title)+ return++ selected = rows[:top_n]+ labels = [_short_label(row.get("phase")) for row in selected]+ values = [_float(row.get("union_us")) for row in selected]+ categories = [str(row.get("category") or "other") for row in selected]+ colors = [_CATEGORY_COLORS.get(category, _CATEGORY_COLORS["other"]) for category in categories]++ ax.barh(labels, values, color=colors)+ ax.invert_yaxis()+ ax.set_xlabel("Union time (us)")+ ax.set_title(title)+ ax.grid(True, axis="x", linestyle="--", alpha=0.35)+++def plot_analysis_charts(+ output_path: str,+ phase_summary: List[dict],+ category_summary: List[dict],+ core_group_summary: List[dict],+ top_n: int = 12,+) -> str:+ plt = _load_pyplot()+ fig = plt.figure(figsize=(16, 10))+ grid = fig.add_gridspec(2, 2, height_ratios=[0.9, 1.2])++ _draw_core_group(fig.add_subplot(grid[0, 0]), core_group_summary)+ _draw_category_pie(fig.add_subplot(grid[0, 1]), category_summary)+ _draw_top_phases(fig.add_subplot(grid[1, :]), phase_summary, top_n=min(top_n, 12))++ fig.suptitle("Trace Statistical Overview", fontsize=16, y=0.995)+ fig.tight_layout(rect=[0, 0, 1, 0.98])+ fig.savefig(output_path, dpi=180, bbox_inches="tight")+ plt.close(fig)+ return output_path+++def generate_summary_plots(+ output_dir: str,+ phase_summary: List[dict],+ category_summary: List[dict],+ core_group_summary: List[dict],+ top_n: int = 12,+) -> List[str]:+ os.makedirs(output_dir, exist_ok=True)+ filename = "analysis_charts.png"+ plot_analysis_charts(+ output_path=os.path.join(output_dir, filename),+ phase_summary=phase_summary,+ category_summary=category_summary,+ core_group_summary=core_group_summary,+ top_n=top_n,+ )+ return [filename]diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/reporter.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/reporter.pynew file mode 100644index 0000000000..dacfed131c--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/analyzers/reporter.py@@ -0,0 +1,490 @@+from __future__ import annotations++import csv+import json+import os+from dataclasses import dataclass+from typing import Any, Iterable, List, Optional+++@dataclass+class StatisticalSummaryInput:+ overview: dict+ phase_summary: List[dict]+ category_summary: List[dict]+ core_group_summary: List[dict]+ category_core_group_summary: List[dict]+ overlap_summary: List[dict]+ bubble_summary: List[dict]+ heading: str = "## Statistical Highlights"+++@dataclass+class MarkdownReportInput:+ overview: dict+ phase_summary: List[dict]+ category_summary: List[dict]+ core_group_summary: List[dict]+ phase_core_group_summary: List[dict]+ category_core_group_summary: List[dict]+ name_summary: List[dict]+ overlap_summary: List[dict]+ bubble_summary: List[dict]+ diagnosis: dict+ llm_analysis: Optional[dict] = None+ plot_files: Optional[List[str]] = None+ statistical_summary: Optional[str] = None+ top_n: int = 20+++_CORE_GROUP_TABLE_COLS = [+ "core_group",+ "core_kind",+ "core_type",+ "observed_core_count",+ "count",+ "union_us",+ "ratio_to_total_wall",+ "total_us",+]++_BUBBLE_TABLE_COLS = [+ "parent_phase",+ "parent_union_us",+ "child_covered_us",+ "bubble_us",+ "bubble_ratio",+ "gap_count",+ "max_gap_us",+]+++def ensure_dir(path: str) -> None:+ os.makedirs(path, exist_ok=True)+++def _collect_fieldnames(rows: List[dict], preferred: Optional[Iterable[str]] = None) -> List[str]:+ fieldnames: List[str] = []+ for name in preferred or []:+ if name not in fieldnames:+ fieldnames.append(name)++ for row in rows:+ for key in row.keys():+ if key not in fieldnames:+ fieldnames.append(key)++ return fieldnames+++def save_table(rows: List[dict], path: str, fieldnames: Optional[Iterable[str]] = None) -> None:+ columns = _collect_fieldnames(rows, fieldnames)+ with open(path, "w", encoding="utf-8", newline="") as f:+ writer = csv.DictWriter(f, fieldnames=columns)+ writer.writeheader()+ for row in rows:+ writer.writerow(row)+++def save_dataframe(rows: List[dict], path: str) -> None:+ # Backward-compatible name used by app.py.+ save_table(rows, path)+++def save_json(data: Any, path: str) -> None:+ with open(path, "w", encoding="utf-8") as f:+ json.dump(data, f, ensure_ascii=False, indent=2)+++def _format_cell(value: Any) -> str:+ if value is None:+ return ""+ if isinstance(value, list):+ return ", ".join(str(item) for item in value)+ if isinstance(value, float):+ if abs(value) >= 100:+ return f"{value:.3f}".rstrip("0").rstrip(".")+ return f"{value:.6f}".rstrip("0").rstrip(".")+ return str(value)+++def _as_float(value: Any) -> float:+ try:+ return float(value)+ except (TypeError, ValueError):+ return 0.0+++def _fmt_us(value: Any) -> str:+ return f"{_as_float(value):.3f} us"+++def _fmt_pct(value: Any) -> str:+ return f"{_as_float(value) * 100:.1f}%"+++def _top_rows(rows: List[dict], key: str, limit: int = 3) -> List[dict]:+ return sorted(rows, key=lambda row: _as_float(row.get(key)), reverse=True)[:limit]+++def _join_row_summaries(rows: List[dict], label_key: str, value_key: str, ratio_key: str) -> str:+ parts = []+ for row in rows:+ parts.append(+ f"{row.get(label_key)}={_fmt_us(row.get(value_key))} ({_fmt_pct(row.get(ratio_key))})"+ )+ return ", ".join(parts)+++def _join_share_summaries(rows: List[dict], label_key: str, value_key: str) -> str:+ total = sum(_as_float(row.get(value_key)) for row in rows)+ if total <= 0:+ return ""+ parts = []+ for row in rows:+ share = _as_float(row.get(value_key)) / total+ parts.append(f"{row.get(label_key)}={_fmt_us(row.get(value_key))} ({share * 100:.1f}%)")+ return ", ".join(parts)+++def _find_overlap_pair(rows: List[dict], phase_a: str, phase_b: str) -> Optional[dict]:+ target = {phase_a, phase_b}+ for row in rows:+ if {row.get("phase_a"), row.get("phase_b")} == target:+ return row+ return None+++def build_statistical_summary(inp: StatisticalSummaryInput) -> str:+ overview = inp.overview+ phase_summary = inp.phase_summary+ category_summary = inp.category_summary+ core_group_summary = inp.core_group_summary+ category_core_group_summary = inp.category_core_group_summary+ heading = inp.heading+ lines: List[str] = [heading, ""]++ core_groups = overview.get("core_groups") or []+ lines.append(+ "- Trace scope: "+ f"{overview.get('num_instances', 0)} mapped intervals, "+ f"{overview.get('num_phases', 0)} phases, "+ f"{overview.get('num_tids', 0)} tids, "+ f"core groups={', '.join(str(group) for group in core_groups)}, "+ f"wall={_fmt_us(overview.get('total_wall_us'))}."+ )++ if core_group_summary:+ top_core_groups = _top_rows(core_group_summary, "union_us", 3)+ lines.append(+ "- Core group wall coverage: "+ + _join_row_summaries(top_core_groups, "core_group", "union_us", "ratio_to_total_wall")+ + "."+ )++ actionable_categories = [+ row for row in category_summary+ if row.get("category") not in {None, "", "container"}+ ]+ if actionable_categories:+ top_categories = _top_rows(actionable_categories, "union_us", 4)+ lines.append(+ "- Top non-container categories by wall coverage: "+ + _join_row_summaries(top_categories, "category", "union_us", "ratio_to_total_wall")+ + "."+ )+ event_time_rows = _top_rows(actionable_categories, "total_us", 8)+ lines.append(+ "- Category pie basis: non-container category event-time share uses `total_us`, so slices sum to 100%. "+ + _join_share_summaries(event_time_rows, "category", "total_us")+ + "."+ )++ if category_core_group_summary:+ per_group = []+ for core_group in core_groups:+ group_rows = []+ for row in category_core_group_summary:+ if row.get("core_group") != core_group:+ continue+ if row.get("category") in {None, "", "container"}:+ continue+ group_rows.append(row)+ if not group_rows:+ continue+ top_row = _top_rows(group_rows, "union_us", 1)[0]+ per_group.append(+ f"{core_group}: {top_row.get('category')} "+ f"{_fmt_us(top_row.get('union_us'))} "+ f"({_fmt_pct(top_row.get('ratio_to_core_group_wall'))} of group)"+ )+ if per_group:+ lines.append("- Leading category per core group: " + "; ".join(per_group) + ".")++ actionable_phases = [+ row for row in phase_summary+ if row.get("category") != "container"+ ]+ if actionable_phases:+ top_phases = _top_rows(actionable_phases, "union_us", 5)+ phase_parts = [+ f"{row.get('phase')}={_fmt_us(row.get('union_us'))} "+ f"({_fmt_pct(row.get('ratio_to_total_wall'))}, {row.get('category')})"+ for row in top_phases+ ]+ lines.append("- Top non-container phases: " + ", ".join(phase_parts) + ".")++ lines.append("")+ return "\n".join(lines)+++def _markdown_table(rows: List[dict], columns: List[str], limit: Optional[int] = None) -> str:+ if not rows:+ return "No data."++ selected = rows[:limit] if limit else rows+ header = "| " + " | ".join(columns) + " |"+ sep = "| " + " | ".join("---" for _ in columns) + " |"+ body = [+ "| " + " | ".join(_format_cell(row.get(column)) for column in columns) + " |"+ for row in selected+ ]+ return "\n".join([header, sep] + body)+++def _diagnosis_lines(diagnosis: dict) -> List[str]:+ lines: List[str] = []+ headline = diagnosis.get("headline")+ if headline:+ lines.append(headline)+ lines.append("")++ findings = diagnosis.get("findings", [])+ if not findings:+ lines.append("No automatic findings.")+ return lines++ for idx, finding in enumerate(findings, 1):+ title = finding.get("title", "Finding")+ severity = finding.get("severity", "info")+ lines.append(f"{idx}. [{severity}] {title}")+ detail = finding.get("detail")+ if detail:+ lines.append(f" Evidence: {detail}")+ recommendation = finding.get("recommendation")+ if recommendation:+ lines.append(f" Action: {recommendation}")+ return lines+++def _sort_low_overlap_rows(overlap_summary: List[dict]) -> List[dict]:+ candidates: List[dict] = []+ for row in overlap_summary:+ if row.get("overlap_ratio_min", 0.0) > 0.2:+ continue+ ua = row.get("union_us_a", 0.0)+ ub = row.get("union_us_b", 0.0)+ if min(ua, ub) <= 0:+ continue+ candidates.append(row)+ candidates.sort(+ key=lambda r: (+ min(r.get("union_us_a", 0.0), r.get("union_us_b", 0.0)),+ -r.get("overlap_us", 0.0),+ ),+ reverse=True,+ )+ return candidates+++def build_markdown_report(inp: MarkdownReportInput) -> str:+ overview = inp.overview+ phase_summary = inp.phase_summary+ category_summary = inp.category_summary+ core_group_summary = inp.core_group_summary+ phase_core_group_summary = inp.phase_core_group_summary+ category_core_group_summary = inp.category_core_group_summary+ name_summary = inp.name_summary+ overlap_summary = inp.overlap_summary+ bubble_summary = inp.bubble_summary+ diagnosis = inp.diagnosis+ llm_analysis = inp.llm_analysis+ plot_files = inp.plot_files+ statistical_summary = inp.statistical_summary+ top_n = inp.top_n+ lines: List[str] = []+ lines.append("# Ascend MoE Trace Report")+ lines.append("")++ lines.append("## Overview")+ lines.append("")+ lines.append(+ _markdown_table(+ [overview],+ [+ "num_instances",+ "num_phases",+ "num_names",+ "num_pids",+ "num_tids",+ "num_core_groups",+ "core_groups",+ "total_wall_us",+ ],+ )+ )+ lines.append("")++ if plot_files:+ lines.append("## Visualizations")+ lines.append("")+ for plot_file in plot_files:+ title = os.path.splitext(os.path.basename(plot_file))[0].replace("_", " ").title()+ lines.append(f"")+ lines.append("")++ if statistical_summary:+ lines.append(statistical_summary.strip())+ lines.append("")++ lines.append("## Automatic Diagnosis")+ lines.append("")+ lines.extend(_diagnosis_lines(diagnosis))+ lines.append("")++ if llm_analysis and llm_analysis.get("enabled"):+ lines.append("## LLM Analysis")+ lines.append("")+ if llm_analysis.get("analysis"):+ lines.append(llm_analysis["analysis"])+ else:+ lines.append(+ "LLM analysis was requested, but no analysis text was produced. "+ "See `llm_prompt.md` and `llm_analysis_meta.json` in the output directory."+ )+ lines.append("")++ lines.append("## Core Group Summary")+ lines.append("")+ lines.append(+ _markdown_table(+ core_group_summary,+ _CORE_GROUP_TABLE_COLS,+ top_n,+ )+ )+ lines.append("")++ lines.append("## Category By Core Group")+ lines.append("")+ lines.append(+ _markdown_table(+ category_core_group_summary,+ [+ "core_group",+ "category",+ "observed_core_count",+ "count",+ "union_us",+ "ratio_to_core_group_wall",+ "ratio_to_total_wall",+ "total_us",+ ],+ top_n * 3,+ )+ )+ lines.append("")++ lines.append("## Phase By Core Group")+ lines.append("")+ lines.append(+ _markdown_table(+ phase_core_group_summary,+ [+ "core_group",+ "phase",+ "category",+ "observed_core_count",+ "count",+ "union_us",+ "ratio_to_core_group_wall",+ "total_us",+ ],+ top_n * 3,+ )+ )+ lines.append("")++ lines.append("## Category Summary")+ lines.append("")+ lines.append(+ _markdown_table(+ category_summary,+ ["category", "count", "union_us", "ratio_to_total_wall", "total_us", "tid_nunique"],+ top_n,+ )+ )+ lines.append("")++ lines.append("## Phase Summary")+ lines.append("")+ lines.append(+ _markdown_table(+ phase_summary,+ ["phase", "category", "count", "union_us", "ratio_to_total_wall", "total_us", "tid_nunique"],+ top_n,+ )+ )+ lines.append("")++ lines.append("## Bubble Summary")+ lines.append("")+ lines.append(+ _markdown_table(+ bubble_summary,+ _BUBBLE_TABLE_COLS,+ top_n,+ )+ )+ lines.append("")++ lines.append("## Top Raw Names")+ lines.append("")+ lines.append(+ _markdown_table(+ name_summary,+ ["name", "phase", "category", "count", "total_us", "union_us", "tid_nunique"],+ top_n,+ )+ )+ lines.append("")++ lines.append("## High Overlap Pairs")+ lines.append("")+ lines.append(+ _markdown_table(+ overlap_summary,+ ["phase_a", "phase_b", "overlap_us", "overlap_ratio_a", "overlap_ratio_b", "union_us_a", "union_us_b"],+ top_n,+ )+ )+ lines.append("")++ low_overlap = _sort_low_overlap_rows(overlap_summary)+ lines.append("## Low Overlap Pairs")+ lines.append("")+ lines.append(+ _markdown_table(+ low_overlap,+ ["phase_a", "phase_b", "overlap_us", "overlap_ratio_min", "union_us_a", "union_us_b"],+ top_n,+ )+ )+ lines.append("")++ return "\n".join(lines)+++def save_text(text: str, path: str) -> None:+ with open(path, "w", encoding="utf-8") as f:+ f.write(text)diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/app.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/app.pynew file mode 100644index 0000000000..235144e6b2--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/app.py@@ -0,0 +1,324 @@+from __future__ import annotations++import argparse+import logging+import os+from dataclasses import dataclass++from analyzers.parser import parse_trace_json, events_to_dicts+from analyzers.phase_mapper import PhaseMapper+from analyzers.metrics import (+ build_phase_instances,+ build_phase_summary,+ build_category_summary,+ build_core_group_summary,+ build_phase_core_group_summary,+ build_category_core_group_summary,+ build_name_summary,+ build_phase_tid_summary,+ build_overlap_summary,+ build_bubble_summary,+ build_trace_overview,+)+from analyzers.diagnosis import AutoDiagnosisInput, build_auto_diagnosis+from analyzers.llm_analysis import LLMPromptInput, build_llm_prompt, generate_llm_analysis+from analyzers.reporter import (+ MarkdownReportInput,+ StatisticalSummaryInput,+ ensure_dir,+ save_dataframe,+ save_json,+ build_markdown_report,+ build_statistical_summary,+ save_text,+)++logger = logging.getLogger(__name__)+++@dataclass+class RunSummaryInput:+ raw_events_count: int+ overview: dict+ phase_summary: list+ category_summary: list+ core_group_summary: list+ diagnosis: dict+ output_dir: str+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Ascend MoE trace analysis: Chrome/Perfetto JSON (ascend-moe-optimizer-trace-analyzer skill)"+ )+ parser.add_argument(+ "--trace",+ required=True,+ help="Path to trace json",+ )+ parser.add_argument(+ "--phase-map",+ default="config/phase_map.yaml",+ help="Path to phase mapping yaml",+ )+ parser.add_argument(+ "--output-dir",+ default="output",+ help="Directory to save outputs",+ )+ parser.add_argument(+ "--top-n",+ type=int,+ default=20,+ help="Rows to show in markdown report sections",+ )+ parser.add_argument(+ "--llm-analysis",+ action="store_true",+ help="Run an optional LLM command and append its analysis to report.md",+ )+ parser.add_argument(+ "--llm-command",+ default=None,+ help="External LLM command. It receives the analysis prompt on stdin. Can also use TRACE_ANALYSIS_LLM_CMD.",+ )+ parser.add_argument(+ "--llm-timeout",+ type=int,+ default=120,+ help="Timeout in seconds for --llm-analysis command",+ )+ return parser.parse_args()+++def validate_inputs(trace_path: str, phase_map_path: str) -> None:+ if not os.path.exists(trace_path):+ raise FileNotFoundError(f"Trace file not found: {trace_path}")++ if not os.path.exists(phase_map_path):+ raise FileNotFoundError(f"Phase map file not found: {phase_map_path}")+++def log_run_summary(ctx: RunSummaryInput) -> None:+ logger.info("Trace analysis completed.")+ logger.info("Raw parsed events: %s", ctx.raw_events_count)+ logger.info("Mapped phase instances: %s", ctx.overview.get("num_instances", 0))+ logger.info("Unique phases: %s", ctx.overview.get("num_phases", 0))+ logger.info("Unique raw names: %s", ctx.overview.get("num_names", 0))+ logger.info("Unique pids: %s", ctx.overview.get("num_pids", 0))+ logger.info("Unique tids: %s", ctx.overview.get("num_tids", 0))+ logger.info("Core groups: %s", ", ".join(ctx.overview.get("core_groups", [])))+ logger.info("Trace wall time (us): %.3f", ctx.overview.get("total_wall_us", 0.0))++ if ctx.diagnosis.get("headline"):+ logger.info("")+ logger.info("Diagnosis: %s", ctx.diagnosis["headline"])++ if ctx.phase_summary:+ logger.info("")+ logger.info("Top phases by union_us:")+ for row in ctx.phase_summary[:10]:+ logger.info(+ " %s: count=%s, union_us=%.3f, total_us=%.3f, category=%s",+ row.get("phase"),+ row.get("count"),+ row.get("union_us", 0.0),+ row.get("total_us", 0.0),+ row.get("category"),+ )++ if ctx.category_summary:+ logger.info("")+ logger.info("Top categories by union_us:")+ for row in ctx.category_summary[:10]:+ logger.info(+ " %s: count=%s, union_us=%.3f, ratio=%.3f",+ row.get("category"),+ row.get("count"),+ row.get("union_us", 0.0),+ row.get("ratio_to_total_wall", 0.0),+ )++ if ctx.core_group_summary:+ logger.info("")+ logger.info("Core groups by union_us:")+ for row in ctx.core_group_summary:+ logger.info(+ " %s: cores=%s, union_us=%.3f, ratio=%.3f",+ row.get("core_group"),+ row.get("observed_core_count"),+ row.get("union_us", 0.0),+ row.get("ratio_to_total_wall", 0.0),+ )++ logger.info("")+ logger.info("Outputs saved to: %s", ctx.output_dir)+++def main() -> None:+ args = parse_args()+ validate_inputs(args.trace, args.phase_map)++ ensure_dir(args.output_dir)++ # 1. parse trace+ parsed_events = parse_trace_json(args.trace)+ raw_dicts = events_to_dicts(parsed_events)++ # 2. phase mapping+ mapper = PhaseMapper(args.phase_map)++ # 3. build tables+ instances_df = build_phase_instances(raw_dicts, mapper)+ phase_summary_df = build_phase_summary(instances_df)+ category_summary_df = build_category_summary(instances_df)+ core_group_summary_df = build_core_group_summary(instances_df)+ phase_core_group_summary_df = build_phase_core_group_summary(instances_df)+ category_core_group_summary_df = build_category_core_group_summary(instances_df)+ name_summary_df = build_name_summary(instances_df)+ phase_tid_summary_df = build_phase_tid_summary(instances_df)+ overlap_df = build_overlap_summary(instances_df)+ bubble_df = build_bubble_summary(instances_df)+ overview = build_trace_overview(instances_df)+ overview["raw_parsed_events"] = len(raw_dicts)++ diagnosis = build_auto_diagnosis(+ AutoDiagnosisInput(+ overview=overview,+ phase_summary=phase_summary_df,+ category_summary=category_summary_df,+ core_group_summary=core_group_summary_df,+ phase_core_group_summary=phase_core_group_summary_df,+ category_core_group_summary=category_core_group_summary_df,+ name_summary=name_summary_df,+ overlap_summary=overlap_df,+ bubble_summary=bubble_df,+ )+ )++ llm_prompt = build_llm_prompt(+ LLMPromptInput(+ overview=overview,+ diagnosis=diagnosis,+ phase_summary=phase_summary_df,+ category_summary=category_summary_df,+ core_group_summary=core_group_summary_df,+ phase_core_group_summary=phase_core_group_summary_df,+ category_core_group_summary=category_core_group_summary_df,+ name_summary=name_summary_df,+ overlap_summary=overlap_df,+ bubble_summary=bubble_df,+ top_n=args.top_n,+ )+ )+ llm_analysis = generate_llm_analysis(+ prompt=llm_prompt,+ enabled=args.llm_analysis,+ command=args.llm_command,+ timeout_s=args.llm_timeout,+ )++ plot_files = []+ try:+ from analyzers.plots import generate_summary_plots++ plot_files.extend(+ generate_summary_plots(+ output_dir=args.output_dir,+ phase_summary=phase_summary_df,+ category_summary=category_summary_df,+ core_group_summary=core_group_summary_df,+ top_n=args.top_n,+ )+ )+ except ModuleNotFoundError as exc:+ logger.warning("summary plots skipped: missing dependency (%s)", exc)++ statistical_summary = build_statistical_summary(+ StatisticalSummaryInput(+ overview=overview,+ phase_summary=phase_summary_df,+ category_summary=category_summary_df,+ core_group_summary=core_group_summary_df,+ category_core_group_summary=category_core_group_summary_df,+ overlap_summary=overlap_df,+ bubble_summary=bubble_df,+ heading="## Statistical Highlights",+ )+ )+ standalone_statistical_summary = build_statistical_summary(+ StatisticalSummaryInput(+ overview=overview,+ phase_summary=phase_summary_df,+ category_summary=category_summary_df,+ core_group_summary=core_group_summary_df,+ category_core_group_summary=category_core_group_summary_df,+ overlap_summary=overlap_df,+ bubble_summary=bubble_df,+ heading="# Statistical Highlights",+ )+ )++ # 4. save tables+ save_dataframe(instances_df, f"{args.output_dir}/phase_instances.csv")+ save_dataframe(phase_summary_df, f"{args.output_dir}/phase_summary.csv")+ save_dataframe(category_summary_df, f"{args.output_dir}/category_summary.csv")+ save_dataframe(core_group_summary_df, f"{args.output_dir}/core_group_summary.csv")+ save_dataframe(phase_core_group_summary_df, f"{args.output_dir}/phase_core_group_summary.csv")+ save_dataframe(category_core_group_summary_df, f"{args.output_dir}/category_core_group_summary.csv")+ save_dataframe(name_summary_df, f"{args.output_dir}/name_summary.csv")+ save_dataframe(phase_tid_summary_df, f"{args.output_dir}/phase_tid_summary.csv")+ save_dataframe(overlap_df, f"{args.output_dir}/overlap_summary.csv")+ save_dataframe(bubble_df, f"{args.output_dir}/bubble_summary.csv")+ save_text(standalone_statistical_summary, f"{args.output_dir}/statistical_summary.md")+ save_text(llm_prompt, f"{args.output_dir}/llm_prompt.md")+ save_json(llm_analysis, f"{args.output_dir}/llm_analysis_meta.json")+ if llm_analysis.get("analysis"):+ save_text(llm_analysis["analysis"], f"{args.output_dir}/llm_analysis.md")++ # 6. save report+ report_md = build_markdown_report(+ MarkdownReportInput(+ overview=overview,+ phase_summary=phase_summary_df,+ category_summary=category_summary_df,+ core_group_summary=core_group_summary_df,+ phase_core_group_summary=phase_core_group_summary_df,+ category_core_group_summary=category_core_group_summary_df,+ name_summary=name_summary_df,+ overlap_summary=overlap_df,+ bubble_summary=bubble_df,+ diagnosis=diagnosis,+ llm_analysis=llm_analysis,+ plot_files=plot_files,+ statistical_summary=statistical_summary,+ top_n=args.top_n,+ )+ )+ save_text(report_md, f"{args.output_dir}/report.md")++ # 7. save overview json+ save_json(overview, f"{args.output_dir}/summary.json")+ save_json(diagnosis, f"{args.output_dir}/diagnosis.json")+ if args.llm_analysis and llm_analysis.get("status") != "ok":+ logger.warning(+ "LLM analysis skipped: %s",+ llm_analysis.get("error") or llm_analysis.get("status"),+ )++ log_run_summary(+ RunSummaryInput(+ raw_events_count=len(raw_dicts),+ overview=overview,+ phase_summary=phase_summary_df,+ category_summary=category_summary_df,+ core_group_summary=core_group_summary_df,+ diagnosis=diagnosis,+ output_dir=args.output_dir,+ )+ )+++if __name__ == "__main__":+ logging.basicConfig(level=logging.INFO, format="%(message)s")+ main()diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/config/phase_map.yaml b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/config/phase_map.yamlnew file mode 100644index 0000000000..3bad2de8fd--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer/config/phase_map.yaml@@ -0,0 +1,224 @@+phases:+ processing:+ - "^processing"++ dispatch_init:+ - "^dispatch init"+ dispatch_process:+ - "^dispatch process"+ dispatch_sync_all:+ - "^dispatch sync-all"++ dispatch_gmm1_wait_shared_token:+ - "^dispatch-gmm1 wait-shared-token"+ dispatch_gmm1_wait_moe_token:+ - "^dispatch-gmm1 wait-moe-token"+ dispatch_gmm1_sleep:+ - "^dispatch-gmm1 sleep"+ dispatch_gmm1_sync_block_mmad:+ - "^dispatch-gmm1 sync-block-mmad"+ dispatch_gmm1_sync_aiv:+ - "^dispatch-gmm1 sync-aiv"+ dispatch_gmm1_sync:+ - "^dispatch-gmm1.*sync"+ dispatch_gmm1_shared_dispatch_swiglu_wait_flag:+ - "^dispatch-gmm1 shared-dispatch-swiglu wait-flag"+ dispatch_gmm1_moe_dispatch_swiglu_wait_flag:+ - "^dispatch-gmm1 moe-dispatch-swiglu wait-flag"+ dispatch_gmm1_shared_process:+ - "^dispatch-gmm1 shared-process"+ - "^dispatch-gmm1.*shared-pro"+ - "^dispatch-gmm1.*shared-prologue"+ dispatch_gmm1_moe_process:+ - "^dispatch-gmm1 moe-process"+ dispatch_gmm1_comp_core:+ - "^dispatch-gmm1 CompCoreFunc"+ dispatch_gmm1_send_core:+ - "^dispatch-gmm1 SendCoreFunc"+ dispatch_gmm1_recv_core:+ - "^dispatch-gmm1 RecvCoreFunc"+ dispatch_gmm1_share_quant_core:+ - "^dispatch-gmm1 shareQuantCoreFunc"+ dispatch_gmm1_share_swiglu_core:+ - "^dispatch-gmm1 shareSwigluCoreFunc"+ dispatch_gmm1_recv_token_calc:+ - "^dispatch-gmm1 recv-token-calc"+ dispatch_gmm1_recv_token:+ - "^dispatch-gmm1 recv-token"+ dispatch_gmm1_recv_count:+ - "^dispatch-gmm1 recv-count"+ dispatch_gmm1_get_cum_sum:+ - "^dispatch-gmm1 get-cum-sum"+ dispatch_gmm1_dispatch_send:+ - "^dispatch-gmm1 dispatch-send"+ dispatch_gmm1_moe_dispatch_send:+ - "^dispatch-gmm1 moe-dispatch-send"+ dispatch_gmm1_shared_dispatch_swiglu:+ - "^dispatch-gmm1 shared-dispatch-swiglu"+ dispatch_gmm1_moe_dispatch_swiglu:+ - "^dispatch-gmm1 moe-dispatch-swiglu"+ dispatch_gmm1_shared_quant:+ - "^dispatch-gmm1 shared-quant"+ dispatch_gmm1_moe_quant:+ - "^dispatch-gmm1 moe-quant"+ dispatch_gmm1_aiv_init_params:+ - "^dispatch-gmm1 aiv-init-params"+ dispatch_gmm1_aiv_init_state:+ - "^dispatch-gmm1 aiv-init-state"+ dispatch_gmm1_update_clean_info:+ - "^dispatch-gmm1 UpdateAndCleanInfo"+ dispatch_gmm1_aiv:+ - "^dispatch-gmm1 aiv"+ dispatch_gmm1_aic:+ - "^dispatch-gmm1 aic"+ dispatch_gmm1:+ - "^dispatch-gmm1"++ combine_init:+ - "^combine init"++ gmm2_combine_wait_quant:+ - "^gmm2-combine wait quant"+ gmm2_combine_block_mmad_waiting:+ - "^gmm2-combine block-mmad waiting"+ gmm2_combine_block_mmad_copy_out:+ - "^gmm2-combine block-mmad copy-out"+ gmm2_combine_shared_wait_combine:+ - "^gmm2-combine block-epilogue shared-wait-combine"+ - "^gmm2-combine.*shared-wait-combine"+ gmm2_combine_block_epilogue_shared_waiting:+ - "^gmm2-combine block-epilogue shared-waiting"+ gmm2_combine_block_epilogue_waiting:+ - "^gmm2-combine block-epilogue waiting"+ gmm2_combine_block_epilogue_shared_calc:+ - "^gmm2-combine block-epilogue shared-calc"+ gmm2_combine_block_epilogue_calc:+ - "^gmm2-combine block-epilogue calc"+ gmm2_combine_block_epilogue_shared_group:+ - "^gmm2-combine block-epilogue shared-group"+ gmm2_combine_block_epilogue_group:+ - "^gmm2-combine block-epilogue group"+ gmm2_combine_block_epilogue:+ - "^gmm2-combine block-epilogue"+ gmm2_combine_combine_barrier_all:+ - "^gmm2-combine combine-barrier-all"+ gmm2_combine_combine_wait_send:+ - "^gmm2-combine combine-wait-send"+ gmm2_combine_combine_wait_status:+ - "^gmm2-combine combine-wait-status"+ gmm2_combine_combine_set_status:+ - "^gmm2-combine combine-set-status"+ gmm2_combine_combine_local_copy:+ - "^gmm2-combine combine-local-copy"+ gmm2_combine_combine_send:+ - "^gmm2-combine combine-send"+ gmm2_combine_combine_recv:+ - "^gmm2-combine combine-recv"+ gmm2_combine_combine:+ - "^gmm2-combine combine"+ gmm2_combine_send_calc:+ - "^gmm2-combine send-calc"+ gmm2_combine_clean_flags:+ - "^gmm2-combine clean-flags"+ gmm2_combine_sync_gmm2:+ - "^gmm2-combine sync-gmm2"+ gmm2_combine_sync:+ - "^gmm2-combine.*sync"+ gmm2_combine_moe_gmm2:+ - "^gmm2-combine moe-gmm2"+ gmm2_combine_shared_gmm2:+ - "^gmm2-combine shared-gmm2"+ gmm2_combine_aiv:+ - "^gmm2-combine aiv"+ gmm2_combine_aic:+ - "^gmm2-combine aic"+ gmm2_combine:+ - "^gmm2-combine"++phase_categories:+ processing: container+ dispatch_gmm1: container+ dispatch_gmm1_aic: container+ dispatch_gmm1_aiv: container+ gmm2_combine: container+ gmm2_combine_aic: container+ gmm2_combine_aiv: container+ dispatch_init: init+ combine_init: init+ dispatch_gmm1_wait_shared_token: wait+ dispatch_gmm1_wait_moe_token: wait+ dispatch_gmm1_sleep: wait+ dispatch_gmm1_shared_dispatch_swiglu_wait_flag: wait+ dispatch_gmm1_moe_dispatch_swiglu_wait_flag: wait+ gmm2_combine_wait_quant: wait+ gmm2_combine_block_mmad_waiting: wait+ gmm2_combine_block_epilogue_waiting: wait+ gmm2_combine_block_epilogue_shared_waiting: wait+ gmm2_combine_shared_wait_combine: wait+ gmm2_combine_combine_wait_send: wait+ gmm2_combine_combine_wait_status: wait+ gmm2_combine_combine_barrier_all: wait+ dispatch_gmm1_sync: sync+ dispatch_gmm1_sync_aiv: sync+ dispatch_gmm1_sync_block_mmad: sync+ dispatch_sync_all: sync+ gmm2_combine_sync: sync+ gmm2_combine_sync_gmm2: sync+ dispatch_gmm1_comp_core: compute+ dispatch_gmm1_moe_process: compute+ dispatch_gmm1_shared_process: compute+ gmm2_combine_moe_gmm2: compute+ gmm2_combine_shared_gmm2: compute+ gmm2_combine_block_mmad_copy_out: compute+ gmm2_combine_block_epilogue: epilogue+ gmm2_combine_block_epilogue_group: epilogue+ gmm2_combine_block_epilogue_shared_group: epilogue+ gmm2_combine_block_epilogue_calc: epilogue+ gmm2_combine_block_epilogue_shared_calc: epilogue+ dispatch_gmm1_shared_quant: quant+ dispatch_gmm1_moe_quant: quant+ dispatch_gmm1_share_quant_core: quant+ dispatch_gmm1_shared_dispatch_swiglu: quant+ dispatch_gmm1_moe_dispatch_swiglu: quant+ dispatch_gmm1_share_swiglu_core: quant+ dispatch_process: communication+ dispatch_gmm1_send_core: communication+ dispatch_gmm1_recv_core: communication+ dispatch_gmm1_recv_token_calc: communication+ dispatch_gmm1_recv_token: communication+ dispatch_gmm1_recv_count: communication+ dispatch_gmm1_get_cum_sum: communication+ dispatch_gmm1_dispatch_send: communication+ dispatch_gmm1_moe_dispatch_send: communication+ gmm2_combine_combine: communication+ gmm2_combine_combine_send: communication+ gmm2_combine_combine_recv: communication+ gmm2_combine_combine_set_status: communication+ gmm2_combine_combine_local_copy: communication+ gmm2_combine_send_calc: communication+ dispatch_gmm1_aiv_init_params: init+ dispatch_gmm1_aiv_init_state: init+ dispatch_gmm1_update_clean_info: cleanup+ gmm2_combine_clean_flags: cleanup++focus_phases:+ - processing+ - dispatch_gmm1+ - dispatch_gmm1_wait_shared_token+ - dispatch_gmm1_wait_moe_token+ - dispatch_gmm1_moe_process+ - dispatch_gmm1_comp_core+ - dispatch_gmm1_shared_process+ - dispatch_gmm1_sync_aiv+ - dispatch_gmm1_sync_block_mmad+ - gmm2_combine+ - gmm2_combine_wait_quant+ - gmm2_combine_moe_gmm2+ - gmm2_combine_shared_gmm2+ - gmm2_combine_block_epilogue+ - gmm2_combine_block_epilogue_waiting+ - gmm2_combine_block_epilogue_calc+ - gmm2_combine_shared_wait_combine+ - gmm2_combine_combine_wait_send+ - gmm2_combine_combine_wait_status+ - gmm2_combine_sync_gmm2