Merged
refactor: reorganize package layout and add agent guidance #688
zzyyjj012Add on Sep 2
refactor: reorganize package layout and add agent guidance #688
Merged
Total: 150 files changed+1232-337
| @@ -20,16 +20,16 @@ | |||
| 20 | ## 插件仓专属原则 | 20 | ## 插件仓专属原则 |
| 21 | 21 | ||
| 22 | 1. **不修改上游 checkout。** torchtitan-npu 不直接编辑 torchtitan 源码。适配按职责放入以下位置: | 22 | 1. **不修改上游 checkout。** torchtitan-npu 不直接编辑 torchtitan 源码。适配按职责放入以下位置: |
| 23 | - - **Package patch**(`torchtitan_npu/patches/`):补齐 PyTorch PrivateUse1 backend,或替换当前运行时中缺失的 Python/CANN 符号。`patches/torchtitan/` 只允许有上游依据的临时 patch;`patches/torch_npu/` 和 `patches/workaround/` 用于当前有效的 NPU runtime compatibility patch | 23 | + - **Package patch**(`torchtitan_npu/patches/`):补齐 PyTorch PrivateUse1 backend,或替换当前运行时中缺失的 Python/CANN 符号。`patches/torchtitan/` 只允许有上游依据的临时 patch;`patches/torch_npu/` 用于当前有效的 NPU runtime compatibility patch |
| 24 | - **配置级 override**(`torchtitan_npu/override/`):使用 `@override` 声明组件替换,通过 `override.imports` 显式启用 | 24 | - **配置级 override**(`torchtitan_npu/override/`):使用 `@override` 声明组件替换,通过 `override.imports` 显式启用 |
| 25 | - **模型模块**(`torchtitan_npu/models/`):提供 DeepSeek-V3.2 和 DeepSeek-V4 的模型配置、并行化与 checkpoint 适配 | 25 | - **模型模块**(`torchtitan_npu/models/`):提供 DeepSeek-V3.2 和 DeepSeek-V4 的模型配置、并行化与 checkpoint 适配 |
| 26 | - **NPU 算子**(`torchtitan_npu/ops/`):封装 CANN 或设备专属算子能力 | 26 | - **NPU 算子**(`torchtitan_npu/ops/`):封装 CANN 或设备专属算子能力 |
| 27 | 27 | ||
| 28 | -2. **理解 patch 生效机制。** `torchtitan_npu/__init__.py` 导入 `torchtitan_npu.patches`,后者继续导入 `torch_npu`、`torchtitan` 和 `workaround` 子包,因此导入 `torchtitan_npu` 即会注册或应用其中的入口 patch。只有需要随包导入生效的 patch 才应加入对应的 `__init__.py`;供模型或 override 直接复用的兼容模块按调用路径显式导入。 | 28 | +2. **理解 patch 生效机制。** `torchtitan_npu/__init__.py` 导入 `torchtitan_npu.patches`,后者继续导入 `torch_npu` 和 `torchtitan` 子包,因此导入 `torchtitan_npu` 即会注册或应用其中的入口 patch。只有需要随包导入生效的 patch 才应加入对应的 `__init__.py`;供模型或 override 直接复用的兼容模块按调用路径显式导入。 |
| 29 | 29 | ||
| 30 | 3. **Override 显式启用。** 每个 override 工厂使用 `@override` 注册,并以完整的 `module.function` 写入 `override.imports`。不要在 `__init__.py` 中批量导入具体 override。 | 30 | 3. **Override 显式启用。** 每个 override 工厂使用 `@override` 注册,并以完整的 `module.function` 写入 `override.imports`。不要在 `__init__.py` 中批量导入具体 override。 |
| 31 | 31 | ||
| 32 | -4. **固定上游基线。** 当前 torchtitan commit 同时记录在 `requirements.txt` 和 `.ci/setup_torchtitan.sh`。调整上游版本时同步更新两处,并检查 patch 目标、函数签名、模型接口和测试是否仍有效。 | 32 | +4. **固定上游基线。** `requirements.txt` 声明当前 torchtitan 版本;`.ci/setup_torchtitan.sh` 从该版本推导对应 tag。调整上游版本时检查 patch 目标、函数签名、模型接口和测试是否仍有效。 |
| 33 | 33 | ||
| 34 | 5. **临时 patch 可删除。** `torchtitan_npu/patches/torchtitan/` 只保存已提交上游但当前依赖版本尚未包含的临时补丁。补丁文件必须记录对应 PR;上游合入并更新依赖后删除相关补丁和导入。 | 34 | 5. **临时 patch 可删除。** `torchtitan_npu/patches/torchtitan/` 只保存已提交上游但当前依赖版本尚未包含的临时补丁。补丁文件必须记录对应 PR;上游合入并更新依赖后删除相关补丁和导入。 |
| 35 | 35 | ||
| @@ -49,11 +49,14 @@ | |||
| 49 | 49 | ||
| 50 | | 目录 | 职责 | | 50 | | 目录 | 职责 | |
| 51 | | --- | --- | | 51 | | --- | --- | |
| 52 | +| `torchtitan_npu/config/` | NPU 配置 schema、转换器和注册 API | | ||
| 52 | | `torchtitan_npu/patches/torchtitan/` | 包导入时生效的上游临时补丁 | | 53 | | `torchtitan_npu/patches/torchtitan/` | 包导入时生效的上游临时补丁 | |
| 53 | -| `torchtitan_npu/patches/torch_npu/`、`workaround/` | 当前有效的 NPU runtime compatibility patch;保留其自动加载和生效时机 | | 54 | +| `torchtitan_npu/patches/torch_npu/` | 当前有效的 NPU runtime compatibility patch;保留其自动加载和生效时机 | |
| 55 | +| `torchtitan_npu/extensions/` | 永久扩展、组件集成和可选外部 adaptor | | ||
| 54 | | `torchtitan_npu/override/` | 通过 `override.imports` 显式启用的配置级组件替换 | | 56 | | `torchtitan_npu/override/` | 通过 `override.imports` 显式启用的配置级组件替换 | |
| 55 | | `torchtitan_npu/models/` | DeepSeek-V3.2、DeepSeek-V4 模型配置、实现、并行化和 checkpoint 适配 | | 57 | | `torchtitan_npu/models/` | DeepSeek-V3.2、DeepSeek-V4 模型配置、实现、并行化和 checkpoint 适配 | |
| 56 | | `torchtitan_npu/ops/` | CANN 与 NPU 专属算子封装 | | 58 | | `torchtitan_npu/ops/` | CANN 与 NPU 专属算子封装 | |
| 59 | +| `torchtitan_npu/tools/` | 随 package 分发的 checkpoint 转换与导出工具 | | ||
| 57 | | `tests/unit_tests/` | CPU 单测和静态契约测试 | | 60 | | `tests/unit_tests/` | CPU 单测和静态契约测试 | |
| 58 | | `scripts/` | 训练、合规检查及其他仓库级脚本 | | 61 | | `scripts/` | 训练、合规检查及其他仓库级脚本 | |
| 59 | 62 | ||
| @@ -119,5 +122,5 @@ python -m pre_commit run --all-files --show-diff-on-failure | |||
| 119 | ### 5. PR 与流水线 | 122 | ### 5. PR 与流水线 |
| 120 | 123 | ||
| 121 | - PR 描述解释「为什么」而非只写「做了什么」;非简单改动附数值证据,模型变更说明 checkpoint 兼容性。 | 124 | - PR 描述解释「为什么」而非只写「做了什么」;非简单改动附数值证据,模型变更说明 checkpoint 兼容性。 |
| 122 | -- 创建或推送 PR、读取改动与评论时使用 `gitcode-pr`,并按 `.gitcode/PULL_REQUEST_TEMPLATE/PULL_REQUEST_TEMPLATE.md` 填写。标题使用正确的英文类型标签,如 `feat`、`fix`、`refactor`、`docs` 或 `test`;`类型` 和 `Checklist` 只勾选真实完成项,`如何测试` 写实际命令或未执行原因。 | 125 | +- 已安装 `gitcode-pr` skill 时,创建或推送 PR、读取改动与评论使用该 skill,并按 `.gitcode/PULL_REQUEST_TEMPLATE/PULL_REQUEST_TEMPLATE.md` 填写。标题使用正确的英文类型标签,如 `feat`、`fix`、`refactor`、`docs` 或 `test`;`类型` 和 `Checklist` 只勾选真实完成项,`如何测试` 写实际命令或未执行原因。 |
| 123 | -- 用户要求触发或等待 CI 时使用 `gitcode-pipeline`,根据实际失败日志定位问题。 | 126 | +- 已安装 `gitcode-pipeline` skill 时,用户要求触发或等待 CI 使用该 skill,并根据实际失败日志定位问题。 |
| @@ -0,0 +1,62 @@ | |||
| 1 | +# Agent Notes | ||
| 2 | + | ||
| 3 | +Agent Note 记录需要长期保留的架构决定,回答“为什么这样设计”。它不替代当前态文档、功能文档或 PR 描述,也不记录普通工作流水账。 | ||
| 4 | + | ||
| 5 | +## 何时使用 | ||
| 6 | + | ||
| 7 | +满足以下任一情况时,可以创建 Agent Note: | ||
| 8 | + | ||
| 9 | +- 改动跨越多个生产目录,重新划分模块职责或依赖边界。 | ||
| 10 | +- 改变 package 导入、patch、extension、override 或注册机制的生效顺序。 | ||
| 11 | +- 改变公共配置、checkpoint、模型兼容性或长期测试边界。 | ||
| 12 | +- 方案需要多个 PR 分阶段完成,合入后仍有明确的迁移债务和退出条件。 | ||
| 13 | +- 存在多个合理方案,需要保留选择依据,避免后续重复讨论。 | ||
| 14 | + | ||
| 15 | +设计已经确定并开始实施时,Agent Note 随第一个实现 PR 提交。纯头脑风暴和没有实施计划的提案保留在本地。 | ||
| 16 | + | ||
| 17 | +以下改动不创建 Agent Note: | ||
| 18 | + | ||
| 19 | +- 普通新功能、Bug 修复、单文件重构和测试补充。 | ||
| 20 | +- 遵循现有规则的机械搬迁、重命名或 import 更新。 | ||
| 21 | +- 临时排障、命令记录、测试日志和运行结果。 | ||
| 22 | +- 已能由代码、当前态文档和 PR 描述完整说明的局部改动。 | ||
| 23 | + | ||
| 24 | +同一架构决定只维护一份 Note。后续 PR 更新原 Note 的状态、阶段和验证结果,不重复创建文件。 | ||
| 25 | + | ||
| 26 | +## 状态与目录 | ||
| 27 | + | ||
| 28 | +仓库使用两个活跃状态: | ||
| 29 | + | ||
| 30 | +- `proposed/architecture/`:未完成或分阶段实施的提案,可写目标目录、迁移步骤、验收条件和风险。 | ||
| 31 | +- `implemented/architecture/`:已完整落地的决定,只描述当前机制、取舍和持续验证。 | ||
| 32 | + | ||
| 33 | +提案完成后精简并移动到 `implemented/`。如果决定已经被正式文档完整吸收,不再提供额外的设计依据,则删除 Note。被放弃、长期未推进或被其他方案替代的 Note 应删除;只有拒绝原因仍具有长期价值时才归档。 | ||
| 34 | + | ||
| 35 | +## 内容要求 | ||
| 36 | + | ||
| 37 | +文件名为 `YYYY-MM-DD-topic.md`,并包含 `Status`、`Created`、`Last updated` 和关联 Issue/PR。 | ||
| 38 | + | ||
| 39 | +所有 Note 必须包含: | ||
| 40 | + | ||
| 41 | +- `Context`:问题、背景和需要长期保留的约束。 | ||
| 42 | +- `Proposal` 或 `Decision`:计划采用的方案或最终决定。 | ||
| 43 | +- `Consequences`:兼容性、长期约束和后续影响。 | ||
| 44 | + | ||
| 45 | +以下章节按实际需要添加,不能为了满足模板填充空泛内容: | ||
| 46 | + | ||
| 47 | +- `Alternatives considered`:存在需要保留的重要备选方案时。 | ||
| 48 | +- `Acceptance criteria`:分阶段实施或需要明确完成边界时。 | ||
| 49 | +- `Risks`:存在显著兼容性、数值、性能或维护风险时。 | ||
| 50 | +- `Migration plan`:需要多个 PR 或跨版本迁移时。 | ||
| 51 | + | ||
| 52 | +完成后将 `Proposal` 改为 `Decision`,保留仍有价值的背景、方案取舍和影响;删除临时任务清单、过期路径、阶段日志和已经失效的验证计划。架构阶段合入时,同步更新代码、相关 `AGENTS.md`、当前态文档和本 Note。 | ||
| 53 | + | ||
| 54 | +## 体量与清理 | ||
| 55 | + | ||
| 56 | +- 一个文件只记录一个架构决定。 | ||
| 57 | +- 单个 Note 建议不超过 200 行或 20 KiB;超过时拆分独立决定。 | ||
| 58 | +- 不粘贴完整代码、长日志、聊天记录、本机路径、环境名称或临时资源信息。 | ||
| 59 | +- 测试只记录结论和必要命令;大段证据保存在 CI、Issue 或其他产物中。 | ||
| 60 | +- `proposed/` 中超过 90 天未更新的 Note 必须复核,选择继续更新、转为 implemented 或删除。 | ||
| 61 | + | ||
| 62 | +判断标准:如果未来开发者需要理解“为什么这样设计”,并且答案不能只靠代码、当前态文档和 PR 描述获得,就使用 Agent Note。 | ||
| @@ -0,0 +1,114 @@ | |||
| 1 | +# Agent Note: Plugin layout and injection boundaries | ||
| 2 | + | ||
| 3 | +Status: proposed | ||
刷新状态/文件名/路径 ![]() ![]() | |||
| 4 | +Created: 2026-09-02 | ||
| 5 | +Last updated: 2026-10-12 | ||
| 6 | +Tracking: PR #688 | ||
| 7 | + | ||
| 8 | +## Context | ||
| 9 | + | ||
| 10 | +当前包导入依次加载 `patches`、`config`、`extensions` 和 `ops`。临时上游补丁、永久扩展、NPU override、模型代码和算子代码的职责与导入边界尚未完全收敛,重构时容易产生互相导入、重复 monkey-patch 或语义回归。 | ||
| 11 | + | ||
| 12 | +截至 2026-10-12,顶层 `compile/` 已迁入 `extensions/compile/`,主包入口仍自动导入 `config` 和 `ops`,尚未收敛为目标的 `patches → extensions`。多个层级之间仍存在历史反向依赖,extension loader、组件注册表及禁用开关也尚未实现。因此本 Note 同时记录当前迁移状态;`docs/architecture.md` 明确区分当前实现、禁止新增与后续目标。 | ||
| 13 | + | ||
| 14 | +## Proposal | ||
| 15 | + | ||
| 16 | +目标结构由根和目录级 `AGENTS.md` 规定: | ||
| 17 | + | ||
| 18 | +- `patches/` 与 `models/` 是上游待合入层。新增代码不得建立对 `extensions/`、`override/` 或 `ops/` 的反向依赖;现有跨层边按迁移债务逐项收敛。 | ||
| 19 | +- `extensions/` 是本仓永久扩展层,可以依赖 `patches/` 提供的符号,不得新增对 `models/`、`override/` 或 `ops/` 的依赖。 | ||
| 20 | +- patch 先替换 `torchtitan`,extension 随后可以通过 `torchtitan_npu.patches.*` 复用 patch 提供的定义,也可以从正常的 `torchtitan.*`、`torch.*` 或 `torch_npu.*` 导入路径使用替换结果。依赖方向保持单向:patch 不得新增对 extension 的依赖。 | ||
| 21 | +- `override/` 经 `override.imports` 显式替换 NPU/CANN 组件;`ops/` 只承载 kernel 与 `torch.library` 注册。 | ||
| 22 | +- 自动注入的目标顺序是 `patches → extensions`;selected override 随后在组件构建前生效。`models` 与 `ops` 按需导入。 | ||
| 23 | +- patches 是可早期激活的上游替身层;影响 dataclass schema 或默认工厂的 patch 早于依赖该符号的模块。`patches/torchtitan/__init__.py` 的显式导入列表定义当前激活顺序;该顺序由检查保护,不以「trainer 最后导入」这类与当前实现不符的绝对规则表达。extensions 在 patches 完成激活后加载,可以复用 patch 定义,并通过配置外包装、运行期 seam、单目标 hook 或公开注册 API 生效。 | ||
| 24 | +- `config/` 作为公开配置 schema 与转换基础层保留,但其包导入不得隐式安装 patch。 | ||
| 25 | +- `torchtitan_npu/compile/`、`torchtitan_npu/distributed/`、`torchtitan_npu/interfaces/` 和 `torchtitan_npu/patches/workaround/` 已迁移或删除;可安装的 checkpoint 转换工具放在 `torchtitan_npu/tools/`,与根目录仓库维护脚本区分。 | ||
| 26 | +- `experiments/torchao-npu/` 在它仍以独立实验包发布时保留现位置;不将独立 Python distribution 嵌入 `torchtitan_npu/extensions/experiment/`。 | ||
| 27 | + | ||
| 28 | +### Migration baseline | ||
| 29 | + | ||
| 30 | +| 原路径或当前路径 | 职责 | 决策 | 当前或目标路径 | 验证 | 状态 | | ||
| 31 | +| --- | --- | --- | --- | --- | --- | | ||
| 32 | +| `torchtitan_npu/config/` | NPU config schema、Tyro 转换与 loader patch | KEEP;当前导入 `manager` 会安装 ConfigManager loader wrapper,后续拆除包导入副作用 | `torchtitan_npu/config/` | config 解析 UT、隔离导入测试 | planned | | ||
| 33 | +| `torchtitan_npu/compile/` | SDC checksum graph pass | MOVE | `torchtitan_npu/extensions/compile/` | SDC UT 与 smoke test | implemented; NPU smoke not run | | ||
| 34 | +| `torchtitan_npu/distributed/` | HF32 backend 开关 | DELETE,行为归 trainer extension | `torchtitan_npu/extensions/torchtitan/trainer.py` | TrainerEx/config CPU UT | implemented | | ||
| 35 | +| `torchtitan_npu/scripts/` | 可通过 package 调用的 checkpoint 转换工具 | MOVE;删除无调用者的 patch 转发 shim | `torchtitan_npu/tools/` | CLI/import UT | implemented; 37 targeted CPU UT passed; distributed roundtrip blocked by sandbox networking | | ||
| 36 | +| `torchtitan_npu/interfaces/torchao_converter.py` | TorchAO-NPU 与模型 config tree 的适配 | MOVE,禁止继续增加顶层 interface | `torchtitan_npu/extensions/adaptor/torchao/converter.py` | converter UT、可选依赖导入测试 | implemented; targeted CPU UT passed; NPU validation not run | | ||
| 37 | +| `torchtitan_npu/extensions/trainer.py`、`profiler.py`、`tools/utils.py` | 对上游 Trainer 和工具模块的永久扩展 | MOVE,按上游 owner 镜像 | `torchtitan_npu/extensions/torchtitan/trainer.py`、`torchtitan_npu/extensions/torchtitan/tools/` | Trainer/profiler targeted UT | implemented; 7 passed | | ||
| 38 | +| `torchtitan_npu/extensions/components/{checkpoint,metrics,lora_compat,optimizer}.py` | 对上游 components 的永久扩展 | MOVE,按上游 owner 镜像 | `torchtitan_npu/extensions/torchtitan/components/` | 路径、import 与调用点检查 | implemented | | ||
| 39 | +| `torchtitan_npu/extensions/distributed/fsdp.py` | 对上游 FSDP 的永久扩展 | MOVE,按上游 owner 镜像 | `torchtitan_npu/extensions/torchtitan/distributed/fsdp.py` | import 与调用点检查 | implemented | | ||
| 40 | +| `torchtitan_npu/extensions/graph_trainer/` | GraphTrainer 扩展 | MOVE,按上游 experiments owner 镜像 | `torchtitan_npu/extensions/torchtitan/experiments/graph_trainer/` | collection 与路径检查 | implemented | | ||
| 41 | +| `torchtitan_npu/extensions/experiment/torchft/` | TorchFT 容错训练扩展 | MOVE,按上游 experiments owner 镜像 | `torchtitan_npu/extensions/torchtitan/experiments/torchft/` | 路径与 import 引用检查 | implemented; optional dependency required for execution | | ||
| 42 | +| `torchtitan_npu/extensions/ep_process_group.py` | EP mesh 与 DeepEP process group 接线 | MOVE,先归入 TorchTitan 镜像层,后续再拆 owner | `torchtitan_npu/extensions/torchtitan/ep_process_group.py` | isolated CPU UT | implemented; 11 passed | | ||
| 43 | +| `experiments/torchao-npu/` | 独立发布的实验 TorchAO-NPU 包 | KEEP,达到稳定性门槛后再提升 | `experiments/torchao-npu/` | 该 distribution 自有测试 | current | | ||
| 44 | +| `torchtitan_npu/patches/workaround/` | 历史 runtime 与 eager workaround | MOVE 后 DELETE | `torchtitan_npu/patches/torch_npu/` 或 `torchtitan_npu/extensions/torchtitan/` | patch/extension UT 与 NPU smoke | implemented; device-copy/tooling UT 14 passed; Qwen adapter test interrupted; NPU smoke not run | | ||
| 45 | +| `tests/smoke_tests/` | 需要 NPU 语义的小范围验证 | KEEP,纳入正式测试分层 | `tests/smoke_tests/` | smoke runner | current | | ||
| 46 | +| `torchtitan_npu/extensions/experiment/` | 与 TrainerEx 紧密集成的试验性训练能力 | KEEP,不向核心模块泄漏分支 | `torchtitan_npu/extensions/experiment/` | 功能 UT/NPU smoke | current | | ||
| 47 | + | ||
| 48 | +ownership debt manifest、目录布局检查和 extension ownership 检查脚本当前只保存在代码仓外的本地阶段工具目录,不属于本 PR,也不是仓库或 CI 的有效门禁。后续如需引入,必须重新设计、补充自测并作为独立变更评审。 | ||
| 49 | + | ||
| 50 | +### Current dependency debt | ||
| 51 | + | ||
| 52 | +以下边不符合目标单向依赖,但当前代码仍依赖它们。`scripts/check_architecture_boundaries.py` 以 `.ci/architecture_import_baseline.json` 记录直接 import 基线并阻止新增;它不是债务已经清零的证明。 | ||
| 53 | + | ||
| 54 | +| 来源 | 当前直接依赖 | 收敛方向 | | ||
| 55 | +| --- | --- | --- | | ||
| 56 | +| `config/manager.py` | 包导入时安装 `ConfigManager._load_config` wrapper | 将安装时机移至 extension 激活入口,保持 converter 行为和 CLI 兼容 | | ||
| 57 | +| DeepSeek-V4/V4.1 模型配置、并行化与 checkpoint 适配 | `extensions/` 与 `override/` | 提炼公开模型/配置接口后逐项替换,不改变训练、checkpoint 或数值语义 | | ||
| 58 | +| Qwen3.5 模型模块 | 模型专属 `override/` | 通过明确注册或调用边界消除反向依赖 | | ||
| 59 | +| `extensions/torchtitan/trainer.py`、checkpoint extension | `extensions/components/` | 在 loader 和组件注册表稳定后改为按需接线 | | ||
| 60 | +| TorchAO adaptor、CV Parallel 与 TorchFT extension | `models/`、`override/`、`ops/` 或 patch 私有符号 | 用公开 adaptor/extension 接口分阶段替换 | | ||
| 61 | +| `patches/torchtitan/models/qwen3_5/vision_encoder.py` | `extensions/torchtitan/eager_flex.py` | 将 eager 兼容逻辑移到单向可激活层,消除 patch 反向依赖 | | ||
| 62 | + | ||
| 63 | +`patches/torchtitan/` 的新增文件使用 `Upstream-PR:` 头部。现有文件含历史 `Pending upstream PR`/`Upstream PR` 标记和基线中已登记的缺失项;当前门禁只禁止新增元数据债务,统一整理另行完成。 | ||
| 64 | + | ||
| 65 | +### Migration order | ||
| 66 | + | ||
| 67 | +1. 已建立当前态矩阵和目录级规则;本地 ownership 工具未纳入仓库。 | ||
| 68 | +2. 已删除名不副实的 `torchtitan_npu/compile/`、`torchtitan_npu/distributed/`、`torchtitan_npu/scripts/`、`torchtitan_npu/interfaces/` 和 `torchtitan_npu/patches/workaround/`,并保持原有行为与调用时机;仓库根 `scripts/` 继续承载训练与维护脚本。 | ||
| 69 | +3. 已建立 `torchtitan_npu/extensions/torchtitan/` 镜像目录,将具有明确上游 owner 的模块、测试和引用迁入对应路径。 | ||
| 70 | +4. TorchAO converter 已迁入 `torchtitan_npu/extensions/adaptor/torchao/`;它对 patch 定义的依赖符合单向依赖规则,对 model 和 override 实现的依赖保留为后续架构债务,本阶段不重构,避免改变业务逻辑。 | ||
| 71 | +5. 下一阶段实现 extension loader、组件注册表和禁用开关,再收敛主包自动导入为 `patches → extensions`。在此之前,禁用开关仅是设计草案,不作为当前行为约束。 | ||
| 72 | +6. loader 边界稳定后,按实际依赖逐项清理跨层导入和重复 monkey-patch owner,并消除 `patches/torchtitan/models/qwen3_5/vision_encoder.py → extensions/torchtitan/eager_flex.py` 的反向依赖。 | ||
| 73 | + | ||
| 74 | +## Alternatives considered | ||
| 75 | + | ||
| 76 | +### 保持现有顶层目录和导入副作用 | ||
| 77 | + | ||
| 78 | +这无法提供稳定归属和依赖方向,隐式耦合会继续累积。 | ||
| 79 | + | ||
| 80 | +### 让 patch 反向导入 extension | ||
| 81 | + | ||
| 82 | +这会形成与 `patches → extensions` 激活顺序相反的依赖,使 patch 无法独立加载,并可能产生循环导入。extension 可以依赖 patch,patch 不得依赖 extension。 | ||
| 83 | + | ||
| 84 | +### 将所有 NPU 实现放进 override | ||
| 85 | + | ||
| 86 | +override 是配置级显式替换层,不适合承载必须随包导入生效的上游补丁、永久扩展或 kernel 注册。 | ||
| 87 | + | ||
| 88 | +## Acceptance criteria | ||
| 89 | + | ||
| 90 | +- 迁移文件符合所属目录的职责和依赖规则。 | ||
| 91 | +- 当前自动导入顺序是 `patches → config → extensions → ops`;收敛为 `patches → extensions` 是后续目标。override 仍仅由 `override.imports` 选择。 | ||
| 92 | +- extensions 可以依赖 patches;patches 不得新增对 extensions 的依赖。`patches/torchtitan/models/qwen3_5/vision_encoder.py → extensions/torchtitan/eager_flex.py` 是当前已登记的反向依赖债务。 | ||
| 93 | +- extension 禁用不影响 patches、models、override 或 ops 的可导入性。该禁用能力当前尚未实现,不能作为可用运行时配置。 | ||
| 94 | +- 若后续引入 ownership checker,其规则、例外和自测必须随独立变更提交;当前分支不存在该仓库门禁。 | ||
| 95 | +- 迁移矩阵中每个路径只有一个决策和一个目标 owner;状态与代码同步。 | ||
| 96 | +- 每阶段保持训练入口、override 选择、checkpoint 语义和已验证数值行为,并提供相称的 CPU UT、NPU ST 或数值证据。 | ||
| 97 | +- 同一变更更新根规则、受影响目录规则和 `docs/architecture.md`;后者定义目标架构,阶段完成状态记录在本 Agent Note。 | ||
| 98 | + | ||
| 99 | +## Consequences | ||
| 100 | + | ||
| 101 | +目录 owner 和新增代码落点更加明确,但现有调用者必须使用迁移后的 import 路径。本轮不为以下已删除路径保留 re-export shim: | ||
| 102 | + | ||
| 103 | +```text | ||
| 104 | +torchtitan_npu.scripts.checkpoint_conversion | ||
| 105 | +interfaces.torchao_converter | ||
| 106 | +torchtitan_npu.compile.sdc_checksum | ||
| 107 | +torchtitan_npu.distributed.utils | ||
| 108 | +``` | ||
| 109 | + | ||
| 110 | +它们是目录迁移带来的显式 breaking change,PR 与发布说明必须逐项列出。允许 extension 复用 patch 定义可以避免重复实现,同时要求 patch 保持对 extension 的零依赖。主包自动导入、extension 禁用能力和历史跨层依赖仍未收敛,本 Note 在这些验收条件完成前保持 `proposed`。 | ||
| 111 | + | ||
| 112 | +## Risks | ||
| 113 | + | ||
| 114 | +上游 API 漂移、导入顺序变化和错误的依赖判断都可能导致注册时机、checkpoint、分布式路径、性能或数值回归。 | ||
| @@ -0,0 +1,60 @@ | |||
| 1 | +{ | ||
| 2 | + "patch_metadata": { | ||
| 3 | + "missing": [ | ||
| 4 | + "torchtitan_npu/patches/torchtitan/distributed/flex_shard/_optimizer_reshard_schedule.py", | ||
| 5 | + "torchtitan_npu/patches/torchtitan/distributed/flex_shard/dist_muon.py", | ||
| 6 | + "torchtitan_npu/patches/torchtitan/distributed/flex_shard/optimizer_reshard.py", | ||
| 7 | + "torchtitan_npu/patches/torchtitan/distributed/flex_shard/replica_dedup.py", | ||
| 8 | + "torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py", | ||
| 9 | + "torchtitan_npu/patches/torchtitan/hf_datasets/text_datasets.py", | ||
| 10 | + "torchtitan_npu/patches/torchtitan/models/common/rope.py" | ||
| 11 | + ] | ||
| 12 | + }, | ||
| 13 | + "import": [ | ||
| 14 | + {"source": "torchtitan_npu/extensions/adaptor/torchao/converter.py", "target_module": "torchtitan_npu.models.common.metadata_extension"}, | ||
| 15 | + {"source": "torchtitan_npu/extensions/adaptor/torchao/converter.py", "target_module": "torchtitan_npu.models.deepseek_v4.compressor"}, | ||
| 16 | + {"source": "torchtitan_npu/extensions/adaptor/torchao/converter.py", "target_module": "torchtitan_npu.models.deepseek_v4_1.attention"}, | ||
| 17 | + {"source": "torchtitan_npu/extensions/adaptor/torchao/converter.py", "target_module": "torchtitan_npu.models.deepseek_v4_1.compressor"}, | ||
| 18 | + {"source": "torchtitan_npu/extensions/adaptor/torchao/converter.py", "target_module": "torchtitan_npu.models.deepseek_v4_1.indexer"}, | ||
| 19 | + {"source": "torchtitan_npu/extensions/adaptor/torchao/converter.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"}, | ||
| 21 | + {"source": "torchtitan_npu/extensions/experiment/cv_parallel/batch_chunk_metadata.py", "target_module": "torchtitan_npu.models.common.metadata_extension"}, | ||
| 22 | + {"source": "torchtitan_npu/extensions/experiment/cv_parallel/batch_chunk_metadata.py", "target_module": "torchtitan_npu.models.deepseek_v4.metadata"}, | ||
| 23 | + {"source": "torchtitan_npu/extensions/experiment/cv_parallel/batch_chunk_metadata.py", "target_module": "torchtitan_npu.override.deepseek_v4.sparse_attn.ascendc"}, | ||
| 24 | + {"source": "torchtitan_npu/extensions/experiment/cv_parallel/batch_chunk_token_dispatcher.py", "target_module": "torchtitan_npu.ops.ascendc.moe_token_permute"}, | ||
| 25 | + {"source": "torchtitan_npu/extensions/experiment/cv_parallel/batch_chunk_token_dispatcher.py", "target_module": "torchtitan_npu.override.common.token_dispatcher"}, | ||
| 26 | + {"source": "torchtitan_npu/extensions/torchtitan/experiments/torchft/trainer.py", "target_module": "torchtitan_npu.models.deepseek_v4.model"}, | ||
| 27 | + {"source": "torchtitan_npu/extensions/torchtitan/trainer.py", "target_module": "torchtitan_npu.override.common.optimizer"}, | ||
| 28 | + {"source": "torchtitan_npu/patches/torchtitan/models/qwen3_5/vision_encoder.py", "target_module": "torchtitan_npu.extensions.torchtitan.eager_flex"} | ||
| 29 | + ], | ||
| 30 | + "activation_order": { | ||
| 31 | + "torchtitan_npu/extensions/__init__.py": [ | ||
| 32 | + ".torchtitan.ep_process_group", | ||
| 33 | + ".torchtitan.trainer", | ||
| 34 | + ".torchtitan.components.metrics", | ||
| 35 | + ".torchtitan.experiments.graph_trainer", | ||
| 36 | + ".torchtitan.tools.utils", | ||
| 37 | + ".torchtitan.eager_flex" | ||
| 38 | + ], | ||
| 39 | + "torchtitan_npu/patches/torchtitan/__init__.py": [ | ||
| 40 | + ".components.checkpoint", | ||
| 41 | + ".trainer", | ||
| 42 | + ".components.metrics", | ||
| 43 | + ".components.optimizer", | ||
| 44 | + ".components.validate", | ||
| 45 | + ".distributed.context_parallel", | ||
| 46 | + ".distributed.full_dtensor", | ||
| 47 | + ".distributed.parallel_dims", | ||
| 48 | + ".distributed.flex_shard.dist_muon", | ||
| 49 | + ".experiments.graph_trainer.chunked_loss", | ||
| 50 | + ".experiments.graph_trainer.ep_chunk_concretization", | ||
| 51 | + ".experiments.graph_trainer.ep_overlap_shape_queries", | ||
| 52 | + ".experiments.graph_trainer.ep_ready_nodes_dedup", | ||
| 53 | + ".experiments.graph_trainer.ep_shape_live_out", | ||
| 54 | + ".models.common.decoder", | ||
| 55 | + ".models.common.moe", | ||
| 56 | + ".models.common.rope", | ||
| 57 | + ".models.common.token_dispatcher" | ||
| 58 | + ] | ||
| 59 | + } | ||
| 60 | +} | ||
| @@ -26,7 +26,7 @@ source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/common.sh" | |||
| 26 | SMOKE_DESELECT=( | 26 | SMOKE_DESELECT=( |
| 27 | --deselect tests/smoke_tests/ops/test_mhc_triton.py | 27 | --deselect tests/smoke_tests/ops/test_mhc_triton.py |
| 28 | --deselect tests/smoke_tests/ops/test_qwen3_5_npu_runtime.py::test_merged_gdn_forward_backward | 28 | --deselect tests/smoke_tests/ops/test_qwen3_5_npu_runtime.py::test_merged_gdn_forward_backward |
| 29 | - --deselect tests/smoke_tests/sdc/test_sdc.py::test_three_gradient_strikes_activate_checksum_without_recompiling | 29 | + --deselect tests/smoke_tests/sdc/test_sdc_smoke.py::test_three_gradient_strikes_activate_checksum_without_recompiling |
| 30 | ) | 30 | ) |
| 31 | 31 | ||
| 32 | SMOKE_TESTS_START="$(date +%s)" | 32 | SMOKE_TESTS_START="$(date +%s)" |
| @@ -109,7 +109,11 @@ venv.bak/ | |||
| 109 | .opencode/* | 109 | .opencode/* |
| 110 | !.opencode/AGENTS.md | 110 | !.opencode/AGENTS.md |
| 111 | !.opencode/skills | 111 | !.opencode/skills |
| 112 | +.codex/* | ||
| 113 | +!.codex/AGENTS.md | ||
| 114 | +!.codex/skills | ||
| 112 | outputs/ | 115 | outputs/ |
| 116 | +third_party/ | ||
| 113 | 117 | ||
| 114 | # Third-party source trees are managed as submodules and are not scanned as project code. | 118 | # Third-party source trees are managed as submodules and are not scanned as project code. |
| 115 | /third_party/ | 119 | /third_party/ |
| @@ -80,6 +80,12 @@ repos: | |||
| 80 | # OAT compliance check (Open Source Audit Tool) | 80 | # OAT compliance check (Open Source Audit Tool) |
| 81 | - repo: local | 81 | - repo: local |
| 82 | hooks: | 82 | hooks: |
| 83 | + - id: architecture-boundaries | ||
| 84 | + name: Architecture boundary ratchet | ||
| 85 | + entry: python scripts/check_architecture_boundaries.py | ||
| 86 | + language: system | ||
| 87 | + pass_filenames: false | ||
| 88 | + stages: [pre-commit] | ||
| 83 | - id: oat-check | 89 | - id: oat-check |
| 84 | name: OAT Compliance Check | 90 | name: OAT Compliance Check |
| 85 | entry: bash scripts/oat_check.sh | 91 | entry: bash scripts/oat_check.sh |
| @@ -0,0 +1,25 @@ | |||
| 1 | +# torchtitan-npu 仓库规则 | ||
| 2 | + | ||
| 3 | +本文件是跨平台可读的仓库入口。通用开发流程、测试和验证要求见[完整开发指南](.agents/AGENTS.md);目录级规则优先于本文件。 | ||
| 4 | + | ||
| 5 | +## 代码归属 | ||
| 6 | + | ||
| 7 | +| 路径 | 职责 | | ||
| 8 | +| --- | --- | | ||
| 9 | +| `torchtitan_npu/config/` | 配置 schema、转换器和注册 API | | ||
| 10 | +| `torchtitan_npu/patches/` | 上游或 runtime compatibility patch | | ||
| 11 | +| `torchtitan_npu/extensions/` | 永久扩展、可选 adaptor 和组件集成 | | ||
| 12 | +| `torchtitan_npu/override/` | 由 `override.imports` 显式启用的组件替换 | | ||
| 13 | +| `torchtitan_npu/models/` | 模型配置、实现、并行化和 checkpoint 适配 | | ||
| 14 | +| `torchtitan_npu/ops/` | NPU 专属算子与后端注册 | | ||
| 15 | +| `torchtitan_npu/tools/` | 随 package 分发的转换和导出工具 | | ||
| 16 | +| `scripts/` | 仓库维护、训练和合规脚本 | | ||
| 17 | +| `tests/` | CPU UT、NPU smoke/ST 与 tooling 自测 | | ||
| 18 | + | ||
| 19 | +新增或迁移代码先读取[架构边界](docs/architecture.md)及目标目录的 `AGENTS.md`。当前自动导入顺序为 `patches → config → extensions → ops`;`patches → extensions` 是后续收敛目标。extensions 可以依赖 patches;patches 不得新增对 extensions 的依赖。 | ||
| 20 | + | ||
| 21 | +## 上游与验证 | ||
| 22 | + | ||
| 23 | +`requirements.txt` 声明 torchtitan 版本,`.ci/setup_torchtitan.sh` 从该版本推导对应 tag。更新版本时同步核对 patch 目标、接口和测试。 | ||
| 24 | + | ||
| 25 | +完整 lint、测试分层和数值验证要求见[完整开发指南](.agents/AGENTS.md)及[测试规则](tests/AGENTS.md)。`gitcode-pr` 与 `gitcode-pipeline` 是已安装相应 skill 时的可选工作流;仓库本身不提供这些 skill。 | ||
| @@ -232,34 +232,40 @@ pip install -e . | |||
| 232 | 232 | ||
| 233 | # 项目结构 | 233 | # 项目结构 |
| 234 | 234 | ||
| 235 | -`torchtitan-npu` 是 `torchtitan` 的 Ascend NPU 适配层,主要通过三类机制扩展上游能力:`override/` 使用配置级 `@override` 替换组件,并通过 `override.imports` 显式启用;`patches/` 补齐 PyTorch NPU backend 缺口,以及当前依赖版本尚未包含的临时上游能力;`extensions/` 提供 NPU 的扩展能力。模型实现与并行化策略放在 `models/`,CANN 和设备专属算子封装放在 `ops/`。此外,`config/` 提供配置注册与管理,`compile/` 提供编译期扩展,`distributed/` 提供 NPU 后端 HF32 控制。 | 235 | +`torchtitan-npu` 是 `torchtitan` 的 Ascend NPU 适配层,主要通过三类机制扩展上游能力:`override/` 使用配置级 `@override` 替换组件,并通过 `override.imports` 显式启用;`patches/` 补齐 PyTorch NPU backend 缺口,以及当前依赖版本尚未包含的临时上游能力;`extensions/` 提供 NPU 的训练组件、编译和运行期扩展,其中只有包入口显式导入的模块会自动生效,其他模块按调用路径加载。模型实现与并行化策略放在 `models/`,CANN 和设备专属算子封装放在 `ops/`,`config/` 提供配置 schema 与转换,`tools/` 提供随 Python package 分发的离线工具。 |
| 236 | 236 | ||
| 237 | ```text | 237 | ```text |
| 238 | torchtitan-npu/ | 238 | torchtitan-npu/ |
| 239 | ├── torchtitan_npu/ | 239 | ├── torchtitan_npu/ |
| 240 | -│ ├── models/ # 模型实现与并行化(DeepSeek-V3.2/V4/V4.1、Qwen3.5) | ||
| 241 | -│ ├── override/ # 配置级组件替换,含 common 与各模型专属目录 | ||
| 242 | -│ ├── patches/ # 补齐 PyTorch NPU backend 缺口与临时上游能力 | ||
| 243 | -│ ├── extensions/ # 随 package 导入自动生效的运行时扩展 | ||
| 244 | -│ │ ├── components/ # 训练组件扩展(checkpoint/metrics 等) | ||
| 245 | -│ │ ├── experiment/ # 实验性质的特性 | ||
| 246 | -│ │ │ └── torchft/ # TorchFT 容错训练适配 | ||
| 247 | -│ │ ├── novaswap/ # NovaSwap 显存交换扩展 | ||
| 248 | -│ │ └── tools/ # 工具扩展 | ||
| 249 | │ ├── config/ # 配置注册与管理(configs/manager 等) | 240 | │ ├── config/ # 配置注册与管理(configs/manager 等) |
| 250 | -│ ├── compile/ # 编译期扩展(SDC checksum pass) | 241 | +│ ├── patches/ # PyTorch/torch_npu 补丁与临时上游能力 |
| 251 | -│ ├── distributed/ # NPU 后端 HF32 控制(set_allow_hf32) | 242 | +│ ├── extensions/ # 永久训练、编译和运行期扩展 |
| 243 | +│ │ ├── torchtitan/ # 按上游 torchtitan 目录镜像的扩展 | ||
| 244 | +│ │ │ ├── components/ # checkpoint、metrics、LoRA、optimizer 扩展 | ||
| 245 | +│ │ │ ├── distributed/ # FSDP 扩展 | ||
| 246 | +│ │ │ ├── experiments/ # GraphTrainer 与 TorchFT 扩展 | ||
| 247 | +│ │ │ └── tools/ # profiler 与上游工具扩展 | ||
| 248 | +│ │ ├── adaptor/ # TorchAO-NPU 等可选外部包适配,按需导入 | ||
| 249 | +│ │ ├── compile/ # 编译期扩展(SDC checksum pass) | ||
| 250 | +│ │ ├── components/ # 本仓训练组件及接线逻辑 | ||
| 251 | +│ │ ├── cpu_offload/ # CPU offload 运行时与 staging | ||
| 252 | +│ │ ├── distributed/ # 梯度累积与梯度裁剪扩展 | ||
| 253 | +│ │ ├── experiment/ # Anticipatory Routing、CV Parallel 等实验能力 | ||
| 254 | +│ │ ├── mx_storage_reader/ # MX 量化权重读取能力 | ||
| 255 | +│ │ └── novaswap/ # NovaSwap 显存交换扩展 | ||
| 256 | +│ ├── override/ # 配置级组件替换,含 common 与模型专属目录 | ||
| 257 | +│ ├── models/ # 模型实现与并行化(DeepSeek-V3.2/V4/V4.1、Qwen3.5) | ||
| 252 | │ ├── ops/ # CANN 与 NPU 专属算子封装 | 258 | │ ├── ops/ # CANN 与 NPU 专属算子封装 |
| 253 | │ │ ├── ascendc/ # AscendC 算子适配(导入时自动加载) | 259 | │ │ ├── ascendc/ # AscendC 算子适配(导入时自动加载) |
| 254 | │ │ ├── misc/ # 杂项算子 | 260 | │ │ ├── misc/ # 杂项算子 |
| 255 | │ │ ├── pypto/ # PyPTO 算子 | 261 | │ │ ├── pypto/ # PyPTO 算子 |
| 256 | │ │ ├── tilelang/ # TileLang 融合算子 | 262 | │ │ ├── tilelang/ # TileLang 融合算子 |
| 257 | │ │ └── triton/ # Triton 算子(MHC/GDN 等) | 263 | │ │ └── triton/ # Triton 算子(MHC/GDN 等) |
| 264 | +│ ├── tools/ # 随 package 分发的 checkpoint 转换与导出工具 | ||
| 258 | │ ├── __init__.py # 导入 package patch 与 extension | 265 | │ ├── __init__.py # 导入 package patch 与 extension |
| 259 | │ └── train.py # 训练入口 | 266 | │ └── train.py # 训练入口 |
| 260 | ├── examples/ # 各模型训练示例脚本与说明 | 267 | ├── examples/ # 各模型训练示例脚本与说明 |
| 261 | ├── experiments/ # 实验性适配包(torchao-npu 量化) | 268 | ├── experiments/ # 实验性适配包(torchao-npu 量化) |
| 262 | -├── interfaces/ # 量化接入接口(torchao_converter) | ||
| 263 | ├── scripts/ # 训练与仓库辅助脚本 | 269 | ├── scripts/ # 训练与仓库辅助脚本 |
| 264 | ├── tests/ # 单元测试和测试数据 | 270 | ├── tests/ # 单元测试和测试数据 |
| 265 | └── docs/ # 使用指南与设计说明 | 271 | └── docs/ # 使用指南与设计说明 |
| @@ -0,0 +1,31 @@ | |||
| 1 | +# 文档规则 | ||
| 2 | + | ||
| 3 | +撰写、改写或审阅本目录的 README、架构说明、功能说明、操作指南、设计计划或验证报告时,使用 [write-torchtitan-npu-docs](../.agents/skills/write-torchtitan-npu-docs/SKILL.md)。本文件规定文档归属和边界;skill 负责事实核对、中文技术表达、命令校验与交付检查。 | ||
| 4 | + | ||
| 5 | +## 文档归属 | ||
| 6 | + | ||
| 7 | +每个事实只在一个文档中完整解释,其他位置链接到它。文档树位置决定允许的细节,子文档拥有的实现细节不要复制到上层。 | ||
| 8 | + | ||
| 9 | +| 位置 | 职责 | | ||
| 10 | +| --- | --- | | ||
| 11 | +| `architecture.md` | 正式目标架构:目标布局、目录职责、导入/启用关系和验证边界;迁移阶段同步更新 | | ||
| 12 | +| `developer_guides/` | 开发者使用的配置、lint、测试、checkpoint、指标与调试规则 | | ||
| 13 | +| `feature_guides/` | 某项模型、并行、算子或优化能力的行为、启用方式、限制和验证 | | ||
| 14 | +| `user-guides/` | 安装、快速开始和面向使用者的操作说明 | | ||
| 15 | +| `community/` | 治理、贡献和版本等社区规则 | | ||
| 16 | +| `.agents/notes/` | 迁移步骤、替代方案、风险、决策取舍和当前阶段状态;不替代目标架构说明 | | ||
| 17 | + | ||
| 18 | +教程应按完成目标所需的前提顺序组织;参考文档定义稳定的查询范围和当前行为,不按教学步骤叙述。文档类型不扩大其负责范围。 | ||
| 19 | + | ||
| 20 | +## 写作规则 | ||
| 21 | + | ||
| 22 | +- `architecture.md` 可以规定目标正式结构;功能、开发者和用户文档只描述当前已实现事实,不将 PR、提交、迁移进度或未来目录写成当前行为。设计背景和阶段状态链接到 Agent Note。 | ||
| 23 | +- 首先说明读者需要的启用方式、适用条件和限制,再展开内部实现。能力受硬件、runtime、dtype、shape、layout、并行方式或激活模块影响时,明确这些边界。 | ||
| 24 | +- 中文优先;路径、命令、配置键、模块名、环境变量和其他机器可读标识符保持原样。命令必须有源码、配置、脚本或测试依据。 | ||
| 25 | +- 不宣称未经测量的性能或数值结论;区分已实现、已验证、有限支持、未验证和计划中。 | ||
| 26 | +- 不复制完整源码、文件清单、测试清单或另一个文档已拥有的细节。关系复杂时才使用表格、流程图或目录树。 | ||
| 27 | +- 文档变更如影响目标架构、功能启用、支持范围或命令,同步更新拥有该事实的当前态文档;非局部架构决定同时更新或新增 Agent Note。 | ||
| 28 | + | ||
| 29 | +## 验证与交付 | ||
| 30 | + | ||
| 31 | +按 skill 的“验证交付”流程核对链接、路径、配置、注册名、命令、支持范围和验证状态。运行成本可控的相关检查;不为文档校对无理由触发昂贵 NPU 训练,也不把未执行或替代命令写成已通过。 | ||
| @@ -0,0 +1,86 @@ | |||
| 1 | +# torchtitan-npu 架构边界 | ||
| 2 | + | ||
| 3 | +本文区分当前实现、禁止新增的依赖与后续目标。当前行为以源码为准;迁移状态和历史债务记录在[目录与注入边界提案](../.agents/notes/proposed/architecture/2026-09-02-plugin-layout-and-injection-boundaries.md)。 | ||
| 4 | + | ||
| 5 | +## Repository layout | ||
| 6 | + | ||
| 7 | +```text | ||
| 8 | +torchtitan_npu/ Ascend NPU 插件主体 | ||
| 9 | +experiments/ 独立实验包;当前包含 torchao-npu distribution | ||
| 10 | +docs/ 架构、开发者、功能和用户文档 | ||
| 11 | +examples/ 可运行 recipe、模型配置与示例 launcher | ||
| 12 | +scripts/ 训练、转换、合规检查与辅助脚本 | ||
| 13 | +tests/ CPU UT、NPU ST 与 tooling 自测 | ||
| 14 | +.agents/ Agent Notes 与可复用 skills | ||
| 15 | +``` | ||
| 16 | + | ||
| 17 | +根目录只保留工程配置、包/训练入口及上述目录。`third_party/` 的普通内容默认忽略;已跟踪的 `third_party/agent-skills/KPBot` 是 submodule。不新增其他生产代码落点。 | ||
| 18 | + | ||
| 19 | +## 插件主体 | ||
| 20 | + | ||
| 21 | +`torchtitan_npu/` 的正式生产子包为 `config/`、`patches/`、`extensions/`、`override/`、`models/`、`ops/` 与 `tools/`。可选外部包适配位于 `extensions/adaptor/`。 | ||
| 22 | + | ||
| 23 | +| 子包 | 职责 | 直接依赖边界 | | ||
| 24 | +| --- | --- | --- | | ||
| 25 | +| `config/` | NPU config schema、纯转换器和显式注册 API | 当前包导入会安装 ConfigManager loader wrapper;目标是移至 extension 激活入口且不反向导入具体 extension | | ||
| 26 | +| `patches/` | 上游 `torchtitan` 或 `torch_npu` 的待合入补丁 | 不得新增对 `extensions/` 的依赖;现有反向边记录为迁移债务 | | ||
| 27 | +| `models/` | 尚未上游化的模型定义、配置、并行化与 checkpoint 适配 | 现有跨层依赖为迁移债务,不以本文宣称已清零 | | ||
| 28 | +| `extensions/` | 本仓永久额外扩展、组件集成与图编译注册 | 可以依赖 `patches/` 提供的定义;不得新增对 `models/`、`override/` 或 `ops/` 的依赖 | | ||
| 29 | +| `extensions/adaptor/` | 可选外部 distribution 的适配器 | 使用公开配置、模型、算子或 extension API;对 patch 私有符号的现有使用为迁移债务 | | ||
| 30 | +| `override/` | `override.imports` 显式启用的 NPU/CANN 组件替换 | 可使用 `ops/`;现有对 `extensions/` 的依赖为迁移债务 | | ||
| 31 | +| `ops/` | 设备后端 kernel、最小启动封装与 `torch.library` 注册 | 仅保留实现算子所需的后端代码 | | ||
| 32 | +| `tools/` | 随 package 分发的 checkpoint 转换与导出工具 | 依赖公开模型与 integration API,不承载训练期自动注入 | | ||
| 33 | + | ||
| 34 | +模型无关能力放在最通用的适用位置。完整的开发约束见 [主包规则](../torchtitan_npu/AGENTS.md) 及其目录级规则。 | ||
| 35 | + | ||
| 36 | +## 导入与启用 | ||
| 37 | + | ||
| 38 | +当前 `torchtitan_npu/__init__.py` 的自动导入顺序是: | ||
| 39 | + | ||
| 40 | +```text | ||
| 41 | +patches → config → extensions → ops | ||
| 42 | +``` | ||
| 43 | + | ||
| 44 | +这是当前运行时行为,不是目标顺序。`patches` 先替换上游实现;`extensions` 可从 `torchtitan_npu.patches.*` 复用 patch 提供的定义,也可经 `torchtitan.*`、`torch.*` 或 `torch_npu.*` 使用已替换结果。反向的 `patches → extensions` 依赖不得新增。 | ||
| 45 | + | ||
| 46 | +`config` 当前导入 `manager` 时会安装 `ConfigManager._load_config` 的转换 wrapper;该副作用是现有配置转换链的一部分。将其改为仅由 extension 激活入口安装是后续目标,不是当前行为。 | ||
| 47 | + | ||
| 48 | +`override` 不自动加载;一次训练由 `override.imports` 显式选择。将自动导入收敛为下列顺序是后续目标,不能据此描述当前行为: | ||
| 49 | + | ||
| 50 | +```text | ||
| 51 | +patches → extensions → selected override | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +> **当前未实现。** `TORCHTITAN_NPU_DISABLE_EXTENSIONS` 与 `TORCHTITAN_NPU_DISABLE_COMPONENTS` 仅是目标加载接口,当前包入口仍会无条件加载已有 extension;不得将它们作为可用运行时配置。 | ||
| 55 | + | ||
| 56 | +实现后,`TORCHTITAN_NPU_DISABLE_EXTENSIONS=1` 只禁用 extensions。`TORCHTITAN_NPU_DISABLE_COMPONENTS=1` 禁用全部已声明组件,逗号分隔组件名只禁用对应组件;两个开关都不得破坏 patches、models、override 或 ops 的可导入性。 | ||
| 57 | + | ||
| 58 | +### 两阶段时序语义 | ||
| 59 | + | ||
| 60 | +`patches` 与 `extensions` 是不同的注入阶段。`patches` 承载尚未合入上游的替身,能够在显式激活顺序中替换类、函数和 `.Config` schema;影响 dataclass schema 或默认工厂的替换必须早于依赖该符号的模块。`patches/torchtitan/__init__.py` 的现有导入顺序是运行时契约,必须通过显式列表和测试维护,不以「trainer 必须最后导入」这类与当前实现不符的绝对规则约束。 | ||
| 61 | + | ||
| 62 | +patch 替换后必须刷新或说明上游 `from ... import ...` 已捕获的绑定;无法穷尽捕获点时,改用公开注册机制或 extension。extensions 默认上游模块和 dataclass 都已存在,因此不依赖早期导入,也不替换被上游 dataclass 捕获的 `.Config`。它只使用配置外包装、运行期方法 seam、单目标 hook 注册组件或公开注册 API(例如 `torch.library`、graph-pass registry)。不属于 patches 且无法通过这些机制实现的能力,不以 monkey-patch 落地,而应提出稳定扩展点或扩展本仓配置外包装。 | ||
| 63 | + | ||
| 64 | +## 目标子层 | ||
| 65 | + | ||
| 66 | +### patches | ||
| 67 | + | ||
| 68 | +`patches/torchtitan/` 镜像上游模块路径。新增实际 patch 模块在许可证头后的固定头部区域使用 `Upstream-PR:` 记录上游依据;`__init__.py` 与 `patches/torch_npu/` runtime compatibility patch 不适用该要求。当前 architecture ratchet 同时兼容历史 `Pending upstream PR`/`Upstream PR` 标记,并允许基线中已登记的缺失项,因此它只阻止新增元数据债务。上游合入并升级 pinned 依赖后删除该 patch 和激活入口。强制 eager 的上游行为兼容放 `extensions/torchtitan/`。 | ||
| 69 | + | ||
| 70 | +带副作用的 monkey-patch 模块把变更收敛至 `apply()` 并在模块末尾调用,由所属 `__init__.py` 显式导入激活。其他模块不得导入带 `apply()` 的模块;定义型无副作用模块可按需复用。替换必须使用完整点路径赋值。 | ||
| 71 | + | ||
| 72 | +### extensions | ||
| 73 | + | ||
| 74 | +`extensions/torchtitan/` 放镜像上游结构的 monkey-patch 激活模块;新增替换必须声明 owner 和顺序。现有 `MetricsProcessor.log`、`CheckpointManager` 与 `ConfigManager._load_config` 的多层包装保留为历史例外,包装顺序由对应测试保护,本轮不合并其业务行为。`extensions/components/` 放带声明名称的自包含集成;当前 TrainerEx、checkpoint extension 和 DeepSeek-V4.1 配置仍存在组件顶层接线或反向使用,这是迁移债务,不是新组件约束。`extensions/compile/` 放 graph-pass 注册基础设施和具体 pattern。 | ||
| 75 | + | ||
| 76 | +`extensions/` 当前还包含 `adaptor/`、`cpu_offload/`、`distributed/`、`mx_storage_reader/`、`novaswap/` 与 `experiment/`。其中仅包入口显式列出的模块自动加载;其余目录由调用路径按需导入。各目录的职责和加载方式见 [extensions 规则](../torchtitan_npu/extensions/AGENTS.md)。 | ||
| 77 | + | ||
| 78 | +### override、models 与 ops | ||
| 79 | + | ||
| 80 | +override 使用 `@override` 注册并由完整 `module.function` 选择;它保持输入输出、DTensor、sharding、checkpoint 与 `torch.compile` 语义。依赖 extension 的 override 显式声明此前提;extension 禁用时 warn-once 是禁用开关落地后的目标行为。 | ||
| 81 | + | ||
| 82 | +目标上 models 保持对 NPU 实现细节的零直接依赖,需要 kernel 时经上游或 override 注入。当前 DeepSeek-V4/V4.1 与 Qwen3.5 仍有 extension 或 override 的直接导入,属于已登记的迁移债务;新增模型代码不得复制这种模式。ops 按后端或语言组织,后端目录声明 token,算子命名为 `torchtitan_npu::{backend}_{kernel}`。ops 不放上游替换或组件封装,反向通过 `register_autograd` 注册,且 `ops/__init__.py` 不批量导入子模块。 | ||
| 83 | + | ||
| 84 | +## 验证 | ||
| 85 | + | ||
| 86 | +架构迁移阶段同步更新代码、根与受影响目录的 `AGENTS.md`、本文及 Agent Note。使用 CPU UT、NPU ST 和数值验证证明训练入口、override 选择、checkpoint 语义与已验证数值行为不回归。具体测试与数值要求见 [根开发规则](../.agents/AGENTS.md) 和 [测试规则](../tests/AGENTS.md)。 | ||
| @@ -47,7 +47,7 @@ class TrainingExtensionConfig: | |||
| 47 | 47 | ||
| 48 | 1. 在 `torchtitan_npu/config/configs.py` 中定义 NPU 配置类型,并继承对应的上游类型。 | 48 | 1. 在 `torchtitan_npu/config/configs.py` 中定义 NPU 配置类型,并继承对应的上游类型。 |
| 49 | 2. 在 `TrainerEx.Config` 中将该字段声明为 NPU 配置类型。 | 49 | 2. 在 `TrainerEx.Config` 中将该字段声明为 NPU 配置类型。 |
| 50 | -3. 在 `torchtitan_npu/extensions/trainer.py` 的 `component_types` 中加入字段名和配置类型。 | 50 | +3. 在 `torchtitan_npu/extensions/torchtitan/trainer.py` 的 `component_types` 中加入字段名和配置类型。 |
| 51 | 4. 在对应 Trainer 或组件中读取并应用新增字段。 | 51 | 4. 在对应 Trainer 或组件中读取并应用新增字段。 |
| 52 | 52 | ||
| 53 | 字段需要独立的 NPU 命名空间时,优先增加 `extension` 子配置;字段本身属于组件的公开 | 53 | 字段需要独立的 NPU 命名空间时,优先增加 `extension` 子配置;字段本身属于组件的公开 |
| @@ -11,7 +11,7 @@ | |||
| 11 | `tests/unit_tests/` 是 CPU 测试的统一执行根目录。生产语义测试按 `torchtitan_npu/` 的职责镜像放置: | 11 | `tests/unit_tests/` 是 CPU 测试的统一执行根目录。生产语义测试按 `torchtitan_npu/` 的职责镜像放置: |
| 12 | 12 | ||
| 13 | - `tests/unit_tests/compile/`、`config/`、`models/`、`ops/` 和 `override/` 分别保护对应的生产模块; | 13 | - `tests/unit_tests/compile/`、`config/`、`models/`、`ops/` 和 `override/` 分别保护对应的生产模块; |
| 14 | -- `tests/unit_tests/patches/torchtitan/` 只镜像有上游依据的临时 patch;`tests/unit_tests/patches/torch_npu/` 和 `tests/unit_tests/patches/workaround/` 镜像当前有效的 NPU runtime compatibility patch; | 14 | +- `tests/unit_tests/patches/torchtitan/` 只镜像有上游依据的临时 patch;`tests/unit_tests/patches/torch_npu/` 镜像当前有效的 NPU runtime compatibility patch; |
| 15 | - `tests/unit_tests/tooling/` 放仓库脚本和 skill 的自测,便于沿用现有 unit-test 入口执行,但这类测试不计入产品行为覆盖; | 15 | - `tests/unit_tests/tooling/` 放仓库脚本和 skill 的自测,便于沿用现有 unit-test 入口执行,但这类测试不计入产品行为覆盖; |
| 16 | - 多进程 worker 与启动它的测试放在同一个语义目录; | 16 | - 多进程 worker 与启动它的测试放在同一个语义目录; |
| 17 | - `tests/integration_tests/` 只放进入真实 `torchtitan.train` 的 NPU 模型 ST,不把 CPU UT、kernel pytest 或 runner 自测计入 ST。 | 17 | - `tests/integration_tests/` 只放进入真实 `torchtitan.train` 的 NPU 模型 ST,不把 CPU UT、kernel pytest 或 runner 自测计入 ST。 |
| @@ -29,7 +29,7 @@ tests/unit_tests/tooling/training_log_visualization/test_training_log_visualizat | |||
| 29 | 29 | ||
| 30 | `torchtitan_npu/patches/torchtitan/` 只保存当前固定上游版本尚未包含、且已有上游 PR 或 commit 依据的临时 patch。上游版本吸收对应改动后,应删除 patch、导入入口和专用测试。 | 30 | `torchtitan_npu/patches/torchtitan/` 只保存当前固定上游版本尚未包含、且已有上游 PR 或 commit 依据的临时 patch。上游版本吸收对应改动后,应删除 patch、导入入口和专用测试。 |
| 31 | 31 | ||
| 32 | -`torchtitan_npu/patches/torch_npu/` 与 `torchtitan_npu/patches/workaround/` 的现有文件不是「上游 torchtitan 临时 patch」:它们改变 PyTorch、Inductor 或 `torch_npu` 的运行时行为,例如 `determinism.py` 替换 `torch.use_deterministic_algorithms`,`device_copy.py` 修改 Inductor 的 `DeviceCopy` 和 `prims.device_put`。这两个目录是当前有效的 runtime compatibility 归属,可以继续维护;本次测试目录整理不移动生产代码,也不要求新增 `runtime/compat` 层。若未来要迁移,必须另开包含导入时机、兼容别名和真实激活测试的原子架构变更。 | 32 | +`torchtitan_npu/patches/torch_npu/` 中的文件不是「上游 torchtitan 临时 patch」:它们改变 PyTorch、Inductor 或 `torch_npu` 的 NPU 运行时行为,例如 `determinism.py` 替换 `torch.use_deterministic_algorithms`,`device_copy.py` 修改 Inductor 的 `DeviceCopy` 和 `prims.device_put`。对应测试镜像到 `tests/unit_tests/patches/torch_npu/`;强制 eager 的 TorchTitan 兼容行为则归 `extensions/torchtitan/`。 |
| 33 | 33 | ||
| 34 | ## 执行归属 | 34 | ## 执行归属 |
| 35 | 35 | ||
| @@ -157,7 +157,7 @@ engine 在初始化时包装当前 checkpointer 实例的 `save()`。恢复阶 | |||
| 157 | 157 | ||
| 158 | | 路径 | 职责 | | 158 | | 路径 | 职责 | |
| 159 | | ------------------------------------------------------------ | ------------------------------------------------------------------------------------ | | 159 | | ------------------------------------------------------------ | ------------------------------------------------------------------------------------ | |
| 160 | -| `torchtitan_npu/extensions/trainer.py` | 配置接入、一次初始化及训练上下文编排。 | | 160 | +| `torchtitan_npu/extensions/torchtitan/trainer.py` | 配置接入、一次初始化及训练上下文编排。 | |
| 161 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/config.py` | 声明恢复配置、参数范围及配置兼容性校验。 | | 161 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/config.py` | 声明恢复配置、参数范围及配置兼容性校验。 | |
| 162 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/engine.py` | 组件初始化、loss 汇总、仅前向隔离、checkpoint 选择及恢复、保存保护。 | | 162 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/engine.py` | 组件初始化、loss 汇总、仅前向隔离、checkpoint 选择及恢复、保存保护。 | |
| 163 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/schedule.py` | 管理 FIFO 队列、阶段转换、训练数据供应及 spike 响应。 | | 163 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/schedule.py` | 管理 FIFO 队列、阶段转换、训练数据供应及 spike 响应。 | |
| @@ -180,7 +180,7 @@ engine 在初始化时包装当前 checkpointer 实例的 `save()`。恢复阶 | |||
| 180 | `tests/unit_tests/extensions/experiment/anticipatory_routing/test_detector.py` 覆盖持续水平漂移、恒定 loss 后的微小噪声、 | 180 | `tests/unit_tests/extensions/experiment/anticipatory_routing/test_detector.py` 覆盖持续水平漂移、恒定 loss 后的微小噪声、 |
| 181 | 跨回滚及 ACTIVE/DRAIN 更新的冷却计数、非有限阈值校验、零回滚预算的 checkpoint 校验、PP 拒绝和 ID 存储类型边界。 | 181 | 跨回滚及 ACTIVE/DRAIN 更新的冷却计数、非有限阈值校验、零回滚预算的 checkpoint 校验、PP 拒绝和 ID 存储类型边界。 |
| 182 | 182 | ||
| 183 | -`tests/smoke_tests/anticipatory_routing/test_anticipatory_routing.py` 使用小型 NPU 路由模型和上游训练步,覆盖以下场景: | 183 | +`tests/smoke_tests/anticipatory_routing/test_anticipatory_routing_smoke.py` 使用小型 NPU 路由模型和上游训练步,覆盖以下场景: |
| 184 | 184 | ||
| 185 | - 一次性扰动 labels 引起真实 loss 升高,由自动检测器识别 spike 并触发回滚。 | 185 | - 一次性扰动 labels 引起真实 loss 升高,由自动检测器识别 spike 并触发回滚。 |
| 186 | - 选择并加载磁盘 DCP checkpoint,恢复模型、optimizer、LR scheduler、训练进度及 dataloader 状态。 | 186 | - 选择并加载磁盘 DCP checkpoint,恢复模型、optimizer、LR scheduler、训练进度及 dataloader 状态。 |
| @@ -173,7 +173,7 @@ CPU offload 与 SAR 之前把变异写入显式化为数据流,原生 SAR 随 | |||
| 173 | | SimpleFSDP | `torchtitan/experiments/graph_trainer/simple_fsdp.py` | | 173 | | SimpleFSDP | `torchtitan/experiments/graph_trainer/simple_fsdp.py` | |
| 174 | | 函数式 compressor | `torchtitan_npu/models/deepseek_v4/compressor.py` | | 174 | | 函数式 compressor | `torchtitan_npu/models/deepseek_v4/compressor.py` | |
| 175 | | 变异重算保真(functionalization backport) | `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py` | | 175 | | 变异重算保真(functionalization backport) | `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py` | |
| 176 | -| MoE 保存策略单测 | `tests/unit_tests/compile/test_swiglu_memory_policy.py` | | 176 | +| MoE 保存策略单测 | `tests/unit_tests/models/deepseek_v4/memory_policy/test_swiglu_memory_policy.py` | |
| 177 | 177 | ||
| 178 | ## 7. 结论 | 178 | ## 7. 结论 |
| 179 | 179 | ||
| @@ -199,7 +199,7 @@ FSDP 的参数通信和梯度通信是两个阶段:参数在模块计算前通 | |||
| 199 | 量化入口根据模型类型选择匹配规则,通过 converter 转换模型配置节点,并在模块构建时应用 TorchAO-NPU 量化。本文依据当前配置、转换逻辑和启动脚本整理,未在本文档重构中执行 NPU 训练;不同并行配置的精度与性能需在目标环境中验证。 | 199 | 量化入口根据模型类型选择匹配规则,通过 converter 转换模型配置节点,并在模块构建时应用 TorchAO-NPU 量化。本文依据当前配置、转换逻辑和启动脚本整理,未在本文档重构中执行 NPU 训练;不同并行配置的精度与性能需在目标环境中验证。 |
| 200 | 200 | ||
| 201 | - [量化配置字段](../../torchtitan_npu/config/configs.py) | 201 | - [量化配置字段](../../torchtitan_npu/config/configs.py) |
| 202 | -- [TorchAO-NPU converter 与 recipe](../../interfaces/torchao_converter.py) | 202 | +- [TorchAO-NPU converter 与 recipe](../../torchtitan_npu/extensions/adaptor/torchao/converter.py) |
| 203 | - [Block FP8 权重与 FSDP 预量化实现](../../experiments/torchao-npu/torchao_npu/wrapper_tensors/block_mx_wrapper_tensor.py) | 203 | - [Block FP8 权重与 FSDP 预量化实现](../../experiments/torchao-npu/torchao_npu/wrapper_tensors/block_mx_wrapper_tensor.py) |
| 204 | - [V4.1 Lightning Indexer 量化实现](../../experiments/torchao-npu/torchao_npu/quantized_modules/v41_lightning_indexer.py) | 204 | - [V4.1 Lightning Indexer 量化实现](../../experiments/torchao-npu/torchao_npu/quantized_modules/v41_lightning_indexer.py) |
| 205 | - [V4.1 稀疏 attention 量化实现](../../experiments/torchao-npu/torchao_npu/quantized_modules/v41_sparse_attention.py) | 205 | - [V4.1 稀疏 attention 量化实现](../../experiments/torchao-npu/torchao_npu/quantized_modules/v41_sparse_attention.py) |
| @@ -135,9 +135,9 @@ step 结束时恢复或切换;失败 step 的异常直接向上传播,不执 | |||
| 135 | 135 | ||
| 136 | | 路径 | 职责 | | 136 | | 路径 | 职责 | |
| 137 | | --- | --- | | 137 | | --- | --- | |
| 138 | -| `torchtitan_npu/extensions/trainer.py` | 编排标准 Trainer 与 SDC 生命周期。 | | 138 | +| `torchtitan_npu/extensions/torchtitan/trainer.py` | 编排标准 Trainer 与 SDC 生命周期。 | |
| 139 | | `torchtitan_npu/extensions/components/sdc/sdc.py` | 一次完成配置校验、HCCL、checksum 和 gradient 初始化;在 accumulation 边界直接提交梯度。 | | 139 | | `torchtitan_npu/extensions/components/sdc/sdc.py` | 一次完成配置校验、HCCL、checksum 和 gradient 初始化;在 accumulation 边界直接提交梯度。 | |
| 140 | -| `torchtitan_npu/compile/sdc_checksum.py`、`torchtitan_npu/ops/misc/sdc_checksum.py` | 安装 checksum pass 并注册 custom op。 | | 140 | +| `torchtitan_npu/extensions/compile/sdc_checksum.py`、`torchtitan_npu/ops/misc/sdc_checksum.py` | 安装 checksum pass 并注册 custom op。 | |
| 141 | 141 | ||
| 142 | ## 验证范围 | 142 | ## 验证范围 |
| 143 | 143 | ||
| @@ -145,7 +145,7 @@ step 结束时恢复或切换;失败 step 的异常直接向上传播,不执 | |||
| 145 | 通过 native checker 替身验证 typed tuning、参数筛选和累积提交,并检查 `TrainerEx` | 145 | 通过 native checker 替身验证 typed tuning、参数筛选和累积提交,并检查 `TrainerEx` |
| 146 | 在模型构建后一次初始化 SDC,失败 backward 不提交梯度。 | 146 | 在模型构建后一次初始化 SDC,失败 backward 不提交梯度。 |
| 147 | 147 | ||
| 148 | -`tests/smoke_tests/sdc/test_sdc.py` 为每个场景启动独立 Python worker,覆盖 Eager/compiled | 148 | +`tests/smoke_tests/sdc/test_sdc_smoke.py` 为每个场景启动独立 Python worker,覆盖 Eager/compiled |
| 149 | 控制与无效配置、BF16 gradient、checksum custom-op 输出修改、编译图 consumer、初始化通信后 | 149 | 控制与无效配置、BF16 gradient、checksum custom-op 输出修改、编译图 consumer、初始化通信后 |
| 150 | 启用 HCCL 的训练路径,以及 three-strikes 后不重新编译的 checksum 激活。该文件是专项 NPU | 150 | 启用 HCCL 的训练路径,以及 three-strikes 后不重新编译的 checksum 激活。该文件是专项 NPU |
| 151 | 冒烟测试,不替代 `tests/integration_tests` 中的完整模型训练验证。 | 151 | 冒烟测试,不替代 `tests/integration_tests` 中的完整模型训练验证。 |
| @@ -229,13 +229,13 @@ flowchart TB | |||
| 229 | `scripts/run_train.sh` 与 `scripts/run_train_multinodes.sh` 最终通过 `torchrun` 启动 | 229 | `scripts/run_train.sh` 与 `scripts/run_train_multinodes.sh` 最终通过 `torchrun` 启动 |
| 230 | `torchtitan_npu.train`。训练入口复用上游 `torchtitan.train.main`,同时导入 `torchtitan_npu` 触发插件初始化。 | 230 | `torchtitan_npu.train`。训练入口复用上游 `torchtitan.train.main`,同时导入 `torchtitan_npu` 触发插件初始化。 |
| 231 | 231 | ||
| 232 | -包初始化顺序为: | 232 | +当前包初始化顺序为: |
| 233 | 233 | ||
| 234 | ```text | 234 | ```text |
| 235 | -patches → compile → config → extensions → ops | 235 | +patches → config → extensions → ops |
| 236 | ``` | 236 | ``` |
| 237 | 237 | ||
| 238 | -该顺序是运行时契约。NPU patch 必须在模型构建和首次编译前生效。新增初始化逻辑不能随意调整此顺序。 | 238 | +`compile` 已迁入 `extensions/compile/`,不再是顶层自动导入阶段。该顺序是运行时契约。NPU patch 必须在模型构建和首次编译前生效。新增初始化逻辑不能随意调整此顺序。 |
| 239 | 239 | ||
| 240 | ### 5.2 模型和 loss 编译 | 240 | ### 5.2 模型和 loss 编译 |
| 241 | 241 | ||
| @@ -269,7 +269,7 @@ loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用 | |||
| 269 | 269 | ||
| 270 | | Patch | 解决的问题 | 设计边界 | | 270 | | Patch | 解决的问题 | 设计边界 | |
| 271 | | --- | --- | --- | | 271 | | --- | --- | --- | |
| 272 | -| `patches/workaround/device_copy.py` | non-blocking NPU-to-CPU copy 的 Host 可见性 | 只修正 NPU D2H 和 `prims.device_put`,不把 NPU 全局伪装为 GPU,避免误选 Triton 路径 | | 272 | +| `patches/torch_npu/device_copy.py` | non-blocking NPU-to-CPU copy 的 Host 可见性 | 只修正 NPU D2H 和 `prims.device_put`,不把 NPU 全局伪装为 GPU,避免误选 Triton 路径 | |
| 273 | | `patches/torch_npu/inductor_runtime_estimation.py` | 编译期 roofline 估算探测 CUDA/Triton,以及 standalone compile 的 GraphModule 复制路径 | 仅在 NPU 可用时安装;带宽常量只参与调度估算,不代表硬件峰值 | | 273 | | `patches/torch_npu/inductor_runtime_estimation.py` | 编译期 roofline 估算探测 CUDA/Triton,以及 standalone compile 的 GraphModule 复制路径 | 仅在 NPU 可用时安装;带宽常量只参与调度估算,不代表硬件峰值 | |
| 274 | 274 | ||
| 275 | 两个 patch 都依赖包导入时机。CPU-only import 能验证模块可加载,但不能证明 NPU 条件分支已经生效。 | 275 | 两个 patch 都依赖包导入时机。CPU-only import 能验证模块可加载,但不能证明 NPU 条件分支已经生效。 |
| @@ -320,10 +320,10 @@ loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用 | |||
| 320 | | 本仓 | `scripts/run_train.sh` | 单机启动与 AscendC 默认 Codegen | | 320 | | 本仓 | `scripts/run_train.sh` | 单机启动与 AscendC 默认 Codegen | |
| 321 | | 本仓 | `scripts/run_train_multinodes.sh` | 多机启动和 compile 参数;NPU backend 需在各节点显式统一 | | 321 | | 本仓 | `scripts/run_train_multinodes.sh` | 多机启动和 compile 参数;NPU backend 需在各节点显式统一 | |
| 322 | | 本仓 | `torchtitan_npu/train.py` | 复用上游训练入口并触发插件初始化 | | 322 | | 本仓 | `torchtitan_npu/train.py` | 复用上游训练入口并触发插件初始化 | |
| 323 | -| 本仓 | `torchtitan_npu/__init__.py` | 固定 patches、compile、config、extensions 和 ops 的加载顺序 | | 323 | +| 本仓 | `torchtitan_npu/__init__.py` | 固定 patches、config、extensions 和 ops 的加载顺序 | |
| 324 | -| 本仓 | `torchtitan_npu/patches/workaround/device_copy.py` | NPU 异步 D2H 和 `device_put` 兼容 | | 324 | +| 本仓 | `torchtitan_npu/patches/torch_npu/device_copy.py` | NPU 异步 D2H 和 `device_put` 兼容 | |
| 325 | | 本仓 | `torchtitan_npu/patches/torch_npu/inductor_runtime_estimation.py` | NPU runtime estimation 和 standalone compile 兼容 | | 325 | | 本仓 | `torchtitan_npu/patches/torch_npu/inductor_runtime_estimation.py` | NPU runtime estimation 和 standalone compile 兼容 | |
| 326 | -| 本仓 | `torchtitan_npu/extensions/trainer.py` | 编译感知的 NPU Trainer 与量化转换 | | 326 | +| 本仓 | `torchtitan_npu/extensions/torchtitan/trainer.py` | 编译感知的 NPU Trainer 与量化转换 | |
| 327 | | 上游/外部依赖 | `torchtitan.config.CompileConfig`、`torchtitan.distributed.compile` | 标准 compile 配置、Block 编译、Async TP 和 regional Inductor | | 327 | | 上游/外部依赖 | `torchtitan.config.CompileConfig`、`torchtitan.distributed.compile` | 标准 compile 配置、Block 编译、Async TP 和 regional Inductor | |
| 328 | | 外部依赖 | `torch_npu._inductor.ascendc` 与 CANN AutoFuse | NPU lowering、融合调度、tiling、Kernel 生成和编译 | | 328 | | 外部依赖 | `torch_npu._inductor.ascendc` 与 CANN AutoFuse | NPU lowering、融合调度、tiling、Kernel 生成和编译 | |
| 329 | 329 | ||
| @@ -0,0 +1,8 @@ | |||
| 1 | +# examples 规则 | ||
| 2 | + | ||
| 3 | +`examples/` 放置面向用户的 recipe launcher、参数组合和小规模 debug 入口。 | ||
| 4 | + | ||
| 5 | +- launcher 只组合已实现的 module、config 和 `override.imports`,不承载可复用生产逻辑。 | ||
| 6 | +- 保留用户传入的额外 CLI 参数;不在 wrapper 中隐式改变 checkpoint、数值或并行语义。 | ||
| 7 | +- 每个示例的模型、硬件代际、进程数、可选依赖和默认 override 必须可从脚本和相关文档中确认。 | ||
| 8 | +- `debug/` 只表示小规模调试配置,不代表数值或性能已验收。 | ||
| @@ -0,0 +1,7 @@ | |||
| 1 | +# experiments 规则 | ||
| 2 | + | ||
| 3 | +`experiments/` 放置具有独立打包、依赖和测试边界的实验性 distribution,不作为 `torchtitan_npu` 主包的自动导入层。 | ||
| 4 | + | ||
| 5 | +- 每个子项目保持独立 `pyproject.toml`、可选安装方式和自有测试。 | ||
| 6 | +- 主包不得因导入 `torchtitan_npu` 而要求实验包已安装;集成入口必须按需导入并在缺少依赖时给出清晰错误。 | ||
| 7 | +- 实验包达到稳定 API、版本、发布和验证要求后,再通过 Agent Note 决定是否提升为正式顶层 distribution。 | ||
| @@ -0,0 +1,8 @@ | |||
| 1 | +# torchao-npu 实验包规则 | ||
| 2 | + | ||
| 3 | +`torchao-npu` 是独立安装的实验性 Python distribution,包含 NPU 量化 config、wrapper tensor、算子和 serialization 能力。 | ||
| 4 | + | ||
| 5 | +- 保持 `torchao_npu` 包对 `torchtitan_npu` 的独立性;反向适配由 `torchtitan_npu/extensions/adaptor/torchao/` 承担。 | ||
| 6 | +- 不将该 distribution 整体移入 `torchtitan_npu/extensions/experiment/`,否则会混淆包发布边界与主包激活边界。 | ||
| 7 | +- 新能力在本目录的 `tests/` 中验证;涉及 torchtitan-npu 模型集成时,主仓同时补充 integration 测试。 | ||
| 8 | +- 文档必须明确该包需要单独安装,不将仓内源码存在写成默认可用。 | ||
| @@ -0,0 +1,3 @@ | |||
| 1 | +# scripts 规则 | ||
| 2 | + | ||
| 3 | +`scripts/` 放仓库级训练、转换、合规检查和辅助脚本,不承载可导入生产库逻辑。参数、环境变量、输入输出和失败条件必须明确;训练 wrapper 只透传参数,不隐式选择 override 或改变模型语义。 | ||
| @@ -0,0 +1,167 @@ | |||
| 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 | +"""Ratchet direct imports that cross the torchtitan-npu architecture layers.""" | ||
| 7 | + | ||
| 8 | +from __future__ import annotations | ||
| 9 | + | ||
| 10 | +import argparse | ||
| 11 | +import ast | ||
| 12 | +import json | ||
| 13 | +import re | ||
| 14 | +from dataclasses import dataclass | ||
| 15 | +from pathlib import Path | ||
| 16 | + | ||
| 17 | +PACKAGE_ROOT = "torchtitan_npu" | ||
| 18 | +LAYER_NAMES = frozenset({"extensions", "models", "ops", "override", "patches"}) | ||
| 19 | +FORBIDDEN_TARGETS = { | ||
| 20 | + "extensions": frozenset({"models", "ops", "override"}), | ||
| 21 | + "patches": frozenset({"extensions"}), | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +@dataclass(frozen=True, order=True) | ||
| 26 | +class ImportEdge: | ||
| 27 | + """One direct import between top-level torchtitan-npu layers.""" | ||
| 28 | + | ||
| 29 | + source: str | ||
| 30 | + target_module: str | ||
| 31 | + | ||
| 32 | + @property | ||
| 33 | + def target_layer(self) -> str: | ||
| 34 | + return self.target_module.split(".", 2)[1] | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def _layer_for_path(path: Path) -> str | None: | ||
| 38 | + try: | ||
| 39 | + parts = path.parts | ||
| 40 | + start = parts.index(PACKAGE_ROOT) | ||
| 41 | + except ValueError: | ||
| 42 | + return None | ||
| 43 | + return parts[start + 1] if len(parts) > start + 1 and parts[start + 1] in LAYER_NAMES else None | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _imported_modules(tree: ast.AST) -> set[str]: | ||
| 47 | + modules: set[str] = set() | ||
| 48 | + for node in ast.walk(tree): | ||
| 49 | + if isinstance(node, ast.Import): | ||
| 50 | + modules.update(alias.name for alias in node.names) | ||
| 51 | + elif isinstance(node, ast.ImportFrom) and node.module is not None: | ||
| 52 | + modules.add(node.module) | ||
| 53 | + return modules | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def _modules_for_file(path: Path) -> set[str]: | ||
| 57 | + """Extract imports with AST, falling back for newer syntax on older Python.""" | ||
| 58 | + source = path.read_text(encoding="utf-8") | ||
| 59 | + try: | ||
| 60 | + return _imported_modules(ast.parse(source, filename=str(path))) | ||
| 61 | + except SyntaxError: | ||
| 62 | + # Local environments can be older than the repository Python target. | ||
| 63 | + # Ruff and Pyrefly remain responsible for reporting syntax errors. | ||
| 64 | + return { | ||
| 65 | + module | ||
| 66 | + for match in re.finditer(r"^\s*(?:from\s+([\w.]+)\s+import|import\s+([\w.]+))", source, re.MULTILINE) | ||
| 67 | + for module in match.groups() | ||
| 68 | + if module is not None | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def collect_edges(root: Path) -> set[ImportEdge]: | ||
| 73 | + """Return forbidden direct imports found below ``root/torchtitan_npu``.""" | ||
| 74 | + edges: set[ImportEdge] = set() | ||
| 75 | + package = root / PACKAGE_ROOT | ||
| 76 | + for path in package.rglob("*.py"): | ||
| 77 | + source_layer = _layer_for_path(path) | ||
| 78 | + if source_layer is None: | ||
| 79 | + continue | ||
| 80 | + relative = path.relative_to(root).as_posix() | ||
| 81 | + source = relative | ||
| 82 | + for module in _modules_for_file(path): | ||
| 83 | + parts = module.split(".") | ||
| 84 | + if len(parts) < 2 or parts[0] != PACKAGE_ROOT or parts[1] not in LAYER_NAMES: | ||
| 85 | + continue | ||
| 86 | + target_layer = parts[1] | ||
| 87 | + if target_layer in FORBIDDEN_TARGETS.get(source_layer, frozenset()): | ||
| 88 | + edges.add(ImportEdge(source=source, target_module=module)) | ||
| 89 | + return edges | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +def _header_has_upstream_metadata(path: Path) -> bool: | ||
| 93 | + """Accept legacy upstream markers in the fixed header region only.""" | ||
| 94 | + header = "\n".join(path.read_text(encoding="utf-8").splitlines()[:40]) | ||
| 95 | + return "Upstream-PR:" in header or "upstream PR:" in header or "Upstream PR:" in header | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def collect_missing_patch_metadata(root: Path) -> set[str]: | ||
| 99 | + """Find actual TorchTitan patch modules without header metadata.""" | ||
| 100 | + patch_root = root / PACKAGE_ROOT / "patches" / "torchtitan" | ||
| 101 | + return { | ||
| 102 | + path.relative_to(root).as_posix() | ||
| 103 | + for path in patch_root.rglob("*.py") | ||
| 104 | + if path.name != "__init__.py" and not _header_has_upstream_metadata(path) | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def _imports_from_init(path: Path) -> list[str]: | ||
| 109 | + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) | ||
| 110 | + imports: list[str] = [] | ||
| 111 | + for node in tree.body: | ||
| 112 | + if not isinstance(node, ast.ImportFrom) or node.level != 1: | ||
| 113 | + continue | ||
| 114 | + prefix = f".{node.module}." if node.module is not None else "." | ||
| 115 | + imports.extend(f"{prefix}{alias.name}" for alias in node.names) | ||
| 116 | + return imports | ||
| 117 | + | ||
| 118 | + | ||
| 119 | +def _baseline_entries(raw_entries: list[dict[str, str]]) -> set[ImportEdge]: | ||
| 120 | + return {ImportEdge(source=entry["source"], target_module=entry["target_module"]) for entry in raw_entries} | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +def load_baseline(path: Path) -> tuple[set[ImportEdge], set[str], dict[str, list[str]]]: | ||
| 124 | + data = json.loads(path.read_text(encoding="utf-8")) | ||
| 125 | + imports = _baseline_entries(data.get("import", [])) | ||
| 126 | + metadata = set(data.get("patch_metadata", {}).get("missing", [])) | ||
| 127 | + activation = {name: list(order) for name, order in data.get("activation_order", {}).items()} | ||
| 128 | + return imports, metadata, activation | ||
| 129 | + | ||
| 130 | + | ||
| 131 | +def check(root: Path, baseline_path: Path) -> list[str]: | ||
| 132 | + """Return violations; baseline entries may disappear but may not grow.""" | ||
| 133 | + baseline_imports, baseline_metadata, activation = load_baseline(baseline_path) | ||
| 134 | + current_imports = collect_edges(root) | ||
| 135 | + current_metadata = collect_missing_patch_metadata(root) | ||
| 136 | + violations = [ | ||
| 137 | + f"new forbidden import: {edge.source} -> {edge.target_module}" | ||
| 138 | + for edge in sorted(current_imports - baseline_imports) | ||
| 139 | + ] | ||
| 140 | + violations.extend( | ||
| 141 | + f"new patch missing upstream metadata: {path}" for path in sorted(current_metadata - baseline_metadata) | ||
| 142 | + ) | ||
| 143 | + for relative_path, expected in sorted(activation.items()): | ||
| 144 | + actual = _imports_from_init(root / relative_path) | ||
| 145 | + if actual != expected: | ||
| 146 | + violations.append(f"activation order changed: {relative_path}; expected {expected}, got {actual}") | ||
| 147 | + return violations | ||
| 148 | + | ||
| 149 | + | ||
| 150 | +def main() -> int: | ||
| 151 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 152 | + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) | ||
| 153 | + parser.add_argument("--baseline", type=Path, default=None) | ||
| 154 | + args = parser.parse_args() | ||
| 155 | + root = args.root.resolve() | ||
| 156 | + baseline = args.baseline.resolve() if args.baseline is not None else root / ".ci/architecture_import_baseline.json" | ||
| 157 | + violations = check(root, baseline) | ||
| 158 | + if violations: | ||
| 159 | + print("Architecture boundary check failed:") | ||
| 160 | + print("\n".join(f"- {violation}" for violation in violations)) | ||
| 161 | + return 1 | ||
| 162 | + print("Architecture boundary check passed.") | ||
| 163 | + return 0 | ||
| 164 | + | ||
| 165 | + | ||
| 166 | +if __name__ == "__main__": | ||
| 167 | + raise SystemExit(main()) | ||
| @@ -0,0 +1,7 @@ | |||
| 1 | +# 测试规则 | ||
| 2 | + | ||
| 3 | +`tests/unit_tests/` 是 CPU 生产语义与静态契约测试根;`tests/smoke_tests/` 是真实 NPU runtime 上的小范围设备语义验证根;`tests/integration_tests/` 是 NPU 集成与训练测试根。测试尽量镜像生产代码;脚本和 skill 自测放 `tests/unit_tests/tooling/`,不作为产品行为覆盖证据。 | ||
| 4 | + | ||
| 5 | +需要新增、修正或重构 testcase 时,使用 [developer-tests-review 的“更新测试” workflow](../.agents/skills/developer-tests-review/SKILL.md#workflow-1更新测试):它允许修改测试并要求执行相关 UT、ST、runner 或 golden 验证。仅审查 PR 或既有测试是否覆盖真实路径时,使用同一 skill 的 [“review测试” workflow](../.agents/skills/developer-tests-review/SKILL.md#workflow-2review测试):它只读,不修改或执行测试。两种 workflow 都先读取本文件;详细的 UT、ST、格式和报告规则只在 skill 中维护,不在此重复。 | ||
| 6 | + | ||
| 7 | +Python 逻辑至少运行相关 CPU UT;分布式、NPU kernel、override、patch 或训练行为补充 NPU 验证。数值重构比较同 checkpoint、固定随机性的逐 step loss 与 grad_norm,并报告实际命令和未运行原因。 | ||
| @@ -0,0 +1,3 @@ | |||
| 1 | +# NPU 集成测试规则 | ||
| 2 | + | ||
| 3 | +本目录验证真实 NPU、分布式通信、模型训练、kernel 和 checkpoint 路径。测试说明硬件、并行度、模型和数据前提;保留实际命令、环境与关键日志/指标位置。CPU 单测不能替代此类验证。 | ||
| @@ -11,8 +11,8 @@ from functools import wraps | |||
| 11 | def main(): | 11 | def main(): |
| 12 | import torchtitan_npu # noqa: F401 | 12 | import torchtitan_npu # noqa: F401 |
| 13 | from torchtitan.train import main as train_main | 13 | from torchtitan.train import main as train_main |
| 14 | - from torchtitan_npu.extensions.trainer import TrainerEx | 14 | + from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 15 | - from torchtitan_npu.extensions.components.checkpoint import CheckpointManager | 15 | + from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager |
| 16 | from torchtitan_npu.extensions.experiment.anticipatory_routing.router import AnticipatoryHashRouter | 16 | from torchtitan_npu.extensions.experiment.anticipatory_routing.router import AnticipatoryHashRouter |
| 17 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import Phase | 17 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import Phase |
| 18 | 18 | ||
| @@ -17,7 +17,7 @@ from torchtitan.train import main | |||
| 17 | 17 | ||
| 18 | import torchtitan_npu # noqa: F401 | 18 | import torchtitan_npu # noqa: F401 |
| 19 | from tests.integration_tests import OverrideDefinitions | 19 | from tests.integration_tests import OverrideDefinitions |
| 20 | -from torchtitan_npu.extensions.components.checkpoint import CheckpointManager | 20 | +from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager |
| 21 | 21 | ||
| 22 | _save = CheckpointManager.dcp_save | 22 | _save = CheckpointManager.dcp_save |
| 23 | _load = CheckpointManager.dcp_load | 23 | _load = CheckpointManager.dcp_load |
| @@ -15,7 +15,7 @@ from safetensors.torch import load_file | |||
| 15 | from torch.distributed.tensor import DTensor | 15 | from torch.distributed.tensor import DTensor |
| 16 | from torchtitan.tools.logging import logger | 16 | from torchtitan.tools.logging import logger |
| 17 | 17 | ||
| 18 | -from torchtitan_npu.extensions.trainer import TrainerEx | 18 | +from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 19 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | 19 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel |
| 20 | from torchtitan_npu.models.deepseek_v4.lora import DeepSeekV4LoRAConverter | 20 | from torchtitan_npu.models.deepseek_v4.lora import DeepSeekV4LoRAConverter |
| 21 | from torchtitan.distributed.flex_shard.dist_muon import DistMuon | 21 | from torchtitan.distributed.flex_shard.dist_muon import DistMuon |
| @@ -0,0 +1,8 @@ | |||
| 1 | +# NPU smoke test 规则 | ||
| 2 | + | ||
| 3 | +`tests/smoke_tests/` 验证需要真实 NPU runtime 、但不需要完整多步训练的小范围行为。 | ||
| 4 | + | ||
| 5 | +- smoke test 不是 CPU UT,不得通过全量 mock NPU 语义来伪装设备验证。 | ||
| 6 | +- 测试必须明确设备数、runtime/算子依赖、dtype、shape 和预期失败条件。 | ||
| 7 | +- 只覆盖最小设备语义、注册或数值 sanity;分布式训练、checkpoint resume 和多 step 数值对齐放在 `tests/integration_tests/`。 | ||
| 8 | +- 结果必须记录实际执行环境;仅静态检查时不声称 smoke test 已通过。 | ||
Rtests/smoke_tests/anticipatory_routing/test_anticipatory_routing.py→tests/smoke_tests/anticipatory_routing/test_anticipatory_routing_smoke.py+59-25
| @@ -7,9 +7,9 @@ | |||
| 7 | 7 | ||
| 8 | import logging | 8 | import logging |
| 9 | import os | 9 | import os |
| 10 | -from pathlib import Path | ||
| 11 | import subprocess | 10 | import subprocess |
| 12 | import sys | 11 | import sys |
| 12 | +from pathlib import Path | ||
| 13 | 13 | ||
| 14 | import pytest | 14 | import pytest |
| 15 | 15 | ||
| @@ -26,16 +26,34 @@ def test_loss_spike_rollback_and_route_replay(tmp_path): | |||
| 26 | env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(root), env.get("PYTHONPATH")])) | 26 | env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(root), env.get("PYTHONPATH")])) |
| 27 | probe = subprocess.run( | 27 | probe = subprocess.run( |
| 28 | [sys.executable, str(_THIS_FILE), "--probe"], | 28 | [sys.executable, str(_THIS_FILE), "--probe"], |
| 29 | - cwd=root, env=env, check=False, capture_output=True, text=True, timeout=60, | 29 | + cwd=root, |
| 30 | + env=env, | ||
| 31 | + check=False, | ||
| 32 | + capture_output=True, | ||
| 33 | + text=True, | ||
| 34 | + timeout=60, | ||
| 30 | ) | 35 | ) |
| 31 | if probe.returncode == _NO_NPU_EXIT_CODE: | 36 | if probe.returncode == _NO_NPU_EXIT_CODE: |
| 32 | pytest.skip(probe.stderr.strip() or "Ascend NPU is required") | 37 | pytest.skip(probe.stderr.strip() or "Ascend NPU is required") |
| 33 | assert probe.returncode == 0, probe.stdout + probe.stderr | 38 | assert probe.returncode == 0, probe.stdout + probe.stderr |
| 34 | result = subprocess.run( | 39 | result = subprocess.run( |
| 35 | - [sys.executable, "-m", "torch.distributed.run", "--standalone", | 40 | + [ |
| 36 | - f"--nproc-per-node={_WORLD_SIZE}", "--max-restarts=0", | 41 | + sys.executable, |
| 37 | - str(_THIS_FILE), "--worker", str(tmp_path)], | 42 | + "-m", |
| 38 | - cwd=root, env=env, check=False, capture_output=True, text=True, timeout=360, | 43 | + "torch.distributed.run", |
| 44 | + "--standalone", | ||
| 45 | + f"--nproc-per-node={_WORLD_SIZE}", | ||
| 46 | + "--max-restarts=0", | ||
| 47 | + str(_THIS_FILE), | ||
| 48 | + "--worker", | ||
| 49 | + str(tmp_path), | ||
| 50 | + ], | ||
| 51 | + cwd=root, | ||
| 52 | + env=env, | ||
| 53 | + check=False, | ||
| 54 | + capture_output=True, | ||
| 55 | + text=True, | ||
| 56 | + timeout=360, | ||
| 39 | ) | 57 | ) |
| 40 | if result.returncode == _NO_NPU_EXIT_CODE: | 58 | if result.returncode == _NO_NPU_EXIT_CODE: |
| 41 | pytest.skip(result.stderr.strip() or "isolated anticipatory routing worker has no available Ascend NPU") | 59 | pytest.skip(result.stderr.strip() or "isolated anticipatory routing worker has no available Ascend NPU") |
| @@ -63,21 +81,22 @@ def _worker(folder): | |||
| 63 | from types import SimpleNamespace | 81 | from types import SimpleNamespace |
| 64 | 82 | ||
| 65 | import torch | 83 | import torch |
| 66 | - import torch_npu # noqa: F401 | ||
| 67 | import torch.distributed as dist | 84 | import torch.distributed as dist |
| 68 | import torch.distributed.checkpoint as dcp | 85 | import torch.distributed.checkpoint as dcp |
| 69 | import torch.nn.functional as F | 86 | import torch.nn.functional as F |
| 87 | + import torch_npu # noqa: F401 | ||
| 70 | 88 | ||
| 71 | rank = dist.get_rank() | 89 | rank = dist.get_rank() |
| 72 | local_rank = int(os.environ["LOCAL_RANK"]) | 90 | local_rank = int(os.environ["LOCAL_RANK"]) |
| 73 | 91 | ||
| 74 | - from torchtitan.components.checkpoint import MODEL, OPTIMIZER, LR_SCHEDULER, DATALOADER, TRAIN_STATE | 92 | + from torchtitan.components.checkpoint import DATALOADER, LR_SCHEDULER, MODEL, OPTIMIZER, TRAIN_STATE |
| 75 | - from torchtitan_npu.extensions.trainer import TrainerEx | 93 | + |
| 94 | + from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode | ||
| 76 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig | 95 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig |
| 77 | from torchtitan_npu.extensions.experiment.anticipatory_routing.detector import LossSpikeDetector | 96 | from torchtitan_npu.extensions.experiment.anticipatory_routing.detector import LossSpikeDetector |
| 78 | - from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode | ||
| 79 | - from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase | ||
| 80 | from torchtitan_npu.extensions.experiment.anticipatory_routing.router import AnticipatoryHashRouter | 97 | from torchtitan_npu.extensions.experiment.anticipatory_routing.router import AnticipatoryHashRouter |
| 98 | + from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase | ||
| 99 | + from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx | ||
| 81 | 100 | ||
| 82 | class Loader: | 101 | class Loader: |
| 83 | def __init__(self): | 102 | def __init__(self): |
| @@ -163,18 +182,25 @@ def _worker(folder): | |||
| 163 | trainer.num_pipeline_parallel_microbatches = 1 | 182 | trainer.num_pipeline_parallel_microbatches = 1 |
| 164 | trainer.config = SimpleNamespace( | 183 | trainer.config = SimpleNamespace( |
| 165 | anticipatory=AnticipatoryRoutingConfig( | 184 | anticipatory=AnticipatoryRoutingConfig( |
| 166 | - enable=True, delay_steps=2, active_steps=2, | 185 | + enable=True, |
| 186 | + delay_steps=2, | ||
| 187 | + active_steps=2, | ||
| 167 | detector=LossSpikeDetector.Config(warmup_steps=4), | 188 | detector=LossSpikeDetector.Config(warmup_steps=4), |
| 168 | ), | 189 | ), |
| 169 | training=SimpleNamespace(steps=10, disable_cuda_graphs=True, max_norm=100.0), | 190 | training=SimpleNamespace(steps=10, disable_cuda_graphs=True, max_norm=100.0), |
| 170 | checkpoint=SimpleNamespace(interval=2, keep_latest_k=0), | 191 | checkpoint=SimpleNamespace(interval=2, keep_latest_k=0), |
| 171 | ) | 192 | ) |
| 172 | trainer.parallel_dims = SimpleNamespace( | 193 | trainer.parallel_dims = SimpleNamespace( |
| 173 | - pp_enabled=False, dp_enabled=False, ep_enabled=False, dp_cp_enabled=False, | 194 | + pp_enabled=False, |
| 195 | + dp_enabled=False, | ||
| 196 | + ep_enabled=False, | ||
| 197 | + dp_cp_enabled=False, | ||
| 174 | get_optional_mesh=lambda name: None, | 198 | get_optional_mesh=lambda name: None, |
| 175 | ) | 199 | ) |
| 176 | trainer.metrics_processor = SimpleNamespace( | 200 | trainer.metrics_processor = SimpleNamespace( |
| 177 | - ntokens_since_last_log=0, data_loading_times=[], should_log=lambda step: False, | 201 | + ntokens_since_last_log=0, |
| 202 | + data_loading_times=[], | ||
| 203 | + should_log=lambda step: False, | ||
| 178 | ) | 204 | ) |
| 179 | trainer.train_context = nullcontext | 205 | trainer.train_context = nullcontext |
| 180 | trainer._sdc = SimpleNamespace(finalize_sdc_step=lambda: None) | 206 | trainer._sdc = SimpleNamespace(finalize_sdc_step=lambda: None) |
| @@ -187,12 +213,14 @@ def _worker(folder): | |||
| 187 | 213 | ||
| 188 | trainer.post_dataloading_process = process | 214 | trainer.post_dataloading_process = process |
| 189 | trainer.loss_fn = lambda pred, labels, count, **kwargs: ( | 215 | trainer.loss_fn = lambda pred, labels, count, **kwargs: ( |
| 190 | - F.cross_entropy(pred.flatten(0, 1), labels.flatten(), reduction="sum") / count, None | 216 | + F.cross_entropy(pred.flatten(0, 1), labels.flatten(), reduction="sum") / count, |
| 217 | + None, | ||
| 191 | ) | 218 | ) |
| 192 | trainer.fwd_bwd_fn = trainer._forward_backward_body | 219 | trainer.fwd_bwd_fn = trainer._forward_backward_body |
| 193 | 220 | ||
| 194 | class DiskCheckpoint: | 221 | class DiskCheckpoint: |
| 195 | """DCP adapter with upstream flat model keys and resumable training state.""" | 222 | """DCP adapter with upstream flat model keys and resumable training state.""" |
| 223 | + | ||
| 196 | def __init__(self): | 224 | def __init__(self): |
| 197 | self.folder = folder | 225 | self.folder = folder |
| 198 | self.states = {MODEL: model} | 226 | self.states = {MODEL: model} |
| @@ -207,12 +235,14 @@ def _worker(folder): | |||
| 207 | 235 | ||
| 208 | def payload(self): | 236 | def payload(self): |
| 209 | state = dict(model.state_dict()) | 237 | state = dict(model.state_dict()) |
| 210 | - state.update({ | 238 | + state.update( |
| 211 | - OPTIMIZER: trainer.optimizers.state_dict(), | 239 | + { |
| 212 | - LR_SCHEDULER: trainer.lr_schedulers.state_dict(), | 240 | + OPTIMIZER: trainer.optimizers.state_dict(), |
| 213 | - DATALOADER: trainer.dataloader.state_dict(), | 241 | + LR_SCHEDULER: trainer.lr_schedulers.state_dict(), |
| 214 | - TRAIN_STATE: trainer.state_dict(), | 242 | + DATALOADER: trainer.dataloader.state_dict(), |
| 215 | - }) | 243 | + TRAIN_STATE: trainer.state_dict(), |
| 244 | + } | ||
| 245 | + ) | ||
| 216 | return state | 246 | return state |
| 217 | 247 | ||
| 218 | def save(self, curr_step, last_step=False): | 248 | def save(self, curr_step, last_step=False): |
| @@ -263,8 +293,11 @@ def _worker(folder): | |||
| 263 | assert trainer.checkpointer.saved == [2, 4, 8, 10] | 293 | assert trainer.checkpointer.saved == [2, 4, 8, 10] |
| 264 | assert blocked == [4, 5, 6, 7] | 294 | assert blocked == [4, 5, 6, 7] |
| 265 | assert transitions[5:10] == [ | 295 | assert transitions[5:10] == [ |
| 266 | - (4, Phase.ACTIVE, 2), (5, Phase.ACTIVE, 2), | 296 | + (4, Phase.ACTIVE, 2), |
| 267 | - (6, Phase.DRAIN, 2), (7, Phase.DRAIN, 1), (8, Phase.NORMAL, 0), | 297 | + (5, Phase.ACTIVE, 2), |
| 298 | + (6, Phase.DRAIN, 2), | ||
| 299 | + (7, Phase.DRAIN, 1), | ||
| 300 | + (8, Phase.NORMAL, 0), | ||
| 268 | ] | 301 | ] |
| 269 | assert [i for i, _ in model.trained] == list(range(12)) + list(range(8, 20)) | 302 | assert [i for i, _ in model.trained] == list(range(12)) + list(range(8, 20)) |
| 270 | assert [mode for _, mode in model.trained[12:]] == [RoutingMode.REPLAY] * 8 + [RoutingMode.OFF] * 4 | 303 | assert [mode for _, mode in model.trained[12:]] == [RoutingMode.REPLAY] * 8 + [RoutingMode.OFF] * 4 |
| @@ -283,11 +316,12 @@ if __name__ == "__main__": | |||
| 283 | if sys.argv[1:] == ["--probe"]: | 316 | if sys.argv[1:] == ["--probe"]: |
| 284 | raise SystemExit(_probe()) | 317 | raise SystemExit(_probe()) |
| 285 | if len(sys.argv) != 3 or sys.argv[1] != "--worker": | 318 | if len(sys.argv) != 3 or sys.argv[1] != "--worker": |
| 286 | - raise SystemExit("Usage: test_anticipatory_routing.py --worker CHECKPOINT_DIR") | 319 | + raise SystemExit("Usage: test_anticipatory_routing_smoke.py --worker CHECKPOINT_DIR") |
| 287 | from datetime import timedelta | 320 | from datetime import timedelta |
| 321 | + | ||
| 288 | import torch | 322 | import torch |
| 289 | - import torch_npu # noqa: F401 | ||
| 290 | import torch.distributed as dist | 323 | import torch.distributed as dist |
| 324 | + import torch_npu # noqa: F401 | ||
| 291 | 325 | ||
| 292 | torch.npu.set_device(int(os.environ["LOCAL_RANK"])) | 326 | torch.npu.set_device(int(os.environ["LOCAL_RANK"])) |
| 293 | dist.init_process_group("hccl", timeout=timedelta(seconds=120)) | 327 | dist.init_process_group("hccl", timeout=timedelta(seconds=120)) |
| @@ -344,7 +344,7 @@ def _check_gradient_without_checksum_pass() -> None: | |||
| 344 | def _check_checksum_pass_installed_during_initialization() -> None: | 344 | def _check_checksum_pass_installed_during_initialization() -> None: |
| 345 | from torch._inductor import config as inductor_config | 345 | from torch._inductor import config as inductor_config |
| 346 | 346 | ||
| 347 | - import torchtitan_npu.compile.sdc_checksum as checksum_pass | 347 | + import torchtitan_npu.extensions.compile.sdc_checksum as checksum_pass |
| 348 | from torchtitan_npu.extensions.components.sdc import SDC | 348 | from torchtitan_npu.extensions.components.sdc import SDC |
| 349 | 349 | ||
| 350 | previous_pass = inductor_config.post_grad_custom_post_pass | 350 | previous_pass = inductor_config.post_grad_custom_post_pass |
| @@ -414,7 +414,7 @@ def _check_checksum_output_mutation(torch: Any, torch_npu: Any) -> None: | |||
| 414 | 414 | ||
| 415 | 415 | ||
| 416 | def _check_compiled_consumer_observes_checksum_output_mutation(torch: Any, torch_npu: Any) -> None: | 416 | def _check_compiled_consumer_observes_checksum_output_mutation(torch: Any, torch_npu: Any) -> None: |
| 417 | - from torchtitan_npu.compile.sdc_checksum import install_checksum_pass | 417 | + from torchtitan_npu.extensions.compile.sdc_checksum import install_checksum_pass |
| 418 | 418 | ||
| 419 | device = torch.device("npu:0") | 419 | device = torch.device("npu:0") |
| 420 | checker, checksum_calls = _install_checksum_output_mutator(torch, torch_npu, device) | 420 | checker, checksum_calls = _install_checksum_output_mutator(torch, torch_npu, device) |
| @@ -637,7 +637,7 @@ def _assert_three_strikes_activated( | |||
| 637 | 637 | ||
| 638 | 638 | ||
| 639 | def _check_three_strikes_enable_checksum(torch: Any, torch_npu: Any) -> None: | 639 | def _check_three_strikes_enable_checksum(torch: Any, torch_npu: Any) -> None: |
| 640 | - import torchtitan_npu.compile.sdc_checksum as checksum_pass | 640 | + import torchtitan_npu.extensions.compile.sdc_checksum as checksum_pass |
| 641 | from torchtitan_npu.extensions.components.sdc import SDC | 641 | from torchtitan_npu.extensions.components.sdc import SDC |
| 642 | 642 | ||
| 643 | device = torch.device("npu:0") | 643 | device = torch.device("npu:0") |
| @@ -0,0 +1,11 @@ | |||
| 1 | +# CPU 单测规则 | ||
| 2 | + | ||
| 3 | +本目录验证 CPU 可运行的生产语义和静态契约,不以 CPU mock 替代需要 NPU 语义的集成验证。脚本和 skill 自测放 `tooling/`。 | ||
| 4 | + | ||
| 5 | +通常从仓库根运行: | ||
| 6 | + | ||
| 7 | +```bash | ||
| 8 | +TORCH_DEVICE_BACKEND_AUTOLOAD=0 python -m pytest -v --tb=short tests/unit_tests -x | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +优先运行与变更相关的测试。 | ||
| @@ -14,7 +14,7 @@ from torchtitan.config import TrainingConfig as UpstreamTrainingConfig | |||
| 14 | from torchtitan.trainer import Trainer | 14 | from torchtitan.trainer import Trainer |
| 15 | 15 | ||
| 16 | import torchtitan_npu.config as npu_config | 16 | import torchtitan_npu.config as npu_config |
| 17 | -import torchtitan_npu.extensions.trainer as trainer_module | 17 | +import torchtitan_npu.extensions.torchtitan.trainer as trainer_module |
| 18 | from torchtitan_npu.config import ( | 18 | from torchtitan_npu.config import ( |
| 19 | ExtensionConfig, | 19 | ExtensionConfig, |
| 20 | MuonOptimizerProfile, | 20 | MuonOptimizerProfile, |
| @@ -26,10 +26,9 @@ from torchtitan_npu.config import TrainingConfig as NPUTrainingConfig | |||
| 26 | from torchtitan_npu.config import manager as config_manager | 26 | from torchtitan_npu.config import manager as config_manager |
| 27 | from torchtitan_npu.config.configs import KVNormQuantizationConfig | 27 | from torchtitan_npu.config.configs import KVNormQuantizationConfig |
| 28 | from torchtitan_npu.config.converters import TrainerConfigConverter | 28 | from torchtitan_npu.config.converters import TrainerConfigConverter |
| 29 | -from torchtitan_npu.distributed import utils as distributed_utils | 29 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import GraphTrainerEx |
| 30 | -from torchtitan_npu.extensions.graph_trainer import GraphTrainerEx | 30 | +from torchtitan_npu.extensions.torchtitan.tools.profiler import CANNProfiler |
| 31 | -from torchtitan_npu.extensions.profiler import CANNProfiler | 31 | +from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 32 | -from torchtitan_npu.extensions.trainer import TrainerEx | ||
| 33 | 32 | ||
| 34 | 33 | ||
| 35 | def _install_config_registry( | 34 | def _install_config_registry( |
| @@ -442,7 +441,7 @@ def test_trainer_ex_applies_enabled_quantization_before_base_initialization(monk | |||
| 442 | events = [] | 441 | events = [] |
| 443 | source_model_spec = object() | 442 | source_model_spec = object() |
| 444 | quantized_model_spec = object() | 443 | quantized_model_spec = object() |
| 445 | - converter_module = types.ModuleType("interfaces.torchao_converter") | 444 | + converter_module = types.ModuleType("torchtitan_npu.extensions.adaptor.torchao.converter") |
| 446 | 445 | ||
| 447 | def apply_quantization(model_spec, quantization_config, *, model_compile_enabled): | 446 | def apply_quantization(model_spec, quantization_config, *, model_compile_enabled): |
| 448 | events.append( | 447 | events.append( |
| @@ -467,7 +466,7 @@ def test_trainer_ex_applies_enabled_quantization_before_base_initialization(monk | |||
| 467 | events.append(("initialize_base", base_config.model_spec)) | 466 | events.append(("initialize_base", base_config.model_spec)) |
| 468 | 467 | ||
| 469 | converter_module.apply_quantization_converter = apply_quantization | 468 | converter_module.apply_quantization_converter = apply_quantization |
| 470 | - monkeypatch.setitem(sys.modules, "interfaces.torchao_converter", converter_module) | 469 | + monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.adaptor.torchao.converter", converter_module) |
| 471 | monkeypatch.setattr(trainer_module, "set_allow_hf32", apply_hf32) | 470 | monkeypatch.setattr(trainer_module, "set_allow_hf32", apply_hf32) |
| 472 | monkeypatch.setattr(TrainerEx.__base__, "__init__", initialize_base_trainer) | 471 | monkeypatch.setattr(TrainerEx.__base__, "__init__", initialize_base_trainer) |
| 473 | 472 | ||
| @@ -497,7 +496,7 @@ def test_trainer_ex_applies_enabled_quantization_before_base_initialization(monk | |||
| 497 | def test_trainer_ex_skips_disabled_quantization_and_preserves_model_spec(monkeypatch): | 496 | def test_trainer_ex_skips_disabled_quantization_and_preserves_model_spec(monkeypatch): |
| 498 | source_model_spec = object() | 497 | source_model_spec = object() |
| 499 | initialized_model_specs = [] | 498 | initialized_model_specs = [] |
| 500 | - converter_module = types.ModuleType("interfaces.torchao_converter") | 499 | + converter_module = types.ModuleType("torchtitan_npu.extensions.adaptor.torchao.converter") |
| 501 | 500 | ||
| 502 | def unexpected_quantization(*args, **kwargs): | 501 | def unexpected_quantization(*args, **kwargs): |
| 503 | raise AssertionError("quantization converter must remain disabled") | 502 | raise AssertionError("quantization converter must remain disabled") |
| @@ -508,7 +507,7 @@ def test_trainer_ex_skips_disabled_quantization_and_preserves_model_spec(monkeyp | |||
| 508 | initialized_model_specs.append(base_config.model_spec) | 507 | initialized_model_specs.append(base_config.model_spec) |
| 509 | 508 | ||
| 510 | converter_module.apply_quantization_converter = unexpected_quantization | 509 | converter_module.apply_quantization_converter = unexpected_quantization |
| 511 | - monkeypatch.setitem(sys.modules, "interfaces.torchao_converter", converter_module) | 510 | + monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.adaptor.torchao.converter", converter_module) |
| 512 | monkeypatch.setattr(trainer_module, "set_allow_hf32", lambda _allow_hf32: None) | 511 | monkeypatch.setattr(trainer_module, "set_allow_hf32", lambda _allow_hf32: None) |
| 513 | monkeypatch.setattr(TrainerEx.__base__, "__init__", initialize_base_trainer) | 512 | monkeypatch.setattr(TrainerEx.__base__, "__init__", initialize_base_trainer) |
| 514 | 513 | ||
| @@ -564,25 +563,3 @@ def test_trainer_ex_config_build_constructs_trainer_ex(monkeypatch): | |||
| 564 | assert len(built_configs) == 1 | 563 | assert len(built_configs) == 1 |
| 565 | assert isinstance(built_configs[0], TrainerEx.Config) | 564 | assert isinstance(built_configs[0], TrainerEx.Config) |
| 566 | assert built_configs[0].training.extension.allow_hf32 is False | 565 | assert built_configs[0].training.extension.allow_hf32 is False |
| 567 | - | ||
| 568 | - | ||
| 569 | -@pytest.mark.parametrize( | ||
| 570 | - "allow_hf32", | ||
| 571 | - [False, True], | ||
| 572 | - ids=("disabled", "enabled"), | ||
| 573 | -) | ||
| 574 | -def test_set_allow_hf32_updates_all_backends(monkeypatch, allow_hf32): | ||
| 575 | - fake_torch_npu = types.SimpleNamespace( | ||
| 576 | - npu=types.SimpleNamespace( | ||
| 577 | - matmul=types.SimpleNamespace(allow_hf32=None), | ||
| 578 | - conv=types.SimpleNamespace(allow_hf32=None), | ||
| 579 | - aclnn=types.SimpleNamespace(allow_hf32=None), | ||
| 580 | - ) | ||
| 581 | - ) | ||
| 582 | - monkeypatch.setitem(sys.modules, "torch_npu", fake_torch_npu) | ||
| 583 | - | ||
| 584 | - distributed_utils.set_allow_hf32(allow_hf32) | ||
| 585 | - | ||
| 586 | - assert fake_torch_npu.npu.matmul.allow_hf32 is allow_hf32 | ||
| 587 | - assert fake_torch_npu.npu.conv.allow_hf32 is allow_hf32 | ||
| 588 | - assert fake_torch_npu.npu.aclnn.allow_hf32 is allow_hf32 | ||
| @@ -94,11 +94,11 @@ def _load_checkpoint_conversion_module() -> types.ModuleType: | |||
| 94 | _register_packages( | 94 | _register_packages( |
| 95 | [ | 95 | [ |
| 96 | ("torchtitan_npu", package_root), | 96 | ("torchtitan_npu", package_root), |
| 97 | - ("torchtitan_npu.scripts", package_root / "scripts"), | 97 | + ("torchtitan_npu.tools", package_root / "tools"), |
| 98 | - ("torchtitan_npu.scripts.checkpoint_conversion", package_root / "scripts" / "checkpoint_conversion"), | 98 | + ("torchtitan_npu.tools.checkpoint_conversion", package_root / "tools" / "checkpoint_conversion"), |
| 99 | ] | 99 | ] |
| 100 | ) | 100 | ) |
| 101 | - return importlib.import_module("torchtitan_npu.scripts.checkpoint_conversion.convert_to_hf") | 101 | + return importlib.import_module("torchtitan_npu.tools.checkpoint_conversion.convert_to_hf") |
| 102 | 102 | ||
| 103 | 103 | ||
| 104 | @pytest.fixture | 104 | @pytest.fixture |
| @@ -505,7 +505,7 @@ def test_ema_schema_is_inherited_by_npu_trainer_ex_config() -> None: | |||
| 505 | # A full package import registers custom ops; sys.modules rollback cannot | 505 | # A full package import registers custom ops; sys.modules rollback cannot |
| 506 | # restore the PyTorch dispatcher after registering the same ops again. | 506 | # restore the PyTorch dispatcher after registering the same ops again. |
| 507 | script = textwrap.dedent(""" | 507 | script = textwrap.dedent(""" |
| 508 | - from torchtitan_npu.extensions.trainer import TrainerEx | 508 | + from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 509 | from torchtitan_npu.patches.torchtitan import trainer as trainer_module | 509 | from torchtitan_npu.patches.torchtitan import trainer as trainer_module |
| 510 | from torchtitan_npu.patches.torchtitan.components.checkpoint import EMACheckpointManager | 510 | from torchtitan_npu.patches.torchtitan.components.checkpoint import EMACheckpointManager |
| 511 | import torchtitan.components.checkpoint as upstream_checkpoint | 511 | import torchtitan.components.checkpoint as upstream_checkpoint |
Rtests/unit_tests/interfaces/test_torchao_converter.py→tests/unit_tests/extensions/adaptor/torchao/test_converter.py+8-8
| @@ -20,12 +20,12 @@ def converter_module(): | |||
| 20 | # TorchAO-NPU is an optional dependency of the training plugin. | 20 | # TorchAO-NPU is an optional dependency of the training plugin. |
| 21 | pytest.importorskip("torchao_npu") | 21 | pytest.importorskip("torchao_npu") |
| 22 | importlib.import_module("torchtitan_npu") | 22 | importlib.import_module("torchtitan_npu") |
| 23 | - return importlib.import_module("interfaces.torchao_converter") | 23 | + return importlib.import_module("torchtitan_npu.extensions.adaptor.torchao.converter") |
| 24 | 24 | ||
| 25 | 25 | ||
| 26 | @pytest.fixture(autouse=True) | 26 | @pytest.fixture(autouse=True) |
| 27 | def restore_quantized_module_cache(converter_module): | 27 | def restore_quantized_module_cache(converter_module): |
| 28 | - from interfaces.torchao_converter import _npu_quantized_module_cache | 28 | + from torchtitan_npu.extensions.adaptor.torchao.converter import _npu_quantized_module_cache |
| 29 | 29 | ||
| 30 | original = _npu_quantized_module_cache.copy() | 30 | original = _npu_quantized_module_cache.copy() |
| 31 | yield | 31 | yield |
| @@ -48,7 +48,7 @@ def quantization_calls(monkeypatch, converter_module): | |||
| 48 | 48 | ||
| 49 | @pytest.mark.parametrize("source_kind", ["grouped", "asc"]) | 49 | @pytest.mark.parametrize("source_kind", ["grouped", "asc"]) |
| 50 | def test_quantized_grouped_experts_keep_config_and_skip_reconversion(converter_module, quantization_calls, source_kind): | 50 | def test_quantized_grouped_experts_keep_config_and_skip_reconversion(converter_module, quantization_calls, source_kind): |
| 51 | - from interfaces.torchao_converter import _mxfp8_param_swap | 51 | + from torchtitan_npu.extensions.adaptor.torchao.converter import _mxfp8_param_swap |
| 52 | 52 | ||
| 53 | source_cls = converter_module.GroupedExperts if source_kind == "grouped" else converter_module.AscGroupedExperts | 53 | source_cls = converter_module.GroupedExperts if source_kind == "grouped" else converter_module.AscGroupedExperts |
| 54 | source = source_cls.Config(dim=2, hidden_dim=4, num_experts=2, swiglu_limit=1.5) | 54 | source = source_cls.Config(dim=2, hidden_dim=4, num_experts=2, swiglu_limit=1.5) |
| @@ -72,7 +72,7 @@ def test_quantized_grouped_experts_keep_config_and_skip_reconversion(converter_m | |||
| 72 | 72 | ||
| 73 | 73 | ||
| 74 | def test_quantization_converter_preserves_custom_experts(converter_module, quantization_calls): | 74 | def test_quantization_converter_preserves_custom_experts(converter_module, quantization_calls): |
| 75 | - from interfaces.torchao_converter import _mxfp8_param_swap | 75 | + from torchtitan_npu.extensions.adaptor.torchao.converter import _mxfp8_param_swap |
| 76 | 76 | ||
| 77 | class CustomExperts(converter_module.GroupedExperts): | 77 | class CustomExperts(converter_module.GroupedExperts): |
| 78 | @dataclass(kw_only=True, slots=True) | 78 | @dataclass(kw_only=True, slots=True) |
| @@ -102,7 +102,7 @@ def test_quantization_converter_preserves_custom_experts(converter_module, quant | |||
| 102 | 102 | ||
| 103 | 103 | ||
| 104 | def test_quantization_converter_keeps_linear_forward(converter_module, quantization_calls): | 104 | def test_quantization_converter_keeps_linear_forward(converter_module, quantization_calls): |
| 105 | - from interfaces.torchao_converter import _mxfp8_param_swap | 105 | + from torchtitan_npu.extensions.adaptor.torchao.converter import _mxfp8_param_swap |
| 106 | 106 | ||
| 107 | source = converter_module.Linear.Config(in_features=2, out_features=2, bias=False) | 107 | source = converter_module.Linear.Config(in_features=2, out_features=2, bias=False) |
| 108 | quant_config = _mxfp8_param_swap() | 108 | quant_config = _mxfp8_param_swap() |
| @@ -122,7 +122,7 @@ def test_quantization_converter_keeps_linear_forward(converter_module, quantizat | |||
| 122 | 122 | ||
| 123 | 123 | ||
| 124 | def test_quantization_converter_preserves_li_metadata_replacement(converter_module, quantization_calls): | 124 | def test_quantization_converter_preserves_li_metadata_replacement(converter_module, quantization_calls): |
| 125 | - from interfaces.torchao_converter import _QuantizedLightningIndexerMetadataAdapter | 125 | + from torchtitan_npu.extensions.adaptor.torchao.converter import _QuantizedLightningIndexerMetadataAdapter |
| 126 | 126 | ||
| 127 | source = converter_module.LightningIndexerMetadata.Config(index_n_heads=64, index_head_dim=128, index_topk=512) | 127 | source = converter_module.LightningIndexerMetadata.Config(index_n_heads=64, index_head_dim=128, index_topk=512) |
| 128 | replacement_type = _QuantizedLightningIndexerMetadataAdapter.Config | 128 | replacement_type = _QuantizedLightningIndexerMetadataAdapter.Config |
| @@ -262,7 +262,7 @@ def test_apply_quantization_converter_passes_model_type(converter_module, monkey | |||
| 262 | 262 | ||
| 263 | 263 | ||
| 264 | def test_parameter_quantization_skips_li_metadata(converter_module, quantization_calls): | 264 | def test_parameter_quantization_skips_li_metadata(converter_module, quantization_calls): |
| 265 | - from interfaces.torchao_converter import _mxfp8_param_swap | 265 | + from torchtitan_npu.extensions.adaptor.torchao.converter import _mxfp8_param_swap |
| 266 | 266 | ||
| 267 | source = converter_module.LightningIndexerMetadata.Config() | 267 | source = converter_module.LightningIndexerMetadata.Config() |
| 268 | converter = converter_module.NpuQuantizeConverter.Config( | 268 | converter = converter_module.NpuQuantizeConverter.Config( |
| @@ -275,7 +275,7 @@ def test_parameter_quantization_skips_li_metadata(converter_module, quantization | |||
| 275 | 275 | ||
| 276 | @pytest.mark.parametrize("quant_format", ["mx", "block_mx"]) | 276 | @pytest.mark.parametrize("quant_format", ["mx", "block_mx"]) |
| 277 | def test_quantized_experts_preserve_wrappers_through_forward(monkeypatch, converter_module, quant_format): | 277 | def test_quantized_experts_preserve_wrappers_through_forward(monkeypatch, converter_module, quant_format): |
| 278 | - from interfaces.torchao_converter import _block_fp8_param_swap, _mxfp8_param_swap | 278 | + from torchtitan_npu.extensions.adaptor.torchao.converter import _block_fp8_param_swap, _mxfp8_param_swap |
| 279 | 279 | ||
| 280 | wrapper_module = importlib.import_module(f"torchao_npu.wrapper_tensors.{quant_format}_wrapper_tensor") | 280 | wrapper_module = importlib.import_module(f"torchao_npu.wrapper_tensors.{quant_format}_wrapper_tensor") |
| 281 | if quant_format == "mx": | 281 | if quant_format == "mx": |
Rtests/unit_tests/interfaces/test_mx_quantize.py→tests/unit_tests/extensions/adaptor/torchao/test_mx_quantize.py+1-1
| @@ -34,7 +34,7 @@ def mx_module(monkeypatch): | |||
| 34 | for token in ("float8_e4m3fn", "float8_e5m2", "float8_e8m0fnu", "float4_e2m1fn_x2", "hifloat8"): | 34 | for token in ("float8_e4m3fn", "float8_e5m2", "float8_e8m0fnu", "float4_e2m1fn_x2", "hifloat8"): |
| 35 | setattr(npu, token, object()) | 35 | setattr(npu, token, object()) |
| 36 | monkeypatch.setitem(sys.modules, "torch_npu", npu) | 36 | monkeypatch.setitem(sys.modules, "torch_npu", npu) |
| 37 | - monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[3] / "experiments" / "torchao-npu")) | 37 | + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[5] / "experiments" / "torchao-npu")) |
| 38 | for name in original_modules: | 38 | for name in original_modules: |
| 39 | del sys.modules[name] | 39 | del sys.modules[name] |
| 40 | try: | 40 | try: |
Rtests/unit_tests/interfaces/test_torchao_converter_prequantize.py→tests/unit_tests/extensions/adaptor/torchao/test_torchao_converter_prequantize.py+4-4
| @@ -15,18 +15,18 @@ concern (the wrapper tensor's fail-fast guard), not a config-stage one. | |||
| 15 | import pytest | 15 | import pytest |
| 16 | from torchtitan.models.common.linear import Linear | 16 | from torchtitan.models.common.linear import Linear |
| 17 | 17 | ||
| 18 | -# TorchAO-NPU is an optional dependency (see interfaces/torchao_converter's | 18 | +# TorchAO-NPU is an optional dependency (see adaptor converter's |
| 19 | # module docstring): environments without it (e.g. the CI UT runner) must skip | 19 | # module docstring): environments without it (e.g. the CI UT runner) must skip |
| 20 | # this module at collection instead of failing the import below, mirroring the | 20 | # this module at collection instead of failing the import below, mirroring the |
| 21 | -# importorskip in the converter_module fixture of test_torchao_converter.py. | 21 | +# importorskip in the converter_module fixture of test_converter.py. |
| 22 | pytest.importorskip("torchao_npu") | 22 | pytest.importorskip("torchao_npu") |
| 23 | 23 | ||
| 24 | -from interfaces.torchao_converter import ( | 24 | +from torchtitan_npu.config.configs import QuantizationExtensionConfig |
| 25 | +from torchtitan_npu.extensions.adaptor.torchao.converter import ( | ||
| 25 | _PREQUANTIZE_DEFAULT_FQNS, | 26 | _PREQUANTIZE_DEFAULT_FQNS, |
| 26 | _match_fqn_suffix, | 27 | _match_fqn_suffix, |
| 27 | apply_quantization_converter, | 28 | apply_quantization_converter, |
| 28 | ) | 29 | ) |
| 29 | -from torchtitan_npu.config.configs import QuantizationExtensionConfig | ||
| 30 | from torchtitan_npu.models.deepseek_v4 import model_registry | 30 | from torchtitan_npu.models.deepseek_v4 import model_registry |
| 31 | 31 | ||
| 32 | 32 | ||
| @@ -17,7 +17,7 @@ import torch_npu | |||
| 17 | from torchtitan_npu.config.configs import MuonOptimizerProfile, OptimizerConfig, TrainingConfig | 17 | from torchtitan_npu.config.configs import MuonOptimizerProfile, OptimizerConfig, TrainingConfig |
| 18 | from torchtitan_npu.extensions.cpu_offload.cpu_offload_adamw import CpuOffloadAdamW | 18 | from torchtitan_npu.extensions.cpu_offload.cpu_offload_adamw import CpuOffloadAdamW |
| 19 | from torchtitan_npu.extensions.cpu_offload.staging import CpuStaging | 19 | from torchtitan_npu.extensions.cpu_offload.staging import CpuStaging |
| 20 | -from torchtitan_npu.extensions.trainer import TrainerEx | 20 | +from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 21 | 21 | ||
| 22 | requires_npu = pytest.mark.skipif( | 22 | requires_npu = pytest.mark.skipif( |
| 23 | not torch_npu.npu.is_available(), reason="NPU not available" | 23 | not torch_npu.npu.is_available(), reason="NPU not available" |
| @@ -13,7 +13,7 @@ import pytest | |||
| 13 | import torch | 13 | import torch |
| 14 | from torch import nn | 14 | from torch import nn |
| 15 | 15 | ||
| 16 | -from torchtitan_npu.extensions.trainer import Trainer, TrainerEx | 16 | +from torchtitan_npu.extensions.torchtitan.trainer import Trainer, TrainerEx |
| 17 | from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode | 17 | from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode |
| 18 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig | 18 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig |
| 19 | 19 | ||
| @@ -944,7 +944,7 @@ def test_chunk_config_prebuilds_metadata_with_full_qk_contract( | |||
| 944 | 944 | ||
| 945 | if quantized: | 945 | if quantized: |
| 946 | pytest.importorskip("torchao_npu") | 946 | pytest.importorskip("torchao_npu") |
| 947 | - from interfaces import torchao_converter | 947 | + from torchtitan_npu.extensions.adaptor.torchao import converter as torchao_converter |
| 948 | from torchtitan_npu.config.configs import QuantizationExtensionConfig | 948 | from torchtitan_npu.config.configs import QuantizationExtensionConfig |
| 949 | 949 | ||
| 950 | monkeypatch.setattr(torchao_converter, "_npu_quantized_module_cache", {}) | 950 | monkeypatch.setattr(torchao_converter, "_npu_quantized_module_cache", {}) |
Rtests/unit_tests/extensions/components/test_checkpoint.py→tests/unit_tests/extensions/torchtitan/components/test_checkpoint.py+10-24
| @@ -55,9 +55,7 @@ checkpoint_stub.AsyncMode = _AsyncMode | |||
| 55 | checkpoint_stub.CheckpointManager = _CheckpointManager | 55 | checkpoint_stub.CheckpointManager = _CheckpointManager |
| 56 | components_stub.checkpoint = checkpoint_stub | 56 | components_stub.checkpoint = checkpoint_stub |
| 57 | observability_stub = types.ModuleType("torchtitan.observability") | 57 | observability_stub = types.ModuleType("torchtitan.observability") |
| 58 | -observability_stub.structured_logger = types.SimpleNamespace( | 58 | +observability_stub.structured_logger = types.SimpleNamespace(log_trace_span=lambda name: lambda function: function) |
| 59 | - log_trace_span=lambda name: lambda function: function | ||
| 60 | -) | ||
| 61 | torchtitan_stub.observability = observability_stub | 59 | torchtitan_stub.observability = observability_stub |
| 62 | tools_stub = types.ModuleType("torchtitan.tools") | 60 | tools_stub = types.ModuleType("torchtitan.tools") |
| 63 | tools_stub.__path__ = [] | 61 | tools_stub.__path__ = [] |
| @@ -65,18 +63,13 @@ torchtitan_stub.tools = tools_stub | |||
| 65 | utils_stub = types.ModuleType("torchtitan.tools.utils") | 63 | utils_stub = types.ModuleType("torchtitan.tools.utils") |
| 66 | utils_stub.GarbageCollection = MagicMock() | 64 | utils_stub.GarbageCollection = MagicMock() |
| 67 | tools_stub.utils = utils_stub | 65 | tools_stub.utils = utils_stub |
| 68 | -validation_stub = types.ModuleType( | 66 | +validation_stub = types.ModuleType("torchtitan_npu.extensions.components.validation") |
| 69 | - "torchtitan_npu.extensions.components.validation" | ||
| 70 | -) | ||
| 71 | validation_stub.mark_checkpoint_manifest_pending = MagicMock() | 67 | validation_stub.mark_checkpoint_manifest_pending = MagicMock() |
| 72 | validation_stub.verify_checkpoint_manifest = MagicMock() | 68 | validation_stub.verify_checkpoint_manifest = MagicMock() |
| 73 | validation_stub.write_checkpoint_manifest = MagicMock() | 69 | validation_stub.write_checkpoint_manifest = MagicMock() |
| 74 | 70 | ||
| 75 | -module_path = ( | 71 | +module_path = Path(__file__).resolve().parents[5] / "torchtitan_npu/extensions/torchtitan/components/checkpoint.py" |
| 76 | - Path(__file__).resolve().parents[4] | 72 | +module_name = "torchtitan_npu.extensions.torchtitan.components.checkpoint" |
| 77 | - / "torchtitan_npu/extensions/components/checkpoint.py" | ||
| 78 | -) | ||
| 79 | -module_name = "torchtitan_npu.extensions.components.checkpoint" | ||
| 80 | module_spec = importlib.util.spec_from_file_location(module_name, module_path) | 73 | module_spec = importlib.util.spec_from_file_location(module_name, module_path) |
| 81 | product_checkpoint = importlib.util.module_from_spec(module_spec) | 74 | product_checkpoint = importlib.util.module_from_spec(module_spec) |
| 82 | 75 | ||
| @@ -106,9 +99,7 @@ def test_config_defaults_hash_manifest_verification_to_disabled(): | |||
| 106 | 99 | ||
| 107 | def test_manager_reads_hash_manifest_extension_config(): | 100 | def test_manager_reads_hash_manifest_extension_config(): |
| 108 | config = product_checkpoint.CheckpointManager.Config( | 101 | config = product_checkpoint.CheckpointManager.Config( |
| 109 | - extensions=product_checkpoint.CheckpointExtensions( | 102 | + extensions=product_checkpoint.CheckpointExtensions(verify_hash_manifest=True) |
| 110 | - verify_hash_manifest=True | ||
| 111 | - ) | ||
| 112 | ) | 103 | ) |
| 113 | 104 | ||
| 114 | manager = product_checkpoint.CheckpointManager(config) | 105 | manager = product_checkpoint.CheckpointManager(config) |
| @@ -117,9 +108,7 @@ def test_manager_reads_hash_manifest_extension_config(): | |||
| 117 | 108 | ||
| 118 | 109 | ||
| 119 | def test_manager_rejects_pinned_async_for_swap_optimizer(): | 110 | def test_manager_rejects_pinned_async_for_swap_optimizer(): |
| 120 | - config = product_checkpoint.CheckpointManager.Config( | 111 | + config = product_checkpoint.CheckpointManager.Config(async_mode="async_with_pinned_mem") |
| 121 | - async_mode="async_with_pinned_mem" | ||
| 122 | - ) | ||
| 123 | optimizers = types.SimpleNamespace(supports_async_with_pinned_mem=False) | 112 | optimizers = types.SimpleNamespace(supports_async_with_pinned_mem=False) |
| 124 | 113 | ||
| 125 | with pytest.raises( | 114 | with pytest.raises( |
| @@ -130,9 +119,7 @@ def test_manager_rejects_pinned_async_for_swap_optimizer(): | |||
| 130 | 119 | ||
| 131 | 120 | ||
| 132 | def test_manager_keeps_pinned_async_for_native_optimizer(): | 121 | def test_manager_keeps_pinned_async_for_native_optimizer(): |
| 133 | - config = product_checkpoint.CheckpointManager.Config( | 122 | + config = product_checkpoint.CheckpointManager.Config(async_mode="async_with_pinned_mem") |
| 134 | - async_mode="async_with_pinned_mem" | ||
| 135 | - ) | ||
| 136 | 123 | ||
| 137 | manager = product_checkpoint.CheckpointManager(config, optimizers=object()) | 124 | manager = product_checkpoint.CheckpointManager(config, optimizers=object()) |
| 138 | 125 | ||
| @@ -179,9 +166,9 @@ def test_save_failure_keeps_pending_and_skips_manifest_write(): | |||
| 179 | side_effect=RuntimeError("checkpoint save failed"), | 166 | side_effect=RuntimeError("checkpoint save failed"), |
| 180 | ), | 167 | ), |
| 181 | patch.object(product_checkpoint, "write_checkpoint_manifest") as write, | 168 | patch.object(product_checkpoint, "write_checkpoint_manifest") as write, |
| 169 | + pytest.raises(RuntimeError, match="checkpoint save failed"), | ||
| 182 | ): | 170 | ): |
| 183 | - with pytest.raises(RuntimeError, match="checkpoint save failed"): | 171 | + manager.save(curr_step=1) |
| 184 | - manager.save(curr_step=1) | ||
| 185 | 172 | ||
| 186 | mark.assert_called_once_with(manager, 1, False) | 173 | mark.assert_called_once_with(manager, 1, False) |
| 187 | write.assert_not_called() | 174 | write.assert_not_called() |
| @@ -216,8 +203,7 @@ def test_dcp_load_verifies_manifest_before_upstream_load(): | |||
| 216 | patch.object( | 203 | patch.object( |
| 217 | _CheckpointManager, | 204 | _CheckpointManager, |
| 218 | "dcp_load", | 205 | "dcp_load", |
| 219 | - side_effect=lambda *args, **kwargs: events.append("load checkpoint") | 206 | + side_effect=lambda *args, **kwargs: events.append("load checkpoint") or "loaded", |
| 220 | - or "loaded", | ||
| 221 | ), | 207 | ), |
| 222 | ): | 208 | ): |
| 223 | result = manager.dcp_load({}, "checkpoint") | 209 | result = manager.dcp_load({}, "checkpoint") |
Rtests/unit_tests/extensions/graph_trainer/test_auto_overlap.py→tests/unit_tests/extensions/torchtitan/experiments/graph_trainer/test_auto_overlap.py+6-6
| @@ -8,9 +8,9 @@ import pytest | |||
| 8 | import torch | 8 | import torch |
| 9 | from torchtitan.experiments.graph_trainer.registry import PASS_PIPELINE_REGISTRY | 9 | from torchtitan.experiments.graph_trainer.registry import PASS_PIPELINE_REGISTRY |
| 10 | 10 | ||
| 11 | -import torchtitan_npu.extensions.graph_trainer as graph_trainer_extension | 11 | +import torchtitan_npu.extensions.torchtitan.experiments.graph_trainer as graph_trainer_extension |
| 12 | -from torchtitan_npu.extensions.graph_trainer import auto_overlap as graph_trainer_auto_overlap | 12 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import auto_overlap as graph_trainer_auto_overlap |
| 13 | -from torchtitan_npu.extensions.graph_trainer.utils import node_id | 13 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer.utils import node_id |
| 14 | 14 | ||
| 15 | 15 | ||
| 16 | def _config(*, debug_graph_passes: bool = False) -> SimpleNamespace: | 16 | def _config(*, debug_graph_passes: bool = False) -> SimpleNamespace: |
| @@ -155,7 +155,7 @@ def test_npu_auto_overlap_keeps_precompiled_runtime_pipeline(caplog): | |||
| 155 | 155 | ||
| 156 | @pytest.mark.parametrize("debug", [False, True]) | 156 | @pytest.mark.parametrize("debug", [False, True]) |
| 157 | def test_npu_auto_overlap_writes_back_scheduler_result(monkeypatch, tmp_path, caplog, debug): | 157 | def test_npu_auto_overlap_writes_back_scheduler_result(monkeypatch, tmp_path, caplog, debug): |
| 158 | - from torchtitan_npu.extensions.graph_trainer import npu_moe_auto_scheduler | 158 | + from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import npu_moe_auto_scheduler |
| 159 | 159 | ||
| 160 | class Scheduler: | 160 | class Scheduler: |
| 161 | def __init__(self, candidate_gm, **_kwargs): | 161 | def __init__(self, candidate_gm, **_kwargs): |
| @@ -288,8 +288,8 @@ def test_two_whole_graph_rounds_measure_previous_schedule_and_keep_latest_fallba | |||
| 288 | monkeypatch, | 288 | monkeypatch, |
| 289 | tmp_path, | 289 | tmp_path, |
| 290 | ): | 290 | ): |
| 291 | - from torchtitan_npu.extensions.graph_trainer import npu_moe_auto_scheduler as scheduler_module | 291 | + from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import npu_moe_auto_scheduler as scheduler_module |
| 292 | - from torchtitan_npu.extensions.graph_trainer import whole_graph_benchmark as benchmark_module | 292 | + from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import whole_graph_benchmark as benchmark_module |
| 293 | 293 | ||
| 294 | graph = torch.fx.Graph() | 294 | graph = torch.fx.Graph() |
| 295 | x = graph.placeholder("x") | 295 | x = graph.placeholder("x") |
Rtests/unit_tests/extensions/graph_trainer/test_collective_benchmark.py→tests/unit_tests/extensions/torchtitan/experiments/graph_trainer/test_collective_benchmark.py+3-3
| @@ -3,7 +3,7 @@ | |||
| 3 | import pytest | 3 | import pytest |
| 4 | import torch | 4 | import torch |
| 5 | 5 | ||
| 6 | -from torchtitan_npu.extensions.graph_trainer.collective_benchmark import ( | 6 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer.collective_benchmark import ( |
| 7 | _a2a_splits_for_rank, | 7 | _a2a_splits_for_rank, |
| 8 | _balanced_splits, | 8 | _balanced_splits, |
| 9 | _build_a2a_split_matrix, | 9 | _build_a2a_split_matrix, |
| @@ -94,7 +94,7 @@ def test_balanced_splits_rejects_invalid_inputs(total, parts): | |||
| 94 | def test_event_benchmark_uses_npu_a2a_materializer(monkeypatch): | 94 | def test_event_benchmark_uses_npu_a2a_materializer(monkeypatch): |
| 95 | from types import SimpleNamespace | 95 | from types import SimpleNamespace |
| 96 | 96 | ||
| 97 | - from torchtitan_npu.extensions.graph_trainer import collective_benchmark | 97 | + from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import collective_benchmark |
| 98 | 98 | ||
| 99 | node = SimpleNamespace(target=torch.ops._c10d_functional.all_to_all_single.default) | 99 | node = SimpleNamespace(target=torch.ops._c10d_functional.all_to_all_single.default) |
| 100 | calls = [] | 100 | calls = [] |
| @@ -144,7 +144,7 @@ def test_event_benchmark_delegates_non_a2a_collectives(): | |||
| 144 | def test_cann_batch_deduplicates_before_materialization(monkeypatch): | 144 | def test_cann_batch_deduplicates_before_materialization(monkeypatch): |
| 145 | from torch._inductor.fx_passes import node_runtime_estimation | 145 | from torch._inductor.fx_passes import node_runtime_estimation |
| 146 | 146 | ||
| 147 | - from torchtitan_npu.extensions.graph_trainer import collective_benchmark | 147 | + from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import collective_benchmark |
| 148 | 148 | ||
| 149 | class Node: | 149 | class Node: |
| 150 | def __init__(self, name, signature): | 150 | def __init__(self, name, signature): |
Rtests/unit_tests/extensions/graph_trainer/test_compute_benchmark.py→tests/unit_tests/extensions/torchtitan/experiments/graph_trainer/test_compute_benchmark.py+2-2
| @@ -5,8 +5,8 @@ from types import SimpleNamespace | |||
| 5 | import pytest | 5 | import pytest |
| 6 | import torch | 6 | import torch |
| 7 | 7 | ||
| 8 | -from torchtitan_npu.extensions.graph_trainer import compute_benchmark | 8 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import compute_benchmark |
| 9 | -from torchtitan_npu.extensions.graph_trainer.compute_benchmark import ( | 9 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer.compute_benchmark import ( |
| 10 | ComputeBenchmarker, | 10 | ComputeBenchmarker, |
| 11 | _balanced_group_boundaries, | 11 | _balanced_group_boundaries, |
| 12 | _grouped_mm_benchmark_spec, | 12 | _grouped_mm_benchmark_spec, |
Rtests/unit_tests/extensions/graph_trainer/test_npu_moe_auto_scheduler.py→tests/unit_tests/extensions/torchtitan/experiments/graph_trainer/test_npu_moe_auto_scheduler.py+6-6
| @@ -9,19 +9,19 @@ from types import SimpleNamespace | |||
| 9 | import pytest | 9 | import pytest |
| 10 | import torch | 10 | import torch |
| 11 | 11 | ||
| 12 | -from torchtitan_npu.extensions.graph_trainer import npu_moe_auto_scheduler as scheduler_module | 12 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import npu_moe_auto_scheduler as scheduler_module |
| 13 | -from torchtitan_npu.extensions.graph_trainer.compute_benchmark import ( | 13 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer.compute_benchmark import ( |
| 14 | benchmark_npu_compute_node, | 14 | benchmark_npu_compute_node, |
| 15 | make_npu_do_bench, | 15 | make_npu_do_bench, |
| 16 | ) | 16 | ) |
| 17 | -from torchtitan_npu.extensions.graph_trainer.npu_moe_auto_scheduler import ( | 17 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer.npu_moe_auto_scheduler import ( |
| 18 | NpuMoeAutoOverlapScheduler, | 18 | NpuMoeAutoOverlapScheduler, |
| 19 | _Exchange, | 19 | _Exchange, |
| 20 | _exchange_label, | 20 | _exchange_label, |
| 21 | _is_token_count_sync_copy, | 21 | _is_token_count_sync_copy, |
| 22 | _is_zero_cost_schedulable_node, | 22 | _is_zero_cost_schedulable_node, |
| 23 | ) | 23 | ) |
| 24 | -from torchtitan_npu.extensions.graph_trainer.utils import ( | 24 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer.utils import ( |
| 25 | assign_stable_node_tags, | 25 | assign_stable_node_tags, |
| 26 | is_metadata_only_compute_node, | 26 | is_metadata_only_compute_node, |
| 27 | node_id, | 27 | node_id, |
| @@ -130,7 +130,7 @@ def test_auto_scheduler_uses_profiler_for_compute_and_events_for_collective( | |||
| 130 | ): | 130 | ): |
| 131 | from torch._inductor.runtime.benchmarking import TorchProfilerBenchmarker | 131 | from torch._inductor.runtime.benchmarking import TorchProfilerBenchmarker |
| 132 | 132 | ||
| 133 | - from torchtitan_npu.extensions.graph_trainer import collective_benchmark | 133 | + from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import collective_benchmark |
| 134 | 134 | ||
| 135 | calls = [] | 135 | calls = [] |
| 136 | 136 | ||
| @@ -355,7 +355,7 @@ def test_uniform_a2a_assumption_rejects_different_dispatch_rows(): | |||
| 355 | 355 | ||
| 356 | 356 | ||
| 357 | def test_permutation_assumptions_use_count_exchange_expert_dimension(monkeypatch): | 357 | def test_permutation_assumptions_use_count_exchange_expert_dimension(monkeypatch): |
| 358 | - from torchtitan_npu.extensions.graph_trainer import npu_moe_auto_scheduler as module | 358 | + from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import npu_moe_auto_scheduler as module |
| 359 | 359 | ||
| 360 | gm, refs = _build_two_chunk_graph() | 360 | gm, refs = _build_two_chunk_graph() |
| 361 | monkeypatch.setattr(module, "PERMUTATION_TARGETS", {str(refs["setup0"].target)}) | 361 | monkeypatch.setattr(module, "PERMUTATION_TARGETS", {str(refs["setup0"].target)}) |
Rtests/unit_tests/extensions/graph_trainer/test_utils.py→tests/unit_tests/extensions/torchtitan/experiments/graph_trainer/test_utils.py+1-1
| @@ -6,7 +6,7 @@ from pathlib import Path | |||
| 6 | import pytest | 6 | import pytest |
| 7 | import torch | 7 | import torch |
| 8 | 8 | ||
| 9 | -from torchtitan_npu.extensions.graph_trainer.utils import ( | 9 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer.utils import ( |
| 10 | assign_stable_node_tags, | 10 | assign_stable_node_tags, |
| 11 | canonical_order, | 11 | canonical_order, |
| 12 | dump_fx_graph, | 12 | dump_fx_graph, |
Rtests/unit_tests/extensions/graph_trainer/test_whole_graph_benchmark.py→tests/unit_tests/extensions/torchtitan/experiments/graph_trainer/test_whole_graph_benchmark.py+3-3
| @@ -8,12 +8,12 @@ from types import SimpleNamespace | |||
| 8 | import pytest | 8 | import pytest |
| 9 | import torch | 9 | import torch |
| 10 | 10 | ||
| 11 | -from torchtitan_npu.extensions.graph_trainer import whole_graph_benchmark as benchmark_module | 11 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import whole_graph_benchmark as benchmark_module |
| 12 | -from torchtitan_npu.extensions.graph_trainer.utils import ( | 12 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer.utils import ( |
| 13 | assign_stable_node_tags, | 13 | assign_stable_node_tags, |
| 14 | node_id, | 14 | node_id, |
| 15 | ) | 15 | ) |
| 16 | -from torchtitan_npu.extensions.graph_trainer.whole_graph_benchmark import ( | 16 | +from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer.whole_graph_benchmark import ( |
| 17 | _align_costs, | 17 | _align_costs, |
| 18 | _collective_count_manifest, | 18 | _collective_count_manifest, |
| 19 | _cross_rank_semantic_keys, | 19 | _cross_rank_semantic_keys, |
Rtorchtitan_npu/distributed/__init__.py→tests/unit_tests/extensions/torchtitan/experiments/torchft/conftest.py+4-2
| @@ -3,6 +3,8 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 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. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | -__all__ = ["set_allow_hf32"] | 6 | +"""Collect TorchFT tests only when their optional distribution is installed.""" |
| 7 | 7 | ||
| 8 | -from .utils import set_allow_hf32 | 8 | +from importlib.util import find_spec |
| 9 | + | ||
| 10 | +collect_ignore_glob = ["test_*.py"] if find_spec("torchft") is None else [] | ||
Rtests/unit_tests/extensions/experiment/torchft/test_discard_manager.py→tests/unit_tests/extensions/torchtitan/experiments/torchft/test_discard_manager.py+2-2
| @@ -12,8 +12,8 @@ import torch | |||
| 12 | from torchft.manager import Manager, WorldSizeMode | 12 | from torchft.manager import Manager, WorldSizeMode |
| 13 | from torchft.process_group import ProcessGroupWrapper | 13 | from torchft.process_group import ProcessGroupWrapper |
| 14 | 14 | ||
| 15 | -from torchtitan_npu.extensions.experiment.torchft.manager import ManagerEx, TorchFTCommitTimeoutError | 15 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.manager import ManagerEx, TorchFTCommitTimeoutError |
| 16 | -from torchtitan_npu.extensions.experiment.torchft.process_group import ProcessGroupHCCLEx | 16 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.process_group import ProcessGroupHCCLEx |
| 17 | 17 | ||
| 18 | 18 | ||
| 19 | def test_begin_step_leaves_quorum_failure_for_commit_vote(): | 19 | def test_begin_step_leaves_quorum_failure_for_commit_vote(): |
Rtests/unit_tests/extensions/experiment/torchft/test_discard_training.py→tests/unit_tests/extensions/torchtitan/experiments/torchft/test_discard_training.py+2-2
| @@ -5,8 +5,8 @@ from unittest.mock import Mock | |||
| 5 | 5 | ||
| 6 | import pytest | 6 | import pytest |
| 7 | 7 | ||
| 8 | -from torchtitan_npu.extensions.experiment.torchft.manager import TorchFTCommitTimeoutError | 8 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.manager import TorchFTCommitTimeoutError |
| 9 | -from torchtitan_npu.extensions.experiment.torchft.recovery import step_recovery | 9 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.recovery import step_recovery |
| 10 | 10 | ||
| 11 | 11 | ||
| 12 | def test_device_recovery_discards_attempt_without_loading_training_state(monkeypatch): | 12 | def test_device_recovery_discards_attempt_without_loading_training_state(monkeypatch): |
Rtests/unit_tests/extensions/experiment/torchft/test_ft_manager.py→tests/unit_tests/extensions/torchtitan/experiments/torchft/test_ft_manager.py+3-3
| @@ -9,7 +9,7 @@ def test_synchronous_npu_manager_contract(): | |||
| 9 | program = """ | 9 | program = """ |
| 10 | from unittest.mock import Mock, patch | 10 | from unittest.mock import Mock, patch |
| 11 | 11 | ||
| 12 | -from torchtitan_npu.extensions.experiment.torchft import ft_manager as module | 12 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft import ft_manager as module |
| 13 | 13 | ||
| 14 | with patch.object(module, 'ManagerEx') as manager, \\ | 14 | with patch.object(module, 'ManagerEx') as manager, \\ |
| 15 | patch.object(module, 'ProcessGroupHCCLEx') as process_group, \\ | 15 | patch.object(module, 'ProcessGroupHCCLEx') as process_group, \\ |
| @@ -57,7 +57,7 @@ from datetime import timedelta | |||
| 57 | from unittest.mock import Mock, patch | 57 | from unittest.mock import Mock, patch |
| 58 | 58 | ||
| 59 | import torch | 59 | import torch |
| 60 | -from torchtitan_npu.extensions.experiment.torchft import process_group as module | 60 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft import process_group as module |
| 61 | 61 | ||
| 62 | with patch('torch_npu._C._distributed_c10d.ProcessGroupHCCL') as hccl, \\ | 62 | with patch('torch_npu._C._distributed_c10d.ProcessGroupHCCL') as hccl, \\ |
| 63 | patch.object(module, 'ProcessGroup') as process_group, \\ | 63 | patch.object(module, 'ProcessGroup') as process_group, \\ |
| @@ -100,7 +100,7 @@ def test_cross_replica_hook_waits_for_the_exact_all_reduce_work(): | |||
| 100 | from unittest.mock import Mock, patch | 100 | from unittest.mock import Mock, patch |
| 101 | 101 | ||
| 102 | import torch | 102 | import torch |
| 103 | -from torchtitan_npu.extensions.experiment.torchft import ft_manager as module | 103 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft import ft_manager as module |
| 104 | 104 | ||
| 105 | events = [] | 105 | events = [] |
| 106 | hooks = [] | 106 | hooks = [] |
Rtests/unit_tests/extensions/experiment/torchft/test_recovery.py→tests/unit_tests/extensions/torchtitan/experiments/torchft/test_recovery.py+5-5
| @@ -14,10 +14,10 @@ import torch_npu | |||
| 14 | from torch.distributed import distributed_c10d | 14 | from torch.distributed import distributed_c10d |
| 15 | from torchft.work import _DummyWork | 15 | from torchft.work import _DummyWork |
| 16 | 16 | ||
| 17 | -from torchtitan_npu.extensions.experiment.torchft.manager import _restore_tensor_leaves, _snapshot_to_cpu | 17 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.manager import _restore_tensor_leaves, _snapshot_to_cpu |
| 18 | -from torchtitan_npu.extensions.experiment.torchft.process_group import ProcessGroupHCCLEx | 18 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.process_group import ProcessGroupHCCLEx |
| 19 | -from torchtitan_npu.extensions.experiment.torchft.recovery import step_recovery | 19 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.recovery import step_recovery |
| 20 | -from torchtitan_npu.extensions.experiment.torchft.recovery.hccl import HcclRecovery, HcclRecoveryError | 20 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.recovery.hccl import HcclRecovery, HcclRecoveryError |
| 21 | 21 | ||
| 22 | 22 | ||
| 23 | def test_cpu_snapshot_survives_optimizer_counter_and_nested_metadata_updates(): | 23 | def test_cpu_snapshot_survives_optimizer_counter_and_nested_metadata_updates(): |
| @@ -154,7 +154,7 @@ def test_only_unfinished_device_work_requests_recovery(monkeypatch, deferred_tim | |||
| 154 | 154 | ||
| 155 | 155 | ||
| 156 | def test_wait_for_completion_retires_only_the_selected_hccl_work(monkeypatch, deferred_timers): | 156 | def test_wait_for_completion_retires_only_the_selected_hccl_work(monkeypatch, deferred_timers): |
| 157 | - monkeypatch.setattr("torchtitan_npu.extensions.experiment.torchft.recovery.hccl.time.sleep", lambda _: None) | 157 | + monkeypatch.setattr("torchtitan_npu.extensions.torchtitan.experiments.torchft.recovery.hccl.time.sleep", lambda _: None) |
| 158 | pg = ProcessGroupHCCLEx(recovery_timeout=timedelta(seconds=1)) | 158 | pg = ProcessGroupHCCLEx(recovery_timeout=timedelta(seconds=1)) |
| 159 | inner_work = Mock(is_completed=Mock(side_effect=[False, True])) | 159 | inner_work = Mock(is_completed=Mock(side_effect=[False, True])) |
| 160 | tracked_work = pg._wrap_work(inner_work, object()) | 160 | tracked_work = pg._wrap_work(inner_work, object()) |
Rtests/unit_tests/extensions/experiment/torchft/test_torchft_optimizer.py→tests/unit_tests/extensions/torchtitan/experiments/torchft/test_torchft_optimizer.py+2-2
| @@ -9,8 +9,8 @@ import pytest | |||
| 9 | import torch | 9 | import torch |
| 10 | from torchtitan.components.optimizer import ParamGroupConfig | 10 | from torchtitan.components.optimizer import ParamGroupConfig |
| 11 | 11 | ||
| 12 | -from torchtitan_npu.extensions.experiment.torchft.optimizer import TorchFTOptimizersContainerEx | 12 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.optimizer import TorchFTOptimizersContainerEx |
| 13 | -from torchtitan_npu.extensions.experiment.torchft.process_group import ProcessGroupHCCLEx | 13 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.process_group import ProcessGroupHCCLEx |
| 14 | 14 | ||
| 15 | 15 | ||
| 16 | def make_optimizer(accepted): | 16 | def make_optimizer(accepted): |
Rtests/unit_tests/extensions/experiment/torchft/test_trainer.py→tests/unit_tests/extensions/torchtitan/experiments/torchft/test_torchft_trainer.py+2-2
| @@ -11,8 +11,8 @@ from unittest.mock import Mock, patch | |||
| 11 | import torch | 11 | import torch |
| 12 | from torchtitan.config import ConfigManager | 12 | from torchtitan.config import ConfigManager |
| 13 | 13 | ||
| 14 | -from torchtitan_npu.extensions.experiment.torchft import trainer as module | 14 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft import trainer as module |
| 15 | -from torchtitan_npu.extensions import trainer as npu_trainer | 15 | +from torchtitan_npu.extensions.torchtitan import trainer as npu_trainer |
| 16 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash, deepseek_v4_flash_8p_torchft | 16 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash, deepseek_v4_flash_8p_torchft |
| 17 | 17 | ||
| 18 | def make_config(): | 18 | def make_config(): |
Rtests/unit_tests/extensions/test_ep_process_group.py→tests/unit_tests/extensions/torchtitan/test_ep_process_group.py+1-1
| @@ -51,7 +51,7 @@ def ep_process_group(): | |||
| 51 | } | 51 | } |
| 52 | previous = {name: sys.modules.get(name) for name in modules} | 52 | previous = {name: sys.modules.get(name) for name in modules} |
| 53 | sys.modules.update(modules) | 53 | sys.modules.update(modules) |
| 54 | - path = Path(__file__).resolve().parents[3] / "torchtitan_npu" / "extensions" / "ep_process_group.py" | 54 | + path = Path(__file__).resolve().parents[4] / "torchtitan_npu" / "extensions" / "torchtitan" / "ep_process_group.py" |
| 55 | spec = importlib.util.spec_from_file_location("ep_process_group_test_impl", path) | 55 | spec = importlib.util.spec_from_file_location("ep_process_group_test_impl", path) |
| 56 | assert spec is not None and spec.loader is not None | 56 | assert spec is not None and spec.loader is not None |
| 57 | module = importlib.util.module_from_spec(spec) | 57 | module = importlib.util.module_from_spec(spec) |
| @@ -0,0 +1,33 @@ | |||
| 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 | +import sys | ||
| 7 | +import types | ||
| 8 | + | ||
| 9 | +import pytest | ||
| 10 | + | ||
| 11 | +from torchtitan_npu.extensions.torchtitan import trainer as trainer_module | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +@pytest.mark.parametrize( | ||
| 15 | + "allow_hf32", | ||
| 16 | + [False, True], | ||
| 17 | + ids=("disabled", "enabled"), | ||
| 18 | +) | ||
| 19 | +def test_set_allow_hf32_updates_all_backends(monkeypatch, allow_hf32): | ||
| 20 | + fake_torch_npu = types.SimpleNamespace( | ||
| 21 | + npu=types.SimpleNamespace( | ||
| 22 | + matmul=types.SimpleNamespace(allow_hf32=None), | ||
| 23 | + conv=types.SimpleNamespace(allow_hf32=None), | ||
| 24 | + aclnn=types.SimpleNamespace(allow_hf32=None), | ||
| 25 | + ) | ||
| 26 | + ) | ||
| 27 | + monkeypatch.setitem(sys.modules, "torch_npu", fake_torch_npu) | ||
| 28 | + | ||
| 29 | + trainer_module.set_allow_hf32(allow_hf32) | ||
| 30 | + | ||
| 31 | + assert fake_torch_npu.npu.matmul.allow_hf32 is allow_hf32 | ||
| 32 | + assert fake_torch_npu.npu.conv.allow_hf32 is allow_hf32 | ||
| 33 | + assert fake_torch_npu.npu.aclnn.allow_hf32 is allow_hf32 | ||
Rtests/unit_tests/extensions/test_peak_flops.py→tests/unit_tests/extensions/torchtitan/tools/test_peak_flops.py+1-7
| @@ -23,13 +23,7 @@ def peak_flops_ext(): | |||
| 23 | 23 | ||
| 24 | original = titan_utils.get_peak_flops | 24 | original = titan_utils.get_peak_flops |
| 25 | 25 | ||
| 26 | - path = ( | 26 | + path = Path(__file__).resolve().parents[5] / "torchtitan_npu" / "extensions" / "torchtitan" / "tools" / "utils.py" |
| 27 | - Path(__file__).resolve().parents[3] | ||
| 28 | - / "torchtitan_npu" | ||
| 29 | - / "extensions" | ||
| 30 | - / "tools" | ||
| 31 | - / "utils.py" | ||
| 32 | - ) | ||
| 33 | spec = importlib.util.spec_from_file_location("peak_flops_test_impl", path) | 27 | spec = importlib.util.spec_from_file_location("peak_flops_test_impl", path) |
| 34 | assert spec is not None and spec.loader is not None | 28 | assert spec is not None and spec.loader is not None |
| 35 | module = importlib.util.module_from_spec(spec) | 29 | module = importlib.util.module_from_spec(spec) |
Rtests/unit_tests/extensions/test_profiler.py→tests/unit_tests/extensions/torchtitan/tools/test_profiler.py+2-3
| @@ -12,13 +12,12 @@ with patch.dict( | |||
| 12 | sys.modules, | 12 | sys.modules, |
| 13 | { | 13 | { |
| 14 | "torch_npu": MagicMock(), | 14 | "torch_npu": MagicMock(), |
| 15 | - "torchtitan_npu.compile": MagicMock(), | ||
| 16 | "torchtitan_npu.patches": MagicMock(), | 15 | "torchtitan_npu.patches": MagicMock(), |
| 17 | }, | 16 | }, |
| 18 | ): | 17 | ): |
| 19 | from torchtitan_npu.config import ProfilerExtensionConfig | 18 | from torchtitan_npu.config import ProfilerExtensionConfig |
| 20 | - from torchtitan_npu.extensions import profiler as profiler_module | 19 | + from torchtitan_npu.extensions.torchtitan.tools import profiler as profiler_module |
| 21 | - from torchtitan_npu.extensions.profiler import ( | 20 | + from torchtitan_npu.extensions.torchtitan.tools.profiler import ( |
| 22 | CANNProfiler, | 21 | CANNProfiler, |
| 23 | _profile_window_schedule, | 22 | _profile_window_schedule, |
| 24 | _resume_aware_schedule, | 23 | _resume_aware_schedule, |
Rtests/unit_tests/compile/test_recompute_policy.py→tests/unit_tests/models/deepseek_v4/memory_policy/test_recompute_policy.py+1-4
| @@ -10,7 +10,6 @@ from torch.utils.checkpoint import CheckpointPolicy | |||
| 10 | from torchtitan.experiments.graph_trainer.memory_policy import ( | 10 | from torchtitan.experiments.graph_trainer.memory_policy import ( |
| 11 | tag_with_memory_policy_pass, | 11 | tag_with_memory_policy_pass, |
| 12 | ) | 12 | ) |
| 13 | -from torchtitan.experiments.graph_trainer.registry import MEMORY_POLICY_REGISTRY | ||
| 14 | from torchtitan.experiments.graph_trainer.selective_activation_remat import ( | 13 | from torchtitan.experiments.graph_trainer.selective_activation_remat import ( |
| 15 | selective_activation_remat_pass, | 14 | selective_activation_remat_pass, |
| 16 | ) | 15 | ) |
| @@ -171,8 +170,6 @@ def test_dsv4_mhc_layer_boundaries_and_moe_save() -> None: | |||
| 171 | assert f"pre{layer_id}_recomputed" in names | 170 | assert f"pre{layer_id}_recomputed" in names |
| 172 | assert f"post{layer_id}_recomputed" not in names | 171 | assert f"post{layer_id}_recomputed" not in names |
| 173 | assert nodes[f"post{layer_id}"] in nodes[f"bwd_post{layer_id}"].all_input_nodes | 172 | assert nodes[f"post{layer_id}"] in nodes[f"bwd_post{layer_id}"].all_input_nodes |
| 174 | - assert f"pre{layer_id}_recomputed" in { | 173 | + assert f"pre{layer_id}_recomputed" in {node.name for node in nodes[f"bwd_pre{layer_id}"].all_input_nodes} |
| 175 | - node.name for node in nodes[f"bwd_pre{layer_id}"].all_input_nodes | ||
| 176 | - } | ||
| 177 | gm.graph.lint() | 174 | gm.graph.lint() |
| 178 | torch.testing.assert_close(gm(*inputs), expected, rtol=0, atol=0) | 175 | torch.testing.assert_close(gm(*inputs), expected, rtol=0, atol=0) |
Rtests/unit_tests/compile/test_swiglu_memory_policy.py→tests/unit_tests/models/deepseek_v4/memory_policy/test_swiglu_memory_policy.py+0-0
File renamed without changes.
| @@ -33,7 +33,7 @@ def test_flash_mtp_4k_model_flops(): | |||
| 33 | 33 | ||
| 34 | 34 | ||
| 35 | def test_debugmodel_uses_cann_profiler_extension(): | 35 | def test_debugmodel_uses_cann_profiler_extension(): |
| 36 | - from torchtitan_npu.extensions.profiler import CANNProfiler | 36 | + from torchtitan_npu.extensions.torchtitan.tools.profiler import CANNProfiler |
| 37 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | 37 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel |
| 38 | 38 | ||
| 39 | config = deepseek_v4_debugmodel() | 39 | config = deepseek_v4_debugmodel() |
| @@ -126,7 +126,7 @@ def test_dsv4_muon_policy_resolves_combined_cp_storage_mesh(tmp_path, mesh_axis) | |||
| 126 | @pytest.fixture | 126 | @pytest.fixture |
| 127 | def ao(monkeypatch): | 127 | def ao(monkeypatch): |
| 128 | pytest.importorskip("torchao_npu") | 128 | pytest.importorskip("torchao_npu") |
| 129 | - module = importlib.import_module("interfaces.torchao_converter") | 129 | + module = importlib.import_module("torchtitan_npu.extensions.adaptor.torchao.converter") |
| 130 | monkeypatch.setattr(module, "_ensure_cann_ops_loaded", lambda: None) | 130 | monkeypatch.setattr(module, "_ensure_cann_ops_loaded", lambda: None) |
| 131 | return module | 131 | return module |
| 132 | 132 | ||
| @@ -50,7 +50,7 @@ def _make_checkpoint_fixture(tmp_path, save_training_state, checkpoint_format, w | |||
| 50 | model = Model() | 50 | model = Model() |
| 51 | if wrapper_scope == "block-fp8": | 51 | if wrapper_scope == "block-fp8": |
| 52 | pytest.importorskip("torchao_npu") | 52 | pytest.importorskip("torchao_npu") |
| 53 | - from interfaces.torchao_converter import _block_fp8_param_swap | 53 | + from torchtitan_npu.extensions.adaptor.torchao.converter import _block_fp8_param_swap |
| 54 | from torchao_npu.wrapper_tensors.block_mx_wrapper_tensor import BlockMXTrainingWeightWrapperTensor | 54 | from torchao_npu.wrapper_tensors.block_mx_wrapper_tensor import BlockMXTrainingWeightWrapperTensor |
| 55 | 55 | ||
| 56 | policy = _block_fp8_param_swap() | 56 | policy = _block_fp8_param_swap() |
| @@ -11,7 +11,7 @@ import pytest | |||
| 11 | import torch | 11 | import torch |
| 12 | from torch.utils.checkpoint import checkpoint, DefaultDeviceType | 12 | from torch.utils.checkpoint import checkpoint, DefaultDeviceType |
| 13 | 13 | ||
| 14 | -from torchtitan_npu.extensions.components import optimizer as host_mod | 14 | +from torchtitan_npu.extensions.torchtitan.components.optimizer import optimizer as host_mod |
| 15 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable | 15 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable |
| 16 | 16 | ||
| 17 | pytestmark = pytest.mark.cpu | 17 | pytestmark = pytest.mark.cpu |
| @@ -22,7 +22,7 @@ from torchtitan_npu.models.deepseek_v4_1 import ( | |||
| 22 | ) | 22 | ) |
| 23 | from torchtitan_npu.models.deepseek_v4_1.state_dict_adapter import DeepSeekV41StateDictAdapter | 23 | from torchtitan_npu.models.deepseek_v4_1.state_dict_adapter import DeepSeekV41StateDictAdapter |
| 24 | from torchtitan_npu.models.deepseek_v4_1.vision.state_dict_adapter import DeepSeekV41VisionStateDictAdapter | 24 | from torchtitan_npu.models.deepseek_v4_1.vision.state_dict_adapter import DeepSeekV41VisionStateDictAdapter |
| 25 | -from torchtitan_npu.scripts.checkpoint_conversion.convert_to_hf import load_dcp_model | 25 | +from torchtitan_npu.tools.checkpoint_conversion.convert_to_hf import load_dcp_model |
迁移 optimizer 时漏改了 test_engram_host.py:14。它仍从 extensions.components 导入 optimizer,而旧模块已不存在,完整 UT 收集会 ImportError。请一并更新到 extensions.torchtitan.components.optimizer.optimizer 的新位置。 ![]() ![]() | |||
| 26 | 26 | ||
| 27 | 27 | ||
| 28 | def _build_model_config(): | 28 | def _build_model_config(): |
| @@ -20,7 +20,7 @@ def _run_isolated(source: str, root: Path) -> None: | |||
| 20 | def test_qwen3_5_launcher_delegates_to_run_train_and_uses_current_gdn_override(): | 20 | def test_qwen3_5_launcher_delegates_to_run_train_and_uses_current_gdn_override(): |
| 21 | root = Path(__file__).resolve().parents[4] | 21 | root = Path(__file__).resolve().parents[4] |
| 22 | script = (root / "examples/qwen3_5/qwen3_5_debugmodel_1p_cpt_512.sh").read_text(encoding="utf-8") | 22 | script = (root / "examples/qwen3_5/qwen3_5_debugmodel_1p_cpt_512.sh").read_text(encoding="utf-8") |
| 23 | - eager_flex = (root / "torchtitan_npu/patches/workaround/eager_flex.py").read_text(encoding="utf-8") | 23 | + eager_flex = (root / "torchtitan_npu/extensions/torchtitan/eager_flex.py").read_text(encoding="utf-8") |
| 24 | 24 | ||
| 25 | 25 | ||
| 26 | assert "bash scripts/run_train.sh" in script | 26 | assert "bash scripts/run_train.sh" in script |
| @@ -57,7 +57,7 @@ def test_qwen3_5_adapter_applies_only_early_compatibility_patches(): | |||
| 57 | assert MultiModalCollator._build_mrope_positions is patched_build_mrope_positions | 57 | assert MultiModalCollator._build_mrope_positions is patched_build_mrope_positions |
| 58 | assert upstream_vision.compiled_create_block_mask is eager_create_block_mask | 58 | assert upstream_vision.compiled_create_block_mask is eager_create_block_mask |
| 59 | assert upstream_vision.Qwen35VisionEncoder.forward is owning_vision_encoder_forward | 59 | assert upstream_vision.Qwen35VisionEncoder.forward is owning_vision_encoder_forward |
| 60 | - from torchtitan_npu.patches.workaround import eager_flex | 60 | + from torchtitan_npu.extensions.torchtitan import eager_flex |
| 61 | assert callable(eager_flex.mark_dense_sdpa_mask_mod) | 61 | assert callable(eager_flex.mark_dense_sdpa_mask_mod) |
| 62 | assert callable(eager_flex._run_eager_flex_attention) | 62 | assert callable(eager_flex._run_eager_flex_attention) |
| 63 | """, | 63 | """, |
| @@ -195,7 +195,7 @@ def test_qwen3_5_flex_attention_preserves_aux_output_protocol(): | |||
| 195 | import torch | 195 | import torch |
| 196 | import torchtitan_npu.models.qwen3_5 | 196 | import torchtitan_npu.models.qwen3_5 |
| 197 | from torch.nn.attention.flex_attention import AuxOutput, AuxRequest, create_block_mask | 197 | from torch.nn.attention.flex_attention import AuxOutput, AuxRequest, create_block_mask |
| 198 | - from torchtitan_npu.patches.workaround.eager_flex import _run_eager_flex_attention | 198 | + from torchtitan_npu.extensions.torchtitan.eager_flex import _run_eager_flex_attention |
| 199 | 199 | ||
| 200 | q = torch.randn(1, 1, 4, 4) | 200 | q = torch.randn(1, 1, 4, 4) |
| 201 | k = torch.randn(1, 1, 4, 4) | 201 | k = torch.randn(1, 1, 4, 4) |
| @@ -100,7 +100,7 @@ def test_cpu_offload_preserves_sparse_training_and_checkpoint(monkeypatch, overr | |||
| 100 | 100 | ||
| 101 | from torchtitan.config import Configurable, OverrideConfig, apply_overrides | 101 | from torchtitan.config import Configurable, OverrideConfig, apply_overrides |
| 102 | 102 | ||
| 103 | - from torchtitan_npu.extensions.components.optimizer import ( | 103 | + from torchtitan_npu.extensions.torchtitan.components.optimizer.optimizer import ( |
| 104 | HostSparseOptimizersContainer, | 104 | HostSparseOptimizersContainer, |
| 105 | ) | 105 | ) |
| 106 | from torchtitan_npu.extensions.distributed import grad_accum, grad_clip | 106 | from torchtitan_npu.extensions.distributed import grad_accum, grad_clip |
| @@ -1178,7 +1178,7 @@ def test_swap_preserves_host_sparse_update(monkeypatch, override_name): | |||
| 1178 | from torchtitan.components.optimizer import ParamGroupConfig | 1178 | from torchtitan.components.optimizer import ParamGroupConfig |
| 1179 | 1179 | ||
| 1180 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable | 1180 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable |
| 1181 | - from torchtitan_npu.extensions.components.optimizer import HostSparseOptimizersContainer | 1181 | + from torchtitan_npu.extensions.torchtitan.components.optimizer.optimizer import HostSparseOptimizersContainer |
| 1182 | 1182 | ||
| 1183 | allocations = [] | 1183 | allocations = [] |
| 1184 | 1184 | ||
| @@ -1245,7 +1245,9 @@ def test_swap_preserves_host_sparse_update(monkeypatch, override_name): | |||
| 1245 | def test_host_sparse_swap_checkpoint_resumes_exactly(monkeypatch, tmp_path, saved_steps): | 1245 | def test_host_sparse_swap_checkpoint_resumes_exactly(monkeypatch, tmp_path, saved_steps): |
| 1246 | from torchtitan.components.optimizer import ParamGroupConfig | 1246 | from torchtitan.components.optimizer import ParamGroupConfig |
| 1247 | 1247 | ||
| 1248 | - from torchtitan_npu.extensions.components.optimizer import HostSparseOptimizersContainer | 1248 | + from torchtitan_npu.extensions.torchtitan.components.optimizer.optimizer import ( |
| 1249 | + HostSparseOptimizersContainer, | ||
| 1250 | + ) | ||
| 1249 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable | 1251 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable |
| 1250 | 1252 | ||
| 1251 | _patch_fake_swap_runtime(monkeypatch) | 1253 | _patch_fake_swap_runtime(monkeypatch) |
| @@ -1326,8 +1328,8 @@ def test_hostsparse_schema_keeps_sparse_lifecycle_under_npu_state(monkeypatch) - | |||
| 1326 | """ | 1328 | """ |
| 1327 | from torchtitan_npu.config.configs import TrainingConfig | 1329 | from torchtitan_npu.config.configs import TrainingConfig |
| 1328 | from torchtitan_npu.extensions import trainer as trainer_module | 1330 | from torchtitan_npu.extensions import trainer as trainer_module |
| 1329 | - from torchtitan_npu.extensions.components.optimizer import HostSparseOptimizersContainer | 1331 | + from torchtitan_npu.extensions.torchtitan.components.optimizer.optimizer import HostSparseOptimizersContainer |
| 1330 | - from torchtitan_npu.extensions.trainer import TrainerEx | 1332 | + from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 1331 | from torchtitan_npu.override.common.optimizer import ( | 1333 | from torchtitan_npu.override.common.optimizer import ( |
| 1332 | CpuOffloadHostSparseNpuStateOptimizersContainer, | 1334 | CpuOffloadHostSparseNpuStateOptimizersContainer, |
| 1333 | CpuOffloadHostSparseOptimizersContainer, | 1335 | CpuOffloadHostSparseOptimizersContainer, |
| @@ -14,7 +14,7 @@ from torch.utils.checkpoint import checkpoint, DefaultDeviceType | |||
| 14 | from torchtitan.config import Configurable, OverrideConfig, TrainingConfig, apply_overrides | 14 | from torchtitan.config import Configurable, OverrideConfig, TrainingConfig, apply_overrides |
| 15 | from torchtitan.components.optimizer import ParamGroupConfig | 15 | from torchtitan.components.optimizer import ParamGroupConfig |
| 16 | 16 | ||
| 17 | -from torchtitan_npu.extensions.components.optimizer import HostSparseOptimizersContainer | 17 | +from torchtitan_npu.extensions.torchtitan.components.optimizer.optimizer import HostSparseOptimizersContainer |
| 18 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable | 18 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable |
| 19 | from torchtitan_npu.models.deepseek_v4_1.parallelize import _shard_engram_tables | 19 | from torchtitan_npu.models.deepseek_v4_1.parallelize import _shard_engram_tables |
| 20 | from torchtitan_npu.override.deepseek_v4_1.engram import ascendc, mxfp8 | 20 | from torchtitan_npu.override.deepseek_v4_1.engram import ascendc, mxfp8 |
Rtests/unit_tests/distributed/test_fsdp_precision.py→tests/unit_tests/patches/torch/distributed/fsdp/test_fsdp_precision.py+0-0
File renamed without changes.
Rtests/unit_tests/patches/workaround/test_device_copy.py→tests/unit_tests/patches/torch_npu/test_device_copy.py+1-1
| @@ -19,7 +19,7 @@ from pathlib import Path | |||
| 19 | import pytest | 19 | import pytest |
| 20 | 20 | ||
| 21 | _REPO = Path(__file__).resolve().parents[3] | 21 | _REPO = Path(__file__).resolve().parents[3] |
| 22 | -_PATCH_PATH = _REPO.parent / "torchtitan_npu" / "patches" / "workaround" / "device_copy.py" | 22 | +_PATCH_PATH = _REPO.parent / "torchtitan_npu" / "patches" / "torch_npu" / "device_copy.py" |
| 23 | 23 | ||
| 24 | 24 | ||
| 25 | class _FakeLayout: | 25 | class _FakeLayout: |
| @@ -56,7 +56,7 @@ class BlockTorchFT(importlib.abc.MetaPathFinder): | |||
| 56 | 56 | ||
| 57 | sys.meta_path.insert(0, BlockTorchFT()) | 57 | sys.meta_path.insert(0, BlockTorchFT()) |
| 58 | import torchtitan_npu | 58 | import torchtitan_npu |
| 59 | -from torchtitan_npu.extensions.trainer import TrainerEx | 59 | +from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 60 | 60 | ||
| 61 | assert not any(name == 'torchft' or name.startswith('torchft.') for name in sys.modules) | 61 | assert not any(name == 'torchft' or name.startswith('torchft.') for name in sys.modules) |
| 62 | common_args = [ | 62 | common_args = [ |
| @@ -65,7 +65,7 @@ def test_dsv4_muon_profile_uses_validated_phase_one_policy(): | |||
| 65 | assert "muon_ns_steps=10" in optimizer_source | 65 | assert "muon_ns_steps=10" in optimizer_source |
| 66 | assert "beta1=0.9" in optimizer_source | 66 | assert "beta1=0.9" in optimizer_source |
| 67 | assert "eps=1e-8" in optimizer_source | 67 | assert "eps=1e-8" in optimizer_source |
| 68 | - trainer_source = (_ROOT / "torchtitan_npu/extensions/trainer.py").read_text() | 68 | + trainer_source = (_ROOT / "torchtitan_npu/extensions/torchtitan/trainer.py").read_text() |
| 69 | assert "tensor_parallel_degree=1" in trainer_source | 69 | assert "tensor_parallel_degree=1" in trainer_source |
| 70 | assert "pipeline_parallel_degree=1" in trainer_source | 70 | assert "pipeline_parallel_degree=1" in trainer_source |
| 71 | assert "def deepseek_v4_debugmodel_muon" not in file_source | 71 | assert "def deepseek_v4_debugmodel_muon" not in file_source |
| @@ -17,7 +17,7 @@ from torch.distributed.tensor import DTensor, Replicate | |||
| 17 | from torchtitan.trainer import Trainer | 17 | from torchtitan.trainer import Trainer |
| 18 | 18 | ||
| 19 | from torchtitan_npu.extensions.components.sdc.sdc import SDC | 19 | from torchtitan_npu.extensions.components.sdc.sdc import SDC |
| 20 | -from torchtitan_npu.extensions.trainer import TrainerEx | 20 | +from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 21 | 21 | ||
| 22 | 22 | ||
| 23 | class TorchNpuCheckerFake: | 23 | class TorchNpuCheckerFake: |
| @@ -321,13 +321,13 @@ def test_sdc_build_finishes_runtime_initialization_in_one_call(monkeypatch) -> N | |||
| 321 | monkeypatch.delenv("NPU_ASD_CONFIG", raising=False) | 321 | monkeypatch.delenv("NPU_ASD_CONFIG", raising=False) |
| 322 | monkeypatch.delenv("NPU_ASD_ENABLE", raising=False) | 322 | monkeypatch.delenv("NPU_ASD_ENABLE", raising=False) |
| 323 | checksum_installs: list[bool] = [] | 323 | checksum_installs: list[bool] = [] |
| 324 | - checksum_module = ModuleType("torchtitan_npu.compile.sdc_checksum") | 324 | + checksum_module = ModuleType("torchtitan_npu.extensions.compile.sdc_checksum") |
| 325 | 325 | ||
| 326 | def install_checksum_pass() -> None: | 326 | def install_checksum_pass() -> None: |
| 327 | checksum_installs.append(True) | 327 | checksum_installs.append(True) |
| 328 | 328 | ||
| 329 | vars(checksum_module)["install_checksum_pass"] = install_checksum_pass | 329 | vars(checksum_module)["install_checksum_pass"] = install_checksum_pass |
| 330 | - monkeypatch.setitem(sys.modules, "torchtitan_npu.compile.sdc_checksum", checksum_module) | 330 | + monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.compile.sdc_checksum", checksum_module) |
| 331 | model = torch.nn.Module() | 331 | model = torch.nn.Module() |
| 332 | model.register_parameter("weight", torch.nn.Parameter(torch.ones(2, 2, dtype=torch.bfloat16))) | 332 | model.register_parameter("weight", torch.nn.Parameter(torch.ones(2, 2, dtype=torch.bfloat16))) |
| 333 | 333 | ||
| @@ -588,7 +588,7 @@ def _patch_trainer_sdc_flow(monkeypatch) -> tuple[list[object], TrainerEx.Config | |||
| 588 | return "base-result" | 588 | return "base-result" |
| 589 | 589 | ||
| 590 | monkeypatch.setattr(TrainerEx.__base__, "__init__", base_init) | 590 | monkeypatch.setattr(TrainerEx.__base__, "__init__", base_init) |
| 591 | - monkeypatch.setattr("torchtitan_npu.extensions.trainer.set_allow_hf32", lambda _allow_hf32: None) | 591 | + monkeypatch.setattr("torchtitan_npu.extensions.torchtitan.trainer.set_allow_hf32", lambda _allow_hf32: None) |
| 592 | monkeypatch.setattr(TrainerEx.__base__, "init_distributed", init_distributed) | 592 | monkeypatch.setattr(TrainerEx.__base__, "init_distributed", init_distributed) |
| 593 | monkeypatch.setattr(TrainerEx.__base__, "forward_backward_step", forward_backward_step) | 593 | monkeypatch.setattr(TrainerEx.__base__, "forward_backward_step", forward_backward_step) |
| 594 | return events, config | 594 | return events, config |
| @@ -0,0 +1,90 @@ | |||
| 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 | +"""CPU tests for the architecture-boundary ratchet.""" | ||
| 7 | + | ||
| 8 | +from pathlib import Path | ||
| 9 | + | ||
| 10 | +import pytest | ||
| 11 | + | ||
| 12 | +from scripts.check_architecture_boundaries import check | ||
| 13 | + | ||
| 14 | +pytestmark = pytest.mark.tooling | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +def _write(root: Path, relative: str, content: str = "") -> None: | ||
| 18 | + path = root / relative | ||
| 19 | + path.parent.mkdir(parents=True, exist_ok=True) | ||
| 20 | + path.write_text(content, encoding="utf-8") | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def _write_baseline(root: Path, content: str = "{}") -> Path: | ||
| 24 | + baseline = root / ".ci/architecture_import_baseline.json" | ||
| 25 | + _write(root, ".ci/architecture_import_baseline.json", content) | ||
| 26 | + return baseline | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def test_allows_registered_legacy_import_but_rejects_new_one(tmp_path): | ||
| 30 | + _write(tmp_path, "torchtitan_npu/extensions/legacy.py", "from torchtitan_npu.models import legacy\n") | ||
| 31 | + _write(tmp_path, "torchtitan_npu/extensions/new.py", "from torchtitan_npu.models import new\n") | ||
| 32 | + baseline = _write_baseline( | ||
| 33 | + tmp_path, | ||
| 34 | + """{ | ||
| 35 | + "import": [ | ||
| 36 | + { | ||
| 37 | + "source": "torchtitan_npu/extensions/legacy.py", | ||
| 38 | + "target_module": "torchtitan_npu.models" | ||
| 39 | + } | ||
| 40 | + ] | ||
| 41 | +}""", | ||
| 42 | + ) | ||
| 43 | + | ||
| 44 | + assert check(tmp_path, baseline) == [ | ||
| 45 | + "new forbidden import: torchtitan_npu/extensions/new.py -> torchtitan_npu.models" | ||
| 46 | + ] | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def test_rejects_patch_to_extension_import(tmp_path): | ||
| 50 | + _write( | ||
| 51 | + tmp_path, | ||
| 52 | + "torchtitan_npu/patches/torchtitan/example.py", | ||
| 53 | + "# Upstream-PR: https://example.invalid/1\nfrom torchtitan_npu.extensions import example\n", | ||
| 54 | + ) | ||
| 55 | + baseline = _write_baseline(tmp_path) | ||
| 56 | + | ||
| 57 | + assert check(tmp_path, baseline) == [ | ||
| 58 | + "new forbidden import: torchtitan_npu/patches/torchtitan/example.py -> torchtitan_npu.extensions" | ||
| 59 | + ] | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def test_rejects_new_patch_without_header_metadata(tmp_path): | ||
| 63 | + _write(tmp_path, "torchtitan_npu/patches/torchtitan/example.py", "VALUE = 1\n") | ||
| 64 | + baseline = _write_baseline(tmp_path) | ||
| 65 | + | ||
| 66 | + assert check(tmp_path, baseline) == [ | ||
| 67 | + "new patch missing upstream metadata: torchtitan_npu/patches/torchtitan/example.py" | ||
| 68 | + ] | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def test_rejects_activation_order_change(tmp_path): | ||
| 72 | + _write( | ||
| 73 | + tmp_path, | ||
| 74 | + "torchtitan_npu/extensions/__init__.py", | ||
| 75 | + "from .torchtitan import second\nfrom .torchtitan import first\n", | ||
| 76 | + ) | ||
| 77 | + baseline = _write_baseline( | ||
| 78 | + tmp_path, | ||
| 79 | + """{ | ||
| 80 | + "activation_order": { | ||
| 81 | + "torchtitan_npu/extensions/__init__.py": [".torchtitan.first", ".torchtitan.second"] | ||
| 82 | + } | ||
| 83 | +}""", | ||
| 84 | + ) | ||
| 85 | + | ||
| 86 | + assert check(tmp_path, baseline) == [ | ||
| 87 | + "activation order changed: torchtitan_npu/extensions/__init__.py; " | ||
| 88 | + "expected ['.torchtitan.first', '.torchtitan.second'], " | ||
| 89 | + "got ['.torchtitan.second', '.torchtitan.first']" | ||
| 90 | + ] | ||
Rtests/unit_tests/scripts/checkpoint_conversion/test_export_dtype.py→tests/unit_tests/tools/checkpoint_conversion/test_export_dtype.py+1-1
| @@ -26,7 +26,7 @@ class IdentityHFAdapter: | |||
| 26 | @pytest.fixture | 26 | @pytest.fixture |
| 27 | def export_module(): | 27 | def export_module(): |
| 28 | root = Path(__file__).resolve().parents[4] | 28 | root = Path(__file__).resolve().parents[4] |
| 29 | - path = root / "torchtitan_npu/scripts/checkpoint_conversion/convert_to_hf.py" | 29 | + path = root / "torchtitan_npu/tools/checkpoint_conversion/convert_to_hf.py" |
| 30 | spec = importlib.util.spec_from_file_location("checkpoint_export_dtype", path) | 30 | spec = importlib.util.spec_from_file_location("checkpoint_export_dtype", path) |
| 31 | assert spec is not None and spec.loader is not None | 31 | assert spec is not None and spec.loader is not None |
| 32 | module = importlib.util.module_from_spec(spec) | 32 | module = importlib.util.module_from_spec(spec) |
Rtests/unit_tests/checkpoint_conversion/test_export_quantized_hf.py→tests/unit_tests/tools/checkpoint_conversion/test_export_quantized_hf.py+2-2
| @@ -13,8 +13,8 @@ from pathlib import Path | |||
| 13 | import pytest | 13 | import pytest |
| 14 | import torch | 14 | import torch |
| 15 | 15 | ||
| 16 | -_REPO = Path(__file__).resolve().parents[3] | 16 | +_REPO = Path(__file__).resolve().parents[4] |
| 17 | -_SCRIPT = _REPO / "torchtitan_npu" / "scripts" / "checkpoint_conversion" / "export_quantized_hf.py" | 17 | +_SCRIPT = _REPO / "torchtitan_npu" / "tools" / "checkpoint_conversion" / "export_quantized_hf.py" |
| 18 | 18 | ||
| 19 | _K = 64 # weight inner dim; 2 MX blocks of 32 per row | 19 | _K = 64 # weight inner dim; 2 MX blocks of 32 per row |
| 20 | _N = 4 # per-expert rows for w1 / w3 | 20 | _N = 4 # per-expert rows for w1 / w3 |
| @@ -0,0 +1,55 @@ | |||
| 1 | +# torchtitan_npu 目标结构与代码放置 | ||
| 2 | + | ||
| 3 | +新增和迁移触及的代码遵循本目标;历史代码按 [架构提案](../.agents/notes/proposed/architecture/2026-09-02-plugin-layout-and-injection-boundaries.md) 收敛。正式目标见 [目标架构](../docs/architecture.md),当前实现状态以代码和该 Agent Note 的迁移矩阵为准。 | ||
| 4 | + | ||
| 5 | +## 代码放置 | ||
| 6 | + | ||
| 7 | +生产子包为 `config/`、`patches/`、`extensions/`、`override/`、`models/`、`ops/` 与 `tools/`。外部包适配位于 `extensions/adaptor/`。根目录只保留包入口与训练入口;不要新增其他生产代码落点。 | ||
| 8 | + | ||
| 9 | +| 目录 | 目标职责 | 允许的直接依赖 | | ||
| 10 | +| --- | --- | --- | | ||
| 11 | +| `config/` | NPU config schema、纯转换器与显式注册 API | 标准库与上游配置 API;当前包导入会安装 ConfigManager loader wrapper,拆除该副作用是后续目标 | | ||
| 12 | +| `patches/` | 上游 `torchtitan` 或 `torch_npu` 的待合入补丁 | 不得新增对 `extensions/` 的依赖 | | ||
| 13 | +| `models/` | 应由上游 TorchTitan 拥有、但尚未合入的模型定义、配置、并行化与 checkpoint 适配 | 现有跨层依赖是迁移债务,不宣称已清零 | | ||
| 14 | +| `extensions/` | 本仓永久额外扩展、组件集成与图编译注册 | 可依赖 `patches/` 定义;不得新增对 `models/`、`override/` 或 `ops/` 的依赖 | | ||
| 15 | +| `extensions/adaptor/` | 可选外部 distribution 与本仓公开配置/模型接口的适配 | 使用公开接口;现有 patch 私有依赖是迁移债务 | | ||
| 16 | +| `override/` | `override.imports` 显式选择的 NPU/CANN 组件替换 | 可使用 `ops/`;现有对 `extensions/` 的依赖是迁移债务 | | ||
| 17 | +| `ops/` | 设备 kernel、最小启动封装与 `torch.library` 注册 | 仅实现算子所需的后端代码 | | ||
| 18 | +| `tools/` | 需要随 Python package 分发的 checkpoint 转换与导出工具 | 上游包与公开的本仓模型/集成 API | | ||
| 19 | + | ||
| 20 | +新增代码遵守单向边界:`extensions/` 可以依赖 `patches/`,`patches/` 不得新增对 `extensions/` 的依赖;`extensions/` 不得新增对 `models/`、`override/` 或 `ops/` 的依赖。现有反向边在架构 Agent Note 中登记并逐项收敛。 | ||
| 21 | + | ||
| 22 | +模型无关能力放在最通用的适用位置。不要把通用 patch、extension、算子或配置逻辑放进模型专属文件;不要为了绕开上述依赖方向增加临时 wrapper。 | ||
| 23 | + | ||
| 24 | +## 注入与启用 | ||
| 25 | + | ||
| 26 | +当前 `__init__.py` 的自动导入顺序是: | ||
| 27 | + | ||
| 28 | +```text | ||
| 29 | +patches → config → extensions → ops | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +- `patches/` 先导入并完成上游替换;`extensions/` 随后可复用 patch 定义或经上游路径使用其效果。 | ||
| 33 | +- `config/` 当前通过导入 `manager` 安装 `ConfigManager._load_config` wrapper;该副作用服务于现有配置转换,尚未迁入 extension 激活入口。 | ||
| 34 | +- `override/` 不是自动导入层;它由 `override.imports` 显式选择。 | ||
| 35 | +- 收敛为 `patches → extensions` 是后续目标。当前 `config` 和 `ops` 仍由包入口导入,不能把目标顺序写成已实现行为。 | ||
| 36 | +- `TORCHTITAN_NPU_DISABLE_EXTENSIONS` 和 `TORCHTITAN_NPU_DISABLE_COMPONENTS` 是未实现的目标加载接口,当前不能作为运行时配置使用;实现状态见 [extensions 规则](extensions/AGENTS.md)。 | ||
| 37 | + | ||
| 38 | +## patches 与 extensions 的时序边界 | ||
| 39 | + | ||
| 40 | +以下是目标约束;尚未迁移的历史入口不能据此被视为已经满足。 | ||
| 41 | + | ||
| 42 | +- `patches/` 是尚未合入上游代码的替身,可在显式激活顺序中替换上游类、函数及 `.Config` schema。凡影响上游 dataclass schema 或默认工厂的替换,必须先于任何会导入上游 `trainer` 的激活模块执行。 | ||
| 43 | +- `patches/torchtitan/__init__.py` 的显式导入列表定义当前激活顺序。该列表不能因 import 自动排序、代码整理或自动发现改变;用相应检查保护具体顺序,不使用与当前列表不符的「trainer 必须最后导入」规则。 | ||
| 44 | +- 替换上游符号后,必须刷新或明确说明所有已被上游 `from ... import ...` 捕获的绑定。无法确认不存在未知捕获点时,优先使用上游公开注册机制,或将能力改为下述 extension 机制。 | ||
| 45 | +- `extensions/` 在 patches 之后运行,默认所有上游模块已导入、所有 dataclass 已生成;新增 extension 不得依赖「导入足够早」,也不得替换已被上游 dataclass 捕获的 `.Config`。 | ||
| 46 | +- extension 仅可通过时序无关的机制生效:配置外包装、运行期方法 seam、单目标 hook 注册组件、公开注册 API(如 `torch.library` 或 graph-pass registry)。 | ||
| 47 | +- 某项能力既不属于待上游化的 patches,又不能使用上述机制时,不实施 monkey-patch;应提出稳定扩展点,或扩展本仓的配置外包装。 | ||
| 48 | + | ||
| 49 | +## 迁移守则 | ||
| 50 | + | ||
| 51 | +- `patches/torchtitan/` 镜像上游模块结构。实际 patch 模块在许可证头后的固定头部区域记录 `Upstream-PR`;`__init__.py` 与 `patches/torch_npu/` runtime compatibility patch 不适用该要求。上游合入并升级 pinned 依赖后删除对应 patch。 | ||
| 52 | +- 需要 monkey-patch 的模块将变更收敛到 `apply()` 并在模块末尾调用;所属 `__init__.py` 显式导入激活,禁止自动发现。除所属 `__init__.py` 外,其他模块不得导入带 `apply()` 的 patch/extension 模块;只提供定义的无副作用模块可按需复用。 | ||
| 53 | +- monkey-patch 只使用完整点路径赋值,不能以短别名或预先绑定引用掩盖替换目标。linter 对必要属性替换报错时,在赋值行添加窄的抑制注释。 | ||
| 54 | +- 新增 monkey-patch 必须声明唯一 owner,其余能力通过该模块公开的注册接口接入。现有重复包装链是迁移债务,未经独立设计与行为验证不得合并。extensions 的固定目标子树及组件/compile 细则见 [torchtitan](extensions/torchtitan/AGENTS.md)、[components](extensions/components/AGENTS.md)、[compile](extensions/compile/AGENTS.md)。 | ||
| 55 | +- 目录边界、导入顺序、checkpoint 语义或可选组件行为发生变化时,在同一变更中更新局部规则、根规则、当前架构文档和 Agent Note。 | ||
| @@ -12,9 +12,6 @@ | |||
| 12 | from torchtitan_npu import ( | 12 | from torchtitan_npu import ( |
| 13 | patches as _patches, | 13 | patches as _patches, |
| 14 | ) | 14 | ) |
| 15 | -from torchtitan_npu import ( | ||
| 16 | - compile as _compile, | ||
| 17 | -) | ||
| 18 | from torchtitan_npu import ( | 15 | from torchtitan_npu import ( |
| 19 | config as _config, | 16 | config as _config, |
| 20 | ) | 17 | ) |
| @@ -0,0 +1,10 @@ | |||
| 1 | +# config 规则 | ||
| 2 | + | ||
| 3 | +`config/` 是 NPU 配置 schema、纯 config 转换器与显式注册 API 的公共基础层。 | ||
| 4 | + | ||
| 5 | +- schema 只描述类型、默认值、校验和组件归属,不在 dataclass 中执行设备初始化或训练副作用。 | ||
| 6 | +- converter 保持纯 config-tree 转换;不导入具体模型、override 或 extension 实现。 | ||
| 7 | +- **当前行为:** `config/__init__.py` 导入 `manager`,后者安装 `ConfigManager._load_config` 的转换 wrapper。这是现有配置转换链的一部分。 | ||
| 8 | +- **目标状态:** `config/__init__.py` 只导出 schema 和注册 API;ConfigManager wrapper 由 extension 激活入口显式安装。完成前,不得把「导入 config 无副作用」写成当前事实。 | ||
| 9 | +- 新配置字段按 owner 放入上游组件子配置或 `ExtensionConfig` 分组;不为了 CLI 便利复制另一个已有字段。 | ||
| 10 | +- 修改 schema 时同时检查 Tyro CLI、`derive`/converter、recipe builder、checkpoint 兼容性和 config UT。 | ||
| @@ -6,6 +6,7 @@ | |||
| 6 | """Register trainer config converters and install them before Tyro parsing.""" | 6 | """Register trainer config converters and install them before Tyro parsing.""" |
| 7 | 7 | ||
| 8 | from functools import wraps | 8 | from functools import wraps |
| 9 | +from typing import cast | ||
| 9 | 10 | ||
| 10 | from torchtitan.config.manager import ConfigManager | 11 | from torchtitan.config.manager import ConfigManager |
| 11 | from torchtitan.trainer import Trainer | 12 | from torchtitan.trainer import Trainer |
| @@ -14,24 +15,32 @@ from torchtitan_npu.config.converters import TrainerConfigConverter | |||
| 14 | 15 | ||
| 15 | _original_load_config = ConfigManager._load_config | 16 | _original_load_config = ConfigManager._load_config |
| 16 | 17 | ||
| 17 | -_CONFIG_CONVERTERS: dict[type[Trainer.Config], TrainerConfigConverter] = {} | 18 | +_CONFIG_CONVERTERS: dict[type[object], TrainerConfigConverter] = {} |
| 18 | 19 | ||
| 19 | 20 | ||
| 20 | def register_config_converter( | 21 | def register_config_converter( |
| 21 | config_type: type[Trainer.Config], | 22 | config_type: type[Trainer.Config], |
| 22 | converter: TrainerConfigConverter, | 23 | converter: TrainerConfigConverter, |
| 23 | ) -> None: | 24 | ) -> None: |
| 24 | - """Register a converter for one exact Trainer config type.""" | 25 | + """Register a converter for a Trainer config type and its config bases.""" |
| 25 | _CONFIG_CONVERTERS[config_type] = converter | 26 | _CONFIG_CONVERTERS[config_type] = converter |
| 27 | + # ``patches.torchtitan.trainer`` can replace ``torchtitan.trainer.Trainer`` | ||
| 28 | + # during package activation. A config registry imported before that | ||
| 29 | + # replacement may still return the original base ``Trainer.Config``. | ||
| 30 | + # Register its config bases as well, while retaining an explicitly | ||
| 31 | + # registered converter for a more specialized type. | ||
| 32 | + for base in config_type.__mro__[1:]: | ||
| 33 | + if base is object: | ||
| 34 | + break | ||
| 35 | + _CONFIG_CONVERTERS.setdefault(base, converter) | ||
| 26 | 36 | ||
| 27 | 37 | ||
| 28 | @wraps(_original_load_config) | 38 | @wraps(_original_load_config) |
| 29 | def _patched_load_config(self, args: list[str]) -> tuple[object, list[str]]: | 39 | def _patched_load_config(self, args: list[str]) -> tuple[object, list[str]]: |
| 30 | config, filtered_args = _original_load_config(self, args) | 40 | config, filtered_args = _original_load_config(self, args) |
| 31 | - if isinstance(config, Trainer.Config): | 41 | + converter = _CONFIG_CONVERTERS.get(type(config)) |
| 32 | - converter = _CONFIG_CONVERTERS.get(type(config)) | 42 | + if converter is not None: |
| 33 | - if converter is not None: | 43 | + config = converter.convert(cast("Trainer.Config", config)) |
| 34 | - config = converter.convert(config) | ||
| 35 | return config, filtered_args | 44 | return config, filtered_args |
| 36 | 45 | ||
| 37 | 46 | ||
| @@ -1,15 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | -# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 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 | - | ||
| 8 | -def set_allow_hf32(allow: bool) -> None: | ||
| 9 | - """Set HF32 consistently on the NPU math backends.""" | ||
| 10 | - | ||
| 11 | - import torch_npu | ||
| 12 | - | ||
| 13 | - torch_npu.npu.matmul.allow_hf32 = allow | ||
| 14 | - torch_npu.npu.conv.allow_hf32 = allow | ||
| 15 | - torch_npu.npu.aclnn.allow_hf32 = allow | ||
| @@ -0,0 +1,19 @@ | |||
| 1 | +# extensions 规则 | ||
| 2 | + | ||
| 3 | +`extensions/` 是本仓永久额外扩展层。`torchtitan/` 按上游 TorchTitan 的目录归属存放对应扩展;`adaptor/` 存放按需使用的外部集成,不能由包入口自动导入。 | ||
| 4 | + | ||
| 5 | +- patch 型扩展将变更收敛到 `apply()` 并在模块末尾调用;所属 `__init__.py` 显式导入激活,注册型扩展使用明确注册 API。 | ||
| 6 | +- 除所属 `__init__.py` 外,其他模块不得导入带 `apply()` 的模块;只提供定义的无副作用模块可按需复用。直接 monkey-patch 只使用完整点路径赋值。 | ||
| 7 | +- 新增代码只依赖标准库、上游包、`extensions/` 内部模块和所需的 `patches/` 定义;不得新增对 `models`、`override` 或 `ops` 的依赖。现有跨层边是迁移债务,不以本规则宣称已经消除。 | ||
| 8 | +- extensions 可以导入 `torchtitan_npu.patches.*` 复用 patch 提供的定义,也可以通过 `torchtitan.*`、`torch.*` 或 `torch_npu.*` 使用已替换结果;`patches/` 不得新增反向依赖。 | ||
| 9 | +- 新增直接 monkey-patch 必须声明唯一 owner 和激活顺序。现有重复包装链是迁移债务,未经单独设计和行为验证不得合并。 | ||
| 10 | +- **当前状态:加载策略尚未实现。** `extensions/torchtitan/` 已按上游目录建立边界,`adaptor/` 已迁入本层;[包入口](__init__.py) 仍会无条件导入现有 extension。统一加载器和下列环境变量尚未实现。 | ||
| 11 | +- **目标接口(迁移时实现):** 在 `extensions/__init__.py` 的唯一加载入口先读取 `TORCHTITAN_NPU_DISABLE_EXTENSIONS`:值为 `1` 时跳过全部 extension 的自动加载,但不影响 `patches`、`models`、`override`、`ops` 的导入。未禁用时,加载器再读取 `TORCHTITAN_NPU_DISABLE_COMPONENTS`:`1` 跳过全部已声明组件;否则按逗号分隔的组件名跳过对应组件。组件必须在加载器的注册表中有唯一名称;未知名称应报清晰错误,不能静默忽略。 | ||
| 12 | +- 实现该接口时,新增或迁移的加载器及对应测试必须落到 [包入口](__init__.py)、[components](components/AGENTS.md) 和 [测试规则](../../tests/AGENTS.md) 所指的位置;`torchtitan`、`components`、`compile` 的职责边界见各自规则文件。 | ||
| 13 | + | ||
| 14 | +| 目录 | 当前职责 | 当前加载方式 | | ||
| 15 | +| --- | --- | --- | | ||
| 16 | +| `torchtitan/` | 镜像上游结构的永久扩展 | 包入口按显式顺序导入其中的激活模块 | | ||
| 17 | +| `adaptor/` | 可选外部 distribution 适配器 | 按量化或导出调用路径导入 | | ||
| 18 | +| `components/`、`compile/`、`experiment/` | 组件、图编译和实验能力 | 由 owner 或调用路径导入 | | ||
| 19 | +| `cpu_offload/`、`distributed/`、`mx_storage_reader/`、`novaswap/` | NPU 训练、状态与 checkpoint 支持 | 按 trainer、override、模型或 checkpoint 调用路径导入 | | ||
| @@ -5,10 +5,11 @@ | |||
| 5 | 5 | ||
| 6 | """extensions for torchtitan-npu.""" | 6 | """extensions for torchtitan-npu.""" |
| 7 | 7 | ||
| 8 | -from . import ( | 8 | +# The import order is the extension activation order. Do not sort this block. |
| 9 | - ep_process_group, # noqa: F401 | 9 | +# ruff: noqa: I001,F401 |
| 10 | - graph_trainer, # noqa: F401 | 10 | +from .torchtitan import ep_process_group |
| 11 | - trainer, # noqa: F401 | 11 | +from .torchtitan import trainer |
| 12 | -) | 12 | +from .torchtitan.components import metrics |
| 13 | -from .components import metrics # noqa: F401 | 13 | +from .torchtitan.experiments import graph_trainer |
| 14 | -from .tools import utils # noqa: F401 | 14 | +from .torchtitan.tools import utils |
| 15 | +from .torchtitan import eager_flex | ||
| @@ -0,0 +1,8 @@ | |||
| 1 | +# adaptor 规则 | ||
| 2 | + | ||
| 3 | +`adaptor/` 放置可选外部 Python distribution 与 torchtitan-npu 公开配置、模型和运行时接口之间的适配器。 | ||
| 4 | + | ||
| 5 | +- 包入口保持无副作用;不在 `adaptor/__init__.py` 中批量导入可选 adaptor。 | ||
| 6 | +- adaptor 由其 owner 在需要时按需导入,缺少可选依赖时给出清晰错误。 | ||
| 7 | +- 新代码只依赖各层公开 API,不新增对 patch 或 override 私有符号的依赖。历史迁移债务在局部规则和 Agent Note 中显式记录。 | ||
| 8 | +- 测试镜像放在 `tests/unit_tests/extensions/adaptor/`;真实设备语义仍按 tests 分层放入 smoke 或 integration tests。 | ||
| @@ -3,4 +3,4 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 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. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | -"""Compile-time extensions for NPU models.""" | 6 | +"""Optional third-party adaptors for torchtitan-npu.""" |
| @@ -0,0 +1,8 @@ | |||
| 1 | +# TorchAO-NPU adaptor 规则 | ||
| 2 | + | ||
| 3 | +`torchao/` 连接独立安装的 `torchao_npu` distribution 与 torchtitan-npu model config tree。 | ||
| 4 | + | ||
| 5 | +- `converter.py` 只在量化训练或量化导出路径中按需导入;不由 package 入口自动加载。 | ||
| 6 | +- 现有 model、override 和 patch 私有依赖属于 Agent Note 已记录的迁移债务;新增代码使用公开接口。 | ||
| 7 | +- 私有依赖通过等价公开接口逐步替换,保持 recipe、filter、config-tree 替换顺序、默认值和数值行为不变。 | ||
| 8 | +- 相关 CPU 测试位于 `tests/unit_tests/extensions/adaptor/torchao/`;可选包未安装时保持现有 skip 语义。 | ||
Rtorchtitan_npu/extensions/tools/__init__.py→torchtitan_npu/extensions/adaptor/torchao/__init__.py+1-1
| @@ -3,4 +3,4 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 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. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | -"""Extensions for torchtitan tools.""" | 6 | +"""TorchAO-NPU adaptor loaded explicitly by its consumers.""" |
| @@ -0,0 +1,7 @@ | |||
| 1 | +# extensions/compile 目标规则 | ||
| 2 | + | ||
| 3 | +本目录放图 pattern 基础设施与具体 pattern。 | ||
| 4 | + | ||
| 5 | +- graph pass 通过公开注册 API 接入,属于注册,不是 monkey-patch。 | ||
| 6 | +- 具体 pattern 按需显式导入;`__init__.py` 不批量加载 pattern。 | ||
| 7 | +- pattern 的环境变量、注册时机和验证路径必须在其 owning 文档或测试中明确。 | ||
| @@ -0,0 +1,9 @@ | |||
| 1 | +# extensions/components 目标规则 | ||
| 2 | + | ||
| 3 | +本目录放带声明名称的自包含集成单元,尤其是可选独立包的适配。 | ||
| 4 | + | ||
| 5 | +- 组件不直接 monkey-patch,也不定义 `apply()`;它们只通过 `extensions/torchtitan` 的注册接口接线。 | ||
不是而是 ![]() ![]() | |||
| 6 | +- 依赖方向固定为 `extensions/torchtitan → extensions/components`,禁止反向导入。 | ||
| 7 | +- **目标状态:** 核心 extension 不在模块顶层导入组件;组件仅在需要时惰性加载。组件禁用后的可用性在禁用开关实现时验证。 | ||
| 8 | +- **当前债务:** `TrainerEx` 顶层导入 SDC,checkpoint extension 顶层导入 validation,DeepSeek-V4.1 配置直接导入 gradient clipping。它们是现有接线,不能作为新组件的依赖模式;收敛状态记录在架构 Agent Note。 | ||
| 9 | +- `TORCHTITAN_NPU_DISABLE_COMPONENTS` 是未实现的目标开关;落地后,值为 `1` 禁用全部声明组件,逗号分隔的组件名只禁用对应组件。该开关只影响 extension 的组件接线。 | ||
| @@ -95,7 +95,7 @@ class SDC(Configurable): | |||
| 95 | checker.set_grad_sample_interval(config.grad_sample_interval) | 95 | checker.set_grad_sample_interval(config.grad_sample_interval) |
| 96 | if config.with_checksum: | 96 | if config.with_checksum: |
| 97 | # Model compile wrappers exist, but the first training graph is still lazy. | 97 | # Model compile wrappers exist, but the first training graph is still lazy. |
| 98 | - from torchtitan_npu.compile.sdc_checksum import install_checksum_pass | 98 | + from torchtitan_npu.extensions.compile.sdc_checksum import install_checksum_pass |
| 99 | 99 | ||
| 100 | install_checksum_pass() | 100 | install_checksum_pass() |
| 101 | 101 | ||
| @@ -0,0 +1,8 @@ | |||
| 1 | +# extensions/experiment 规则 | ||
| 2 | + | ||
| 3 | +`extensions/experiment/` 放置与 `TrainerEx` 或训练调度紧密集成、尚未承诺稳定 API 的试验性能力。 | ||
| 4 | + | ||
| 5 | +- 实验能力必须显式配置或显式选择,默认不影响核心 TrainerEx 路径。 | ||
| 6 | +- 不在核心 patch、model、override 或 ops 中增加对实验功能的反向依赖或条件分支。 | ||
| 7 | +- 当前跨 `patches`、`models`、`override` 和 `ops` 的直接依赖是待迁移债务,不作为新模块的先例。 | ||
| 8 | +- 功能转正前先通过 Agent Note 确认 owner、公开接口、默认状态和退出条件,再迁入正式 extension 子层。 | ||
| @@ -0,0 +1,8 @@ | |||
| 1 | +# extensions/torchtitan 目标规则 | ||
| 2 | + | ||
| 3 | +本目录放镜像上游 `torchtitan` 结构的永久 monkey-patch 激活模块。 | ||
| 4 | + | ||
| 5 | +- 每个上游目标只允许一个激活模块直接 monkey-patch,避免覆盖顺序不确定。迁移阶段的 ownership 检查脚本保存在代码仓外的本地工具目录;新增 patch 仍必须人工确认 owner、目标路径和激活顺序。 | ||
| 6 | +- 激活模块通过公开注册接口接纳其他扩展;需要扩展同一目标时,不得新增第二个直接 patch 模块。 | ||
| 7 | +- 组件接线模块只注册 hook,不定义 `apply()`,也不直接 monkey-patch。组件禁用时只跳过对应接线模块,核心激活模块仍可加载。 | ||
| 8 | +- 核心模块不得在顶层导入组件;在真正注册或需要时再惰性加载已声明组件。 | ||
| @@ -0,0 +1 @@ | |||
| 1 | +"""NPU extensions arranged by their TorchTitan integration point.""" | ||
| @@ -0,0 +1 @@ | |||
| 1 | +"""Extensions for TorchTitan components.""" | ||
Rtorchtitan_npu/extensions/components/checkpoint.py→torchtitan_npu/extensions/torchtitan/components/checkpoint.py+1-1
| @@ -22,7 +22,7 @@ from torchtitan.components.checkpoint import ( | |||
| 22 | from torchtitan.observability import structured_logger as sl | 22 | from torchtitan.observability import structured_logger as sl |
| 23 | from torchtitan.tools.utils import GarbageCollection | 23 | from torchtitan.tools.utils import GarbageCollection |
| 24 | 24 | ||
| 25 | -from .validation import ( | 25 | +from torchtitan_npu.extensions.components.validation import ( |
| 26 | mark_checkpoint_manifest_pending, | 26 | mark_checkpoint_manifest_pending, |
| 27 | verify_checkpoint_manifest, | 27 | verify_checkpoint_manifest, |
| 28 | write_checkpoint_manifest, | 28 | write_checkpoint_manifest, |
Rtorchtitan_npu/extensions/components/lora_compat.py→torchtitan_npu/extensions/torchtitan/components/lora.py+0-0
File renamed without changes.
Rtorchtitan_npu/extensions/components/metrics.py→torchtitan_npu/extensions/torchtitan/components/metrics.py+0-0
File renamed without changes.
| @@ -0,0 +1 @@ | |||
| 1 | +"""Extensions for TorchTitan optimizer components.""" | ||
Rtorchtitan_npu/extensions/components/optimizer.py→torchtitan_npu/extensions/torchtitan/components/optimizer/optimizer.py+0-0
Rtorchtitan_npu/extensions/distributed/fsdp.py→torchtitan_npu/extensions/torchtitan/distributed/fsdp.py+0-0
Rtorchtitan_npu/patches/workaround/eager_flex.py→torchtitan_npu/extensions/torchtitan/eager_flex.py+8-6
Rtorchtitan_npu/extensions/ep_process_group.py→torchtitan_npu/extensions/torchtitan/ep_process_group.py+0-0
Rtorchtitan_npu/extensions/graph_trainer/__init__.py→torchtitan_npu/extensions/torchtitan/experiments/graph_trainer/__init__.py+3-3
Rtorchtitan_npu/extensions/graph_trainer/auto_overlap.py→torchtitan_npu/extensions/torchtitan/experiments/graph_trainer/auto_overlap.py+3-3
Rtorchtitan_npu/extensions/graph_trainer/collective_benchmark.py→torchtitan_npu/extensions/torchtitan/experiments/graph_trainer/collective_benchmark.py+0-0
Rtorchtitan_npu/extensions/graph_trainer/compute_benchmark.py→torchtitan_npu/extensions/torchtitan/experiments/graph_trainer/compute_benchmark.py+0-0
Rtorchtitan_npu/extensions/graph_trainer/npu_moe_auto_scheduler.py→torchtitan_npu/extensions/torchtitan/experiments/graph_trainer/npu_moe_auto_scheduler.py+0-0
Rtorchtitan_npu/extensions/graph_trainer/utils.py→torchtitan_npu/extensions/torchtitan/experiments/graph_trainer/utils.py+0-0
Rtorchtitan_npu/extensions/graph_trainer/whole_graph_benchmark.py→torchtitan_npu/extensions/torchtitan/experiments/graph_trainer/whole_graph_benchmark.py+0-0
Rtorchtitan_npu/extensions/experiment/torchft/__init__.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/__init__.py+0-0
Rtorchtitan_npu/extensions/experiment/torchft/ft_manager.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/ft_manager.py+2-2
Rtorchtitan_npu/extensions/experiment/torchft/manager.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/manager.py+1-1
Rtorchtitan_npu/extensions/experiment/torchft/optimizer.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/optimizer.py+1-1
Rtorchtitan_npu/extensions/experiment/torchft/process_group.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/process_group.py+1-1
Rtorchtitan_npu/extensions/experiment/torchft/recovery/__init__.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/recovery/__init__.py+0-0
Rtorchtitan_npu/extensions/experiment/torchft/recovery/hccl.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/recovery/hccl.py+0-0
Rtorchtitan_npu/extensions/experiment/torchft/recovery/step_recovery.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/recovery/step_recovery.py+1-1
Rtorchtitan_npu/extensions/experiment/torchft/recovery/work.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/recovery/work.py+0-0
Rtorchtitan_npu/extensions/experiment/torchft/trainer.py→torchtitan_npu/extensions/torchtitan/experiments/torchft/trainer.py+5-5
Rtorchtitan_npu/patches/workaround/assert_async.py→torchtitan_npu/patches/torch_npu/assert_async.py+0-0
Rtorchtitan_npu/patches/workaround/device_copy.py→torchtitan_npu/patches/torch_npu/device_copy.py+0-0
Rtorchtitan_npu/scripts/checkpoint_conversion/convert_to_hf.py→torchtitan_npu/tools/checkpoint_conversion/convert_to_hf.py+0-0
Rtorchtitan_npu/scripts/checkpoint_conversion/export_quantized_hf.py→torchtitan_npu/tools/checkpoint_conversion/export_quantized_hf.py+5-5


以后这个notes也会一直在仓里对吧,那未完成的是不应该保留在本地,等对应开发者完成了再统一提交?还是notes的文件大小和哪些时候应该记录等是不是应该限制更明确一点,不然容易导致该目录很快膨胀