草稿
[WIP]refactor: retire CV parallel experiment #3
zhenyu创建于 26 天前
[WIP]refactor: retire CV parallel experiment #3
草稿
zhenyu创建于 26 天前
共 33 个文件变更+6-7518
@@ -57,7 +57,7 @@ ownership debt manifest、目录布局检查和 extension ownership 检查脚本
57| DeepSeek-V4/V4.1 模型配置、并行化与 checkpoint 适配 | `extensions/` 与 `override/` | 提炼公开模型/配置接口后逐项替换,不改变训练、checkpoint 或数值语义 |57| DeepSeek-V4/V4.1 模型配置、并行化与 checkpoint 适配 | `extensions/` 与 `override/` | 提炼公开模型/配置接口后逐项替换,不改变训练、checkpoint 或数值语义 |
58| Qwen3.5 模型模块 | 模型专属 `override/` | 通过明确注册或调用边界消除反向依赖 |58| Qwen3.5 模型模块 | 模型专属 `override/` | 通过明确注册或调用边界消除反向依赖 |
59| `extensions/torchtitan/trainer.py`、checkpoint extension | `extensions/components/` | 在 loader 和组件注册表稳定后改为按需接线 |59| `extensions/torchtitan/trainer.py`、checkpoint extension | `extensions/components/` | 在 loader 和组件注册表稳定后改为按需接线 |
60-| TorchAO adaptor、CV Parallel 与 TorchFT extension | `models/`、`override/`、`ops/` 或 patch 私有符号 | 用公开 adaptor/extension 接口分阶段替换 |60+| TorchAO adaptor 与 TorchFT extension | `models/`、`override/`、`ops/` 或 patch 私有符号 | 用公开 adaptor/extension 接口分阶段替换 |
61| `patches/torchtitan/models/qwen3_5/vision_encoder.py` | `extensions/torchtitan/eager_flex.py` | 将 eager 兼容逻辑移到单向可激活层,消除 patch 反向依赖 |61| `patches/torchtitan/models/qwen3_5/vision_encoder.py` | `extensions/torchtitan/eager_flex.py` | 将 eager 兼容逻辑移到单向可激活层,消除 patch 反向依赖 |
62 62 
63`patches/torchtitan/` 的新增文件使用 `Upstream-PR:` 头部。现有文件含历史 `Pending upstream PR`/`Upstream PR` 标记和基线中已登记的缺失项;当前门禁只禁止新增元数据债务,统一整理另行完成。63`patches/torchtitan/` 的新增文件使用 `Upstream-PR:` 头部。现有文件含历史 `Pending upstream PR`/`Upstream PR` 标记和基线中已登记的缺失项;当前门禁只禁止新增元数据债务,统一整理另行完成。
@@ -43,7 +43,7 @@
43| 数据、SFT、验证 | batch 改为 `TrainingMicrobatch`;padding、长文档拆分和恢复状态变化;新增多轮 SFT;验证增加空数据保护 | 迁移本地 loader、视觉数据、调度缓存;单独检查数据语义变化 |43| 数据、SFT、验证 | batch 改为 `TrainingMicrobatch`;padding、长文档拆分和恢复状态变化;新增多轮 SFT;验证增加空数据保护 | 迁移本地 loader、视觉数据、调度缓存;单独检查数据语义变化 |
44| Checkpoint | `#4190/#4191/#4528` 统一 load 后端、完善 HF consolidation;新 EMA 状态结构 | 迁移 DCP load hook、hash、PEFT、量化读取和导出;默认继续使用 DCP |44| Checkpoint | `#4190/#4191/#4528` 统一 load 后端、完善 HF consolidation;新 EMA 状态结构 | 迁移 DCP load hook、hash、PEFT、量化读取和导出;默认继续使用 DCP |
45| AC 与编译 | `#4497` 引入 torch_remat/RegionAC;FullAC 默认 early-stop;`#4895` 删除常规逐 block compile | 保全既有 NPU FullAC/SelectiveAC 和模型编译功能;RegionAC 不纳入默认支持 |45| AC 与编译 | `#4497` 引入 torch_remat/RegionAC;FullAC 默认 early-stop;`#4895` 删除常规逐 block compile | 保全既有 NPU FullAC/SelectiveAC 和模型编译功能;RegionAC 不纳入默认支持 |
46-| GraphTrainer | `#4666/#4884/#4952` 统一 GraphRuntime,收敛到 AOT tracing,删除 graph-based EP chunking | **必须迁移** NPU auto-overlap、runtime context、全图校准和 CV parallel;使用 eager chunking |46+| GraphTrainer | `#4666/#4884/#4952` 统一 GraphRuntime,收敛到 AOT tracing,删除 graph-based EP chunking | **必须迁移** NPU auto-overlap、runtime context 和全图校准;使用 eager chunking |
47| CUDA graphs | 新增梯度累积 capture、graph-owned gradients、独立 optimizer capture、looped PP | 属于 CUDA 能力;NPU 不自动启用,验证不会进入 CUDA 专属执行分支 |47| CUDA graphs | 新增梯度累积 capture、graph-owned gradients、独立 optimizer capture、looped PP | 属于 CUDA 能力;NPU 不自动启用,验证不会进入 CUDA 专属执行分支 |
48| 模型扩展与工程设施 | Qwen3.5 tying/多模态修复;新增 Qwen3.6 registry;Kimi K3 TP/PP/packing;RL 搬迁与扩展;日志和 CI 重组 | Qwen 现有路径回归;公共修复继承;新模型/RL 专属功能另列后续项,不复制 GPU CI/golden |48| 模型扩展与工程设施 | Qwen3.5 tying/多模态修复;新增 Qwen3.6 registry;Kimi K3 TP/PP/packing;RL 搬迁与扩展;日志和 CI 重组 | Qwen 现有路径回归;公共修复继承;新模型/RL 专属功能另列后续项,不复制 GPU CI/golden |
49 49 
@@ -180,11 +180,10 @@
180- 迁到 `GraphTrainingEngine` 与 GraphRuntime,重新接入 trace/runtime context、全图校准、NPU pass registry。180- 迁到 `GraphTrainingEngine` 与 GraphRuntime,重新接入 trace/runtime context、全图校准、NPU pass registry。
181- 删除 graph-based EP chunking,统一 eager chunking;更新 launcher 中旧 strategy 和执行模式配置。181- 删除 graph-based EP chunking,统一 eager chunking;更新 launcher 中旧 strategy 和执行模式配置。
182- auto-overlap 放在 eager chunk metadata 已产生、FSDP bucketing 完成后的调度位置,不再依赖已删除的 concretization pass。182- auto-overlap 放在 eager chunk metadata 已产生、FSDP bucketing 完成后的调度位置,不再依赖已删除的 concretization pass。
183-- CV parallel 单独迁到新的 graph builder/runtime 接口;不能只修默认 GraphTrainer 就宣称该能力已保全。
184- 校准不得改变模型参数、grad、buffer、随机状态或训练进度。183- 校准不得改变模型参数、grad、buffer、随机状态或训练进度。
185- NPU 默认关闭 CUDA graph capture;新增 WGrad fusion、RegionAC 等优化不混入基础兼容性验收。184- NPU 默认关闭 CUDA graph capture;新增 WGrad fusion、RegionAC 等优化不混入基础兼容性验收。
186 185 
187-**阶段出口:** eager 与 graph 的现有训练组合、梯度累积、EP overlap、校准和 CV parallel 均有独立结果。186+**阶段出口:** eager 与 graph 的现有训练组合、梯度累积、EP overlap 和校准均有独立结果。
188 187 
189### 阶段七:迁移 TorchFT、多模态并清理补丁188### 阶段七:迁移 TorchFT、多模态并清理补丁
190 189 
@@ -18,10 +18,6 @@
18 {"source": "torchtitan_npu/extensions/adaptor/torchao/configs/deepseek_v4.py", "target_module": "torchtitan_npu.models.deepseek_v4.compressor"},18 {"source": "torchtitan_npu/extensions/adaptor/torchao/configs/deepseek_v4.py", "target_module": "torchtitan_npu.models.deepseek_v4.compressor"},
19 {"source": "torchtitan_npu/extensions/adaptor/torchao/configs/deepseek_v4.py", "target_module": "torchtitan_npu.override.common.swiglu_group.ascendc"},19 {"source": "torchtitan_npu/extensions/adaptor/torchao/configs/deepseek_v4.py", "target_module": "torchtitan_npu.override.common.swiglu_group.ascendc"},
20 {"source": "torchtitan_npu/extensions/compile/sdc_checksum.py", "target_module": "torchtitan_npu.ops.misc.sdc_checksum"},20 {"source": "torchtitan_npu/extensions/compile/sdc_checksum.py", "target_module": "torchtitan_npu.ops.misc.sdc_checksum"},
21- {"source": "torchtitan_npu/extensions/experiment/cv_parallel/batch_chunk_metadata.py", "target_module": "torchtitan_npu.models.deepseek_v4.metadata"},
22- {"source": "torchtitan_npu/extensions/experiment/cv_parallel/batch_chunk_metadata.py", "target_module": "torchtitan_npu.override.deepseek_v4.sparse_attn.ascendc"},
23- {"source": "torchtitan_npu/extensions/experiment/cv_parallel/batch_chunk_token_dispatcher.py", "target_module": "torchtitan_npu.ops.ascendc.moe_token_permute"},
24- {"source": "torchtitan_npu/extensions/experiment/cv_parallel/batch_chunk_token_dispatcher.py", "target_module": "torchtitan_npu.override.common.token_dispatcher"},
25 {"source": "torchtitan_npu/extensions/torchtitan/experiments/torchft/trainer.py", "target_module": "torchtitan_npu.models.deepseek_v4.model"},21 {"source": "torchtitan_npu/extensions/torchtitan/experiments/torchft/trainer.py", "target_module": "torchtitan_npu.models.deepseek_v4.model"},
26 {"source": "torchtitan_npu/extensions/torchtitan/trainer.py", "target_module": "torchtitan_npu.override.common.optimizer"},22 {"source": "torchtitan_npu/extensions/torchtitan/trainer.py", "target_module": "torchtitan_npu.override.common.optimizer"},
27 {"source": "torchtitan_npu/patches/torchtitan/models/qwen3_5/vision_encoder.py", "target_module": "torchtitan_npu.extensions.torchtitan.eager_flex"}23 {"source": "torchtitan_npu/patches/torchtitan/models/qwen3_5/vision_encoder.py", "target_module": "torchtitan_npu.extensions.torchtitan.eager_flex"}
@@ -249,7 +249,7 @@ torchtitan-npu/
249│ │ ├── components/ # 本仓训练组件及接线逻辑249│ │ ├── components/ # 本仓训练组件及接线逻辑
250│ │ ├── cpu_offload/ # CPU offload 运行时与 staging250│ │ ├── cpu_offload/ # CPU offload 运行时与 staging
251│ │ ├── distributed/ # 梯度累积与梯度裁剪扩展251│ │ ├── distributed/ # 梯度累积与梯度裁剪扩展
252-│ │ ├── experiment/ # Anticipatory Routing、CV Parallel 等实验能力252+│ │ ├── experiment/ # Anticipatory Routing 等实验能力
253│ │ ├── mx_storage_reader/ # MX 量化权重读取能力253│ │ ├── mx_storage_reader/ # MX 量化权重读取能力
254│ │ └── novaswap/ # NovaSwap 显存交换扩展254│ │ └── novaswap/ # NovaSwap 显存交换扩展
255│ ├── override/ # 配置级组件替换,含 common 与模型专属目录255│ ├── override/ # 配置级组件替换,含 common 与模型专属目录
@@ -1,187 +0,0 @@
1-# DeepSeek-V4 batch 双流调度
2- 
3-该实验将 local batch 等分为两个 chunk,分别放在主流和辅助流。启动时先测量 free 双流图,再通过同流局部重排和跨流 event 增加重叠。搜索优先平衡提高「Cube 被 Vector 掩盖」和「Vector 被 Cube 掩盖」两种覆盖率,再提高纯 Cube/Vector(CV)重叠;每次修改都不允许 CC 或 VV 重叠增加。只有每个 rank 的成本模型都预测两种覆盖率严格提高时才选择 scheduled 图;随后的设备实测用于报告和告警,不再触发 `dependency_only` 回退。
4- 
5-## 运行
6- 
7-当前解析契约针对 CANN 9.2 和 `requirements.txt` 固定的 torch-npu 版本,需要匹配的 torchtitan、CANN/HCCL 环境和空闲 NPU。在仓库根目录执行:
8- 
9-```bash
10-ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
11-bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5_cv_parallel.sh \
12- --dump-folder outputs/dual_chunk_cv > dual_chunk_cv.log 2>&1
13-```
14- 
15-默认复用 `graph_trainer_deepseek_v4_flash_43layers_16experts` 配置,使用 8 卡、43 层、EP8/FSDP8、MBS=2;GBS=64、seq4096、100 步等通用默认值继承 A5 launcher。可通过 `CONFIG` 和 `NGPU` 选择配置与卡数,通过追加 `--training.steps`、`--training.global-batch-size`、`--training.seq-len` 和 `--dump-folder` 调整训练参数。tokenizer、数据和 checkpoint 路径沿用 A5 launcher 的 `HF_ASSETS_PATH`、`DATASET_PATH`、`CKPT_SAVE_LOAD_PATH` 设置;运行前应配置有效路径。卡数须满足模型的 EP/FSDP 拓扑要求。
16- 
17-后四卡的小模型验证使用仓库已有的 `deepseek_v4_debugmodel` 的 GraphTrainer 入口:
18- 
19-```bash
20-ASCEND_RT_VISIBLE_DEVICES=4,5,6,7 \
21-CONFIG=graph_trainer_deepseek_v4_debugmodel \
22-NGPU=4 \
23-bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5_cv_parallel.sh \
24- --training.global-batch-size 8 --training.seq-len 512 --training.steps 10 \
25- --dump-folder outputs/dual_chunk_debug_cv > dual_chunk_debug_cv.log 2>&1
26-```
27- 
28-脚本从仓库根目录运行,使用当前 Python 环境,并返回训练退出码。日志输出到标准输出/错误,示例命令将其重定向到文件。配置入口为:
29- 
30-```text
31-module = torchtitan_npu.models.deepseek_v4
32-config = graph_trainer_deepseek_v4_flash_43layers_16experts
33-```
34- 
35-双 chunk 的启用参数由脚本传入:`--training.local-batch-size 2`、`--compile.ep-overlap.enabled`、`--compile.ep-overlap.chunk-dim batch`、`--compile.ep-overlap.strategy graph`、`--compile.ep-overlap.module-fqn 'layers.*'` 和 `--compile.pass-pipeline cv_parallel`。实际调用的 A5 launcher 默认启用 `all_block_fp8`、LI FP8 和 KV norm MXFP8;GraphTrainer 配置名不会关闭这些 CLI 参数。需要 BF16 训练时,在命令末尾追加 `--extension.quantization.no-enable-quantized-training`。
36- 
37-如果通过 CLI 整体替换 `--override.imports`,须保留以下实验依赖:
38- 
39-```text
40-torchtitan_npu.override.deepseek_v4.lightning_indexer.asc
41-torchtitan_npu.extensions.experiment.cv_parallel.batch_chunk_token_dispatcher.asc_dispatcher
42-```
43- 
44-实验 dispatcher 入口 `batch_chunk_token_dispatcher.asc_dispatcher` 在启用时注册 `cv_parallel` pipeline,
45-并在 trainer 的 per-step hook 里安装 metadata 重切。它替换 `common.token_dispatcher.asc`,同一配置节点不能
46-同时启用两种 override。RoPE 沿用公共实现;
47-dispatcher 的包装只适配符号 token 数,实际前后向仍调用原生 NPU kernel。普通配置不会选中实验实现。
48- 
49-> **接缝**:DeepSeek-V4 的 metadata 由 attention backend 自己的 config 按几何构建
50-> (upstream PR #4897)。fused compressor 的状态表由同一个构建器在 eager 边界写进 plan
51-> (表宽随 batch 的文档走,不能在建图时构)。
52-> CV chunking 的重切不发生在模型里:`cv_parallel` 的 post-init hook 在每一步的
53-> `_make_fx_forward_backward_step` 入口把 `extra_kwargs` 里的每条 entry 重切成
54-> full + 两个 chunk(`batch_chunk_metadata.chunk_attention_metadata`),因此重切发生在
55-> 追踪/重放之前、每 rank 的 plan 上,模型与内核都不需要知道实验的存在;几何与 LI provider
56-> 契约从被重切的元数据读出。
57- 
58-完整 batch 在追踪时约束为 `B >= 2`,图切分后每个 chunk 可以只有一个样本。运行时输入和追踪适配通过 `cv_parallel` 的 post-init hook 绑定到当前 trainer 实例,不替换公共 GraphTrainer 方法或原有 `ep_overlap` 注册项。
59- 
60-## 实现流程
61- 
62-1. 在 eager 阶段把每条已构建的 entry 重切成 full + 两个半 batch。文档边界必须与等分点对齐;压缩 plan、AscendC 记录和 host 字段不能按 tensor 长度机械切半。
63-2. 复用 torchtitan 的 batch graph chunk pass,将两个 chunk 固定到两条流,并把 duplicated layer 的 metadata 输入重映射到预构建的局部值。
64-3. `dependency_only_schedule` 保留数据依赖、流内 FIFO、通信、主机观察和共享状态屏障;跨流消费和最终输出汇合仍会产生必要 event。
65-4. 对同一个 batch 重放 free 图,采集各 rank 的节点设备耗时和 kernel 资源类型。校准会克隆输入、恢复可变 buffer,并验证参数和梯度状态未改变。
66-5. 搜索器按双向 CV 掩盖率、纯 CV 时间、同类重叠和 MIX 重叠依次比较局部重排或 event gate。候选不得降低任一方向的掩盖率,不得增加 CC/VV,且全图预测 span 不得超过 free。通信、RNG、原地写、未知调用及强制屏障不会被跨越。
67-6. 每个 rank 的最终预测必须同时提高两种 CV 掩盖率,且不增加 CC/VV;否则回退到已校准的 `dependency_only` 图。选中 scheduled 图后再次计时并采集 profile,记录纯 CV、双向掩盖率、CC/VV 和同步 F/B 的验收结果。实测未提高时保留 scheduled 图继续训练,并在报告中写入 `validation_warning`。
68- 
69-free 校准预热 3 次、计时 3 次;scheduled 预热 1 次、计时 3 次;两者各采集一次详细 profile。同步计时覆盖完整前后向,但不含输入克隆、状态检查、profiler 和优化器。
70- 
71-### 搜索计算开销
72- 
73-自动搜索以通信、RNG、原地写、未知调用等不可跨越的强屏障划分区域。节点数不超过 512 的区域完整枚举可重排节点的全部合法目标位置、所有独立 Cube/Vector phase 组合及其可用等待源,并持续迭代到该区域不再产生改进。超过 512 个节点的区域使用自适应有界搜索:最多执行 8 轮,每类最多选择 16 个高收益重排节点,每个节点最多尝试 24 个近邻、指数间隔和全局目标位置;每轮最多检查 2048 个 CV 候选,每个候选最多检查 32 个等待源。搜索仍不生成 VV gate。
74- 
75-区域彼此不存在可调度的跨界候选,因此按屏障拆分不会缩小合法搜索空间;区域候选仍与区域外已累计的覆盖量合并后,按全图双向覆盖率打分。重叠查询缓存区间前缀覆盖值;新增等待只传播发生延后的父节点完成时间。窗口评分复用相同节点和开始时间的覆盖值,重排依赖集合按目标位置增量构建。小区域不裁剪候选;大区域的上述预算用于限制启动搜索成本。
76- 
77-搜索还缓存三类可复用结果:按 `(node, start_time)` 缓存平移后的 kernel phase;按完整窗口顺序和移动节点缓存所有依赖安全的重排模板;按调度状态版本缓存 event/reorder trial。前两类只依赖不可变 phase 或精确窗口顺序,可跨 `refresh()` 复用;trial 依赖 clocks、开始时间、gate 和覆盖量,每次 `refresh()` 必须失效。缓存均有容量上限。区域数、最大区域节点数、搜索模式、预算、完整 trial 数、缓存命中、候选跳过数量和 trial 失效数量写入 `schedule_feedback.json`。
78- 
79-最后删除不降低双向 CV 掩盖率、不增加 CC/VV、跨度或计算并集的冗余 gate。依赖当前 clocks、时间线或 coverage 的缓存随调度状态重建而失效;只有不可变 phase 和精确窗口顺序对应的模板允许跨状态复用。搜索是区域内贪心迭代,不等价于组合意义上的全局穷举;小区域迭代到收敛,大区域达到收敛或预算上限后停止。
80- 
81-MIX 分类沿用 `a95f74f` 的逐 launch 计数器规则:优先读取 `op_summary*.csv`,没有该文件时读取 `kernel_details.csv`,按名称、开始时间、时长及可用的 stream/task ID 匹配。主核时间占比至少 75%、次核累计时间不超过 0.1 ms 时,细分为 `mix_aiv` 或 `mix_aic`;有效的 MAC/Vector 执行单元时间优先于整核时间。缺少有效计数器、匹配不唯一或不满足阈值时保留 `mix`,不凭 MIX 名称推断主核。
82- 
83-节点成本、kernel phase 与重叠统计使用同一分类规则。该分类只是调度近似,不保证次核空闲,MIX 不计入纯 CV。统计另列 Cube×`mix_aiv` 和 Vector×`mix_aic`;搜索在双向纯 CV 掩盖率、纯 CV 及 CC/VV 目标之后比较 MIX 重叠。DeepEP 屏障保持不变。恢复分类不代表恢复旧环境的全部成本输入或 A5 实测收益。
84- 
85-## 接入已有 graph pipeline
86- 
87-已有 pipeline 完成切分并为节点写入 `chunk_id=0/1` 后,可把调度 pass 放在最后:
88- 
89-```python
90-from functools import partial
91-from pathlib import Path
92- 
93-from torchtitan_npu.extensions.experiment.cv_parallel.cv_parallel import schedule_pass
94- 
95-passes.append(partial(
96- schedule_pass,
97- profile_root=Path(config.dump_folder) / "profiling",
98- runtime_context=runtime_context,
99-))
100-```
101- 
102-`runtime_context` 须显式提供 `traced_result`、`module`、本次追踪参数 `args` 和 `train_context`;`cv_parallel` pipeline 从实例 hook 获取这些对象。输入必须是可重放的完整前后向 FX 图,并保留 split、合并、梯度累加、通信和共享状态依赖。该入口只负责 profile、调度和验收,不提供 seq 切分语义,也不能与另一套跨流调度叠加。
103- 
104-## 输出与判读
105- 
106-校准结果默认位于 `--dump-folder` 指定目录下的 `profiling/schedule_feedback.json`;设置 `CV_PARALLEL_PROFILING_DIR` 时使用该目录:
107- 
108-- `status=applied` 且 `selected=profile_guided_cv`:逐卡预测满足双向 CV 掩盖率提高且 CC/VV 不增加,scheduled 图用于训练。
109-- `status=fallback` 且 `selected=dependency_only`:至少一个 rank 没有有效预测收益;原因记录在 `fallback_reason`。设备实测结果不会产生该状态。
110-- `prediction`:free 成本模型的双向掩盖率、CV/CC/VV、compute union 和 span 预测,不等于设备提速。
111-- `schedule.cv_validation_by_rank`:逐卡实测 CV 时间、双向掩盖率及 CC/VV 差值。
112-- `validation_passed` 与 `validation_warning`:记录 scheduled 实测是否满足全部验收项及首个告警原因。验收失败只告警,不切换执行图。
113-- `schedule.forward_backward_delta_ms`:scheduled 相对 free 的前后向中位数变化,正值表示变慢;此时 `forward_backward_guard_passed=false`,但仍保留 scheduled 图。
114- 
115-rank 0 的原生 profile 保存在 `profiling/dependency_only/rank0/` 和 `profiling/profile_guided_cv_validation/rank0/`。可用以下命令查看关键阶段:
116- 
117-```bash
118-rg 'CV parallel regional search|CV parallel predicted gains:|CV parallel waits:|CV parallel scheduled measured:|CV parallel CV guard:' dual_chunk_cv.log
119-```
120- 
121-### 正常训练输出
122- 
123-调度实现按职责分为三个模块:`schedule_search.py` 生成候选并控制区域搜索;`schedule_simulation.py` 维护依赖、时间线和预测缓存;`schedule_scoring.py` 提供指标公式与候选接受规则。搜索器持有独立的模拟对象。`schedule_calibration.py` 在本地搜索返回后汇总各 rank 的预测并检查通信顺序,再进入候选图实测。预测使用固定 profile 时长,不代表实际争用或完整 step 加速。
124- 
125-`profile_overlap.py` 是启动校准的指标计算模块:`profile_whole_graph_costs` 调用它,从实际 profile 中计算前后向计算并集及 C/V、CC/VV、MIX 重叠,供基础图与候选图的实测验收和告警使用。它不生成多模式比较报表,也不直接执行调度搜索;搜索使用另行提取的节点成本和 kernel phase。当前校准流程仍需要该模块。
126- 
127-入口直接启用 C/V 双流调度,不额外生成 manifest、Git 快照或状态 JSON。训练输出由 `--dump-folder` 控制;需要 TensorBoard 时显式追加 `--metrics.enable-tensorboard`。
128- 
129-启动校准仍会生成调度所需的 profile 和验收报告。未找到预测收益时使用保留依赖和屏障的 free 双流图继续训练。校准的前后向耗时和重叠率不能证明完整训练 step 提速。
130- 
131-## 性能与内存测试报告
132- 
133-### 测试配置
134- 
135-测试配置采用仓库内的启动脚本 [deepseek_v4_flash_8p_cpt_4k_a5_cv_parallel.sh](../../examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5_cv_parallel.sh),测试设备为 **A5 服务器**。对比 baseline 的 `graphtrainer` 与开启图级 CV 并行的 `cv_parallel`。
136- 
137-### 训练耗时与内存
138- 
139-| 指标 | baseline | cv_parallel |
140-| --- | ---: | ---: |
141-| 状态 | 完成 | 完成 |
142-| 稳态 E2E 中位数(ms/step) | 24536.326 | 24360.393 |
143-| F/B scope(ms) | 23750.771 | 23664.367 |
144-| 计算跨度(ms) | 23792.064 | 23739.603 |
145-| 计算并集(ms) | 17027.062 | 16650.671 |
146-| 计算加速比(按计算并集) | 1.000× | 1.023× |
147-| E2E 加速比(按稳态中位数) | 1.000× | 1.007× |
148-| 内存(GB) | 62.95 | 77.61 |
149- 
150-计算并集减少 **376.391 ms(2.21%)**,稳态 E2E 中位数减少 **175.933 ms(0.72%)**。E2E 包含通信、同步及其他开销,因此计算并集的改善不会按同样比例转化成完整 step 的改善。
151- 
152-内存增加 **14.66 GB(23.29%)**。双流执行与重排可能延长张量存活时间,但现有数据不足以把增量归因到某一环节。
153- 
154-### 资源重叠
155- 
156-| 指标 | baseline | cv_parallel |
157-| --- | ---: | ---: |
158-| 未重叠计算(ms) | 17027.062 | 3434.019 |
159-| 总重叠(ms) | 0.000 | 13216.652 |
160-| 纯 CV 重叠(ms) | 0.000 | 3072.006 |
161-| Cube × MIX_AIV 重叠(ms) | 0.000 | 16.253 |
162-| Vector × MIX_AIC 重叠(ms) | 0.000 | 971.115 |
163-| CC 重叠(ms) | 0.000 | 3719.612 |
164-| VV 重叠(ms) | 0.000 | 1631.421 |
165-| MIX/不明确重叠(ms) | 0.000 | 4793.613 |
166-| 总掩盖率(%) | 0.000 | 79.376 |
167-| 纯 CV / 计算并集(%) | 0.000 | 18.450 |
168-| Cube 被 Vector 覆盖(%) | 0.000 | 31.959 |
169-| Vector 被 Cube 覆盖(%) | 0.000 | 34.645 |
170- 
171-纯 CV 重叠由 0 增至 **3072.006 ms**,说明本次 profile 中 Cube 与 Vector 的执行区间形成了并发。Cube 被 Vector 覆盖 **31.959%**,Vector 被 Cube 覆盖 **34.645%**,分别从两类资源自身的执行时间衡量重叠程度。总重叠还包含 CC、VV 和 MIX/不明确重叠,因此 **79.376%** 的总掩盖率不能解释为纯 CV 协同收益。
172- 
173-### 统计口径与结果边界
174- 
175-- **E2E** 是完整训练 step 的端到端耗时。稳态统计排除预热、性能采样与调度搜索阶段;加速比采用 baseline 中位数除以 cv_parallel 中位数。
176-- **F/B scope** 是前向与反向测量范围的耗时;**计算跨度**是首个计算 kernel 开始到最后一个计算 kernel 结束的时间,包含其中的间隙。两者与完整 step 的测量边界不同。
177-- **计算并集**是计算 kernel 执行区间的并集:重叠部分只计一次,不含纯通信与空闲区间。计算加速比采用 baseline 计算并集除以 cv_parallel 计算并集。
178-- **总重叠**按本次数据为计算并集中至少两个计算 kernel 同时执行的时间;未重叠计算与总重叠之和等于计算并集。总掩盖率以计算并集为分母。
179-- **纯 CV 重叠**不含 MIX 算子,占比以计算并集为分母。两项覆盖比例分别以 Cube 和 Vector 各自的执行时间为分母,不能相加。
180- 
181-## 限制
182- 
183-- 当前只支持整层栈的等分 batch chunk,不支持该 metadata 路径上的 context parallel;文档不能跨半 batch 边界。
184-- profiler 依赖 CANN 9.2 导出的 `trace_view.json`、`kernel_details.csv` 及 torch-npu `analyse()` 接口;升级 CANN 或 torch-npu 后须先回归 trace 命名、CSV 列和 launch 关联测试。
185-- event 只约束先后,不能保证 kernel 同时开始。预测 span 不增也不代表实测加速,因此仍采集设备验收数据,但验收结果不触发执行图回退。
186-- 搜索优先平衡两种方向的 CV 掩盖率,并限制 CC/VV 不增加;小区域完整枚举并收敛,大区域使用固定预算,两者都是贪心搜索,不承诺组合意义上的全局最优或端到端提速。通信、host 下发、event 开销和新的资源竞争可能抵消收益。
187-- 校准 batch 通过不保证后续每步都获得相同收益;重排还可能延长张量存活时间。
@@ -1,42 +0,0 @@
1-#!/usr/bin/env bash
2-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
3-#
4-# This source code is licensed under the BSD-style license found in the
5-# LICENSE file in the root directory of this source tree.
6- 
7-# Add batch C/V scheduling to the A5 training recipe.
8-# Append CLI arguments to override training defaults, for example:
9-# bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5_cv_parallel.sh --training.steps 10
10-set -euo pipefail
11- 
12-export MODULE=torchtitan_npu.models.deepseek_v4
13-export CONFIG="${CONFIG:-graph_trainer_deepseek_v4_flash_43layers_16experts}"
14-export NGPU="${NGPU:-8}"
15- 
16-bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5.sh \
17- --parallelism.data-parallel-shard-degree "${NGPU}" \
18- --parallelism.data-parallel-replicate-degree 1 \
19- --parallelism.expert-parallel-degree "${NGPU}" \
20- --compile.enable-passes \
21- --compile.backend aot_eager \
22- --compile.inductor-compilation regional \
23- --compile.pass-pipeline cv_parallel \
24- --compile.memory-policy full \
25- --compile.ep-overlap.enabled \
26- --compile.ep-overlap.chunk-dim batch \
27- --compile.ep-overlap.module-fqn "layers.*" \
28- --compile.no-enable-autoparallel \
29- --compile.no-enable-fsdp-ag-rs-overlap \
30- --compile.no-enable-fsdp-dense-region-overlap \
31- --compile.no-numerics-changing-optim \
32- --override.imports \
33- torchtitan_npu.override.common.rms_norm.asc \
34- torchtitan_npu.override.common.rope.asc_partial \
35- torchtitan_npu.override.common.swiglu_group.asc \
36- torchtitan_npu.override.common.swiglu_group.asc_shared_experts \
37- torchtitan_npu.override.deepseek_v4.lightning_indexer.asc \
38- torchtitan_npu.override.deepseek_v4.sparse_attn.asc \
39- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_pre \
40- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_post \
41- torchtitan_npu.extensions.experiment.cv_parallel.batch_chunk_token_dispatcher.asc_dispatcher \
42- "$@"
@@ -42,8 +42,6 @@ def my_run():
42或直接使用 `scripts/run_train.sh` 并在 recipe 中配置训练参数。Pro、CP 等其他入口需要42或直接使用 `scripts/run_train.sh` 并在 recipe 中配置训练参数。Pro、CP 等其他入口需要
43编译时,也在对应 recipe 中显式设置 `CompileConfig`,再通过 `MODULE` / `CONFIG` 选择。43编译时,也在对应 recipe 中显式设置 `CompileConfig`,再通过 `MODULE` / `CONFIG` 选择。
44 44 
45-CV Parallel 调试入口在当前固定 TorchTitan 版本中仅完成配置与注册适配。上游已删除其依赖的 Graph EP 分块机制,CV 运行迁移尚未完成,入口会明确报错;详见 [CV 迁移状态](../../torchtitan_npu/extensions/experiment/cv_parallel/README.md)。
46- 
47## 常用环境变量45## 常用环境变量
48 46 
49运行前至少根据环境设置以下路径和节点信息:47运行前至少根据环境设置以下路径和节点信息:
@@ -32,7 +32,6 @@ sys.path.insert(0, str(_REPO))
32# skip marks cannot prevent imports of removed upstream symbols.32# skip marks cannot prevent imports of removed upstream symbols.
33collect_ignore = [33collect_ignore = [
34 "ema",34 "ema",
35- "extensions/experiment/cv_parallel",
36 "extensions/torchtitan/experiments/graph_trainer",35 "extensions/torchtitan/experiments/graph_trainer",
37 "patches/torchtitan/experiments/graph_trainer",36 "patches/torchtitan/experiments/graph_trainer",
38 # Qwen runtime migration is deferred. Upstream eagerly imports CUDA-only37 # Qwen runtime migration is deferred. Upstream eagerly imports CUDA-only
@@ -1,243 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-"""CPU checks for symbolic CV batch chunking and isolated calibration."""
3- 
4-from contextlib import contextmanager, nullcontext
5-from types import SimpleNamespace
6- 
7-import pytest
8-import torch
9-from torch.fx.experimental.symbolic_shapes import ShapeEnv
10-from torchtitan.config import ConfigManager
11-from torchtitan.experiments.graph_trainer.make_fx_tracer import minimal_fx_tracer, run_traced
12- 
13-from torchtitan_npu.extensions.experiment.cv_parallel import batch_chunk, symbolic_meta
14-from torchtitan_npu.extensions.experiment.cv_parallel.batch_chunk import _make_run_candidate
15- 
16- 
17-def test_mx_meta_family_keeps_flattened_batch_symbolic():
18- shape_env = ShapeEnv()
19- batch = shape_env.create_unbacked_symint()
20- activation = torch.empty((4096 * batch, 7168), device="meta")
21- 
22- q1, scale1, q2, scale2 = symbolic_meta._symbolic_dynamic_mx_quant_with_dual_axis_meta(
23- activation,
24- dst_type=292,
25- scale_alg=1,
26- )
27- 
28- assert q1.shape == q2.shape == activation.shape
29- assert q1.dtype == q2.dtype == torch.float8_e4m3fn
30- assert scale1.shape == (4096 * batch, 112, 2)
31- assert scale2.shape == (64 * batch, 7168, 2)
32- assert scale2.shape[0].node.hint is None
33- 
34- q, scale = symbolic_meta._symbolic_dynamic_mx_quant_meta(
35- activation,
36- axis=0,
37- dst_type=292,
38- block_size=32,
39- scale_alg=1,
40- )
41- block_q, block_scale1, block_scale2 = symbolic_meta._symbolic_dynamic_block_mx_quant_meta(
42- activation,
43- dst_type=292,
44- scale_alg=1,
45- )
46- 
47- assert q.shape == block_q.shape == activation.shape
48- assert scale.shape == (64 * batch, 7168, 2)
49- assert block_scale1.shape == scale1.shape
50- assert block_scale2.shape == scale2.shape
51- 
52- 
53-def test_symbolic_meta_override_is_scoped_and_destroyed_on_error(monkeypatch):
54- events = []
55- 
56- class FakeLibrary:
57- def __init__(self, *args):
58- events.append(("create", args))
59- 
60- def impl(self, op_name, function, *, allow_override):
61- events.append(("impl", op_name, function, allow_override))
62- 
63- def _destroy(self):
64- events.append(("destroy",))
65- 
66- monkeypatch.setattr(symbolic_meta, "_vendor_mx_supports_unbacked", lambda _: False)
67- monkeypatch.setattr(torch.library, "Library", FakeLibrary)
68- 
69- with symbolic_meta.batch_chunk_symbolic_meta_context(enabled=False):
70- assert not events
71- 
72- with (
73- pytest.raises(RuntimeError, match="trace failed"),
74- symbolic_meta.batch_chunk_symbolic_meta_context(enabled=True),
75- ):
76- raise RuntimeError("trace failed")
77- 
78- assert [event[0] for event in events] == ["create", "impl", "impl", "impl", "destroy"]
79- 
80- 
81-def test_calibration_replays_restore_buffers_and_preserve_inputs_and_gradients():
82- model = torch.nn.Module()
83- model.weight = torch.nn.Parameter(torch.tensor([[0.2, 0.4], [0.6, 0.8]]))
84- model.register_buffer("counter", torch.tensor([3.0]))
85- inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
86- 
87- def step(x):
88- model.counter.add_(1)
89- x.add_(0.25)
90- loss = (x @ model.weight).square().sum()
91- return loss, *torch.autograd.grad(loss, (model.weight,))
92- 
93- traced = minimal_fx_tracer(step, module=model)(inputs.clone())
94- model.counter.fill_(3)
95- model.weight.grad = torch.full_like(model.weight, 0.5)
96- original_grad = model.weight.grad
97- reference_weight = model.weight.detach().clone().requires_grad_()
98- expected_loss = ((inputs + 0.25) @ reference_weight).square().sum()
99- expected_gradient = torch.autograd.grad(expected_loss, reference_weight)[0]
100- runner = _make_run_candidate(
101- {
102- "module": model,
103- "traced_result": traced,
104- "args": (inputs,),
105- "train_context": nullcontext,
106- }
107- )
108- 
109- for _ in range(2):
110- runner.prepare()
111- try:
112- actual_loss, actual_gradient = runner(traced.gm)
113- torch.testing.assert_close(model.counter, torch.tensor([4.0]), rtol=0, atol=0)
114- finally:
115- runner.finalize()
116- 
117- torch.testing.assert_close(actual_loss, expected_loss, rtol=0, atol=0)
118- torch.testing.assert_close(actual_gradient, expected_gradient, rtol=0, atol=0)
119- torch.testing.assert_close(model.counter, torch.tensor([3.0]), rtol=0, atol=0)
120- torch.testing.assert_close(inputs, torch.tensor([[1.0, 2.0], [3.0, 4.0]]), rtol=0, atol=0)
121- torch.testing.assert_close(model.weight, reference_weight, rtol=0, atol=0)
122- assert model.weight.grad is original_grad
123- torch.testing.assert_close(original_grad, torch.full((2, 2), 0.5), rtol=0, atol=0)
124- 
125- 
126-def test_minimum_batch_preparation_traces_native_loss_and_gradients():
127- # Import after the NPU package patches Trainer.Config.
128- from torchtitan.experiments.graph_trainer.registry import POST_INIT_HOOKS
129- from torchtitan.experiments.graph_trainer.trainer import GraphTrainer
130- 
131- config = ConfigManager().parse_args(
132- [
133- "--module",
134- "torchtitan_npu.models.deepseek_v4",
135- "--config",
136- "graph_trainer_deepseek_v4_debugmodel",
137- "--hf-assets-path",
138- "tests/assets/deepseek_v3",
139- "--training.local-batch-size",
140- "2",
141- "--compile.ep-overlap.enabled",
142- "--compile.ep-overlap.chunk-dim",
143- "batch",
144- "--compile.ep-overlap.strategy",
145- "graph",
146- "--compile.ep-overlap.module-fqn",
147- "layers.*",
148- "--compile.pass-pipeline",
149- "cv_parallel",
150- ]
151- )
152- config.loss.loss_fn.global_vocab_size = 16
153- with torch.random.fork_rng(devices=[]):
154- torch.manual_seed(42)
155- head = torch.nn.Linear(4, 16, bias=False)
156- hidden = torch.randn(config.training.local_batch_size, 16, 4, requires_grad=True)
157- labels = torch.randint(16, (config.training.local_batch_size, 16))
158- loss_fn = config.loss.build()
159- loss_fn.set_lm_head(head)
160- inputs = (hidden, labels, torch.tensor(labels.numel()))
161- 
162- def step(x, target, valid_tokens):
163- head.zero_grad(set_to_none=True)
164- loss, _ = loss_fn(x, target, valid_tokens)
165- return loss, *torch.autograd.grad(loss, (x, head.weight))
166- 
167- expected = step(*inputs)
168- trainer = SimpleNamespace(config=config, model_parts=[head], _make_fx_forward_backward_step=lambda *args: None)
169- trainer._prepare_trace_inputs = lambda args, kwargs: GraphTrainer._prepare_trace_inputs(trainer, args, kwargs)
170- POST_INIT_HOOKS[config.compile.pass_pipeline](trainer)
171- trainer._prepare_trace_inputs(inputs, {})
172- traced = minimal_fx_tracer(step, module=head)(*inputs)
173- actual = run_traced(traced, module=head)(*inputs)
174- 
175- for result, reference in zip(actual, expected, strict=True):
176- torch.testing.assert_close(result, reference, rtol=0, atol=0)
177- # The chunk pass still needs the batch symbol to derive its B//2 shapes.
178- fake_hidden = next(
179- n.meta["val"] for n in traced.gm.graph.nodes if n.op == "placeholder" and n.meta["val"].ndim == 3
180- )
181- assert isinstance(fake_hidden.shape[0], torch.SymInt)
182- 
183- 
184-def test_runtime_context_is_instance_local_and_preserves_training_gradients(monkeypatch):
185- from torchtitan.experiments.graph_trainer.configs import GraphTrainerCompileConfig
186- from torchtitan.experiments.graph_trainer.registry import PASS_PIPELINE_REGISTRY, POST_INIT_HOOKS
187- from torchtitan.experiments.graph_trainer.trainer import GraphTrainer
188- 
189- from torchtitan_npu.extensions.experiment.cv_parallel.batch_chunk import _RUNTIME_CONTEXT
190- 
191- with torch.random.fork_rng(devices=[]):
192- model = torch.nn.Linear(2, 1, bias=False)
193- with torch.no_grad():
194- model.weight.copy_(torch.tensor([[0.2, -0.3]]))
195- inputs = torch.tensor([[1.0, 2.0], [3.0, -1.0]])
196- labels = torch.tensor([[0.7], [-0.5]])
197- valid_tokens = torch.tensor(2)
198- expected_error = inputs @ model.weight.detach().T - labels
199- expected_loss = expected_error.square().sum() / 2
200- expected_gradient = expected_error.T @ inputs
201- observed_contexts = []
202- symbolic_meta_contexts = []
203- 
204- @contextmanager
205- def record_symbolic_meta_context(*, enabled):
206- symbolic_meta_contexts.append(enabled)
207- yield
208- 
209- def inspect_pipeline(traced_result, config, *, parallel_dims):
210- context = _RUNTIME_CONTEXT.get()()
211- assert context["traced_result"] is traced_result
212- assert context["module"] is model
213- assert context["args"][0] is inputs
214- observed_contexts.append(context)
215- return []
216- 
217- monkeypatch.setitem(PASS_PIPELINE_REGISTRY, "cv_parallel", inspect_pipeline)
218- monkeypatch.setattr(batch_chunk, "batch_chunk_symbolic_meta_context", record_symbolic_meta_context)
219- for experimental in (False, True, False):
220- # Exercise the real CPU trace/replay without NPU Trainer initialization.
221- trainer = object.__new__(GraphTrainer)
222- compile_config = GraphTrainerCompileConfig(enable_passes=experimental, pass_pipeline="cv_parallel")
223- compile_config.ep_overlap.enabled = experimental
224- trainer.config = SimpleNamespace(compile=compile_config)
225- trainer.parallel_dims = None
226- trainer.model_parts = [model]
227- trainer._traced_step = None
228- trainer.train_context = nullcontext
229- trainer.loss_fn = lambda pred, target, global_valid_tokens: (pred - target).square().sum() / global_valid_tokens
230- if experimental:
231- POST_INIT_HOOKS[trainer.config.compile.pass_pipeline](trainer)
232- else:
233- assert "_make_fx_forward_backward_step" not in vars(trainer)
234- assert "_prepare_trace_inputs" not in vars(trainer)
235- model.zero_grad(set_to_none=True)
236- 
237- loss = trainer._make_fx_forward_backward_step(model, inputs, labels, valid_tokens, list(model.parameters()), {})
238- 
239- torch.testing.assert_close(loss, expected_loss, rtol=0, atol=0)
240- torch.testing.assert_close(model.weight.grad, expected_gradient, rtol=0, atol=0)
241- assert _RUNTIME_CONTEXT.get() is None
242- assert len(observed_contexts) == 1
243- assert symbolic_meta_contexts == [True]
@@ -1,69 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-"""CV-chunk symbolic token permutation and dispatcher isolation."""
3- 
4-import torch
5-import torch_npu
6-from torch._dynamo.decorators import mark_unbacked
7-from torchtitan.config.override import apply_overrides
8-from torchtitan.experiments.graph_trainer.make_fx_tracer import minimal_fx_tracer, run_traced
9- 
10-from torchtitan_npu.extensions.experiment.cv_parallel.batch_chunk_token_dispatcher import BatchChunkTokenDispatcher
11-from torchtitan_npu.models.deepseek_v4.config_registry import graph_trainer_deepseek_v4_debugmodel
12-from torchtitan_npu.override.common.token_dispatcher import AscAllToAllTokenDispatcher
13-from torchtitan_npu.patches.torchtitan.models.common.token_dispatcher import AllToAllTokenDispatcher
14- 
15- 
16-def test_symbolic_dispatch_preserves_gradients_without_changing_ordinary_dispatch(monkeypatch):
17- # Emulate only the native NPU kernel boundary; config selection and tracing are real.
18- backward_calls = []
19- 
20- def fake_permute(tokens, indices):
21- if torch.overrides.has_torch_function((tokens, indices)):
22- return torch.overrides.handle_torch_function(fake_permute, (tokens, indices), tokens, indices)
23- order = indices.flatten().argsort(stable=True)
24- return tokens.repeat_interleave(indices.shape[1], dim=0)[order], order.argsort().to(torch.int32)
25- 
26- def fake_backward(grad, sorted_indices, num_tokens, dtype, topk):
27- backward_calls.append((num_tokens, dtype, topk))
28- return grad[sorted_indices.long()].reshape(num_tokens, topk, grad.shape[-1]).sum(1).to(dtype)
29- 
30- monkeypatch.setattr(torch_npu, "npu_moe_token_permute", fake_permute)
31- monkeypatch.setattr(torch_npu, "npu_moe_token_permute_grad_v2", fake_backward)
32- for experimental in (False, True, False):
33- config = graph_trainer_deepseek_v4_debugmodel()
34- config.override.imports = [
35- "torchtitan_npu.extensions.experiment.cv_parallel.batch_chunk_token_dispatcher.asc_dispatcher"
36- if experimental
37- else "torchtitan_npu.override.common.token_dispatcher.asc"
38- ]
39- apply_overrides(config.override, config)
40- dispatcher = next(config.model_spec.model.traverse(AllToAllTokenDispatcher.Config))[1].build()
41- assert type(dispatcher) is (BatchChunkTokenDispatcher if experimental else AscAllToAllTokenDispatcher)
42- tokens = (torch.arange(6, dtype=torch.float64).reshape(2, 3) / 8 - 0.25).requires_grad_()
43- scores = ((torch.arange(6, dtype=torch.float64).reshape(2, 3) + 1) / 16).requires_grad_()
44- ids = torch.tensor([[3, 0, 1], [2, 1, 0]])
45- counts = torch.tensor([2, 2, 1, 1])
46- # Hand-enumerated expert-major token and score rows for these assignments.
47- expected_routed = tokens[[0, 1, 0, 1, 1, 0]] * scores.flatten()[[1, 5, 2, 4, 3, 0], None]
48- expected = (expected_routed, *torch.autograd.grad(expected_routed.square().sum(), (tokens, scores)))
49- 
50- def step(x, probabilities, assignments, expert_counts, *, selected_dispatcher=dispatcher):
51- routed, _, metadata = selected_dispatcher.dispatch(x, probabilities, assignments, expert_counts)
52- weighted = routed * metadata.routed_scores_R[:, None]
53- return weighted, *torch.autograd.grad(weighted.square().sum(), (x, probabilities))
54- 
55- before = len(backward_calls)
56- if experimental:
57- for tensor in (tokens, scores, ids):
58- mark_unbacked(tensor, 0, min=2, shape_id="batch_chunk_override")
59- traced = minimal_fx_tracer(step)(tokens, scores, ids, counts)
60- actual = run_traced(traced)(tokens, scores, ids, counts)
61- fake_tokens = next(n.meta["val"] for n in traced.gm.graph.nodes if n.op == "placeholder")
62- assert isinstance(fake_tokens.shape[0], torch.SymInt)
63- assert sorted(backward_calls[before:]) == [(2, torch.float64, 3), (6, torch.float64, 1)]
64- else:
65- actual = step(tokens, scores, ids, counts)
66- assert len(backward_calls) == before
67- 
68- for result, target in zip(actual, expected, strict=True):
69- torch.testing.assert_close(result, target, rtol=0, atol=0)
@@ -1,49 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-"""Hand-computed candidate policy boundaries."""
3- 
4-import pytest
5- 
6-from torchtitan_npu.extensions.experiment.cv_parallel.schedule_scoring import (
7- candidate_score,
8- predicted_coverage_improved,
9-)
10- 
11- 
12-@pytest.mark.parametrize(
13- "vector,cc,accepted",
14- [(51.0, 0.0, True), (50.0, 0.0, False), (49.0, 0.0, False), (51.0, 2e-9, False)],
15-)
16-def test_candidate_policy_preserves_directional_and_same_type_guards(vector, cc, accepted):
17- metrics = {
18- "cube_covered_by_vector_percent": 50.0,
19- "vector_covered_by_cube_percent": vector,
20- "cv_ms": 5.0,
21- "mixed_cv_ms": 0.0,
22- "cc_ms": cc,
23- "vv_ms": 0.0,
24- "span_ms": 10.0,
25- }
26- # Baseline: 50% in both directions, 5 ms CV, zero same-type overlap.
27- baseline_score = (50.0, 100.0, 5.0, 0.0, 0.0, 0.0, 0.0, -10.0)
28- result = candidate_score((50.0, 50.0, 0.0, 0.0), baseline_score, metrics)
29- assert (result is not None) is accepted
30- baseline = {**metrics, "vector_covered_by_cube_percent": 50.0, "cc_ms": 0.0}
31- # Final validation requires both directions to improve, unlike a local edit.
32- assert not predicted_coverage_improved(baseline, metrics)
33- 
34- 
35-def test_final_prediction_requires_strict_gains_after_rounding():
36- baseline = {
37- "cube_covered_by_vector_percent": 50.0,
38- "vector_covered_by_cube_percent": 50.0,
39- "cc_ms": 0.0,
40- "vv_ms": 0.0,
41- }
42- assert predicted_coverage_improved(
43- baseline,
44- {**baseline, "cube_covered_by_vector_percent": 51.0, "vector_covered_by_cube_percent": 51.0},
45- )
46- assert not predicted_coverage_improved(
47- baseline,
48- {**baseline, "cube_covered_by_vector_percent": 50.0 + 1e-10, "vector_covered_by_cube_percent": 51.0},
49- )
@@ -1,288 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-"""CPU checks for CV-chunk CANN mapping and profile summaries."""
3- 
4-import csv
5-import json
6-from types import SimpleNamespace
7- 
8-import pytest
9-import torch
10-from torch import fx
11- 
12-from torchtitan_npu.extensions.experiment.cv_parallel.cann_kernel_metrics import CannKernelMetrics
13-from torchtitan_npu.extensions.experiment.cv_parallel.cann_launches import associate_cann_launches
14-from torchtitan_npu.extensions.experiment.cv_parallel.profile_overlap import SCOPE, summarize_profile
15-from torchtitan_npu.extensions.experiment.cv_parallel.whole_graph_runtime_profile import (
16- _collective_count_manifest,
17- _extract_cann_node_measurements,
18- _match_fx_nodes_to_host_scopes,
19- assign_stable_node_tags,
20- collective_order_keys,
21- node_id,
22-)
23-from torchtitan_npu.ops.ascendc.moe_token_permute import npu_moe_token_permute # noqa: F401
24- 
25- 
26-def test_cann_connection_recovers_launch_without_torch_to_npu_flow():
27- scope = {"ph": "X", "cat": "cpu_op", "pid": 1, "tid": 10, "ts": 0, "dur": 20}
28- device_task = {
29- "ph": "X",
30- "name": "custom_kernel",
31- "pid": 3,
32- "tid": 30,
33- "ts": 100,
34- "dur": 5,
35- "args": {"connection_id": 99},
36- }
37- events = [
38- {"ph": "M", "name": "process_name", "pid": 2, "args": {"name": "CANN"}},
39- {"ph": "M", "name": "process_name", "pid": 3, "args": {"name": "Ascend Hardware"}},
40- scope,
41- {
42- "ph": "X",
43- "cat": "enqueue",
44- "pid": 1,
45- "tid": 10,
46- "ts": 5,
47- "dur": 2,
48- "args": {"correlation_id": 7},
49- },
50- {
51- "ph": "X",
52- "cat": "dequeue",
53- "pid": 1,
54- "tid": 20,
55- "ts": 30,
56- "dur": 20,
57- "args": {"correlation_id": 7},
58- },
59- {
60- "ph": "X",
61- "pid": 2,
62- "tid": 20,
63- "ts": 35,
64- "dur": 5,
65- "args": {"level": "acl", "connection_id": 99},
66- },
67- device_task,
68- ]
69- 
70- assert associate_cann_launches(events, {"node": scope}) == {"node": [device_task]}
71- 
72- 
73-def test_collective_identity_and_counts_survive_execution_reordering():
74- graph = fx.Graph()
75- x = graph.placeholder("x")
76- reduce = torch.ops._c10d_functional.all_reduce.default
77- first = graph.call_function(reduce, (x, "sum", "local_group_a"))
78- second = graph.call_function(reduce, (x,), {"reduce_op": "sum", "group_name": "local_group_b"})
79- repeated = graph.call_function(reduce, (x, "sum", "local_group_a"))
80- gather = graph.call_function(torch.ops._c10d_functional.all_gather_into_tensor.default, (x, 2, "local_group_a"))
81- wait = graph.call_function(torch.ops._c10d_functional.wait_tensor.default, (first,))
82- graph.output((wait, second, repeated, gather))
83- gm = fx.GraphModule({}, graph)
84- assign_stable_node_tags(gm)
85- first.prepend(second)
86- 
87- keys = collective_order_keys(gm)
88- manifest = _collective_count_manifest(gm)
89- 
90- assert keys == {
91- first: (0, "_c10d_functional::all_reduce", 0),
92- second: (1, "_c10d_functional::all_reduce", 0),
93- repeated: (0, "_c10d_functional::all_reduce", 1),
94- gather: (0, "_c10d_functional::all_gather_into_tensor", 0),
95- }
96- assert manifest == (
97- (0, "_c10d_functional::all_gather_into_tensor", 1),
98- (0, "_c10d_functional::all_reduce", 2),
99- (1, "_c10d_functional::all_reduce", 1),
100- )
101- 
102- 
103-def test_deepep_stages_share_ordered_communication_group():
104- graph = fx.Graph()
105- x = graph.placeholder("x")
106- stages = []
107- for schema_name in (
108- "deepep::dispatch",
109- "deepep::combine",
110- "deepep::dispatch_backward",
111- "deepep::combine_backward",
112- ):
113- 
114- def stage(value):
115- return value
116- 
117- stage.__name__ = schema_name.removeprefix("deepep::")
118- stage._schema = SimpleNamespace(name=schema_name, arguments=())
119- stages.append(graph.call_function(stage, (x,)))
120- graph.output(tuple(stages))
121- gm = fx.GraphModule({}, graph)
122- assign_stable_node_tags(gm)
123- 
124- keys = collective_order_keys(gm)
125- manifest = _collective_count_manifest(gm)
126- 
127- assert list(keys.values()) == [
128- (0, "deepep::dispatch", 0),
129- (0, "deepep::combine", 0),
130- (0, "deepep::dispatch_backward", 0),
131- (0, "deepep::combine_backward", 0),
132- ]
133- assert manifest == (
134- (0, "deepep::combine", 1),
135- (0, "deepep::combine_backward", 1),
136- (0, "deepep::dispatch", 1),
137- (0, "deepep::dispatch_backward", 1),
138- )
139- 
140- 
141-def test_native_profiler_step_preserves_fx_host_matching():
142- graph = fx.Graph()
143- x = graph.placeholder("x")
144- first = graph.call_function(torch.ops.aten.sin.default, (x,))
145- second = graph.call_function(torch.ops.aten.sin.default, (first,))
146- graph.output(second)
147- gm = fx.GraphModule({}, graph)
148- assign_stable_node_tags(gm)
149- common = {"cat": "cpu_op", "ph": "X", "pid": 1, "tid": 1}
150- first_scope = dict(common, name="aten::sin", ts=10, dur=20)
151- second_scope = dict(common, name="aten::sin", ts=40, dur=20)
152- trace = {
153- "traceEvents": [
154- dict(common, name="ProfilerStep#0", ts=0, dur=100),
155- first_scope,
156- dict(common, name="aclnnSin", ts=12, dur=5),
157- second_scope,
158- ]
159- }
160- 
161- matched, stats = _match_fx_nodes_to_host_scopes(trace, gm)
162- 
163- assert matched == {node_id(first): first_scope, node_id(second): second_scope}
164- assert stats["matched"] == 2
165- assert stats["missing"] == 0
166- 
167- 
168-@pytest.mark.parametrize("wrapped", [False, True], ids=["native_scope_only", "outer_wrapper_scope"])
169-def test_permute_native_scope_maps_device_cost_without_shifting_later_calls(wrapped, tmp_path):
170- graph = fx.Graph()
171- x = graph.placeholder("x")
172- indices = graph.placeholder("indices")
173- permute = graph.call_function(torch.ops.torchtitan_npu.npu_moe_token_permute.default, (x, indices))
174- sine = graph.call_function(torch.ops.aten.sin.default, (x,))
175- graph.output((permute, sine))
176- gm = fx.GraphModule({}, graph)
177- assign_stable_node_tags(gm)
178- host = {"cat": "cpu_op", "ph": "X", "pid": 1, "tid": 1}
179- scopes = [
180- dict(host, name="npu::npu_moe_token_permute", ts=10, dur=10),
181- dict(host, name="aten::sin", ts=30, dur=10),
182- ]
183- if wrapped:
184- scopes.insert(0, dict(host, name="torchtitan_npu::npu_moe_token_permute", ts=9, dur=12))
185- flow = {"cat": "async_npu", "name": "torch_to_npu"}
186- trace = {
187- "traceEvents": scopes
188- + [{"ph": "M", "name": "process_name", "pid": 2, "args": {"name": "Ascend Hardware"}}]
189- + [
190- event
191- for index, (ts, duration) in enumerate(((12, 280), (32, 20)))
192- for event in (
193- dict(flow, id=index, ph="s", pid=1, tid=1, ts=ts),
194- dict(flow, id=index, ph="f", pid=2, tid=7, ts=1000 + index * 1000),
195- {
196- "ph": "X",
197- "name": "kernel",
198- "pid": 2,
199- "tid": 7,
200- "ts": 1000 + index * 1000,
201- "dur": duration,
202- "args": {"Task Type": "MIX_AIV" if index == 0 else "AI_VECTOR_CORE", "Physic Stream Id": 7},
203- },
204- )
205- ]
206- }
207- with (tmp_path / "op_summary_0.csv").open("w", newline="") as stream:
208- writer = csv.writer(stream)
209- writer.writerow(
210- [
211- "Op Name",
212- "Task Start Time(us)",
213- "Task Duration(us)",
214- "Stream Id",
215- "aicore_time(us)",
216- "aiv_time(us)",
217- "aic_mac_time(us)",
218- "aiv_vec_time(us)",
219- ]
220- )
221- # Same launch name/time on another stream must not supply its counters.
222- writer.writerow(["kernel", 1000, 280, 8, 140, 140, 250, 5])
223- writer.writerow(["kernel", 1000, 280, 7, 140, 140, 5, 250])
224- observations = {}
225- 
226- matched, stats = _match_fx_nodes_to_host_scopes(trace, gm)
227- costs, resources = _extract_cann_node_measurements(
228- trace,
229- {node_id(n): n for n in (permute, sine)},
230- matched,
231- kernel_metrics=CannKernelMetrics(tmp_path),
232- kernel_observations=observations,
233- )
234- 
235- assert stats["missing"] == 0
236- assert costs == {node_id(permute): 0.28, node_id(sine): 0.02}
237- assert resources == {node_id(permute): "mix_aiv", node_id(sine): "aiv"}
238- assert observations[node_id(permute)] == [(0.0, 0.28, "(2, 7)", "mix_aiv")]
239- 
240- 
241-@pytest.mark.parametrize("with_counters", [False, True], ids=["unclassified_mix", "classified_mix"])
242-def test_profile_summary_counts_only_pure_cv_overlap(tmp_path, with_counters):
243- output = tmp_path / "ASCEND_PROFILER_OUTPUT"
244- output.mkdir()
245- (output / "trace_view.json").write_text(
246- json.dumps({"traceEvents": [{"ph": "X", "name": SCOPE, "ts": 500, "dur": 3000}]})
247- )
248- with (output / "kernel_details.csv").open("w", newline="") as stream:
249- writer = csv.writer(stream)
250- writer.writerow(
251- [
252- "Name",
253- "Device_id",
254- "Stream ID",
255- "Accelerator Core",
256- "Start Time(us)",
257- "Duration(us)",
258- "aic_time(us)",
259- "aiv_time(us)",
260- ]
261- )
262- writer.writerow(["cube", 0, 0, "AI_CORE", 1000, 2000, "", ""])
263- # Vector/MIX overlap on the same stream must not count as pure CV.
264- writer.writerow(["vector", 0, 1, "AI_VECTOR_CORE", 1500, 1250, "", ""])
265- writer.writerow(["vector", 0, 0, "AI_VECTOR_CORE", 3000, 500, "", ""])
266- writer.writerow(["mix", 0, 1, "MIX_AIV", 2500, 500, *([5, 450] if with_counters else ["", ""])])
267- writer.writerow(["mix", 0, 1, "MIX_AIC", 3000, 500, *([450, 5] if with_counters else ["", ""])])
268- profile_link = tmp_path / "training_profile"
269- profile_link.symlink_to(output, target_is_directory=True)
270- 
271- summary = summarize_profile(profile_link)
272- 
273- assert summary["time_ms"]["cv_overlap"] == 1.0
274- assert summary["time_ms"]["compute_union"] == 2.5
275- assert summary["cv_percent_of_compute"] == 40.0
276- assert summary["kernel_counts"] == {"cube": 1, "vector": 2, "mix": 2}
277- assert summary["mixed_kernel_counts"] == ({"mix_aiv": 1, "mix_aic": 1} if with_counters else {"mix": 2})
278- assert summary["time_ms"]["cube_mix_aiv_overlap"] == (0.25 if with_counters else 0.0)
279- assert summary["time_ms"]["vector_mix_aic_overlap"] == (0.5 if with_counters else 0.0)
280- assert summary["time_ms"]["mixed_overlap"] == 1.0
281- assert summary["time_ms"]["mix_busy"] == 1.0
282- assert summary["time_ms"]["forward_backward_scope"] == 3.0
283- assert summary["time_ms"]["overlap"] == 2.0
284- assert summary["time_ms"]["single_stream"] == 0.5
285- assert summary["time_ms"]["kernel_duration_sum"] == 4.75
286- assert summary["stream_busy_ms"] == {"0": 2.5, "1": 2.0}
287- assert summary["overlap_percent"] == 80.0
288- assert summary["cube_covered_by_vector_percent"] == 50.0
@@ -16,7 +16,6 @@ import torch.nn.functional as F
16from torchtitan.config import ConfigManager, apply_overrides16from torchtitan.config import ConfigManager, apply_overrides
17from torchtitan.models.common.activation import SiTUGLU, SwiGLU17from torchtitan.models.common.activation import SiTUGLU, SwiGLU
18 18 
19-from torchtitan_npu.extensions.experiment.cv_parallel.batch_chunk_token_dispatcher import BatchChunkTokenDispatcher
20from torchtitan_npu.override.common.swiglu_group import AscSwiGLU19from torchtitan_npu.override.common.swiglu_group import AscSwiGLU
21from torchtitan_npu.override.common.token_dispatcher import AscAllToAllTokenDispatcher20from torchtitan_npu.override.common.token_dispatcher import AscAllToAllTokenDispatcher
22from torchtitan_npu.patches.torchtitan.models.common.moe import ClampedSwiGLU21from torchtitan_npu.patches.torchtitan.models.common.moe import ClampedSwiGLU
@@ -24,10 +23,6 @@ from torchtitan_npu.patches.torchtitan.models.common.moe import ClampedSwiGLU
24_SWIGLU = "torchtitan_npu.override.common.swiglu_group."23_SWIGLU = "torchtitan_npu.override.common.swiglu_group."
25_DISPATCHERS = {24_DISPATCHERS = {
26 "standard": ("torchtitan_npu.override.common.token_dispatcher.asc", AscAllToAllTokenDispatcher.Config),25 "standard": ("torchtitan_npu.override.common.token_dispatcher.asc", AscAllToAllTokenDispatcher.Config),
27- "cv": (
28- "torchtitan_npu.extensions.experiment.cv_parallel.batch_chunk_token_dispatcher.asc_dispatcher",
29- BatchChunkTokenDispatcher.Config,
30- ),
31}26}
32_RECIPES = [27_RECIPES = [
33 ("torchtitan_npu.models.deepseek_v4.config_registry", "deepseek_v4_debugmodel"),28 ("torchtitan_npu.models.deepseek_v4.config_registry", "deepseek_v4_debugmodel"),
@@ -50,7 +45,7 @@ def _replacement_fqns(replacements):
50 45 
51 46 
52@pytest.mark.parametrize(("module", "recipe"), _RECIPES, ids=["v4", "v41"])47@pytest.mark.parametrize(("module", "recipe"), _RECIPES, ids=["v4", "v41"])
53-@pytest.mark.parametrize("dispatcher", ["standard", "cv"])48+@pytest.mark.parametrize("dispatcher", ["standard"])
54@pytest.mark.parametrize("dispatcher_first", [False, True])49@pytest.mark.parametrize("dispatcher_first", [False, True])
55def test_activation_and_dispatcher_overrides_compose_without_replacing_expert_owners(50def test_activation_and_dispatcher_overrides_compose_without_replacing_expert_owners(
56 tmp_path, module, recipe, dispatcher, dispatcher_first51 tmp_path, module, recipe, dispatcher, dispatcher_first
@@ -1,7 +0,0 @@
1-# CV parallel 迁移状态
2- 
3-目标 TorchTitan 版本为 `ebdfc8c2a24d89d89c99c0ef96ed8ac149864175`。该版本通过提交 `43f73649f195a7790752daf11548d5523e9306b3` 删除了基于 Graph 的 EP 分块 producer 及其符号工具,并移除了 CV 使用的旧 trainer hooks。
4- 
5-CV 调度器仍可通过真实 ConfigManager 选择,配置 override 会注册目标版本的 pass pipeline 和 post-init hook。CV 自用的符号分析算法保留在 `chunk_symbols.py`,来源为删除前的上游提交 `c04d1bd3b6fd9f6f829bca6be148d9872a563c7a`,不会修改或补造上游模块。
6- 
7-CV Graph 运行路径尚未完成迁移。post-init hook、pipeline 和分块 pass 入口会在访问 runtime 状态前抛出明确的 `NotImplementedError`。配置检查通过仅代表配置与注册可用,不能据此启动 CV 训练。目标版本的 eager 分块使用不同的 metadata 协议,后续迁移需要重新对齐 producer、attention metadata 和调度输入,并验证实际执行语义。
@@ -1,4 +0,0 @@
1-"""Profile-guided dual-stream CV scheduling for batch chunks."""
2- 
3-_BATCH_CHUNK_PAIR_ATTR = "_npu_chunk_cv_metadata_pair"
4-CV_PARALLEL_PIPELINE = "cv_parallel"
@@ -1,212 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6-"""Prebuild full and half-batch attention metadata for CV chunking."""
7- 
8-from dataclasses import dataclass
9-from typing import Any, cast
10- 
11-import torch
12-from torch.utils._pytree import SUPPORTED_NODES, register_dataclass
13- 
14-from torchtitan_npu.models.deepseek_v4.metadata import (
15- DeepSeekV4Metadata,
16- build_v4_metadata,
17-)
18-from torchtitan_npu.override.deepseek_v4.sparse_attn.ascendc import (
19- AscV4Metadata,
20- build_aicpu_metadata,
21-)
22- 
23-from . import _BATCH_CHUNK_PAIR_ATTR
24- 
25- 
26-@dataclass(kw_only=True, slots=True)
27-class BatchChunkAscV4Metadata(AscV4Metadata):
28- batch_chunk_tensors: tuple[tuple[torch.Tensor, ...], ...] | None = None
29- 
30- 
31-if BatchChunkAscV4Metadata not in SUPPORTED_NODES:
32- register_dataclass(
33- BatchChunkAscV4Metadata,
34- serialized_type_name=(f"{BatchChunkAscV4Metadata.__module__}.{BatchChunkAscV4Metadata.__name__}"),
35- )
36- 
37- 
38-def _row_positions(cu_seqlens: torch.Tensor) -> torch.Tensor:
39- """The row's document-relative positions (``[1, N]``), reconstructed from its grid.
40- 
41- They are a function of the boundaries alone -- a document's positions restart at zero --
42- so the metadata carries the grid and every consumer that needs the positions derives them
43- instead of the entry storing a second copy of the row.
44- """
45- lengths = torch.diff(cu_seqlens)
46- return (
47- torch.arange(int(cu_seqlens[-1]), device=cu_seqlens.device) - torch.repeat_interleave(cu_seqlens[:-1], lengths)
48- ).reshape(1, -1)
49- 
50- 
51-def _plain_batch_chunk_metadata(
52- metadata: DeepSeekV4Metadata,
53-) -> tuple[DeepSeekV4Metadata, DeepSeekV4Metadata]:
54- """Build two local plain-stream contracts at an aligned document boundary."""
55- if metadata.cp is not None:
56- raise ValueError("batch chunk metadata does not support context parallelism")
57- cu = metadata.swa_k.cu_seqlens
58- cu_host = tuple(int(value) for value in cu.cpu().tolist())
59- total_tokens = cu_host[-1]
60- if total_tokens < 2 or total_tokens % 2:
61- raise ValueError(f"batch chunk metadata requires an even positive token extent, got {total_tokens}")
62- split_token = total_tokens // 2
63- if split_token not in cu_host:
64- raise ValueError(
65- "batch chunk metadata requires documents not to cross the equal "
66- f"batch boundary at token {split_token}; boundaries={cu_host}"
67- )
68- split_index = cu_host.index(split_token)
69- # One entry is one geometry, so both chunks re-cut the same ratio's grid; the documents do
70- # not cross the split, so each chunk is a whole number of pooling blocks again.
71- ratio = metadata.ratio
72- positions = _row_positions(cu)
73- chunks = []
74- for start_index, end_index, token_offset in (
75- (0, split_index, 0),
76- (split_index, len(cu_host) - 1, split_token),
77- ):
78- local_cu = (cu[start_index : end_index + 1] - token_offset).contiguous()
79- local_positions = positions[..., token_offset : cu_host[end_index]]
80- chunks.append(build_v4_metadata(local_positions, ratio, cu_seq_q=local_cu))
81- return cast(
82- "tuple[DeepSeekV4Metadata, DeepSeekV4Metadata]",
83- tuple(chunks),
84- )
85- 
86- 
87-def _metadata_tensor_fields(
88- metadata: AscV4Metadata,
89-) -> dict[str, torch.Tensor]:
90- """Return tensor fields whose full/chunk values have identical roles.
91- 
92- A tensor that several roles share (the query frame's boundaries *are* the row's, and the
93- sliding-window frame's too) is tagged once, under the first role that names it: two tags on
94- one object would leave whichever was written last. The full batch and its chunks derive
95- their frames the same way, so the surviving role is the same on both sides.
96- """
97- tensors: dict[str, torch.Tensor] = {}
98- tagged: set[int] = set()
99- 
100- def add(name: str, value: object) -> None:
101- if isinstance(value, torch.Tensor) and id(value) not in tagged:
102- tensors[name] = value
103- tagged.add(id(value))
104- 
105- # The kernel frames: the query's, the sliding window's and the compressed axis's. Their
106- # role names stay geometry-free on purpose: the full batch and its chunks carry the same
107- # geometry, so the pairing is by role, and the ratio is part of the metadata, not the name.
108- for frame_name in ("q", "swa_k", "cmp_k"):
109- frame = getattr(metadata, frame_name)
110- if frame is None:
111- continue
112- add(f"{frame_name}.cu_seqlens", frame.cu_seqlens)
113- add(f"{frame_name}.seqused", frame.seqused)
114- add(f"{frame_name}.residual", frame.residual)
115- assert metadata.aicpu_metadata is not None, "batch chunk metadata requires the AscendC record tier"
116- # The records are grouped by the kernel that reads them, one field per direction.
117- for group_name in ("sparse_attn", "lightning_indexer"):
118- group = getattr(metadata.aicpu_metadata, group_name)
119- add(f"aicpu.{group_name}.fwd", group.fwd)
120- add(f"aicpu.{group_name}.bwd", group.bwd)
121- return tensors
122- 
123- 
124-def _tag_batch_chunk_metadata(
125- full: AscV4Metadata,
126- chunks: tuple[AscV4Metadata, AscV4Metadata],
127-) -> tuple[tuple[torch.Tensor, ...], tuple[torch.Tensor, ...]]:
128- """Tag and pack only tensor roles consumed by the full-batch graph.
129- 
130- Vendor builders may produce additional optional tensors for a chunk's
131- document layout. Select only full-batch roles so those extra tensors and
132- data-dependent host fields cannot change the runtime pytree signature.
133- """
134- full_fields = _metadata_tensor_fields(full)
135- chunk_fields = tuple(_metadata_tensor_fields(chunk) for chunk in chunks)
136- missing_by_chunk = {
137- chunk_id: sorted(set(full_fields) - set(fields))
138- for chunk_id, fields in enumerate(chunk_fields)
139- if set(full_fields) - set(fields)
140- }
141- if missing_by_chunk:
142- raise RuntimeError(f"batch-chunk metadata is missing full-batch tensor roles: {missing_by_chunk}")
143- for pair_id, full_tensor in full_fields.items():
144- setattr(full_tensor, _BATCH_CHUNK_PAIR_ATTR, (pair_id, -1))
145- for chunk_id, fields in enumerate(chunk_fields):
146- setattr(
147- fields[pair_id],
148- _BATCH_CHUNK_PAIR_ATTR,
149- (pair_id, chunk_id),
150- )
151- return cast(
152- "tuple[tuple[torch.Tensor, ...], tuple[torch.Tensor, ...]]",
153- tuple(tuple(fields[pair_id] for pair_id in full_fields) for fields in chunk_fields),
154- )
155- 
156- 
157-def _batch_chunk_metadata(metadata: AscV4Metadata) -> BatchChunkAscV4Metadata:
158- """Add the two batch chunks' records beside the full batch's.
159- 
160- The fused core's own config built the full microbatch's metadata (upstream
161- #4897); this re-cuts that contract at the equal batch boundary and rebuilds the
162- local records from the geometry that rides on it. A quantized selector's entry
163- is refused: its records are its own backend's operator, and this re-cut has no
164- backend to ask (mirroring ``QuantV4Metadata.prepare_cp_metadata``).
165- """
166- if type(metadata) is not AscV4Metadata:
167- raise TypeError(
168- "batch chunk metadata cannot re-cut "
169- f"{type(metadata).__name__}: its records are its own backend's "
170- "(the quantized selector refuses the re-cut); run without cv_parallel "
171- "or with the BF16 fused selector."
172- )
173- first, second = _plain_batch_chunk_metadata(metadata)
174- 
175- asc = metadata.aicpu_metadata
176- if asc is None:
177- raise ValueError("batch chunk metadata requires the fused entry's AI_CPU records")
178- geometry = asc.geometry
179- 
180- def doc_chunk_records(chunk: DeepSeekV4Metadata) -> AscV4Metadata:
181- """This tier's records: the selector's and the attention's."""
182- return build_aicpu_metadata(chunk, geometry=geometry)
183- 
184- chunks = (doc_chunk_records(first), doc_chunk_records(second))
185- return BatchChunkAscV4Metadata(
186- ratio=metadata.ratio,
187- q=metadata.q,
188- swa_k=metadata.swa_k,
189- cmp_k=metadata.cmp_k,
190- position_k=metadata.position_k,
191- slots=metadata.slots,
192- cp=metadata.cp,
193- a3_workaround=metadata.a3_workaround,
194- aicpu_metadata=metadata.aicpu_metadata,
195- batch_chunk_tensors=_tag_batch_chunk_metadata(metadata, chunks),
196- )
197- 
198- 
199-def chunk_attention_metadata(extra_kwargs: dict[str, Any]) -> None:
200- """Re-cut this step's built entries into the full batch plus its two chunks, in place.
201- 
202- The fused core's own config built one entry per geometry (upstream #4897); the
203- re-cut is a property of this trainer's batch, so it happens at the step boundary,
204- before anything traces or runs. An entry that already carries the chunks passes
205- through, so a boundary entered twice cannot cut the same entry twice.
206- """
207- metadata = extra_kwargs.get("attention_metadata")
208- if not metadata:
209- return
210- for key, entry in cast("dict[object, AscV4Metadata]", metadata).items():
211- if not isinstance(entry, BatchChunkAscV4Metadata):
212- metadata[key] = _batch_chunk_metadata(entry)
@@ -1,45 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6-"""Opt-in token dispatcher for symbolic CV batch-chunk tracing."""
7- 
8-from dataclasses import dataclass
9- 
10-import torch_npu
11-from torch.overrides import TorchFunctionMode
12-from torchtitan.config import derive, override
13- 
14-from torchtitan_npu.ops.ascendc.moe_token_permute import npu_moe_token_permute
15-from torchtitan_npu.override.common.token_dispatcher import AscAllToAllTokenDispatcher
16-from torchtitan_npu.patches.torchtitan.models.common.token_dispatcher import AllToAllTokenDispatcher
17- 
18- 
19-class _SymbolicPermuteMode(TorchFunctionMode):
20- def __torch_function__(self, func, types, args=(), kwargs=None):
21- if func is torch_npu.npu_moe_token_permute:
22- func = npu_moe_token_permute
23- return func(*args, **(kwargs or {}))
24- 
25- 
26-class BatchChunkTokenDispatcher(AscAllToAllTokenDispatcher):
27- @dataclass(kw_only=True, slots=True)
28- class Config(AscAllToAllTokenDispatcher.Config):
29- pass
30- 
31- def dispatch(self, *args, **kwargs):
32- # The mode is scoped to this call; shared functions and other threads
33- # retain native dispatch. Reuse the full upstream dispatch algorithm.
34- with _SymbolicPermuteMode():
35- return super().dispatch(*args, **kwargs)
36- 
37- 
38-@override(target=AllToAllTokenDispatcher.Config, exact=True, description="Symbolic-size-safe fused token permutation")
39-def asc_dispatcher(cfg: AllToAllTokenDispatcher.Config) -> BatchChunkTokenDispatcher.Config:
40- # Selecting the experiment's dispatcher is selecting the experiment: this is the entry
41- # that imports the pass pipeline (registering it by name) and, with it, the per-step
42- # metadata re-cut. There is no second metadata node to flip.
43- from . import cv_parallel # noqa: F401
44- 
45- return derive(cfg, BatchChunkTokenDispatcher.Config)
@@ -1,120 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6-"""Join CANN per-launch counters to CV-chunk trace tasks."""
7- 
8-from __future__ import annotations
9- 
10-import csv
11-import math
12-from collections import defaultdict
13-from decimal import Decimal, InvalidOperation
14-from typing import TYPE_CHECKING, Any
15- 
16-if TYPE_CHECKING:
17- from pathlib import Path
18- 
19- 
20-def classify_mixed_core_times(metrics: list[dict[str, Any]]) -> str | None:
21- """Classify this launch/group by counters, never by an offline name table.
22- 
23- Dominance is a scheduling approximation, not a pure-core guarantee. Use
24- the same rule for FX resource attribution and native overlap reporting.
25- """
26- ratio_threshold, minor_max_ms = 0.75, 0.1
27- aic_us = aiv_us = 0.0
28- for counters in metrics:
29- aic_value = counters.get("aicore_time(us)", counters.get("aic_time(us)"))
30- aiv_value = counters.get("aiv_time(us)")
31- if aic_value is None or aiv_value is None:
32- return None
33- try:
34- aic, aiv = float(aic_value), float(aiv_value)
35- except (TypeError, ValueError):
36- return None
37- if not all(math.isfinite(value) and value >= 0 for value in (aic, aiv)) or aic + aiv <= 0:
38- return None
39- # Prefer execution units to whole-core times that also include transfers.
40- try:
41- mac = float(counters["aic_mac_time(us)"])
42- vec = float(counters["aiv_vec_time(us)"])
43- except (KeyError, TypeError, ValueError):
44- mac = vec = float("nan")
45- if all(math.isfinite(value) and value >= 0 for value in (mac, vec)) and mac + vec > 0:
46- aic, aiv = mac, vec
47- aic_us += aic
48- aiv_us += aiv
49- total = aic_us + aiv_us
50- if total > 0 and min(aic_us, aiv_us) <= minor_max_ms * 1000:
51- if aic_us / total >= ratio_threshold:
52- return "mix_aic"
53- if aiv_us / total >= ratio_threshold:
54- return "mix_aiv"
55- return None
56- 
57- 
58-def _decimal(value: Any) -> Decimal | None:
59- try:
60- result = Decimal(str(value).strip())
61- except InvalidOperation:
62- return None
63- return result if result.is_finite() else None
64- 
65- 
66-class CannKernelMetrics:
67- """Counters retain CANN column names, units and raw values.
68- 
69- Trace and CSV timestamps share the CANN clock. Decimal preserves sub-us
70- identity even for epoch timestamps too large for float precision. Never
71- match by kernel name alone or average launches with different shapes.
72- """
73- 
74- def __init__(self, work_path: Path):
75- self._rows: dict[tuple[str, Decimal], list[dict[str, Any]]] = defaultdict(list)
76- # op_summary retains all counter fields even when kernel_details is
77- # configured to export only its basic columns. Avoid reading both
78- # representations of the same launch.
79- paths = sorted(work_path.rglob("op_summary*.csv")) or sorted(work_path.rglob("kernel_details.csv"))
80- for path in paths:
81- with path.open(newline="", encoding="utf-8-sig") as stream:
82- for row in csv.DictReader(stream):
83- name = row.get("Op Name", row.get("Name"))
84- start = _decimal(row.get("Task Start Time(us)", row.get("Start Time(us)")))
85- duration = _decimal(row.get("Task Duration(us)", row.get("Duration(us)")))
86- if not name or start is None or duration is None:
87- continue
88- self._rows[name, start.quantize(Decimal("0.001"))].append({"row": row, "duration": duration})
89- 
90- def core_metrics(self, event: dict[str, Any]) -> dict[str, Any]:
91- args = event.get("args", {})
92- start = _decimal(event["ts"])
93- duration = _decimal(event["dur"])
94- if start is None or duration is None:
95- return {}
96- candidates = [
97- entry
98- for entry in self._rows.get((str(event.get("name")), start.quantize(Decimal("0.001"))), ())
99- if abs(entry["duration"] - duration) <= Decimal("0.001")
100- ]
101- # When available, stream/task identity disambiguates simultaneous
102- # launches. Multiple remaining rows (including different devices)
103- # remain explicitly ambiguous rather than borrowing another counter.
104- for csv_keys, trace_key in (
105- (("Stream Id", "Stream ID"), "Physic Stream Id"),
106- (("Task Id", "Task ID"), "Task Id"),
107- ):
108- if trace_key in args:
109- candidates = [
110- entry
111- for entry in candidates
112- if all(entry["row"][key].strip() == str(args[trace_key]) for key in csv_keys if key in entry["row"])
113- ]
114- if len(candidates) != 1:
115- return {}
116- return {
117- key: value
118- for key, value in candidates[0]["row"].items()
119- if key.lower().startswith(("aic_", "aiv_", "aicore_"))
120- }
@@ -1,97 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6-"""Recover CV-chunk CANN launches without a torch-to-NPU flow."""
7- 
8-from __future__ import annotations
9- 
10-from bisect import bisect_right
11-from collections import defaultdict
12-from decimal import Decimal
13-from typing import Any
14- 
15- 
16-def associate_cann_launches(
17- events: list[dict[str, Any]],
18- node_scopes: dict[str, dict[str, Any]],
19-) -> dict[str, list[dict[str, Any]]]:
20- """Recover missing torch_to_npu links via ACL connection and queue IDs.
21- 
22- Some custom launches have a device connection_id and AscendCL record but
23- no HostToDevice start/torch_to_npu flow. Follow the concrete launch through
24- Dequeue -> correlation_id -> Enqueue -> native FX scope. Host intervals
25- establish ownership only; their durations are never device costs.
26- """
27- process_names = {
28- event.get("pid"): event.get("args", {}).get("name")
29- for event in events
30- if event.get("ph") == "M" and event.get("name") == "process_name"
31- }
32- enqueue: dict[tuple[Any, Any], list[dict[str, Any]]] = defaultdict(list)
33- dequeues: dict[Any, list[dict[str, Any]]] = defaultdict(list)
34- scopes: dict[tuple[Any, Any], list[dict[str, Any]]] = defaultdict(list)
35- scope_ids = {id(scope): stable_id for stable_id, scope in node_scopes.items()}
36- for scope in node_scopes.values():
37- scopes[scope.get("pid"), scope.get("tid")].append(scope)
38- for event in events:
39- if event.get("ph") != "X":
40- continue
41- if event.get("cat") == "enqueue":
42- enqueue[event.get("pid"), event.get("args", {}).get("correlation_id")].append(event)
43- elif event.get("cat") == "dequeue":
44- dequeues[event.get("tid")].append(event)
45- 
46- def index_ranges(groups):
47- times = {}
48- for lane, ranges in groups.items():
49- ranges.sort(key=lambda event: Decimal(str(event["ts"])))
50- times[lane] = [Decimal(str(event["ts"])) for event in ranges]
51- return times
52- 
53- dequeue_times = index_ranges(dequeues)
54- scope_times = index_ranges(scopes)
55- 
56- def containing(ranges, times, event):
57- begin = Decimal(str(event["ts"]))
58- end = begin + Decimal(str(event["dur"]))
59- index = bisect_right(times, begin) - 1
60- if index < 0:
61- return None
62- parent = ranges[index]
63- if end <= Decimal(str(parent["ts"])) + Decimal(str(parent["dur"])):
64- return parent
65- return None
66- 
67- connection_owners: dict[Any, set[str]] = defaultdict(set)
68- for event in events:
69- args = event.get("args", {})
70- if (
71- event.get("ph") != "X"
72- or process_names.get(event.get("pid")) != "CANN"
73- or args.get("level") != "acl"
74- or args.get("connection_id") is None
75- ):
76- continue
77- tid = event.get("tid")
78- dequeue = containing(dequeues.get(tid, ()), dequeue_times.get(tid, ()), event)
79- if dequeue is None:
80- continue
81- queue_key = dequeue.get("pid"), dequeue.get("args", {}).get("correlation_id")
82- enqueues = enqueue.get(queue_key, ())
83- if queue_key[1] is None or len(enqueues) != 1:
84- continue
85- launch = enqueues[0]
86- lane = launch.get("pid"), launch.get("tid")
87- scope = containing(scopes.get(lane, ()), scope_times.get(lane, ()), launch)
88- if scope is not None:
89- connection_owners[args["connection_id"]].add(scope_ids[id(scope)])
90- result: dict[str, list[dict[str, Any]]] = defaultdict(list)
91- for event in events:
92- if event.get("ph") != "X" or process_names.get(event.get("pid")) != "Ascend Hardware":
93- continue
94- owners = connection_owners.get(event.get("args", {}).get("connection_id"), ())
95- if len(owners) == 1:
96- result[next(iter(owners))].append(event)
97- return dict(result)
@@ -1,84 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6-"""Shared CV-chunk CANN capture, parsing and per-rank isolation."""
7- 
8-from __future__ import annotations
9- 
10-import logging
11-import os
12-import tempfile
13-from contextlib import ExitStack, contextmanager
14-from pathlib import Path
15-from typing import TYPE_CHECKING
16- 
17-logger = logging.getLogger(__name__)
18- 
19-if TYPE_CHECKING:
20- from collections.abc import Iterator
21- 
22- 
23-@contextmanager
24-def cann_profile() -> Iterator[None]:
25- """Capture one replay; callers synchronize within their measured scope."""
26- import torch_npu
27- 
28- with torch_npu.profiler.profile(
29- activities=[torch_npu.profiler.ProfilerActivity.CPU, torch_npu.profiler.ProfilerActivity.NPU],
30- schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=1, repeat=1),
31- record_shapes=False,
32- profile_memory=False,
33- with_stack=False,
34- experimental_config=torch_npu.profiler._ExperimentalConfig(
35- profiler_level=torch_npu.profiler.ProfilerLevel.Level1,
36- aic_metrics=torch_npu.profiler.AiCMetrics.PipeUtilization,
37- record_op_args=False,
38- ),
39- ) as profiler:
40- yield
41- profiler.step()
42- 
43- 
44-def parse_cann_profile(work_path: Path) -> Path:
45- """Synchronously parse this isolated capture and return its output directory."""
46- from torch_npu.profiler.profiler import analyse
47- 
48- paths = sorted(work_path.rglob("*_ascend_pt"))
49- if len(paths) != 1:
50- raise RuntimeError(f"Expected one CANN capture under {work_path}, found {len(paths)}")
51- analyse(str(paths[0]), max_process_number=1)
52- output = paths[0] / "ASCEND_PROFILER_OUTPUT"
53- if not all((output / name).is_file() for name in ("trace_view.json", "kernel_details.csv")):
54- raise RuntimeError(f"Native profiler parsing incomplete: {output}")
55- logger.info("Parsed native NPU profile: %s", paths[0])
56- return output
57- 
58- 
59-@contextmanager
60-def isolated_cann_profiler_work_path(root: Path, *, prefix: str) -> Iterator[Path]:
61- """Retain rank 0 raw/parsed data, including partial captures on failure.
62- 
63- The caller must stop and synchronously parse the profiler inside this
64- context. Restore ASCEND_WORK_PATH so other profiler sessions stay isolated.
65- """
66- previous = os.environ.get("ASCEND_WORK_PATH")
67- rank = int(os.getenv("RANK", "0"))
68- # Every rank calibrates locally; only rank 0 retains native artifacts.
69- with ExitStack() as stack:
70- if rank != 0:
71- temporary: tempfile.TemporaryDirectory[str] = tempfile.TemporaryDirectory(prefix="npu_chunk_profile_")
72- work_path = Path(stack.enter_context(temporary))
73- else:
74- root = root.expanduser().resolve() / prefix / f"rank{rank}"
75- root.mkdir(parents=True, exist_ok=True)
76- work_path = Path(tempfile.mkdtemp(prefix="session_", dir=root))
77- os.environ["ASCEND_WORK_PATH"] = str(work_path)
78- try:
79- yield work_path
80- finally:
81- if previous is None:
82- os.environ.pop("ASCEND_WORK_PATH", None)
83- else:
84- os.environ["ASCEND_WORK_PATH"] = previous
@@ -1,126 +0,0 @@
1-# Copyright (c) Meta Platforms, Inc. and affiliates.
2-# All rights reserved.
3-#
4-# This source code is licensed under the BSD-style license found in the
5-# LICENSE file in the root directory of this source tree.
6- 
7-"""Symbol analysis owned by the CV graph-chunk experiment.
8- 
9-These helpers retain the real graph-chunk metadata algorithm from TorchTitan
10-c04d1bd3b6fd9f6f829bca6be148d9872a563c7a, ep_pass_utils.py. Upstream removed
11-that producer and these helpers in 43f73649f195a7790752daf11548d5523e9306b3.
12-They do not patch or recreate upstream modules. In particular, the folded
13-batch/sequence input protocol intentionally examines leading dimension zero.
14-"""
15- 
16-from __future__ import annotations
17- 
18-from typing import Any, cast
19- 
20-import torch
21-import torch.fx as fx
22- 
23-CHUNK_SYMBOL_HINTS_META = "torchtitan_chunk_symbol_hints"
24- 
25- 
26-def require_graph_chunk_runtime() -> None:
27- """Fail before touching runtime state until CV owns a new chunk producer."""
28- raise NotImplementedError(
29- "CV parallel runtime migration is pending: this TorchTitan target "
30- "removed graph-based EP chunking and its trainer hooks. "
31- "CV configuration and dispatcher registration remain available; "
32- "the eager chunk producer has a different metadata contract."
33- )
34- 
35- 
36-def tensor_meta(node: fx.Node) -> torch.Tensor | None:
37- """Return tensor fake value metadata, if this node has tensor metadata."""
38- val = node.meta.get("val")
39- return val if isinstance(val, torch.Tensor) else None
40- 
41- 
42-def free_symbols(value: object) -> frozenset[object]:
43- """Return symbolic-shape free symbols for values accepted by PyTorch."""
44- from torch.fx.experimental.symbolic_shapes import free_symbols
45- 
46- # PyTorch accepts symbolic scalars, tensors and nested shape expressions.
47- return frozenset(free_symbols(cast("Any", value)))
48- 
49- 
50-def _hint(value: object) -> int | None:
51- """Return a concrete/optimization hint when PyTorch exposes one."""
52- if isinstance(value, int):
53- return value
54- if hasattr(value, "node"):
55- if value.node.hint is not None:
56- return int(value.node.hint)
57- shape_env = getattr(value.node, "shape_env", None)
58- if shape_env is not None:
59- try:
60- return int(shape_env.optimization_hint(value.node.expr))
61- except Exception:
62- return None
63- return None
64- 
65- 
66-def _derive_symbol_hint(expr: object, extent_hint: int, symbol: object) -> int | None:
67- # The algorithm probes the SymPy substitution protocol and rejects other values.
68- expr = cast("Any", expr.node.expr if isinstance(expr, torch.SymInt) else expr)
69- try:
70- zero = expr.subs(symbol, 0)
71- one = expr.subs(symbol, 1)
72- if free_symbols(zero):
73- return None
74- offset = int(zero)
75- coeff = int(one - zero)
76- except (AttributeError, TypeError, ValueError, OverflowError):
77- return None
78- if offset != 0 or coeff <= 0 or extent_hint % coeff:
79- return None
80- return extent_hint // coeff
81- 
82- 
83-def _merge_symbol_hint(hints: dict[object, int], symbol: object, hint: int, *, source: str) -> None:
84- existing = hints.get(symbol)
85- if existing is not None and existing != hint:
86- raise ValueError(f"Chunk symbol {symbol} has conflicting hints: {existing} and {hint} from {source}.")
87- hints[symbol] = hint
88- 
89- 
90-def _record_symbols_from_extent(hints: dict[object, int], extent: object, *, source: str) -> None:
91- symbols = free_symbols(extent)
92- if not symbols:
93- return
94- extent_hint = _hint(extent)
95- if extent_hint is None:
96- raise ValueError(
97- f"Chunk pass found selected dynamic extent {extent} from {source} without an optimization hint."
98- )
99- for symbol in symbols:
100- hint = _derive_symbol_hint(extent, int(extent_hint), symbol)
101- if hint is None:
102- raise ValueError(
103- f"Chunk pass could not derive a base hint for symbol {symbol} from {source} extent {extent}."
104- )
105- _merge_symbol_hint(hints, symbol, hint, source=source)
106- 
107- 
108-def _selected_symbol_hints(node: fx.Node) -> dict[object, int]:
109- hints = node.meta.get(CHUNK_SYMBOL_HINTS_META, {})
110- return hints if isinstance(hints, dict) else {}
111- 
112- 
113-def chunk_symbol_hints_for_mode(gm: fx.GraphModule, mode: str | None = None) -> dict[object, int]:
114- """Collect the selected chunk symbols and their optimization hints."""
115- hints: dict[object, int] = {}
116- for node in gm.graph.nodes:
117- for symbol, hint in _selected_symbol_hints(node).items():
118- _merge_symbol_hint(hints, symbol, int(hint), source=node.name)
119- if mode is None or node.op != "placeholder" or (val := tensor_meta(node)) is None:
120- continue
121- if mode not in ("batch", "seq"):
122- raise ValueError(f"Unknown chunk mode: {mode!r}")
123- dim = 0
124- if dim < len(val.shape):
125- _record_symbols_from_extent(hints, val.shape[dim], source=f"{node.name}.shape[{dim}]")
126- return hints
@@ -1,442 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6-"""Fixed chunk streams, dependency barriers and profile-guided event emission."""
7- 
8-from __future__ import annotations
9- 
10-import functools
11-import heapq
12-import operator
13-import os
14-from dataclasses import dataclass
15-from pathlib import Path
16- 
17-import torch
18-import torch.fx as fx
19-from torch.utils import _pytree as pytree
20-from torchtitan.experiments.graph_trainer.ep_pass_utils import is_c10d_functional_node
21-from torchtitan.experiments.graph_trainer.passes import construct_default_graph_passes
22-from torchtitan.experiments.graph_trainer.registry import register_pass_pipeline
23- 
24-from . import CV_PARALLEL_PIPELINE
25-from .batch_chunk import (
26- _RUNTIME_CONTEXT,
27- _make_run_candidate,
28- _requires_full_stream_barrier,
29- configure_batch_chunk_passes,
30-)
31-from .chunk_symbols import require_graph_chunk_runtime
32-from .whole_graph_runtime_profile import (
33- _is_metadata_only_compute_node,
34- assign_stable_node_tags,
35- is_deepep_communication_node,
36-)
37- 
38- 
39-@dataclass
40-class Schedule:
41- order: list[fx.Node]
42- lanes: dict[fx.Node, int]
43- dependencies: dict[fx.Node, set[fx.Node]]
44- start_ms: dict[fx.Node, float]
45- end_ms: dict[fx.Node, float]
46- algorithm: str = "canonical"
47- 
48- 
49-def _is_stream_barrier(node):
50- return (
51- node.op == "output"
52- or is_c10d_functional_node(node)
53- or is_deepep_communication_node(node)
54- or (_requires_full_stream_barrier(node) and not _is_private_temporary_mutation(node))
55- )
56- 
57- 
58-def dependency_only_schedule(gm):
59- """Alternate ready lanes without resource costs, priorities or resource fences.
60- 
61- Tensor dependencies, per-lane FIFO and collective/state barriers remain
62- mandatory, including the free graph's conservative input completion joins.
63- """
64- nodes = list(gm.graph.nodes)
65- ordinal = {node: index for index, node in enumerate(nodes)}
66- lanes = {node: int(node.meta.get("chunk_id") == 1) for node in nodes}
67- dependencies = {node: set(node.all_input_nodes) for node in nodes}
68- tails = [None, None]
69- fence = None
70- for node in nodes:
71- lane = lanes[node]
72- if tails[lane] is not None:
73- dependencies[node].add(tails[lane])
74- if fence is not None:
75- dependencies[node].add(fence)
76- if _is_stream_barrier(node):
77- dependencies[node].update(tail for tail in tails if tail is not None)
78- fence = node
79- tails[lane] = node
80- successors = {node: [] for node in nodes}
81- remaining = {node: len(dependencies[node]) for node in nodes}
82- ready = [[], []]
83- for node in nodes:
84- for parent in dependencies[node]:
85- successors[parent].append(node)
86- if not remaining[node]:
87- heapq.heappush(ready[lanes[node]], ordinal[node])
88- order = []
89- lane = 0
90- while ready[0] or ready[1]:
91- if not ready[lane]:
92- lane = 1 - lane
93- node = nodes[heapq.heappop(ready[lane])]
94- order.append(node)
95- for child in successors[node]:
96- remaining[child] -= 1
97- if not remaining[child]:
98- heapq.heappush(ready[lanes[child]], ordinal[child])
99- lane = 1 - lane
100- if len(order) != len(nodes):
101- raise ValueError("Free dual-stream graph has a dependency cycle")
102- return Schedule(
103- order=order,
104- lanes=lanes,
105- dependencies=dependencies,
106- start_ms=dict.fromkeys(nodes, 0.0),
107- end_ms=dict.fromkeys(nodes, 0.0),
108- algorithm="dependency_only",
109- )
110- 
111- 
112-def _is_private_temporary_mutation(node):
113- """A sole consumer may update its fresh lane-local allocation in place."""
114- if node.op != "call_function" or node.target not in {
115- torch.ops.aten.scatter_.value,
116- torch.ops.aten.index_put_.default,
117- torch.ops.aten.logical_and_.default,
118- torch.ops.aten.add_.Tensor,
119- }:
120- return False
121- source = node.args[0]
122- if not isinstance(source, fx.Node) or source.op != "call_function":
123- return False
124- schema = getattr(source.target, "_schema", None)
125- return (
126- schema is not None
127- and schema.name.startswith("aten::")
128- and not schema.is_mutable
129- # _unsafe_view has no schema alias annotation but still shares storage.
130- and not _is_metadata_only_compute_node(source)
131- and len(schema.returns) == 1
132- and schema.returns[0].alias_info is None
133- and set(source.users) == {node}
134- and source.meta.get("chunk_id") in (0, 1)
135- and source.meta.get("chunk_id") == node.meta.get("chunk_id")
136- )
137- 
138- 
139-# These kernels allocate their outputs and consume explicit tensor inputs on
140-# the current stream. Keep this list exact: e.g. DeepEP also declares no input
141-# mutation, but its communication/handle effects are not represented by FX edges.
142-# Repo wrappers live in ops/ascendc/moe_token_{permute,unpermute}.py; native
143-# schemas live in torch_npu/csrc/aten/npu_native_functions_by_codegen.yaml.
144-_REORDERABLE_NPU_SCHEMAS = frozenset(
145- {
146- "npu::npu_dynamic_block_mx_quant",
147- "npu::npu_dynamic_mx_quant",
148- "npu::npu_dynamic_mx_quant_with_dual_axis",
149- "npu::npu_dynamic_quant",
150- "npu::npu_grouped_dynamic_mx_quant",
151- "npu::npu_grouped_matmul",
152- "npu::npu_quant_matmul",
153- "npu::npu_rms_norm",
154- "npu::npu_rms_norm_backward",
155- "npu::npu_moe_token_permute",
156- "npu::npu_moe_token_permute_grad_v2",
157- "npu::npu_moe_token_unpermute",
158- "npu::npu_moe_token_unpermute_grad",
159- "torchtitan_npu::npu_moe_token_permute",
160- "torchtitan_npu::npu_moe_token_permute_backward",
161- "torchtitan_npu::npu_moe_token_unpermute",
162- "torchao_npu::mx_last_dim_fake_quantize",
163- }
164-)
165- 
166- 
167-def _is_reorderable_npu_call(node):
168- if node.op != "call_function" or not isinstance(node.target, torch._ops.OpOverload):
169- return False
170- schema = node.target._schema
171- return (
172- schema.name in _REORDERABLE_NPU_SCHEMAS
173- and not schema.overload_name
174- and not schema.is_mutable
175- and all(arg.alias_info is None for arg in (*schema.arguments, *schema.returns))
176- and not _requires_full_stream_barrier(node)
177- )
178- 
179- 
180-def _is_npu_tuple_getitem(node):
181- # Moving a tuple extraction is necessary to expose the following compute.
182- # Do not generalize this to Python __getitem__ or Tensor indexing.
183- if node.op != "call_function" or node.target is not operator.getitem or len(node.args) != 2 or node.kwargs:
184- return False
185- source, index = node.args
186- if not isinstance(source, fx.Node) or not isinstance(source.target, torch._ops.OpOverload):
187- return False
188- num_returns = len(source.target._schema.returns)
189- return (
190- _is_reorderable_npu_call(source)
191- and type(index) is int
192- and num_returns > 1
193- and -num_returns <= index < num_returns
194- )
195- 
196- 
197-def _can_reorder(node):
198- if _is_reorderable_npu_call(node) or _is_npu_tuple_getitem(node):
199- return True
200- # Unreviewed custom/Python calls and alias writes still delimit windows.
201- schema = getattr(node.target, "_schema", None)
202- return (
203- node.op == "call_function"
204- and schema is not None
205- and schema.name.startswith("aten::")
206- and not schema.is_mutable
207- and not _requires_full_stream_barrier(node)
208- )
209- 
210- 
211-def event_frontiers(schedule):
212- """Join device-work frontiers; metadata only forwards its dependencies."""
213- clocks = [[0, 0], [0, 0]]
214- producers = [[], []]
215- frontiers = {}
216- waits = {}
217- for n in schedule.order:
218- required = [0, 0]
219- for p in schedule.dependencies[n]:
220- required[0] = max(required[0], frontiers[p][0])
221- required[1] = max(required[1], frontiers[p][1])
222- metadata = n.op in {"placeholder", "get_attr"} or _is_metadata_only_compute_node(n)
223- if metadata and not _is_stream_barrier(n):
224- # Do not mark the lane as synchronized by host-only work. Its
225- # consumers inherit this logical dependency, including any gates.
226- frontiers[n] = required
227- continue
228- lane = schedule.lanes[n]
229- other = 1 - lane
230- if required[other] > clocks[lane][other]:
231- p = producers[other][required[other] - 1]
232- waits[n] = p
233- clocks[lane] = [max(a, b) for a, b in zip(clocks[lane], frontiers[p], strict=True)]
234- if n.op != "output":
235- producers[lane].append(n)
236- clocks[lane][lane] = len(producers[lane])
237- frontiers[n] = clocks[lane].copy()
238- return waits
239- 
240- 
241-class DualStreamRuntime(torch.nn.Module):
242- """One auxiliary stream, reusable per-edge events, allocator ownership."""
243- 
244- def __init__(self):
245- super().__init__()
246- self.streams = None
247- self.events = {}
248- self._event_topology = None
249- self.active_lane = 0
250- 
251- def bind_event_topology(self, topology):
252- """Bind reusable device events to one immutable producer/wait graph."""
253- if self._event_topology is None:
254- self._event_topology = topology
255- elif self._event_topology != topology:
256- raise RuntimeError("DualStreamRuntime cannot be reused across different event topologies")
257- 
258- def synchronize_for_topology_rebind(self):
259- """Drain the old graph before reusing its event pool for a new topology."""
260- if self.streams is not None:
261- main, _ = self.streams
262- torch.npu.synchronize(main.device) # pyrefly: ignore [missing-attribute]
263- torch.npu.set_stream(main) # pyrefly: ignore [missing-attribute]
264- self.active_lane = 0
265- self._event_topology = None
266- 
267- def begin(self, inputs):
268- anchor = next(
269- (v for v in pytree.tree_leaves(inputs) if isinstance(v, torch.Tensor) and v.device.type == "npu"), None
270- )
271- if anchor is None:
272- return None
273- main = torch.npu.current_stream(anchor.device) # pyrefly: ignore [missing-attribute]
274- if self.streams is None:
275- self.streams = (main, torch.npu.Stream(device=anchor.device)) # pyrefly: ignore [missing-attribute]
276- elif self.streams[0] != main:
277- raise RuntimeError("CV parallel graph must be invoked on its original stream")
278- self.streams[1].wait_stream(main)
279- self.active_lane = 0
280- return anchor.device
281- 
282- def enter(self, lane, event_id, inputs, device):
283- if device is None:
284- return device
285- assert self.streams is not None
286- stream = self.streams[lane]
287- if lane != self.active_lane:
288- torch.npu.set_stream(stream) # pyrefly: ignore [missing-attribute]
289- self.active_lane = lane
290- if event_id >= 0:
291- stream.wait_event(self.events[event_id])
292- for value in pytree.tree_leaves(inputs):
293- if isinstance(value, torch.Tensor) and value.device == device:
294- value.record_stream(stream)
295- return device
296- 
297- def record(self, lane, event_id, values, device):
298- if device is not None:
299- if event_id not in self.events:
300- self.events[event_id] = torch.npu.Event() # pyrefly: ignore [missing-attribute]
301- event = self.events[event_id]
302- assert self.streams is not None
303- event.record(self.streams[lane])
304- return device
305- 
306- def finish(self, outputs, device):
307- if device is not None:
308- assert self.streams is not None
309- main, auxiliary = self.streams
310- main.wait_stream(auxiliary)
311- torch.npu.set_stream(main) # pyrefly: ignore [missing-attribute]
312- for value in pytree.tree_leaves(outputs):
313- if isinstance(value, torch.Tensor) and value.device == device:
314- value.record_stream(main)
315- return outputs
316- 
317- 
318-def materialize(gm, schedule, *, runtime=None):
319- # finish() joins the auxiliary stream; output-only events have no consumer.
320- waits = {n: p for n, p in event_frontiers(schedule).items() if n.op != "output"}
321- producers = set(waits.values())
322- event_ids = {n: i for i, n in enumerate(n for n in schedule.order if n in producers)}
323- runtime = runtime if runtime is not None else DualStreamRuntime()
324- if isinstance(runtime, DualStreamRuntime):
325- runtime.bind_event_topology(
326- tuple(
327- (
328- event_ids[source],
329- source.name,
330- schedule.lanes[source],
331- target.name,
332- schedule.lanes[target],
333- )
334- for target, source in waits.items()
335- )
336- )
337- # GraphModule only needs the source graph long enough to copy referenced
338- # attributes from ``gm``. The emitted graph replaces it below, so cloning
339- # a full training graph here only adds startup time and peak host memory.
340- root = fx.GraphModule(gm, gm.graph)
341- root.add_module("_cv_parallel_runtime", runtime)
342- graph = fx.Graph()
343- mapped = {}
344- previous_lane = None
345- recorded_inputs = [set(), set()]
346- storage_lanes: dict[fx.Node, set[int]] = {}
347- # Placeholder ordering is the public traced graph signature.
348- for n in gm.graph.nodes:
349- if n.op == "placeholder":
350- mapped[n] = graph.node_copy(n, lambda p: mapped[p])
351- storage_lanes[n] = {0}
352- runtime = graph.get_attr("_cv_parallel_runtime")
353- token = graph.call_method("begin", (runtime, tuple(mapped.values())))
354- for n in schedule.order:
355- if n.op == "placeholder":
356- continue
357- if n.op == "output":
358- output = fx.map_arg(n.args[0], lambda p: mapped[p])
359- graph.output(graph.call_method("finish", (runtime, output, token)))
360- continue
361- lane = schedule.lanes[n]
362- p = waits.get(n)
363- event_id = event_ids[p] if p is not None else -1
364- metadata_only = _is_metadata_only_compute_node(n)
365- input_storage_lanes: set[int] = set().union(*(storage_lanes[v] for v in n.all_input_nodes))
366- schema = getattr(n.target, "_schema", None)
367- if n.op == "get_attr":
368- storage_lanes[n] = {0}
369- elif metadata_only:
370- storage_lanes[n] = input_storage_lanes
371- elif schema is None or any(result.alias_info is not None for result in schema.returns):
372- storage_lanes[n] = input_storage_lanes | {lane}
373- else:
374- storage_lanes[n] = {lane}
375- # record_stream registers a storage's stream use until deallocation;
376- # repeating it at every consumer adds host dispatch overhead. Track FX
377- # values only, without retaining runtime tensors past their last use.
378- inputs_to_record = [
379- v
380- for v in n.all_input_nodes
381- if not metadata_only and storage_lanes[v] - {lane} and v not in recorded_inputs[lane]
382- ]
383- recorded_inputs[lane].update(inputs_to_record)
384- cross_inputs = tuple(mapped[v] for v in inputs_to_record)
385- # Views do not use the device. Record their storage only at the actual
386- # compute consumer; recording at the view can delay allocator reuse on
387- # a stream that never reads the storage. Event producers still enter
388- # their assigned lane to preserve the schedule's completion frontier.
389- needs_stream = not metadata_only or p is not None or n in event_ids
390- if needs_stream and (lane != previous_lane or p is not None or cross_inputs):
391- token = graph.call_method("enter", (runtime, lane, event_id, cross_inputs, token))
392- previous_lane = lane
393- mapped[n] = graph.node_copy(n, lambda v: mapped[v])
394- if n in event_ids:
395- token = graph.call_method("record", (runtime, lane, event_ids[n], (mapped[n],), token))
396- graph.lint()
397- root.graph = graph
398- root.recompile()
399- return root, waits
400- 
401- 
402-def schedule_pass(gm, example_inputs, *, profile_root: Path, runtime_context=None):
403- """Profile and schedule a complete F/B graph already lowered into two chunks.
404- 
405- The caller supplies chunk_id=0/1, valid data/state dependencies and live
406- GraphTrainer inputs. Chunk lowering and attention metadata are external
407- to this pass; profile_root is bound by the owning pipeline.
408- """
409- if runtime_context is None:
410- raise RuntimeError("CV parallel profiling requires live training inputs")
411- assign_stable_node_tags(gm)
412- chunks = {n.meta.get("chunk_id") for n in gm.graph.nodes if n.op == "call_function"}
413- if not {0, 1}.issubset(chunks):
414- raise RuntimeError("Fixed chunk streams require both chunks in the final FX graph")
415- run = _make_run_candidate(runtime_context)
416- from .schedule_calibration import calibrate_and_select_schedule
417- 
418- return calibrate_and_select_schedule(gm, run, profile_root=profile_root)
419- 
420- 
421-@register_pass_pipeline(CV_PARALLEL_PIPELINE)
422-def cv_parallel_pipeline(traced_result, config, *, parallelism_context=None):
423- require_graph_chunk_runtime()
424- if config.compile.backend != "aot_eager":
425- raise ValueError("The fixed chunk stream probe currently requires aot_eager")
426- if not config.compile.ep_overlap.enabled:
427- raise ValueError("cv_parallel requires EP chunking to be enabled")
428- passes = construct_default_graph_passes(traced_result, config, parallelism_context=parallelism_context)
429- context_factory = _RUNTIME_CONTEXT.get()
430- if context_factory is None:
431- raise RuntimeError("cv_parallel requires its trainer-instance runtime context")
432- runtime_context = context_factory()
433- passes = configure_batch_chunk_passes(passes, config, runtime_context=runtime_context)
434- profile_root = Path(os.getenv("CV_PARALLEL_PROFILING_DIR", str(Path(config.dump_folder) / "profiling")))
435- passes.append(
436- functools.partial(
437- schedule_pass,
438- profile_root=profile_root,
439- runtime_context=runtime_context,
440- )
441- )
442- return passes
@@ -1,183 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6-"""Measure CV-chunk Cube/Vector overlap in a detailed CANN capture."""
7- 
8-import csv
9-import json
10-from collections import Counter, defaultdict
11-from decimal import Decimal
12-from pathlib import Path
13- 
14-from .cann_kernel_metrics import CannKernelMetrics, classify_mixed_core_times
15- 
16-SCOPE = "NPU::GraphTrainer::forward_backward"
17-CORE_TYPES = {
18- "AI_CORE": "cube",
19- "AICORE": "cube",
20- "AIC": "cube",
21- "CUBE": "cube",
22- "AI_VECTOR_CORE": "vector",
23- "VECTOR_CORE": "vector",
24- "AIVEC": "vector",
25- "AIV": "vector",
26-}
27- 
28- 
29-def _ns(value):
30- number = Decimal(str(value)) * 1000
31- if not number.is_finite():
32- raise ValueError(f"Invalid profiler timestamp: {value}")
33- return int(number)
34- 
35- 
36-def summarize_profile(output: Path, *, trace=None, kernel_metrics=None):
37- """Summarize F/B compute intervals; MIX never contributes to pure CV."""
38- output = output.resolve()
39- if trace is None:
40- trace = json.loads((output / "trace_view.json").read_text(), parse_float=Decimal)
41- trace = trace if isinstance(trace, list) else trace["traceEvents"]
42- windows = []
43- for event in sorted(
44- (e for e in trace if e.get("ph") == "X" and e.get("name") == SCOPE), key=lambda e: _ns(e["ts"])
45- ):
46- start, duration = _ns(event["ts"]), _ns(event["dur"])
47- if duration <= 0:
48- raise ValueError("Forward/backward scope has no duration")
49- end = start + duration
50- if windows and start <= windows[-1][1]:
51- windows[-1] = windows[-1][0], max(end, windows[-1][1])
52- else:
53- windows.append((start, end))
54- if not windows:
55- raise ValueError(f"Missing {SCOPE} scope in {output}")
56- 
57- kernels, devices, counts = [], set(), Counter()
58- mixed_counts = Counter()
59- with (output / "kernel_details.csv").open(newline="", encoding="utf-8-sig") as handle:
60- reader = csv.DictReader(handle)
61- required = {"Device_id", "Stream ID", "Accelerator Core", "Start Time(us)", "Duration(us)"}
62- if missing := required - set(reader.fieldnames or []):
63- raise ValueError(f"Missing detailed profiler columns: {sorted(missing)}")
64- for row in reader:
65- start, duration = _ns(row["Start Time(us)"]), _ns(row["Duration(us)"])
66- if duration < 0:
67- raise ValueError("Negative kernel duration")
68- core = row["Accelerator Core"].strip().upper()
69- kind = "mix" if "MIX" in core else CORE_TYPES.get(core)
70- description = (row.get("Name", "") + " " + row.get("Type", "")).upper()
71- if kind is None or any(word in description for word in ("HCCL", "HCOM", "COMMUNICATION")):
72- continue
73- intervals = [
74- (max(start, begin), min(start + duration, end))
75- for begin, end in windows
76- if min(start + duration, end) > max(start, begin)
77- ]
78- if not intervals:
79- continue
80- devices.add(row["Device_id"])
81- counts[kind] += 1
82- if kind == "mix":
83- if kernel_metrics is None:
84- kernel_metrics = CannKernelMetrics(output.parent)
85- counters = kernel_metrics.core_metrics(
86- {
87- "name": row.get("Name"),
88- "ts": row["Start Time(us)"],
89- "dur": row["Duration(us)"],
90- "args": {"Physic Stream Id": row["Stream ID"]},
91- }
92- )
93- kind = classify_mixed_core_times([counters]) or "mix"
94- mixed_counts[kind] += 1
95- kernels.extend((begin, end, row["Stream ID"], kind) for begin, end in intervals)
96- if len(devices) != 1 or not kernels:
97- raise ValueError(f"Expected compute kernels on one captured device, found {sorted(devices)}")
98- streams = sorted({stream for _, _, stream, _ in kernels})
99- if not 1 <= len(streams) <= 2:
100- raise ValueError(f"Expected one or two compute streams, found {streams}")
101- 
102- events = defaultdict(list)
103- for start, end, stream, kind in kernels:
104- events[start].append((stream, kind, 1))
105- events[end].append((stream, kind, -1))
106- active = {stream: Counter() for stream in streams}
107- totals = Counter()
108- stream_busy = Counter()
109- previous = min(events)
110- for timestamp in sorted(events):
111- duration = timestamp - previous
112- occupied = [
113- {kind for kind, count in active[stream].items() if count > 0}
114- for stream in streams
115- if any(count > 0 for count in active[stream].values())
116- ]
117- if occupied:
118- totals["compute_union"] += duration
119- for stream in streams:
120- if any(count > 0 for count in active[stream].values()):
121- stream_busy[stream] += duration
122- for kind in ("cube", "vector", "mix"):
123- if any(any(value.split("_")[0] == kind for value in kinds) for kinds in occupied):
124- totals[kind + "_busy"] += duration
125- if len(occupied) == 2:
126- totals["overlap"] += duration
127- pair = (
128- {next(iter(kinds)) for kinds in occupied} if all(len(kinds) == 1 for kinds in occupied) else set()
129- )
130- if pair == {"cube", "mix_aiv"}:
131- totals["cube_mix_aiv_overlap"] += duration
132- elif pair == {"vector", "mix_aic"}:
133- totals["vector_mix_aic_overlap"] += duration
134- if any(len(kinds) != 1 or any(kind.startswith("mix") for kind in kinds) for kinds in occupied):
135- category = "mixed_overlap"
136- elif occupied[0] != occupied[1]:
137- category = "cv_overlap"
138- else:
139- category = "cc_overlap" if occupied[0] == {"cube"} else "vv_overlap"
140- totals[category] += duration
141- else:
142- totals["single_stream"] += duration
143- for stream, kind, delta in events[timestamp]:
144- active[stream][kind] += delta
145- previous = timestamp
146- totals["compute_span"] = max(events) - min(events)
147- totals["no_compute_in_span"] = totals["compute_span"] - totals["compute_union"]
148- totals["forward_backward_scope"] = sum(end - start for start, end in windows)
149- totals["kernel_duration_sum"] = sum(end - start for start, end, _, _ in kernels)
150- keys = (
151- "forward_backward_scope",
152- "compute_span",
153- "compute_union",
154- "kernel_duration_sum",
155- "single_stream",
156- "overlap",
157- "cv_overlap",
158- "cube_mix_aiv_overlap",
159- "vector_mix_aic_overlap",
160- "cc_overlap",
161- "vv_overlap",
162- "mixed_overlap",
163- "cube_busy",
164- "vector_busy",
165- "mix_busy",
166- "no_compute_in_span",
167- )
168- return {
169- "device": next(iter(devices)),
170- "streams": streams,
171- "kernel_counts": dict(counts),
172- "mixed_kernel_counts": dict(mixed_counts),
173- "time_ms": {key: totals[key] / 1_000_000 for key in keys},
174- "stream_busy_ms": {stream: stream_busy[stream] / 1_000_000 for stream in streams},
175- "overlap_percent": 100 * totals["overlap"] / totals["compute_union"],
176- "cv_percent_of_compute": 100 * totals["cv_overlap"] / totals["compute_union"],
177- "cube_covered_by_vector_percent": 100 * totals["cv_overlap"] / totals["cube_busy"]
178- if totals["cube_busy"]
179- else None,
180- "vector_covered_by_cube_percent": 100 * totals["cv_overlap"] / totals["vector_busy"]
181- if totals["vector_busy"]
182- else None,
183- }
@@ -1,543 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6-"""Calibrate free execution and report scheduled CV coverage without measured rollback."""
7- 
8-from __future__ import annotations
9- 
10-import hashlib
11-import json
12-import logging
13-import statistics
14-import time
15-from typing import TYPE_CHECKING, Any
16- 
17-import torch
18-import torch.distributed as dist
19- 
20-from .cv_parallel import DualStreamRuntime, dependency_only_schedule, materialize
21-from .schedule_search import build_profile_schedule as build_local_profile_schedule
22-from .whole_graph_runtime_profile import collective_order_keys, node_id, profile_whole_graph_costs
23- 
24-logger = logging.getLogger(__name__)
25- 
26-if TYPE_CHECKING:
27- from pathlib import Path
28- 
29- 
30-def gather_rank_values(value: Any) -> list[Any]:
31- if not dist.is_available() or not dist.is_initialized():
32- return [value]
33- # None is a valid payload, including successful alignment validation.
34- uncollected = object()
35- gathered: list[Any] = [uncollected] * dist.get_world_size()
36- dist.all_gather_object(gathered, value)
37- if any(item is uncollected for item in gathered):
38- raise RuntimeError("Failed to collect every rank's schedule measurements")
39- return gathered
40- 
41- 
42-def build_profile_schedule(gm, profile, *, kernel_observations=None, reference=None):
43- """Validate rank-local plans before any candidate graph executes."""
44- schedule, stats = build_local_profile_schedule(
45- gm, profile, kernel_observations=kernel_observations, reference=reference
46- )
47- keys = collective_order_keys(gm)
48- communication = [keys[n] for n in schedule.order if n in keys]
49- signature = hashlib.sha256(repr(communication).encode()).hexdigest()
50- validation = gather_rank_values(
51- {
52- "signature": signature,
53- "changed": stats.pop("changed_from_free"),
54- "coverage_improved": stats.pop("predicted_coverage_improved"),
55- "prediction": stats.pop("prediction"),
56- }
57- )
58- if any(value["signature"] != signature for value in validation):
59- raise RuntimeError("Collective order differs across ranks; refusing inconsistent events")
60- stats.update(
61- {
62- "changed_from_free_by_rank": [v["changed"] for v in validation],
63- "predicted_coverage_improved_by_rank": [v["coverage_improved"] for v in validation],
64- # Preserve the existing report alias for bidirectional CV gains.
65- "predicted_cv_improved_by_rank": [v["coverage_improved"] for v in validation],
66- "prediction_by_rank": [v["prediction"] for v in validation],
67- }
68- )
69- return schedule, stats
70- 
71- 
72-def _measure_schedule(graph, run_candidate, *, device, warmup, samples, label):
73- """Synchronized F/B only; state copies, measurement collectives and optimizer excluded."""
74- backend = torch.get_device_module(device)
75- distributed = dist.is_available() and dist.is_initialized()
76- main_stream = backend.current_stream(device)
77- measurements = []
78- elapsed = torch.empty(1, device=device, dtype=torch.float32)
79- backend.synchronize(device)
80- backend.empty_cache()
81- backend.reset_peak_memory_stats(device)
82- with torch.random.fork_rng(devices=[device.index], device_type=device.type):
83- cpu_rng = torch.random.get_rng_state()
84- device_rng = backend.get_rng_state(device)
85- for iteration in range(warmup + samples):
86- torch.random.set_rng_state(cpu_rng)
87- backend.set_rng_state(device_rng, device)
88- run_candidate.prepare()
89- try:
90- if distributed:
91- dist.barrier()
92- backend.synchronize(device)
93- started = time.perf_counter()
94- result = run_candidate(graph)
95- backend.synchronize(device)
96- local_ms = (time.perf_counter() - started) * 1000
97- del result
98- finally:
99- try:
100- backend.synchronize(device)
@@ -1,85 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6- 
7-"""Pure overlap metrics and candidate acceptance policy."""
8- 
9- 
10-def _overlap_metrics(coverage, *, cube_work, vector_work, compute_union=None, span=None):
11- cv, mixed_cv, cc, vv = coverage
12- cube_busy = max(0.0, cube_work - cc)
13- vector_busy = max(0.0, vector_work - vv)
14- result = {
15- "cv_ms": cv,
16- "mixed_cv_ms": mixed_cv,
17- "cc_ms": cc,
18- "vv_ms": vv,
19- "cube_busy_ms": cube_busy,
20- "vector_busy_ms": vector_busy,
21- "cube_covered_by_vector_percent": 100 * cv / cube_busy if cube_busy else 0.0,
22- "vector_covered_by_cube_percent": 100 * cv / vector_busy if vector_busy else 0.0,
23- }
24- if compute_union is not None:
25- result["compute_union_ms"] = compute_union
26- result["cv_percent_of_compute"] = 100 * cv / compute_union if compute_union else 0.0
27- if span is not None:
28- result["span_ms"] = span
29- return result
30- 
31- 
32-def _local_coverage_score(coverage):
33- cv, mixed_cv, cc, vv = coverage
34- return (round(cv, 9), -round(cc + vv, 9), -round(cc, 9), -round(vv, 9), round(mixed_cv, 9))
35- 
36- 
37-def _metric_score(metrics):
38- cube = metrics["cube_covered_by_vector_percent"]
39- vector = metrics["vector_covered_by_cube_percent"]
40- return (
41- round(min(cube, vector), 9),
42- round(cube + vector, 9),
43- round(metrics["cv_ms"], 9),
44- -round(metrics["cc_ms"] + metrics["vv_ms"], 9),
45- -round(metrics["cc_ms"], 9),
46- -round(metrics["vv_ms"], 9),
47- round(metrics["mixed_cv_ms"], 9),
48- -round(metrics["span_ms"], 9),
49- )
50- 
51- 
52-def candidate_score(current, current_score, metrics):
53- current_cube, current_vector, current_cc, current_vv = current
54- cube = metrics["cube_covered_by_vector_percent"]
55- vector = metrics["vector_covered_by_cube_percent"]
56- cc = metrics["cc_ms"]
57- vv = metrics["vv_ms"]
58- non_regression = (
59- cube + 1e-9 >= current_cube
60- and vector + 1e-9 >= current_vector
61- and cc <= current_cc + 1e-9
62- and vv <= current_vv + 1e-9
63- )
64- score = _metric_score(metrics)
65- if not non_regression or score <= current_score:
66- return None
67- return score
68- 
69- 
70-def predicted_coverage_improved(free_prediction, scheduled_prediction):
71- """Require strict bidirectional gains for the final baseline comparison."""
72- return (
73- round(
74- scheduled_prediction["cube_covered_by_vector_percent"] - free_prediction["cube_covered_by_vector_percent"],
75- 9,
76- )
77- > 0
78- and round(
79- scheduled_prediction["vector_covered_by_cube_percent"] - free_prediction["vector_covered_by_cube_percent"],
80- 9,
81- )
82- > 0
83- and scheduled_prediction["cc_ms"] <= free_prediction["cc_ms"] + 1e-9
84- and scheduled_prediction["vv_ms"] <= free_prediction["vv_ms"] + 1e-9
85- )