已开启
支持 NovaSwap optimizer state 的 checkpoint 恢复 #1
没有杰创建于 9月10日
支持 NovaSwap optimizer state 的 checkpoint 恢复 #1
已开启
共 217 个文件变更+17715-4933
| @@ -0,0 +1,56 @@ | |||
| 1 | +# KPBot App Tuner | ||
| 2 | + | ||
| 3 | +本目录为 torchtitan-npu 提供 KPBot App Tuner 插件的项目级入口,实际工作流和配套资源复用固定版本的上游 submodule。项目级 Agent 运行时仅注册一个`kpbot-app-tuner` 入口;上游 `subskills` 不单独注册,由主流程按需调用。该设计避免同名入口冲突,不影响用户 prompt 触发主 Skill。 | ||
| 4 | + | ||
| 5 | +## 初始化 | ||
| 6 | + | ||
| 7 | +场景一:克隆 torchtitan-npu 时同时初始化 KPBot 子模块 | ||
| 8 | + | ||
| 9 | +```shell | ||
| 10 | +git clone --recurse-submodules https://gitcode.com/cann/torchtitan-npu.git | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +场景二:已通过普通方式克隆 torchtitan-npu 但尚未初始化 KPBot 子模块 | ||
| 14 | + | ||
| 15 | +```shell | ||
| 16 | +git submodule update --init --recursive third_party/agent-skills/KPBot | ||
| 17 | +``` | ||
| 18 | + | ||
| 19 | +如需仅在本地跟随 KPBot 上游分支更新,可在 torchtitan-npu 仓库根目录执行以下操作,该操作仅实现本地更新: | ||
| 20 | + | ||
| 21 | +```shell | ||
| 22 | +git submodule update --remote -- third_party/agent-skills/KPBot | ||
| 23 | +``` | ||
| 24 | + | ||
| 25 | +## OpenCode 使用 | ||
| 26 | + | ||
| 27 | +在仓库根目录启动 OpenCode,确认 Skill 已注册: | ||
| 28 | + | ||
| 29 | +```shell | ||
| 30 | +opencode debug skill | grep kpbot-app-tuner | ||
| 31 | +opencode | ||
| 32 | +``` | ||
| 33 | + | ||
| 34 | +在对话中调用: | ||
| 35 | + | ||
| 36 | +```text | ||
| 37 | +/kpbot-app-tuner 帮我优化当前 torchtitan-npu 训练任务中host bound场景的性能。请先确认运行环境、启动脚本、训练参数配置、模型参数配置以及明确关注的核心指标,再尝试 CPU 亲和性优化、OS 优化、BIOS优化、编译优化等各方向,涉及运行环境变更操作时先向我确认。 | ||
| 38 | +``` | ||
| 39 | + | ||
| 40 | +入口会读取 `third_party/agent-skills/KPBot/Plugins/app-tuner/opencode/` 覆盖层,并按上游流程执行场景确认、基线建立、证据采集、优化验证、回退和报告输出。 | ||
| 41 | + | ||
| 42 | +## Claude Code 使用 | ||
| 43 | + | ||
| 44 | +在仓库根目录启动 Claude Code;项目中的 `.claude/skills` 会自动发现 `.agents/skills/kpbot-app-tuner/SKILL.md`: | ||
| 45 | + | ||
| 46 | +```shell | ||
| 47 | +claude | ||
| 48 | +``` | ||
| 49 | + | ||
| 50 | +在对话中调用: | ||
| 51 | + | ||
| 52 | +```text | ||
| 53 | +/kpbot-app-tuner 帮我优化当前 torchtitan-npu 训练任务中host bound场景的性能。请先确认运行环境、启动脚本、训练参数配置、模型参数配置以及明确关注的核心指标,再尝试 CPU 亲和性优化、OS 优化、BIOS优化、编译优化等各方向,涉及运行环境变更操作时先向我确认。 | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +Claude Code 入口会读取 `third_party/agent-skills/KPBot/Plugins/app-tuner/skills/kpbot-app-tuner/SKILL.md`,复用上游主 Skill 及其 `references`、`subskills` 和 `scripts`。 | ||
| @@ -0,0 +1,28 @@ | |||
| 1 | +--- | ||
| 2 | +name: kpbot-app-tuner | ||
| 3 | +description: 使用该 skill 构建和执行服务器应用优化 Agent 的自顶向下优化流程,覆盖用户场景输入、Agent 可选操作确认、基线数据确认、环境诊断与备份、磁盘/网卡/内存/CPU/GPU/NPU/硬件规格瓶颈识别、基线后按进程火焰图/热点函数/热点 so/topdown L1 icache miss/L3 cache miss/线程切换等性能信息采集、根据采集信息生成候选优化 skill 列表、按候选列表依次执行 CPU 亲和性、网络参数、性能库、应用配置、BIOS、OS、编译和 Other 等优化 skill、候选完成后覆盖执行未命中 skill、分轮收益统计、review 与环境还原、案例归档和最终报告输出。适用于 Claude Code、Codex、Cursor、OpenCode 以及其他支持目录式 SKILL.md 的编程 Agent 环境。 | ||
| 4 | +--- | ||
| 5 | + | ||
| 6 | +# KPBot App Tuner | ||
| 7 | + | ||
| 8 | +本入口复用固定 commit 的 KPBot 上游流程,不复制其工作流实现。首次 clone 或更新仓库后执行: | ||
| 9 | + | ||
| 10 | +```bash | ||
| 11 | +git submodule update --init --recursive third_party/agent-skills/KPBot | ||
| 12 | +``` | ||
| 13 | + | ||
| 14 | +执行前确认 `third_party/agent-skills/KPBot/` 已初始化;未初始化时不得自行重写或降级 KPBot 流程。 | ||
| 15 | + | ||
| 16 | +## 平台入口 | ||
| 17 | + | ||
| 18 | +- Claude Code:读取 `third_party/agent-skills/KPBot/Plugins/app-tuner/skills/kpbot-app-tuner/SKILL.md`。 | ||
| 19 | +- OpenCode:读取 `third_party/agent-skills/KPBot/Plugins/app-tuner/opencode/kpbot-app-tuner/SKILL.md`。 | ||
| 20 | + | ||
| 21 | +除平台工具调用方式和路径映射外,严格遵循上游 Skill 的用户确认、基线、证据采集、单变量迭代、回退和报告规则。主 Skill 所需的 `scripts`、`references`、`subskills` 和 overlay 均从 `third_party/agent-skills/KPBot` 的同一 submodule commit 读取。 | ||
| 22 | + | ||
| 23 | +## torchtitan-npu 约束 | ||
| 24 | + | ||
| 25 | +1. 先用训练证据确认 host bound,不以单一 NPU 利用率指标下结论。 | ||
| 26 | +2. 固定模型、数据、checkpoint、随机性、并行策略、batch size、sequence length 和精度配置后建立基线。 | ||
| 27 | +3. 默认只分析或调整 host 侧;涉及模型、算子、并行或数值语义变化时单独说明并验证。 | ||
| 28 | +4. BIOS、sysctl、IRQ、重启、重编译、远程执行和持久化配置须经用户明确授权,并保留回退步骤。 | ||
| @@ -52,13 +52,24 @@ git -C "${TORCHTITAN_DIR}" checkout --detach --quiet "${TORCHTITAN_COMMIT}" | |||
| 52 | 52 | ||
| 53 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${TORCHTITAN_DIR}" | 53 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${TORCHTITAN_DIR}" |
| 54 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${PROJECT_ROOT}" | 54 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${PROJECT_ROOT}" |
| 55 | -"${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu' | 55 | + |
| 56 | +# The image predates wheels added to requirements.txt; install only the missing | ||
| 57 | +# wheels, never the whole file, whose torch/torch_npu pins differ from the image | ||
| 58 | +# build. | ||
| 59 | +"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir attn-gym==0.0.9 | ||
| 60 | +# The CI image supplies torch 2.15.0.dev; the matching torchvision nightly | ||
| 61 | +# is installed with --no-deps (resolving its torch pin would fight the image). | ||
| 62 | +"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir --index-url https://download.pytorch.org/whl/nightly/cpu "torchvision==0.30.0.dev20260918" | ||
| 63 | +"${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu, torchvision' | ||
| 56 | 64 | ||
| 57 | export MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" | 65 | export MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" |
| 58 | export CONFIG="${CONFIG:-deepseek_v4_debugmodel}" | 66 | export CONFIG="${CONFIG:-deepseek_v4_debugmodel}" |
| 59 | export NGPU | 67 | export NGPU |
| 60 | export LOG_RANK="${LOG_RANK:-0}" | 68 | export LOG_RANK="${LOG_RANK:-0}" |
| 61 | export PYTHON_BIN | 69 | export PYTHON_BIN |
| 70 | +# The Qwen3.5 launcher resolves tokenizer and cc12m-test assets from the | ||
| 71 | +# torchtitan checkout; expose the clone location to child processes. | ||
| 72 | +export TORCHTITAN_DIR | ||
| 62 | 73 | ||
| 63 | SMOKE_TESTS_START="$(date +%s)" | 74 | SMOKE_TESTS_START="$(date +%s)" |
| 64 | "${PYTHON_BIN}" -m pytest -v --tb=short tests/smoke_tests | 75 | "${PYTHON_BIN}" -m pytest -v --tb=short tests/smoke_tests |
| @@ -53,5 +53,14 @@ git -C "${TORCHTITAN_DIR}" fetch --depth 1 origin "${TORCHTITAN_COMMIT}" | |||
| 53 | git -C "${TORCHTITAN_DIR}" checkout --detach --quiet "${TORCHTITAN_COMMIT}" | 53 | git -C "${TORCHTITAN_DIR}" checkout --detach --quiet "${TORCHTITAN_COMMIT}" |
| 54 | pip install --no-deps -e "${TORCHTITAN_DIR}" | 54 | pip install --no-deps -e "${TORCHTITAN_DIR}" |
| 55 | 55 | ||
| 56 | +# The image predates wheels added to requirements.txt. Install only those wheels: | ||
| 57 | +# the image pins a *different* torch/torch_npu build than requirements.txt does, so | ||
| 58 | +# re-running the whole file would upgrade the CANN stack mid-job (it broke the | ||
| 59 | +# fused-op smoke tests once). New pure-Python runtime wheels go here by name. | ||
| 60 | +pip install --no-deps attn-gym==0.0.9 | ||
| 61 | + | ||
| 62 | +pip install --no-deps torchvision==0.30.0.dev20260918 \ | ||
| 63 | + --extra-index-url https://download.pytorch.org/whl/nightly/cpu | ||
| 64 | + | ||
| 56 | python -c 'from torchtitan.distributed.context_parallel.api import cp_shard; print(cp_shard.__module__)' | 65 | python -c 'from torchtitan.distributed.context_parallel.api import cp_shard; print(cp_shard.__module__)' |
| 57 | python -m pytest -v --tb=short tests/unit_tests | 66 | python -m pytest -v --tb=short tests/unit_tests |
| @@ -40,7 +40,8 @@ stages: | |||
| 40 | with: | 40 | with: |
| 41 | repo_name: ${{ env.repo_name }} | 41 | repo_name: ${{ env.repo_name }} |
| 42 | target_branch: ${{ env.TARGET_BRANCH }} | 42 | target_branch: ${{ env.TARGET_BRANCH }} |
| 43 | - repo_url: ${{ vars.CI_PATH }} | 43 | + comment: ${{ atomgit.event.comment.body }} |
| 44 | + token: ${{ secrets.TESTTOKEN }} | ||
| 44 | - | 45 | - |
| 45 | name: show_output | 46 | name: show_output |
| 46 | run: | | 47 | run: | |
| @@ -98,7 +99,7 @@ stages: | |||
| 98 | uses: checkout | 99 | uses: checkout |
| 99 | with: | 100 | with: |
| 100 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} | 101 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} |
| 101 | - token: ${{secrets.GIT_TOKEN}} | 102 | + allow-unsafe-pr-checkout: true |
| 102 | - | 103 | - |
| 103 | name: download pr files | 104 | name: download pr files |
| 104 | uses: obs-download | 105 | uses: obs-download |
| @@ -20,7 +20,7 @@ jobs: | |||
| 20 | uses: checkout | 20 | uses: checkout |
| 21 | with: | 21 | with: |
| 22 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} | 22 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} |
| 23 | - token: ${{secrets.GIT_TOKEN}} | 23 | + allow-unsafe-pr-checkout: true |
| 24 | - | 24 | - |
| 25 | name: download | 25 | name: download |
| 26 | uses: obs-download | 26 | uses: obs-download |
| @@ -73,7 +73,7 @@ jobs: | |||
| 73 | uses: checkout | 73 | uses: checkout |
| 74 | with: | 74 | with: |
| 75 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} | 75 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} |
| 76 | - token: ${{secrets.GIT_TOKEN}} | 76 | + allow-unsafe-pr-checkout: true |
| 77 | - | 77 | - |
| 78 | name: download | 78 | name: download |
| 79 | uses: obs-download | 79 | uses: obs-download |
| @@ -103,7 +103,7 @@ jobs: | |||
| 103 | uses: checkout | 103 | uses: checkout |
| 104 | with: | 104 | with: |
| 105 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} | 105 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} |
| 106 | - token: ${{secrets.GIT_TOKEN}} | 106 | + allow-unsafe-pr-checkout: true |
| 107 | path: "./runner" | 107 | path: "./runner" |
| 108 | - | 108 | - |
| 109 | name: Checkout | 109 | name: Checkout |
| @@ -135,7 +135,7 @@ jobs: | |||
| 135 | uses: checkout | 135 | uses: checkout |
| 136 | with: | 136 | with: |
| 137 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} | 137 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} |
| 138 | - token: ${{secrets.GIT_TOKEN}} | 138 | + allow-unsafe-pr-checkout: true |
| 139 | path: "./runner" | 139 | path: "./runner" |
| 140 | - | 140 | - |
| 141 | name: Checkout | 141 | name: Checkout |
| @@ -167,7 +167,7 @@ jobs: | |||
| 167 | uses: checkout | 167 | uses: checkout |
| 168 | with: | 168 | with: |
| 169 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} | 169 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} |
| 170 | - token: ${{secrets.GIT_TOKEN}} | 170 | + allow-unsafe-pr-checkout: true |
| 171 | path: "./runner" | 171 | path: "./runner" |
| 172 | - | 172 | - |
| 173 | name: Checkout | 173 | name: Checkout |
| @@ -204,7 +204,7 @@ jobs: | |||
| 204 | uses: checkout | 204 | uses: checkout |
| 205 | with: | 205 | with: |
| 206 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} | 206 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} |
| 207 | - token: ${{secrets.GIT_TOKEN}} | 207 | + allow-unsafe-pr-checkout: true |
| 208 | path: "./runner" | 208 | path: "./runner" |
| 209 | - | 209 | - |
| 210 | name: Checkout | 210 | name: Checkout |
| @@ -23,7 +23,7 @@ jobs: | |||
| 23 | uses: checkout | 23 | uses: checkout |
| 24 | with: | 24 | with: |
| 25 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} | 25 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} |
| 26 | - token: ${{secrets.GIT_TOKEN}} | 26 | + allow-unsafe-pr-checkout: true |
| 27 | - | 27 | - |
| 28 | name: download | 28 | name: download |
| 29 | uses: obs-download | 29 | uses: obs-download |
| @@ -20,7 +20,7 @@ jobs: | |||
| 20 | uses: checkout | 20 | uses: checkout |
| 21 | with: | 21 | with: |
| 22 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} | 22 | ref: ${{ atomgit.event.pull_request.merge_commit_sha }} |
| 23 | - token: ${{secrets.GIT_TOKEN}} | 23 | + allow-unsafe-pr-checkout: true |
| 24 | - | 24 | - |
| 25 | name: download | 25 | name: download |
| 26 | uses: obs-download | 26 | uses: obs-download |
| @@ -111,6 +111,9 @@ venv.bak/ | |||
| 111 | !.opencode/skills | 111 | !.opencode/skills |
| 112 | outputs/ | 112 | outputs/ |
| 113 | 113 | ||
| 114 | +# Third-party source trees are managed as submodules and are not scanned as project code. | ||
| 115 | +/third_party/ | ||
| 116 | + | ||
| 114 | oat_reports/ | 117 | oat_reports/ |
| 115 | 118 | ||
| 116 | log/ | 119 | log/ |
| @@ -0,0 +1,4 @@ | |||
| 1 | +[submodule "KPBot"] | ||
| 2 | + path = third_party/agent-skills/KPBot | ||
| 3 | + url = https://gitcode.com/openeuler/KPBot.git | ||
| 4 | + branch = master | ||
| @@ -25,7 +25,7 @@ repos: | |||
| 25 | - id: check-yaml | 25 | - id: check-yaml |
| 26 | args: ["--allow-multiple-documents"] | 26 | args: ["--allow-multiple-documents"] |
| 27 | - id: check-added-large-files | 27 | - id: check-added-large-files |
| 28 | - exclude: ^tests/assets/tokenizer/ | 28 | + exclude: ^tests/assets/tokenizer/|^tests/assets/cc12m_test/cc12m-train-0000\.tar$ |
| 29 | - id: check-merge-conflict | 29 | - id: check-merge-conflict |
| 30 | - id: detect-private-key | 30 | - id: detect-private-key |
| 31 | - id: check-json | 31 | - id: check-json |
| @@ -160,7 +160,8 @@ torchtitan-npu/ | |||
| 160 | │ ├── override/ | 160 | │ ├── override/ |
| 161 | │ │ ├── common/ # 模型无关的 NPU 组件替换 | 161 | │ │ ├── common/ # 模型无关的 NPU 组件替换 |
| 162 | │ │ ├── deepseek_v3_2/ # DeepSeek-V3.2 专属 override | 162 | │ │ ├── deepseek_v3_2/ # DeepSeek-V3.2 专属 override |
| 163 | -│ │ └── deepseek_v4/ # DeepSeek-V4 专属 override | 163 | +│ │ ├── deepseek_v4/ # DeepSeek-V4 专属 override |
| 164 | +│ │ └── qwen3_5/ # Qwen3.5 专属 override | ||
| 164 | │ ├── patches/ | 165 | │ ├── patches/ |
| 165 | │ │ ├── torchtitan/ # 尚未进入当前上游版本的临时补丁 | 166 | │ │ ├── torchtitan/ # 尚未进入当前上游版本的临时补丁 |
| 166 | │ │ └── workaround/ # NPU 运行时兼容处理 | 167 | │ │ └── workaround/ # NPU 运行时兼容处理 |
| @@ -49,7 +49,7 @@ Hugging Face 权重通常包含 `model.safetensors` 或 | |||
| 49 | 49 | ||
| 50 | ## 常用配置项 | 50 | ## 常用配置项 |
| 51 | 51 | ||
| 52 | -配置类型来自上游 `torchtitan.config.Checkpoint`,Python 配置使用下划线命名,命令行 | 52 | +配置类型来自上游 `torchtitan.components.checkpointer.base`,Python 配置使用下划线命名,命令行 |
| 53 | 使用 tyro 的连字符命名: | 53 | 使用 tyro 的连字符命名: |
| 54 | 54 | ||
| 55 | | 配置项 | 作用 | | 55 | | 配置项 | 作用 | |
| @@ -161,8 +161,7 @@ bash scripts/run_train.sh \ | |||
| 161 | --checkpoint.no-initial-load-model-only | 161 | --checkpoint.no-initial-load-model-only |
| 162 | ``` | 162 | ``` |
| 163 | 163 | ||
| 164 | -如果 `{dump_folder}/{checkpoint.folder}` 已经存在可用 checkpoint,框架会优先从该目录 | 164 | +如果 `{dump_folder}/{checkpoint.folder}` 已经存在可用 checkpoint,框架会优先从该目录加载,并忽略 `initial_load_path`。从新权重启动实验时,应使用新的 `dump-folder` 或 |
| 165 | -优先从该目录加载,并忽略 `initial_load_path`。从新权重启动实验时,应使用新的 `dump-folder` 或 | ||
| 166 | 清理旧的 checkpoint 目录。 | 165 | 清理旧的 checkpoint 目录。 |
| 167 | 166 | ||
| 168 | 如只需要模型和部分训练状态,可以排除不需要的键: | 167 | 如只需要模型和部分训练状态,可以排除不需要的键: |
| @@ -18,7 +18,7 @@ GraphTrainer 是 torchtitan 上游 `experiments/graph_trainer/` 中的编译式 | |||
| 18 | 18 | ||
| 19 | ### 配置入口 | 19 | ### 配置入口 |
| 20 | 20 | ||
| 21 | -`torchtitan_npu/models/deepseek_v4/config_registry.py` 新增 4 个配置工厂,均复用对应 eager 配置,经 `to_graph_trainer_config` 包装为 `GraphTrainer.Config`: | 21 | +`torchtitan_npu/models/deepseek_v4/config_registry.py` 新增 5 个配置工厂,均复用对应 eager 配置,经 `to_graph_trainer_config` 包装为 `GraphTrainer.Config`: |
| 22 | 22 | ||
| 23 | | 配置名 | 对应 eager 配置 | | 23 | | 配置名 | 对应 eager 配置 | |
| 24 | | --- | --- | | 24 | | --- | --- | |
| @@ -26,6 +26,7 @@ GraphTrainer 是 torchtitan 上游 `experiments/graph_trainer/` 中的编译式 | |||
| 26 | | `graph_trainer_deepseek_v4_flash` | `deepseek_v4_flash` | | 26 | | `graph_trainer_deepseek_v4_flash` | `deepseek_v4_flash` | |
| 27 | | `graph_trainer_deepseek_v4_flash_43layers_16experts` | `deepseek_v4_flash_43layers_16experts` | | 27 | | `graph_trainer_deepseek_v4_flash_43layers_16experts` | `deepseek_v4_flash_43layers_16experts` | |
| 28 | | `graph_trainer_deepseek_v4_pro` | `deepseek_v4_pro` | | 28 | | `graph_trainer_deepseek_v4_pro` | `deepseek_v4_pro` | |
| 29 | +| `graph_trainer_deepseek_v4_pro_61layers_32experts` | `deepseek_v4_pro_61layers_32experts` | | ||
| 29 | 30 | ||
| 30 | 编译配置统一为 `mode="aot_fx_trace"`、`memory_policy="full"`、`disable_passes=["cudagraph_pass"]`。模型通过 `_graph_trainer_model_registry` 包装为 `GraphTrainerDeepSeekV4Model.Config`,并行化函数指向 `parallelize_graph_trainer_deepseek_v4`。 | 31 | 编译配置统一为 `mode="aot_fx_trace"`、`memory_policy="full"`、`disable_passes=["cudagraph_pass"]`。模型通过 `_graph_trainer_model_registry` 包装为 `GraphTrainerDeepSeekV4Model.Config`,并行化函数指向 `parallelize_graph_trainer_deepseek_v4`。 |
| 31 | 32 | ||
| @@ -42,7 +43,7 @@ GraphTrainer 是 torchtitan 上游 `experiments/graph_trainer/` 中的编译式 | |||
| 42 | 3. 无条件应用 `apply_simple_fsdp`:fsdp mesh 在 degree 1 时也存在(`ParallelDims._mesh_exist`),因此单卡下 MixedPrecisionPolicy 的 param_dtype cast 仍然生效。 | 43 | 3. 无条件应用 `apply_simple_fsdp`:fsdp mesh 在 degree 1 时也存在(`ParallelDims._mesh_exist`),因此单卡下 MixedPrecisionPolicy 的 param_dtype cast 仍然生效。 |
| 43 | 4. 按模式应用 `apply_graph_trainer_compile`。 | 44 | 4. 按模式应用 `apply_graph_trainer_compile`。 |
| 44 | 45 | ||
| 45 | -入口处有两条硬约束:`spmd_types` backend 不支持(simple_fsdp 构建于 raw DTensor 操作之上,该 backend 会报错);TP 启用时 `seq_len` 必须整除 `parallel_dims.seq_len_divisor`(TP degree × 2·CP degree,`use_local_output=True` 使用 plain tensor)。 | 46 | +入口处有两条硬约束:`spmd_types` backend 不支持(simple_fsdp 构建于 raw DTensor 操作之上,该 backend 会报错);TP 启用时 `seq_len` 必须整除 `parallel_dims.seq_len_divisor`(TP degree × 2 x CP degree,`use_local_output=True` 使用 plain tensor)。 |
| 46 | 47 | ||
| 47 | ### Graph-safe 改造 | 48 | ### Graph-safe 改造 |
| 48 | 49 | ||
| @@ -84,9 +85,10 @@ torchrun --nproc_per_node=8 -m torchtitan.train \ | |||
| 84 | | 并行组合 | FSDP(含 degree 1)、EP 已验证;TP 要求 `seq_len` 整除 `seq_len_divisor` | | 85 | | 并行组合 | FSDP(含 degree 1)、EP 已验证;TP 要求 `seq_len` 整除 `seq_len_divisor` | |
| 85 | | `spmd_types` backend | 不支持(simple_fsdp 依赖 raw DTensor 操作) | | 86 | | `spmd_types` backend | 不支持(simple_fsdp 依赖 raw DTensor 操作) | |
| 86 | | Context Parallel | 不支持(DSV4 稀疏注意力编译路径未适配 CP) | | 87 | | Context Parallel | 不支持(DSV4 稀疏注意力编译路径未适配 CP) | |
| 87 | -| EP overlap(上游实验性 pass) | 未验证 | | 88 | +| EP overlap(上游实验性 pass) | 已通过patch适配;见 [`graph_trainer_ep_overlap.md`](graph_trainer_ep_overlap.md) | |
| 88 | 89 | ||
| 89 | ## 相关文档 | 90 | ## 相关文档 |
| 90 | 91 | ||
| 91 | - 上游 GraphTrainer 说明与 EP overlap 用法:[`torchtitan/experiments/graph_trainer/README.md`](https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/graph_trainer/README.md) | 92 | - 上游 GraphTrainer 说明与 EP overlap 用法:[`torchtitan/experiments/graph_trainer/README.md`](https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/graph_trainer/README.md) |
| 93 | +- EP overlap 适配:[`graph_trainer_ep_overlap.md`](graph_trainer_ep_overlap.md) | ||
| 92 | - DSV4 稀疏注意力与 TND 融合路径:[`deepseek_v4_tnd.md`](deepseek_v4_tnd.md) | 94 | - DSV4 稀疏注意力与 TND 融合路径:[`deepseek_v4_tnd.md`](deepseek_v4_tnd.md) |
| @@ -26,6 +26,7 @@ DSV4 GraphTrainer 工厂默认配置如下: | |||
| 26 | enable = true | 26 | enable = true |
| 27 | mode = "aot_fx_trace" | 27 | mode = "aot_fx_trace" |
| 28 | memory_policy = "full" | 28 | memory_policy = "full" |
| 29 | +pass_pipeline = "mutation-functionalization" | ||
| 29 | disable_passes = ["cudagraph_pass"] | 30 | disable_passes = ["cudagraph_pass"] |
| 30 | ``` | 31 | ``` |
| 31 | 32 | ||
| @@ -90,7 +91,7 @@ torchtitan/experiments/graph_trainer/memory_policy.py | |||
| 90 | ### 4.2 NPU 策略框架 | 91 | ### 4.2 NPU 策略框架 |
| 91 | 92 | ||
| 92 | ```text | 93 | ```text |
| 93 | -torchtitan_npu/patches/torchtitan/graph_trainer/memory_policy.py | 94 | +torchtitan_npu/patches/torchtitan/experiments/graph_trainer/memory_policy.py |
| 94 | ``` | 95 | ``` |
| 95 | 96 | ||
| 96 | NPU 扩展使用 `NodePolicyKey` 按 FX target、模块 FQN 和 occurrence 定位节点,并提供 layer boundary、`MUST_SAVE`、反向节点跳过、`lm_head/loss` 跳过和 SymInt 保存等规则。 | 97 | NPU 扩展使用 `NodePolicyKey` 按 FX target、模块 FQN 和 occurrence 定位节点,并提供 layer boundary、`MUST_SAVE`、反向节点跳过、`lm_head/loss` 跳过和 SymInt 保存等规则。 |
| @@ -125,8 +126,22 @@ flowchart TD | |||
| 125 | 126 | ||
| 126 | 127 | ||
| 127 | 128 | ||
| 129 | +### 4.4 前向变异算子的重算保真 | ||
| 130 | + | ||
| 131 | +原生 SAR 按数据流回放重算节点,无数据输出的前向变异算子(如 partial-RoPE 对 | ||
| 132 | +clone 的原地旋转)不会进入回放链,反向会读到未旋转的值(上游 issue | ||
| 133 | +[#4688](https://github.com/pytorch/torchtitan/issues/4688))。DSV4 GraphTrainer 默认 | ||
| 134 | +启用上游 PR [#4708](https://github.com/pytorch/torchtitan/pull/4708) 的 | ||
| 135 | +`functionalize_recompute_mutations_pass`(见 2.1):在 memory-policy 打标之后、 | ||
| 136 | +CPU offload 与 SAR 之前把变异写入显式化为数据流,原生 SAR 随之自然重算;对无可 | ||
| 137 | +重算变异的图是 no-op。已验证 A3(CANN w0902,backward 走临时 shim)2p/8p 精度 | ||
| 138 | +对齐;A5 原生反向未验证。固定 TorchTitan 依赖自带等价 pass 后,删除本 backport | ||
| 139 | +与 `pass_pipeline` 设置即可。 | ||
| 140 | + | ||
| 128 | ## 5. 支持边界与风险 | 141 | ## 5. 支持边界与风险 |
| 129 | - `dsv4-mhc` 依赖 FQN、FX target 和 occurrence,模型或编译器升级后必须检查规则命中数。 | 142 | - `dsv4-mhc` 依赖 FQN、FX target 和 occurrence,模型或编译器升级后必须检查规则命中数。 |
| 143 | +- 变异算子重算保真依赖上游 #4708 的 functionalization 语义与原生 SAR 的交互;升级 | ||
| 144 | + PyTorch 或 TorchTitan 后需重跑 `test_rope_recompute_integration.py` 的正/负对照。 | ||
| 130 | - 重计算链路依赖 FX tracer、AOTAutograd、Dynamo dynamic annotation 和 Inductor 私有 API,升级 PyTorch、torch-npu 或 TorchTitan 后需重新回归。 | 145 | - 重计算链路依赖 FX tracer、AOTAutograd、Dynamo dynamic annotation 和 Inductor 私有 API,升级 PyTorch、torch-npu 或 TorchTitan 后需重新回归。 |
| 131 | 146 | ||
| 132 | ## 6. 关键文件 | 147 | ## 6. 关键文件 |
| @@ -135,13 +150,13 @@ flowchart TD | |||
| 135 | | --- | --- | | 150 | | --- | --- | |
| 136 | | DSV4 GraphTrainer 配置 | `torchtitan_npu/models/deepseek_v4/config_registry.py` | | 151 | | DSV4 GraphTrainer 配置 | `torchtitan_npu/models/deepseek_v4/config_registry.py` | |
| 137 | | 通用 full policy | `torchtitan/experiments/graph_trainer/memory_policy.py` | | 152 | | 通用 full policy | `torchtitan/experiments/graph_trainer/memory_policy.py` | |
| 138 | -| NPU policy 框架 | `torchtitan_npu/patches/torchtitan/graph_trainer/memory_policy.py` | | 153 | +| NPU policy 框架 | `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/memory_policy.py` | |
| 139 | | `dsv4-mhc` 策略 | `torchtitan_npu/models/deepseek_v4/memory_policy.py` | | 154 | | `dsv4-mhc` 策略 | `torchtitan_npu/models/deepseek_v4/memory_policy.py` | |
| 140 | | FX tracer/replay | `torchtitan/experiments/graph_trainer/make_fx_tracer.py`、`torchtitan/experiments/graph_trainer/trainer.py` | | 155 | | FX tracer/replay | `torchtitan/experiments/graph_trainer/make_fx_tracer.py`、`torchtitan/experiments/graph_trainer/trainer.py` | |
| 141 | | SimpleFSDP | `torchtitan/experiments/graph_trainer/simple_fsdp.py` | | 156 | | SimpleFSDP | `torchtitan/experiments/graph_trainer/simple_fsdp.py` | |
| 142 | | 函数式 compressor | `torchtitan_npu/models/deepseek_v4/compressor.py` | | 157 | | 函数式 compressor | `torchtitan_npu/models/deepseek_v4/compressor.py` | |
| 143 | -| RoPE compiler pattern | `torchtitan_npu/compile/patterns/deepseek_v4/inplace_partial_rope.py` | | 158 | +| 变异重算保真(functionalization backport) | `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py` | |
| 144 | -| 重算单测 | `tests/unit_tests/compile/patterns/deepseek_v4/test_recompute_policy.py` | | 159 | +| 重算单测 | `tests/unit_tests/compile/test_recompute_policy.py` | |
| 145 | 160 | ||
| 146 | ## 7. 结论 | 161 | ## 7. 结论 |
| 147 | 162 | ||
| @@ -9,11 +9,9 @@ | |||
| 9 | | --- | --- | --- | --- | | 9 | | --- | --- | --- | --- | |
| 10 | | 融合算子对应完整可配置组件 | `override` + `ops` | 整体替换组件;已有设备算子可由 replacement 直接调用 | [`torch_npu.npu_rms_norm`](../../torchtitan_npu/override/common/rms_norm.py) | | 10 | | 融合算子对应完整可配置组件 | `override` + `ops` | 整体替换组件;已有设备算子可由 replacement 直接调用 | [`torch_npu.npu_rms_norm`](../../torchtitan_npu/override/common/rms_norm.py) | |
| 11 | | 融合算子是可配置组件的一部分 | `override` + `ops` | 只替换组件中的对应逻辑,其余逻辑沿用上游实现 | [`npu_moe_token_unpermute`](../../torchtitan_npu/ops/ascendc/moe_token_unpermute.py)(接入:[`torchtitan_npu.override.common.token_dispatcher.asc`](../../torchtitan_npu/override/common/token_dispatcher.py)) | | 11 | | 融合算子是可配置组件的一部分 | `override` + `ops` | 只替换组件中的对应逻辑,其余逻辑沿用上游实现 | [`npu_moe_token_unpermute`](../../torchtitan_npu/ops/ascendc/moe_token_unpermute.py)(接入:[`torchtitan_npu.override.common.token_dispatcher.asc`](../../torchtitan_npu/override/common/token_dispatcher.py)) | |
| 12 | -| 融合算子是一段可被 `torch.compile` 捕获的连续计算 | pre-AOT pattern | 在 `compile/patterns/` 中替换编译图中的片段 | [`inplace_partial_rotary_mul`](../../torchtitan_npu/compile/patterns/deepseek_v4/inplace_partial_rope.py) | | ||
| 13 | 12 | ||
| 14 | -`torch.library.custom_op` 只是 `ops` 实现需要进入 `torch.compile` 图时的兼容封装,不改变上述两种 | 13 | +`torch.library.custom_op` 只是 `ops` 实现需要进入 `torch.compile` 图时的兼容封装, |
| 15 | -组件替换方式。仅替换编译图片段时,使用 pre-AOT pattern。 | 14 | +不改变上述两种组件替换方式。 |
| 16 | -片段融合的完整示例见[片段融合算子接入](../graph_pattern_fusion.md)。 | ||
| 17 | 15 | ||
| 18 | ## 目录与命名 | 16 | ## 目录与命名 |
| 19 | 17 | ||
| @@ -70,8 +68,7 @@ torchtitan_npu/override/<scope>/<target>/ | |||
| 70 | - 算子支持的设备代际、CANN 版本、dtype、shape 和并行范围。 | 68 | - 算子支持的设备代际、CANN 版本、dtype、shape 和并行范围。 |
| 71 | 69 | ||
| 72 | 选择最小且稳定的组件边界。融合算子覆盖组件全部计算时,整体替换 Module;只覆盖组件部分计算时, | 70 | 选择最小且稳定的组件边界。融合算子覆盖组件全部计算时,整体替换 Module;只覆盖组件部分计算时, |
| 73 | -继承并重写对应方法;仅替换编译图连续片段时,改用 pre-AOT pattern。模型专属 target 不要放入 | 71 | +继承并重写对应方法。模型专属 target 不要放入 `common/`。 |
| 74 | -`common/`。 | ||
| 75 | 72 | ||
| 76 | ### 2. 实现算子层 | 73 | ### 2. 实现算子层 |
| 77 | 74 | ||
| @@ -222,4 +219,6 @@ python -m torchtitan_npu.train \ | |||
| 222 | - [`deepseek_v4/sparse_attn`](../../torchtitan_npu/override/deepseek_v4/sparse_attn):AscendC、PyPTO 与 golden DSA。 | 219 | - [`deepseek_v4/sparse_attn`](../../torchtitan_npu/override/deepseek_v4/sparse_attn):AscendC、PyPTO 与 golden DSA。 |
| 223 | - [`deepseek_v4/mhc`](../../torchtitan_npu/override/deepseek_v4/mhc):AscendC 与 Triton 多后端替换。 | 220 | - [`deepseek_v4/mhc`](../../torchtitan_npu/override/deepseek_v4/mhc):AscendC 与 Triton 多后端替换。 |
| 224 | - [`torchtitan_npu/override/common/token_dispatcher.py`](../../torchtitan_npu/override/common/token_dispatcher.py):`token_dispatcher.asc` 在 `AllToAllTokenDispatcher` 中替换局部 dispatch/combine 计算。 | 221 | - [`torchtitan_npu/override/common/token_dispatcher.py`](../../torchtitan_npu/override/common/token_dispatcher.py):`token_dispatcher.asc` 在 `AllToAllTokenDispatcher` 中替换局部 dispatch/combine 计算。 |
| 222 | +- [`torchtitan_npu/override/common/rope.py`](../../torchtitan_npu/override/common/rope.py):`rope.asc_partial` 整体替换 partial-RoPE 站点,含可选 CANN 依赖的惰性加载。 | ||
| 223 | +- [`torchtitan_npu/ops/ascendc/inplace_partial_rotary_mul.py`](../../torchtitan_npu/ops/ascendc/inplace_partial_rotary_mul.py):原生 mutator 算子的 functional autograd 包装(clone + 前向/反向原地旋转)。 | ||
| 225 | - [`ops/ascendc/moe_token_unpermute.py`](../../torchtitan_npu/ops/ascendc/moe_token_unpermute.py):custom op、Fake 和 Autograd 注册示例。 | 224 | - [`ops/ascendc/moe_token_unpermute.py`](../../torchtitan_npu/ops/ascendc/moe_token_unpermute.py):custom op、Fake 和 Autograd 注册示例。 |
| @@ -0,0 +1,278 @@ | |||
| 1 | +# GraphTrainer EP overlap 适配 | ||
| 2 | + | ||
| 3 | +EP overlap 是 torchtitan 上游 `experiments/graph_trainer/` 为 MoE + Expert Parallel(EP)训练提供的通用 graph pass:把 MoE 区域按 token 维切成两个 chunk,使一个 chunk 的 all-to-all 通信与另一个 chunk 的专家计算重叠。该能力的配置接口、pass pipeline 和本文的临时补丁均不绑定具体模型名称。本文描述启用该能力所需的四个 `patches/torchtitan/` 临时补丁;这些问题最先由 DeepSeek-V4(DSV4)验证图暴露,当前整网验证也使用 DSV4。 | ||
| 4 | + | ||
| 5 | +| 序号 | pass名称 | 内容 | | ||
| 6 | +| --- | --- | --- | | ||
| 7 | +| 1 | mark_unbacked(前置操作,不属于pass) | 在 trace 前制造 chunk 动态维度及 hint | | ||
| 8 | +| 2 | populate_chunk_dim_metadata_pass | trace 后识别该符号,并登记“这是 EP chunk symbol” | | ||
| 9 | +| 3 | ep_overlap_chunk_pass | 利用 EP chunk symbol 符号切图 | | ||
| 10 | +| 4 | ep_overlap_schedule_pass | 根据两个 chunk 重排通信和计算 | | ||
| 11 | +| 5 | concretize_ep_chunk_symbolic_shapes_pass | 调度结束后,使用筛选后的 hint 具体化相关符号 | | ||
| 12 | + | ||
| 13 | +EP overlap 默认不启用。它只在 GraphTrainer 编译路径(`graph_trainer_*` 配置)下生效,普通 eager 训练不走这些 graph pass;下文配置项中的 `strategy=eager` 指 GraphTrainer 的另一种 chunk 实现方式。DSV4 验证样例所依赖的模型侧 GraphTrainer 适配见 [`deepseek_v4_graph_trainer.md`](deepseek_v4_graph_trainer.md)。 | ||
| 14 | + | ||
| 15 | +## 能力范围、依赖与验证边界 | ||
| 16 | + | ||
| 17 | +| 项 | 值 | | ||
| 18 | +| --- | --- | | ||
| 19 | +| 能力对象 | 使用 GraphTrainer、MoE 和真实 EP token exchange 的训练图;EP degree > 1 | | ||
| 20 | +| 当前整网验证模型 | DeepSeek-V4,使用 `graph_trainer_deepseek_v4_flash_43layers_16experts` 配置 | | ||
| 21 | +| 训练路径 | GraphTrainer `aot_fx_trace`;eager 路径不涉及 | | ||
| 22 | +| torchtitan 基线 | `0.3.0`(`requirements.txt` 固定版本) | | ||
| 23 | +| 环境 | Ascend NPU + `torch-npu` + CANN + HCCL;EP degree > 1 | | ||
| 24 | +| 默认状态 | 关闭,需显式传 `--compile.ep_overlap.enabled` | | ||
| 25 | + | ||
| 26 | +## 实现原理 | ||
| 27 | + | ||
| 28 | +### 四个上游临时补丁 | ||
| 29 | + | ||
| 30 | +补丁位于 `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/`,针对 `requirements.txt` 固定的 torchtitan 0.3.0,在 `import torchtitan_npu` 时经 `patches/torchtitan/__init__.py` 自动 `apply()`。它们修正的是上游 graph pass 的行为,代码不依赖 NPU 专有算子,也不检查模型类型。DSV4 验证图只是这些问题的首个整网复现场景;任何产生相同符号关系、节点标注或调度依赖的 GraphTrainer MoE 图都会进入相同处理逻辑。 | ||
| 31 | + | ||
| 32 | +四个 patch 共替换或包装五个上游函数,均有标记防止重复 `apply()`。它们的执行顺序是:第四个作用于 chunk pass,第二、第三个作用于 overlap schedule pass,第一个作用于调度后的 concretization pass。 | ||
| 33 | + | ||
| 34 | +| 补丁模块 | 替换或包装的上游符号 | 当前修复方案 | | ||
| 35 | +| --- | --- | --- | | ||
| 36 | +| `ep_chunk_concretization` | `ep_pass_utils._placeholder_symbol_hints`、`_concretize_value` | 筛选含 chunk symbol 的 placeholder 维度;与传入 hint 符号无交集的值保持原样 | | ||
| 37 | +| `ep_overlap_shape_queries` | `ep_overlap_pass._collect_token_exchanges` | 清理 body 内 AllToAll launch 的 size query 误继承的 exchange 标注,再调用上游收集器 | | ||
| 38 | +| `ep_ready_nodes_dedup` | `ep_overlap_pass._ready_nodes` | 保留候选遍历和依赖检查,用本轮 `selected` 集合跨 chunk 去重 | | ||
| 39 | +| `ep_shape_live_out` | `ep_chunk_pass._split_live_out_users` | 将同一 root 内直接查询 AllToAll dim-0 的 full user 移到 chunked | | ||
| 40 | + | ||
| 41 | +#### 1. ep_chunk_concretization.py | ||
| 42 | + | ||
| 43 | +报错示例: | ||
| 44 | + | ||
| 45 | +```text | ||
| 46 | +ValueError: Chunk pass could not derive a base hint for symbol u0 from | ||
| 47 | +arg2594_1.shape[0] extent Max(0, u0 - Min(1, u0)) + 1. | ||
| 48 | +``` | ||
| 49 | + | ||
| 50 | +FX 图中既有 EP chunk symbol,也有独立的数据相关 metadata symbol。社区 `ep_pass_utils.py` 中的 `_placeholder_symbol_hints` 遍历所有 tensor placeholder 的 shape 维度,对每个维度调用 `_record_symbols_from_extent`。因此,与 chunk 无关的非线性 metadata 维度也会进入 hint 推导,可能因无法推导 base hint 而报错。 | ||
| 51 | + | ||
| 52 | +社区具体化流程先合并 placeholder hint 和 chunk hint,再调用 `_concretize_value`。原 `_concretize_value` 还可能通过值自身的 hint 把不属于目标范围的动态值折叠成常量。 | ||
| 53 | + | ||
| 54 | +**Patch 方案:** | ||
| 55 | + | ||
| 56 | +| 社区函数 | 当前实现 | | ||
| 57 | +| --- | --- | | ||
| 58 | +| `_placeholder_symbol_hints` | 替换为 `_chunk_placeholder_symbol_hints`:取得 `chunk_symbol_hints_for_mode(gm).keys()`,只对自由符号与它有交集的 placeholder shape 维度调用上游 `_record_symbols_from_extent` | | ||
| 59 | +| `_concretize_value` | 包装原函数:值的自由符号与传入 `symbol_hints.keys()` 无交集时原样返回,否则委托上游原函数具体化 | | ||
| 60 | + | ||
| 61 | +placeholder hint 收集逻辑: | ||
| 62 | + | ||
| 63 | +```python | ||
| 64 | +def _chunk_placeholder_symbol_hints(gm: fx.GraphModule) -> dict[object, int]: | ||
| 65 | + chunk_symbols = ep_pass_utils.chunk_symbol_hints_for_mode(gm).keys() | ||
| 66 | + hints: dict[object, int] = {} | ||
| 67 | + for node in gm.graph.nodes: | ||
| 68 | + if node.op != "placeholder" or (val := ep_pass_utils.tensor_meta(node)) is None: | ||
| 69 | + continue | ||
| 70 | + for dim, extent in enumerate(val.shape): | ||
| 71 | + symbols = ep_pass_utils.free_symbols(extent) | ||
| 72 | + if not symbols & chunk_symbols: | ||
| 73 | + continue | ||
| 74 | + ep_pass_utils._record_symbols_from_extent(hints, extent, source=f"{node.name}.shape[{dim}]") | ||
| 75 | + return hints | ||
| 76 | +``` | ||
| 77 | + | ||
| 78 | +值具体化的包装逻辑: | ||
| 79 | + | ||
| 80 | +```python | ||
| 81 | +def _concretize_chunk_value(value: object, symbol_hints: dict[object, int]) -> object: | ||
| 82 | + if not ep_pass_utils.free_symbols(value) & symbol_hints.keys(): | ||
| 83 | + return value | ||
| 84 | + return original_concretize_value(value, symbol_hints) | ||
| 85 | +``` | ||
| 86 | + | ||
| 87 | +这里有两个不同的筛选集合:placeholder 维度按 **EP chunk symbol** 筛选;值具体化按调用方传入的 **合并后 hint 字典**筛选。若选中的维度包含其他符号且上游能推导其 hint,这些符号也可能进入具体化范围,不能将第二层条件表述为“值必须直接含有 EP chunk symbol”。 | ||
| 88 | + | ||
| 89 | +当前实现不扫描全图的 shape、stride、storage offset,也不计算符号依赖连通分量。选中维度的 hint 推导仍使用上游规则:缺少 hint、无法推导 base hint、hint 冲突都会继续报错,不会被忽略。`apply()` 检查六个所需上游辅助符号,缺失时记录 warning 并跳过此 patch。 | ||
| 90 | + | ||
| 91 | +#### 2. ep_overlap_shape_queries.py | ||
| 92 | + | ||
| 93 | +报错示例: | ||
| 94 | + | ||
| 95 | +```text | ||
| 96 | +ValueError: ep_overlap found EP token-exchange metadata on non-marker | ||
| 97 | +node sym_size_int (aten.sym_size.int). Only all_to_all launches | ||
| 98 | +and their wait_tensor nodes may carry this annotation. | ||
| 99 | +``` | ||
| 100 | + | ||
| 101 | +错误发生在 `ep_overlap_schedule_pass` 的通信节点收集阶段。AllToAll 输出的接收 token 数是数据相关的,trace 会生成 `aten.sym_size.int(all_to_all_output, 0)` 来绑定其首维长度。该节点在通信标注的作用域内生成,可能继承 `EP_token_exchange=dispatch`。社区 `_collect_token_exchanges` 只接受带此标注的 token-exchange launch 及其 wait,遇到 size query 就报错。 | ||
| 102 | + | ||
| 103 | +**Patch 方案:**在原 `_collect_token_exchanges` 前遍历当前 `body.nodes`,仅处理同时满足以下条件的节点: | ||
| 104 | + | ||
| 105 | +- `op == "call_function"`、target 为 `aten.sym_size.int`,且恰有两个位置参数。 | ||
| 106 | +- 第一个参数是当前 body 内的 FX 节点,并且上游 `_is_token_exchange_launch` 将其识别为 token-exchange launch。 | ||
| 107 | + | ||
| 108 | +包装函数的主体如下;只在 `custom` 中存在 `EP_token_exchange` 时复制字典并删除这个键: | ||
| 109 | + | ||
| 110 | +```python | ||
| 111 | +node_set = set(body.nodes) | ||
| 112 | +for node in body.nodes: | ||
| 113 | + if not _is_token_exchange_shape_query(node, node_set): | ||
| 114 | + continue | ||
| 115 | + custom = ep_overlap_pass._custom_meta(node) | ||
| 116 | + if _EP_TOKEN_EXCHANGE in custom: | ||
| 117 | + custom = dict(custom) | ||
| 118 | + del custom[_EP_TOKEN_EXCHANGE] | ||
| 119 | + node.meta["custom"] = custom | ||
| 120 | +return current(body, order=order) | ||
| 121 | +``` | ||
| 122 | + | ||
| 123 | +其余 metadata 保留;删除后即使 `custom` 为空也保留该容器;没有该标签时不改写 metadata。匹配条件不限制查询维度为 0,也不显式检查查询值是否 unbacked。launch/wait 的识别、唯一 wait 检查、顺序检查和 wait 标注归一化仍由上游完成,其他非目标节点的错误继续抛出。 | ||
| 124 | + | ||
| 125 | +当前正式 patch 仍采用“删除 shape query 继承的标签”方案,没有改成“保留标签、仅绕过报错”。 | ||
| 126 | + | ||
| 127 | +#### 3. ep_ready_nodes_dedup.py | ||
| 128 | + | ||
| 129 | +报错示例及调用关系: | ||
| 130 | + | ||
| 131 | +```text | ||
| 132 | +AssertionError: stable topological sort failed | ||
| 133 | + | ||
| 134 | +ep_overlap_schedule_pass() | ||
| 135 | + -> _schedule_ep_overlap_regions() | ||
| 136 | + -> _plan_region() | ||
| 137 | + -> _build_region_phases() | ||
| 138 | + -> _append_ready_blocks() | ||
| 139 | + -> _ready_nodes() # 可能返回重复 node | ||
| 140 | + -> _apply_schedule() | ||
| 141 | + -> _phase_order_deps() # 顺序约束可能构成环 | ||
| 142 | + -> _stable_topological_sort() | ||
| 143 | +``` | ||
| 144 | + | ||
| 145 | +节点有确定的 chunk 所有权,但两个 chunk 的调度候选集合可能有交集。例如,节点 N 属于 chunk0,同时又是 chunk1 后续 AllToAll 的依赖,它可能同时出现在两个 chunk 的候选集中。 | ||
| 146 | + | ||
| 147 | +社区 `_ready_nodes` 对每个 chunk 仅排除此前已经 `emitted` 的节点;`_append_ready_blocks` 要等整个 ready 元组生成后才更新 `emitted`,因此无法排除本轮内部的重复项。若返回结果为 `[N, A, N]`,后续顺序依赖会形成 `N -> A -> N`。 | ||
| 148 | + | ||
| 149 | +**Patch 方案:**当前提交保留 `_ready_nodes` 的遍历实现,在一次调用内新增 `selected` 集合;不修改传入的 `emitted`。替换函数的主体如下: | ||
| 150 | + | ||
| 151 | +```python | ||
| 152 | +ready = [] | ||
| 153 | +selected: set[fx.Node] = set() | ||
| 154 | +for chunk_id in chunk_order: | ||
| 155 | + body = region.bodies_by_chunk[chunk_id] | ||
| 156 | + candidates = sorted(candidates_by_chunk.get(chunk_id, set()) - emitted, key=order.__getitem__) | ||
| 157 | + for node in candidates: | ||
| 158 | + if node in selected: | ||
| 159 | + continue | ||
| 160 | + if not include_waits and ep_overlap_pass._is_c10d_functional_node(node): | ||
| 161 | + continue | ||
| 162 | + deps = ep_overlap_pass._body_deps(node, body=body, owner_by_node=owner_by_node) | ||
| 163 | + if all(dep in emitted for dep in deps): | ||
| 164 | + ready.append(node) | ||
| 165 | + selected.add(node) | ||
| 166 | +return tuple(ready) | ||
| 167 | +``` | ||
| 168 | + | ||
| 169 | +chunk 遍历顺序、chunk 内候选排序、`include_waits` 过滤以及依赖必须已经 `emitted` 的条件都保留;只有实际追加到 ready 的节点才记入 `selected`。每个节点在一次返回中最多出现一次,保留首次被选中的位置。当前代码没有调用原 `_ready_nodes` 后再对返回值去重。 | ||
| 170 | + | ||
| 171 | +#### 4. ep_shape_live_out.py | ||
| 172 | + | ||
| 173 | +报错示例: | ||
| 174 | + | ||
| 175 | +```text | ||
| 176 | +ValueError: Chunk pass cannot materialize live-out without chunk dimension; | ||
| 177 | +all_to_all_single_default from 'layers.0.moe' has full users | ||
| 178 | +['sym_size_int:sym_size.int:fqn=layers.0.moe.dispatcher'] | ||
| 179 | +and requires a forward accumulation proof or a backward parameter-gradient consumer. | ||
| 180 | +``` | ||
| 181 | + | ||
| 182 | +live-out 是 chunk body 内产生、但仍被 body 外节点使用的值。社区 `_split_live_out_users` 将消费者分成 `chunked`(跟随对应 chunk 的值)和 `full`(需要重建完整值)。某些 dispatcher size query 带有 MoE 模块 FQN,却位于 body 外;它们需要查询各 chunk 自己接收的 token 数,但上游分类将其归入 `full`。 | ||
| 183 | + | ||
| 184 | +社区 `_materialize_live_out` 只能在识别到 chunk 维时沿该维 `cat`,或在有加法重建依据时 `add`。AllToAll 输出首维是独立的接收 token symbol,通常不含选定的 chunk symbol,因而无法识别拼接维度;正向也没有适用的加法依据,最终报错。修复此场景的关键是调整消费者归属,使它无需完整值重建。 | ||
| 185 | + | ||
| 186 | +**Patch 方案:**只包装 `_split_live_out_users`。先调用社区原函数,再从 `full` 中筛选: | ||
| 187 | + | ||
| 188 | +- user 是 `call_function` 节点,target 为 `aten.sym_size.int`,恰有两个位置参数,第二个参数为 `0`。 | ||
| 189 | +- 第一个参数直接指向 `call_function` 类型的 `_c10d_functional.all_to_all_single.default` 节点。 | ||
| 190 | +- user 的模块 FQN 位于 `producer_region.root_fqn` 内。 | ||
| 191 | + | ||
| 192 | +```python | ||
| 193 | +chunked, full = current(users, plans, producer_region, symbol_hints) | ||
| 194 | +moved = tuple( | ||
| 195 | + user | ||
| 196 | + for user in full | ||
| 197 | + if _is_dim0_all_to_all_size_user(user) | ||
| 198 | + and ep_chunk_pass.is_module_fqn_inside_root( | ||
| 199 | + ep_chunk_pass._get_module_fqn(user), producer_region.root_fqn | ||
| 200 | + ) | ||
| 201 | +) | ||
| 202 | +if not moved: | ||
| 203 | + return chunked, full | ||
| 204 | +moved_set = set(moved) | ||
| 205 | +return (*chunked, *moved), tuple(user for user in full if user not in moved_set) | ||
| 206 | +``` | ||
| 207 | + | ||
| 208 | +| 函数 | 当前行为 | | ||
| 209 | +| --- | --- | | ||
| 210 | +| `_split_live_out_users` | 将满足上述条件的 user 从 full 移到 chunked;没有匹配者时返回原分类结果 | | ||
| 211 | +| `_materialize_live_out` | **保持社区原函数,不再替换,也不新增 AllToAll dim-0 的 cat fallback** | | ||
| 212 | + | ||
| 213 | +匹配不依赖 `EP_token_exchange` 标签,也不覆盖 wait 输出、普通张量或其他维度的 size query。没有剩余 full users 时,社区 chunk pass 跳过这个 live-out 的完整值重建。仍有 full users 时继续执行社区重建规则和校验,不能重建的情况仍报错。 | ||
| 214 | + | ||
| 215 | +第二个 patch 的标签清理发生在后续 schedule pass,晚于这里的 live-out 分类,因此第四个问题不是删除标签引起的。 | ||
| 216 | + | ||
| 217 | +父模块、其他 root 或缺失 FQN 的 dim-0 query 仍可能被归为 full;若未来要支持这些场景,需要额外定义重建方案,不能将当前补丁的适用范围外推为所有 AllToAll shape live-out 都受支持。 | ||
| 218 | + | ||
| 219 | +## 启用方式 | ||
| 220 | + | ||
| 221 | +EP overlap 通过 `--compile.ep_overlap.*` 打开。满足前述条件的 GraphTrainer MoE recipe 均通过同一组配置项启用;模型入口、dispatcher、并行配置和算子 override 仍由各模型 recipe 负责。 | ||
| 222 | + | ||
| 223 | +下面仅给出本文整网验证使用的 DSV4 示例:flash 43layers/16experts、8 卡、EP=8,复用仓内 DSV4 GraphTrainer 入口脚本。 | ||
| 224 | + | ||
| 225 | +```bash | ||
| 226 | +NGPU=8 \ | ||
| 227 | +HF_ASSETS_PATH=/path/to/DeepSeekV4_tokenizer \ | ||
| 228 | +bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3_graphtrainer.sh \ | ||
| 229 | + --optimizer.name native \ | ||
| 230 | + --compile.disable_passes cudagraph_pass,annotate_flex_attention_for_regional_inductor_pass,regional_inductor_pass \ | ||
| 231 | + --compile.ep_overlap.enabled \ | ||
| 232 | + --compile.ep_overlap.strategy graph \ | ||
| 233 | + --compile.ep_overlap.chunk_dim seq \ | ||
| 234 | + --compile.ep_overlap.module_fqn 'layers.*.moe' | ||
| 235 | +``` | ||
| 236 | + | ||
| 237 | +`EpOverlapConfig`(`torchtitan/experiments/graph_trainer/configs.py`)字段: | ||
| 238 | + | ||
| 239 | +| 字段 | 取值 | 说明 | | ||
| 240 | +| --- | --- | --- | | ||
| 241 | +| `enabled` | `bool`,默认 `False` | 是否启用 EP overlap | | ||
| 242 | +| `strategy` | `eager` / `graph`,默认 `graph` | `eager` 在 trace 前包装模块 forward;`graph` trace 原模型后用 FX pass 切分 | | ||
| 243 | +| `chunk_dim` | `batch` / `seq`,默认 `batch` | 切分的逻辑输入维 | | ||
| 244 | +| `module_fqn` | `layers.*` / `layers.*.moe`,默认 `layers.*` | 被切分的模块 FQN 模式 | | ||
| 245 | +| `disable_early_grad_accumulation` | `bool`,默认 `False` | 关闭 graph chunking 的早期参数梯度累加,用于需要与 eager chunking 保持严格顺序的验证场景 | | ||
| 246 | + | ||
| 247 | +上游 `validate_ep_overlap_config` 约束:`chunk_dim=seq` 仅在 `module_fqn=layers.*.moe` 时可用——序列切分要求完整 K/V 上下文,因此只对 MoE block 根成立。 | ||
| 248 | + | ||
| 249 | +若需把 EP overlap 固化为某个配置的默认值,在 `config_registry.py` 的对应工厂中对 `config.compile.ep_overlap` 赋 `EpOverlapConfig(...)`。 | ||
| 250 | + | ||
| 251 | +## DSV4 整网实跑验证(2026-09-16) | ||
| 252 | + | ||
| 253 | +本节只记录 DSV4 作为验证载体的结果,用于证明通用 EP overlap 能力及临时补丁在这一具体组合上可以完成整网训练。 | ||
| 254 | + | ||
| 255 | +在同一台机器上按“关闭 EP overlap -> 开启 EP overlap”的顺序各运行 10 step。两组均使用 8 张 Ascend 910、CANN 9.2.0、TorchTitan `v0.3.0`(`086bf6c166ec85c1298eb5596fa9bf95f6a2d840`)和本仓库 HEAD `ec98b86809e024e105958b50c7714666c8c65ff2`。模型为 flash 43 layers / 16 experts,EP=8、DP shard=8、TP/CP/PP=1,local/global batch size 为 1/64,sequence length 为 4096,seed 为 42。 | ||
| 256 | + | ||
| 257 | +开启组再追加“启用方式”中的四个 `--compile.ep_overlap.*` 参数;关闭组不追加这些参数。 | ||
| 258 | + | ||
| 259 | +| 指标 | EP overlap 关闭 | EP overlap 开启 | | ||
| 260 | +| --- | ---: | ---: | | ||
| 261 | +| 结果 | 10/10 step,退出码 0 | 10/10 step,退出码 0 | | ||
| 262 | +| graph pass | 7 个,43.617 s | 13 个,228.628 s | | ||
| 263 | +| EP 图变换 | 无 | seq chunking 86 个 region;scheduling 86 个 region | | ||
| 264 | +| step 2-10 平均耗时 | 64.975 s | 62.923 s | | ||
| 265 | +| step 2-10 平均 TPS | 505.000 | 521.222 | | ||
| 266 | +| loss(step 1 -> 10) | 12.19569 -> 9.91401 | 12.19564 -> 9.94998 | | ||
| 267 | +| 日志记录的峰值显存 | 52.22 GiB(85.23%) | 59.37 GiB(96.90%) | | ||
| 268 | + | ||
| 269 | +该次顺序单跑中,开启组 step 2-10 的平均 TPS 比关闭组高约 3.2%。 | ||
| 270 | + | ||
| 271 | +开启组的代价也较明显:日志峰值显存增加 7.15 GiB。 | ||
| 272 | + | ||
| 273 | +## 相关文档 | ||
| 274 | + | ||
| 275 | +- DSV4 模型侧 GraphTrainer 适配:[`deepseek_v4_graph_trainer.md`](deepseek_v4_graph_trainer.md) | ||
| 276 | +- 临时补丁目录约定:[`torchtitan_npu/patches/torchtitan/README.md`](../../torchtitan_npu/patches/torchtitan/README.md) | ||
| 277 | +- Override 注册表:[`torchtitan_npu/override/README.md`](../../torchtitan_npu/override/README.md) | ||
| 278 | +- 上游 GraphTrainer 与 EP overlap 说明:[`torchtitan/experiments/graph_trainer/README.md`](https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/graph_trainer/README.md) | ||
| @@ -120,9 +120,8 @@ AdamW 的 `exp_avg`、`exp_avg_sq`(AMSGrad 时还包括 `max_exp_avg_sq`)按 | |||
| 120 | flat state。每个 bucket 执行 H2D、`WAIT_DEVICE`、上游 AdamW 更新和 D2H,并在当前 bucket | 120 | flat state。每个 bucket 执行 H2D、`WAIT_DEVICE`、上游 AdamW 更新和 D2H,并在当前 bucket |
| 121 | 更新前提交下一个 bucket 的 H2D。 | 121 | 更新前提交下一个 bucket 的 H2D。 |
| 122 | 122 | ||
| 123 | -启用 `swap_optimizer` 的 `OptimizerStateSwapContainer` 不支持 optimizer `state_dict()`、 | 123 | +开启 swap 之后,checkpoint 的存储和加载支持同步模式和基于 CPU snapshot 的异步模式 `async`,暂不支持 |
| 124 | -`load_state_dict()`、完整 optimizer checkpoint 保存或断点续训。需要 checkpoint 互操作时, | 124 | +`async_with_pinned_mem`。 |
| 125 | -移除该 override 并使用普通 optimizer 路径。 | ||
| 126 | 125 | ||
| 127 | 126 | ||
| 128 | ## 能力边界 | 127 | ## 能力边界 |
| @@ -130,4 +129,4 @@ flat state。每个 bucket 执行 H2D、`WAIT_DEVICE`、上游 AdamW 更新和 D | |||
| 130 | 当前方案适合 DSV4 单机 8 卡、TP/PP=1、EP/DP-shard 并行的实验和训练。尚未证明: | 129 | 当前方案适合 DSV4 单机 8 卡、TP/PP=1、EP/DP-shard 并行的实验和训练。尚未证明: |
| 131 | 130 | ||
| 132 | - TP>1 或 PP>1 的 DistMuon; | 131 | - TP>1 或 PP>1 的 DistMuon; |
| 133 | -- swap 开启时的 optimizer checkpoint 保存、加载和断点续训; | 132 | +- `async_with_pinned_mem`、跨 world size 恢复及更复杂并行拓扑下的 swap checkpoint; |
| @@ -17,7 +17,6 @@ Host 下发和中间 Tensor 读写。`torch.compile` 使用 TorchDynamo 捕获 | |||
| 17 | 17 | ||
| 18 | - 复用 TorchTitan 配置选择需要编译的训练组件; | 18 | - 复用 TorchTitan 配置选择需要编译的训练组件; |
| 19 | - 选择 `torch_npu` 内置的 AscendC Inductor 后端; | 19 | - 选择 `torch_npu` 内置的 AscendC Inductor 后端; |
| 20 | -- 提供可选的 pre-AOT graph pattern; | ||
| 21 | - 在包导入阶段安装当前软件栈需要的 NPU 兼容 patch。 | 20 | - 在包导入阶段安装当前软件栈需要的 NPU 兼容 patch。 |
| 22 | 21 | ||
| 23 | 相关机制的边界如下: | 22 | 相关机制的边界如下: |
| @@ -26,32 +25,22 @@ Host 下发和中间 Tensor 读写。`torch.compile` 使用 TorchDynamo 捕获 | |||
| 26 | | --- | --- | --- | | 25 | | --- | --- | --- | |
| 27 | | TorchTitan compile 配置 | 训练组件构建与并行化 | 选择模型或 loss 是否进入 `torch.compile` | | 26 | | TorchTitan compile 配置 | 训练组件构建与并行化 | 选择模型或 loss 是否进入 `torch.compile` | |
| 28 | | AscendC AutoFuse | Inductor lowering 与 Codegen | 自动融合受支持的 Inductor 子图并生成 AscendC Kernel | | 27 | | AscendC AutoFuse | Inductor lowering 与 Codegen | 自动融合受支持的 Inductor 子图并生成 AscendC Kernel | |
| 29 | -| pre-AOT pattern | Dynamo 成图后、AOTAutograd 生成反向前 | 将稳定连续片段替换为专用融合实现 | | ||
| 30 | | override 与 custom op | 模型构建或明确算子边界 | 替换完整组件,或封装已有 CANN/Triton/PyPTO 算子 | | 28 | | override 与 custom op | 模型构建或明确算子边界 | 替换完整组件,或封装已有 CANN/Triton/PyPTO 算子 | |
| 31 | 29 | ||
| 32 | -普通 ATen 图优先交给 AutoFuse;完整组件使用 override;只有稳定且无法由通用融合表达的局部片段才使用 | 30 | +普通 ATen 图优先交给 AutoFuse;完整组件使用 override。这样可以保持模型代码与 NPU 后端解耦, |
| 33 | -pre-AOT pattern。这样可以保持模型代码与 NPU 后端解耦,避免为同一目标维护多套 wrapper。 | 31 | +避免为同一目标维护多套 wrapper。 |
| 34 | 32 | ||
| 35 | ## 2. 用户使用场景与对外接口 | 33 | ## 2. 用户使用场景与对外接口 |
| 36 | 34 | ||
| 37 | ### 2.1 启用 AscendC AutoFuse | 35 | ### 2.1 启用 AscendC AutoFuse |
| 38 | 36 | ||
| 39 | -仓库脚本提供最短启用方式: | 37 | +使用 TorchTitan 原生 CLI 配置编译: |
| 40 | 38 | ||
| 41 | ```bash | 39 | ```bash |
| 42 | TORCHINDUCTOR_NPU_BACKEND=ascendc \ | 40 | TORCHINDUCTOR_NPU_BACKEND=ascendc \ |
| 43 | -COMPILE_BACKEND=inductor \ | ||
| 44 | -bash scripts/run_train.sh <训练参数> | ||
| 45 | -``` | ||
| 46 | - | ||
| 47 | -也可以直接使用 TorchTitan CLI: | ||
| 48 | - | ||
| 49 | -```bash | ||
| 50 | -export TORCHINDUCTOR_NPU_BACKEND=ascendc | ||
| 51 | - | ||
| 52 | bash scripts/run_train.sh \ | 41 | bash scripts/run_train.sh \ |
| 53 | --compile.enable \ | 42 | --compile.enable \ |
| 54 | - --compile.components model,loss \ | 43 | + --compile.components model \ |
| 55 | --compile.backend inductor \ | 44 | --compile.backend inductor \ |
| 56 | <训练参数> | 45 | <训练参数> |
| 57 | ``` | 46 | ``` |
| @@ -64,45 +53,33 @@ export TORCHINDUCTOR_NPU_BACKEND=ascendc | |||
| 64 | 53 | ||
| 65 | NODE_IPS=192.168.1.10,192.168.1.11 \ | 54 | NODE_IPS=192.168.1.10,192.168.1.11 \ |
| 66 | NGPU=16 \ | 55 | NGPU=16 \ |
| 67 | -COMPILE_BACKEND=inductor \ | ||
| 68 | bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \ | 56 | bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \ |
| 69 | - --compile.components model,loss \ | 57 | + --compile.backend inductor \ |
| 58 | + --compile.components model loss \ | ||
| 70 | --training.steps 5 | 59 | --training.steps 5 |
| 71 | ``` | 60 | ``` |
| 72 | 61 | ||
| 73 | 该 wrapper 最终调用 `scripts/run_train_multinodes.sh`;同一节点上的 `torchrun` 子进程会继承启动 shell | 62 | 该 wrapper 最终调用 `scripts/run_train_multinodes.sh`;同一节点上的 `torchrun` 子进程会继承启动 shell |
| 74 | -的环境变量。需要启用 pre-AOT pattern 时,再增加 `PATTERN_IMPORTS`;如果脚本无法自动识别本机地址,设置 | 63 | +的环境变量。如果脚本无法自动识别本机地址,设置对应的 `LOCAL_HOST`。 |
| 75 | -对应的 `LOCAL_HOST`。 | ||
| 76 | 64 | ||
| 77 | ### 2.2 使用 `aot_eager` 检查编译兼容性 | 65 | ### 2.2 使用 `aot_eager` 检查编译兼容性 |
| 78 | 66 | ||
| 79 | ```bash | 67 | ```bash |
| 80 | -COMPILE_BACKEND=aot_eager \ | 68 | +bash scripts/run_train.sh \ |
| 81 | -bash scripts/run_train.sh <训练参数> | 69 | + --compile.enable \ |
| 70 | + --compile.components model \ | ||
| 71 | + --compile.backend aot_eager \ | ||
| 72 | + <训练参数> | ||
| 82 | ``` | 73 | ``` |
| 83 | 74 | ||
| 84 | `aot_eager` 可检查 Dynamo、AOTAutograd、FakeTensor 和训练反向是否可用,但不会把完整模型交给 AscendC | 75 | `aot_eager` 可检查 Dynamo、AOTAutograd、FakeTensor 和训练反向是否可用,但不会把完整模型交给 AscendC |
| 85 | -AutoFuse。当前 DeepSeek-V4 示例默认使用 `aot_eager`;验证 AutoFuse 功能或性能时,需要显式设置 | 76 | +AutoFuse。DeepSeek-V4 Flash A3/A5 示例默认使用 `inductor`;可在命令末尾追加 |
| 86 | -`COMPILE_BACKEND=inductor`。 | 77 | +`--compile.backend aot_eager` 检查编译兼容性。 |
| 87 | 78 | ||
| 88 | 含 FlexAttention 的模型在 `aot_eager` 下可能由上游 regional Inductor 单独编译 FlexAttention 区域。 | 79 | 含 FlexAttention 的模型在 `aot_eager` 下可能由上游 regional Inductor 单独编译 FlexAttention 区域。 |
| 89 | 这仍不等同于完整 TransformerBlock 使用 `inductor` 编译。 | 80 | 这仍不等同于完整 TransformerBlock 使用 `inductor` 编译。 |
| 90 | 81 | ||
| 91 | -### 2.3 注册特定图 pattern | 82 | +### 2.3 配置和环境变量 |
| 92 | - | ||
| 93 | -当融合目标是 Module 内的一段稳定连续计算时,可以在进程启动前导入 pattern 模块: | ||
| 94 | - | ||
| 95 | -```bash | ||
| 96 | -PATTERN_IMPORTS=torchtitan_npu.compile.patterns.deepseek_v4.inplace_partial_rope \ | ||
| 97 | -TORCHINDUCTOR_NPU_BACKEND=ascendc \ | ||
| 98 | -COMPILE_BACKEND=inductor \ | ||
| 99 | -bash scripts/run_train.sh <训练参数> | ||
| 100 | -``` | ||
| 101 | - | ||
| 102 | -多个模块使用逗号分隔。pattern 修改编译图,`override.imports` 修改配置树和组件,两者是独立入口。 | ||
| 103 | -pattern 的开发与验证方法见[片段融合算子接入](../graph_pattern_fusion.md)。 | ||
| 104 | - | ||
| 105 | -### 2.4 配置和环境变量 | ||
| 106 | 83 | ||
| 107 | 本仓直接复用上游 `torchtitan.config.CompileConfig`: | 84 | 本仓直接复用上游 `torchtitan.config.CompileConfig`: |
| 108 | 85 | ||
| @@ -114,17 +91,15 @@ pattern 的开发与验证方法见[片段融合算子接入](../graph_pattern_f | |||
| 114 | | `enable_async_tensor_parallel` | `False` | 是否启用 Inductor Async TP | | 91 | | `enable_async_tensor_parallel` | `False` | 是否启用 Inductor Async TP | |
| 115 | 92 | ||
| 116 | 当前固定的上游基线实际消费 `model` 和 `loss`。配置中写入其他名称,不代表对应组件已经编译。 | 93 | 当前固定的上游基线实际消费 `model` 和 `loss`。配置中写入其他名称,不代表对应组件已经编译。 |
| 117 | -`COMPILE_BACKEND` 便捷入口会显式选择 `model`;需要同时编译 loss 时,在脚本末尾追加 | 94 | +通用启动脚本直接透传 CLI,不自动启用编译。Flash 示例通过 CLI 默认启用 `model` 编译; |
| 118 | -`--compile.components model,loss` 覆盖该默认值。 | 95 | +需要同时编译 loss 时,追加 `--compile.components model loss`;关闭编译使用 `--compile.no-enable`。 |
| 96 | +仅设置 `--compile.backend` 不会自动启用编译,通用入口还需传入 `--compile.enable`。 | ||
| 119 | 97 | ||
| 120 | 仓库相关环境变量如下: | 98 | 仓库相关环境变量如下: |
| 121 | 99 | ||
| 122 | | 环境变量 | 作用 | | 100 | | 环境变量 | 作用 | |
| 123 | | --- | --- | | 101 | | --- | --- | |
| 124 | -| `COMPILE_BACKEND` | 非空时,启动脚本追加 model compile CLI | | ||
| 125 | | `TORCHINDUCTOR_NPU_BACKEND` | 选择 Inductor 内部的 NPU Codegen | | 102 | | `TORCHINDUCTOR_NPU_BACKEND` | 选择 Inductor 内部的 NPU Codegen | |
| 126 | -| `PATTERN_IMPORTS` | `TORCHTITAN_NPU_PATTERN_IMPORTS` 的脚本便捷别名 | | ||
| 127 | -| `TORCHTITAN_NPU_PATTERN_IMPORTS` | 导入并注册以逗号分隔的 pattern 模块 | | ||
| 128 | | `ASCEND_SET_ENV_PATH` | 指定 CANN `set_env.sh`,未设置时按标准安装路径查找 | | 103 | | `ASCEND_SET_ENV_PATH` | 指定 CANN `set_env.sh`,未设置时按标准安装路径查找 | |
| 129 | 104 | ||
| 130 | ## 3. 特殊背景及限制 | 105 | ## 3. 特殊背景及限制 |
| @@ -143,7 +118,7 @@ torch.compile backend: inductor | |||
| 143 | 再修改环境变量,不能可靠切换已经初始化的 Codegen。 | 118 | 再修改环境变量,不能可靠切换已经初始化的 Codegen。 |
| 144 | 119 | ||
| 145 | `scripts/run_train.sh` 在启动 Python 前默认设置 AscendC。当前 `scripts/run_train_multinodes.sh` 不补充该默认值, | 120 | `scripts/run_train.sh` 在启动 Python 前默认设置 AscendC。当前 `scripts/run_train_multinodes.sh` 不补充该默认值, |
| 146 | -多机任务必须在所有节点启动前显式导出同一变量,并确保所有 rank 使用相同 backend 和 pattern 集合。 | 121 | +多机任务必须在所有节点启动前显式导出同一变量,并确保所有 rank 使用相同 backend。 |
| 147 | 122 | ||
| 148 | ### 3.2 当前主线使用 `torch_npu` 内置后端 | 123 | ### 3.2 当前主线使用 `torch_npu` 内置后端 |
| 149 | 124 | ||
| @@ -186,7 +161,7 @@ Codegen、C++ wrapper 和 AscendC Kernel 编译,不能用于稳态性能结论 | |||
| 186 | 161 | ||
| 187 | AscendC 融合 Kernel 默认缓存到 `/tmp/.npu_kernels_<user>`,也可通过 | 162 | AscendC 融合 Kernel 默认缓存到 `/tmp/.npu_kernels_<user>`,也可通过 |
| 188 | `TORCHINDUCTOR_NPU_EXT_CACHE_DIR` 指定。缓存目录依赖文件锁,不能放到无法保证锁语义的跨 OS 共享目录。 | 163 | `TORCHINDUCTOR_NPU_EXT_CACHE_DIR` 指定。缓存目录依赖文件锁,不能放到无法保证锁语义的跨 OS 共享目录。 |
| 189 | -切换软件版本、SoC、backend、模型图、shape 关键配置、pattern 或 custom op 后,应使用隔离缓存或定向失效相关 | 164 | +切换软件版本、SoC、backend、模型图、shape 关键配置或 custom op 后,应使用隔离缓存或定向失效相关 |
| 190 | 产物;不建议每次训练前无条件清空整个 `/tmp`。 | 165 | 产物;不建议每次训练前无条件清空整个 `/tmp`。 |
| 191 | 166 | ||
| 192 | 下列调试选项会改变编译或执行行为,不能直接用于正式性能结论: | 167 | 下列调试选项会改变编译或执行行为,不能直接用于正式性能结论: |
| @@ -212,7 +187,6 @@ flowchart TB | |||
| 212 | 187 | ||
| 213 | subgraph PLUGIN[torchtitan-npu 接入层] | 188 | subgraph PLUGIN[torchtitan-npu 接入层] |
| 214 | PATCH[NPU compatibility patches] | 189 | PATCH[NPU compatibility patches] |
| 215 | - PATTERN[可选 pre-AOT patterns] | ||
| 216 | EXT[TrainerEx 与 override/custom op] | 190 | EXT[TrainerEx 与 override/custom op] |
| 217 | end | 191 | end |
| 218 | 192 | ||
| @@ -223,7 +197,6 @@ flowchart TB | |||
| 223 | 197 | ||
| 224 | subgraph PYTORCH[PyTorch 编译层] | 198 | subgraph PYTORCH[PyTorch 编译层] |
| 225 | DYNAMO[TorchDynamo] | 199 | DYNAMO[TorchDynamo] |
| 226 | - PREAOT[pre-AOT graph pass] | ||
| 227 | AOT[AOTAutograd] | 200 | AOT[AOTAutograd] |
| 228 | INDUCTOR[TorchInductor] | 201 | INDUCTOR[TorchInductor] |
| 229 | FALLBACK[fallback / extern kernel] | 202 | FALLBACK[fallback / extern kernel] |
| @@ -238,11 +211,9 @@ flowchart TB | |||
| 238 | 211 | ||
| 239 | USER --> LAUNCH --> ENTRY | 212 | USER --> LAUNCH --> ENTRY |
| 240 | ENTRY --> PATCH | 213 | ENTRY --> PATCH |
| 241 | - ENTRY --> PATTERN | ||
| 242 | ENTRY --> EXT | 214 | ENTRY --> EXT |
| 243 | ENTRY --> CONFIG --> MODEL --> DYNAMO | 215 | ENTRY --> CONFIG --> MODEL --> DYNAMO |
| 244 | - PATTERN --> PREAOT | 216 | + DYNAMO --> AOT --> INDUCTOR --> BACKEND |
| 245 | - DYNAMO --> PREAOT --> AOT --> INDUCTOR --> BACKEND | ||
| 246 | BACKEND -->|满足 lowering 条件| AUTOFUSE --> CACHE --> KERNEL | 217 | BACKEND -->|满足 lowering 条件| AUTOFUSE --> CACHE --> KERNEL |
| 247 | BACKEND -->|不满足条件| FALLBACK | 218 | BACKEND -->|不满足条件| FALLBACK |
| 248 | ``` | 219 | ``` |
| @@ -264,8 +235,7 @@ flowchart TB | |||
| 264 | patches → compile → config → extensions → ops | 235 | patches → compile → config → extensions → ops |
| 265 | ``` | 236 | ``` |
| 266 | 237 | ||
| 267 | -该顺序是运行时契约。NPU patch 必须在模型构建和首次编译前生效;AscendC backend 的自有 graph pass 先注册, | 238 | +该顺序是运行时契约。NPU patch 必须在模型构建和首次编译前生效。新增初始化逻辑不能随意调整此顺序。 |
| 268 | -仓内 pattern 再追加到已有 pass 链。新增初始化逻辑不能随意调整此顺序。 | ||
| 269 | 239 | ||
| 270 | ### 5.2 模型和 loss 编译 | 240 | ### 5.2 模型和 loss 编译 |
| 271 | 241 | ||
| @@ -285,20 +255,7 @@ SimpleFSDP 顺序,不适用上述标准路径。 | |||
| 285 | loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用同一个 `compile.backend`。模型编译与 loss | 255 | loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用同一个 `compile.backend`。模型编译与 loss |
| 286 | 编译互不隐含。 | 256 | 编译互不隐含。 |
| 287 | 257 | ||
| 288 | -### 5.3 pre-AOT pattern | 258 | +### 5.3 AscendC AutoFuse 与 fallback |
| 289 | - | ||
| 290 | -`torchtitan_npu.compile` 在首次导入时读取 `TORCHTITAN_NPU_PATTERN_IMPORTS`。目标模块调用 | ||
| 291 | -`register_pre_aot_patterns`,将具名 `PatternReplacement` 追加到共享 `_PreAOTPatternPass`: | ||
| 292 | - | ||
| 293 | -- 保留已经存在的 Inductor custom pass; | ||
| 294 | -- 共享 pass 只安装一次; | ||
| 295 | -- pattern 未命中时保留原图; | ||
| 296 | -- pattern 名称、字面量策略、源码和 closure 参数参与 cache identity。 | ||
| 297 | - | ||
| 298 | -模型已经编译后再注册 pattern,不会追溯修改已生成的 compiled callable。DeepSeek-V4 partial RoPE 是当前参考 | ||
| 299 | -实现,详细的 search/replacement、alias 和梯度约束不在本文重复展开。 | ||
| 300 | - | ||
| 301 | -### 5.4 AscendC AutoFuse 与 fallback | ||
| 302 | 259 | ||
| 303 | 选择 `ascendc` 后,`torch_npu` 向 Inductor 注册 NPU scheduling、wrapper Codegen、lowering、decomposition | 260 | 选择 `ascendc` 后,`torch_npu` 向 Inductor 注册 NPU scheduling、wrapper Codegen、lowering、decomposition |
| 304 | 和图优化。后端根据 op、SoC、dtype、shape、stride、layout、数据依赖和 mutation/alias 判断节点能否 lowering | 261 | 和图优化。后端根据 op、SoC、dtype、shape、stride、layout、数据依赖和 mutation/alias 判断节点能否 lowering |
| @@ -308,7 +265,7 @@ loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用 | |||
| 308 | 不满足条件的节点保留为 fallback/extern kernel。这部分实现位于 `torch_npu` 和 CANN,本仓只负责选择、接入和 | 265 | 不满足条件的节点保留为 fallback/extern kernel。这部分实现位于 `torch_npu` 和 CANN,本仓只负责选择、接入和 |
| 309 | 兼容。 | 266 | 兼容。 |
| 310 | 267 | ||
| 311 | -### 5.5 NPU 兼容 patch | 268 | +### 5.4 NPU 兼容 patch |
| 312 | 269 | ||
| 313 | | Patch | 解决的问题 | 设计边界 | | 270 | | Patch | 解决的问题 | 设计边界 | |
| 314 | | --- | --- | --- | | 271 | | --- | --- | --- | |
| @@ -317,7 +274,7 @@ loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用 | |||
| 317 | 274 | ||
| 318 | 两个 patch 都依赖包导入时机。CPU-only import 能验证模块可加载,但不能证明 NPU 条件分支已经生效。 | 275 | 两个 patch 都依赖包导入时机。CPU-only import 能验证模块可加载,但不能证明 NPU 条件分支已经生效。 |
| 319 | 276 | ||
| 320 | -### 5.6 与其他组件的交互 | 277 | +### 5.5 与其他组件的交互 |
| 321 | 278 | ||
| 322 | | 组件 | 交互约束 | | 279 | | 组件 | 交互约束 | |
| 323 | | --- | --- | | 280 | | --- | --- | |
| @@ -325,7 +282,7 @@ loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用 | |||
| 325 | | 量化训练 | `TrainerEx` 在模型构建前执行编译感知的量化配置转换;量化不会自动启用 compile | | 282 | | 量化训练 | `TrainerEx` 在模型构建前执行编译感知的量化配置转换;量化不会自动启用 compile | |
| 326 | | TP/EP/FSDP | 并行化顺序决定编译边界;标准 CompileConfig 不等于 GraphTrainer 的图内通信调度 | | 283 | | TP/EP/FSDP | 并行化顺序决定编译边界;标准 CompileConfig 不等于 GraphTrainer 的图内通信调度 | |
| 327 | | Async TP | 要求 compile 已启用、`components` 包含 `model` 且存在 TP mesh | | 284 | | Async TP | 要求 compile 已启用、`components` 包含 `model` 且存在 TP mesh | |
| 328 | -| 多机训练 | 所有节点必须使用相同软件版本、Codegen backend 和 pattern imports | | 285 | +| 多机训练 | 所有节点必须使用相同软件版本和 Codegen backend | |
| 329 | 286 | ||
| 330 | ## 6. 验证、支持边界与关键文件索引 | 287 | ## 6. 验证、支持边界与关键文件索引 |
| 331 | 288 | ||
| @@ -334,12 +291,11 @@ loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用 | |||
| 334 | 不能仅以「训练成功」判断融合生效。建议按以下顺序验证: | 291 | 不能仅以「训练成功」判断融合生效。建议按以下顺序验证: |
| 335 | 292 | ||
| 336 | 1. 确认日志出现 `Compiling each TransformerBlock with torch.compile` 或 loss 编译日志; | 293 | 1. 确认日志出现 `Compiling each TransformerBlock with torch.compile` 或 loss 编译日志; |
| 337 | -2. 启用 pattern 时,确认出现 `Pre-AOT pattern ... replaced N subgraph(s)`; | 294 | +2. 使用 `TORCH_COMPILE_DEBUG=1` 检查 lowered/fallback summary 和编译产物; |
| 338 | -3. 使用 `TORCH_COMPILE_DEBUG=1` 检查 lowered/fallback summary 和编译产物; | 295 | +3. 用真实输入验证正向、反向、输出和梯度; |
| 339 | -4. 用真实输入验证正向、反向、输出和梯度; | 296 | +4. 通过 profiling 确认真实 `autofused_*` device Kernel 及原生小算子变化; |
| 340 | -5. 通过 profiling 确认真实 `autofused_*` device Kernel 及原生小算子变化; | 297 | +5. 使用相同 checkpoint、输入、并行配置和随机性比较 loss 与 grad norm; |
| 341 | -6. 使用相同 checkpoint、输入、并行配置和随机性比较 loss 与 grad norm; | 298 | +6. 关闭额外调试开关,在 warmup 后的稳定 step 测量性能。 |
| 342 | -7. 关闭额外调试开关,在 warmup 后的稳定 step 测量性能。 | ||
| 343 | 299 | ||
| 344 | 融合可能改变中间结果物化位置和浮点运算分组。数值验收应区分 bit-wise 一致、容差一致和收敛一致,不能只用 | 300 | 融合可能改变中间结果物化位置和浮点运算分组。数值验收应区分 bit-wise 一致、容差一致和收敛一致,不能只用 |
| 345 | 训练是否出现 NaN 作为标准。 | 301 | 训练是否出现 NaN 作为标准。 |
| @@ -352,7 +308,6 @@ loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用 | |||
| 352 | | loss 编译 | `components` 包含 `loss` | 独立于模型编译;收益取决于 loss 图规模和 fallback | | 308 | | loss 编译 | `components` 包含 `loss` | 独立于模型编译;收益取决于 loss 图规模和 fallback | |
| 353 | | AscendC AutoFuse | `backend=inductor` 且 NPU backend 为 `ascendc` | 实际融合范围由 `torch_npu`、CANN、SoC、dtype、shape 和 layout 决定 | | 309 | | AscendC AutoFuse | `backend=inductor` 且 NPU backend 为 `ascendc` | 实际融合范围由 `torch_npu`、CANN、SoC、dtype、shape 和 layout 决定 | |
| 354 | | `aot_eager` 检查 | `backend=aot_eager` | 可验证成图和正反向,不证明 AutoFuse 性能 | | 310 | | `aot_eager` 检查 | `backend=aot_eager` | 可验证成图和正反向,不证明 AutoFuse 性能 | |
| 355 | -| pre-AOT pattern | 显式导入 pattern 模块 | 当前提供 DeepSeek-V4 partial RoPE 示例;真实 Kernel 需在配套算子环境验证 | | ||
| 356 | | GraphTrainer | 选择 `graph_trainer_*` 配置 | 独立特性,不属于本文标准 CompileConfig 路径 | | 311 | | GraphTrainer | 选择 `graph_trainer_*` 配置 | 独立特性,不属于本文标准 CompileConfig 路径 | |
| 357 | 312 | ||
| 358 | 源码存在某条路径不表示全部设备和并行组合均已验证。发布验证应记录模型、SoC、dtype、序列布局、并行策略和 | 313 | 源码存在某条路径不表示全部设备和并行组合均已验证。发布验证应记录模型、SoC、dtype、序列布局、并行策略和 |
| @@ -362,12 +317,10 @@ loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用 | |||
| 362 | 317 | ||
| 363 | | 归属 | 文件或模块 | 作用 | | 318 | | 归属 | 文件或模块 | 作用 | |
| 364 | | --- | --- | --- | | 319 | | --- | --- | --- | |
| 365 | -| 本仓 | `scripts/run_train.sh` | 单机启动、AscendC 默认 Codegen、compile 和 pattern 参数 | | 320 | +| 本仓 | `scripts/run_train.sh` | 单机启动与 AscendC 默认 Codegen | |
| 366 | | 本仓 | `scripts/run_train_multinodes.sh` | 多机启动和 compile 参数;NPU backend 需在各节点显式统一 | | 321 | | 本仓 | `scripts/run_train_multinodes.sh` | 多机启动和 compile 参数;NPU backend 需在各节点显式统一 | |
| 367 | | 本仓 | `torchtitan_npu/train.py` | 复用上游训练入口并触发插件初始化 | | 322 | | 本仓 | `torchtitan_npu/train.py` | 复用上游训练入口并触发插件初始化 | |
| 368 | | 本仓 | `torchtitan_npu/__init__.py` | 固定 patches、compile、config、extensions 和 ops 的加载顺序 | | 323 | | 本仓 | `torchtitan_npu/__init__.py` | 固定 patches、compile、config、extensions 和 ops 的加载顺序 | |
| 369 | -| 本仓 | `torchtitan_npu/compile/__init__.py` | 读取并导入 `TORCHTITAN_NPU_PATTERN_IMPORTS` 指定的 pattern 模块 | | ||
| 370 | -| 本仓 | `torchtitan_npu/compile/pattern_replacement.py` | 共享 pre-AOT pass、注册和 cache identity | | ||
| 371 | | 本仓 | `torchtitan_npu/patches/workaround/device_copy.py` | NPU 异步 D2H 和 `device_put` 兼容 | | 324 | | 本仓 | `torchtitan_npu/patches/workaround/device_copy.py` | NPU 异步 D2H 和 `device_put` 兼容 | |
| 372 | | 本仓 | `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 兼容 | |
| 373 | | 本仓 | `torchtitan_npu/extensions/trainer.py` | 编译感知的 NPU Trainer 与量化转换 | | 326 | | 本仓 | `torchtitan_npu/extensions/trainer.py` | 编译感知的 NPU Trainer 与量化转换 | |
| @@ -376,6 +329,5 @@ loss 由上游 `BaseLoss._maybe_compile` 独立检查 `components`,并使用 | |||
| 376 | 329 | ||
| 377 | ### 6.4 相关文档 | 330 | ### 6.4 相关文档 |
| 378 | 331 | ||
| 379 | -- [片段融合算子接入](../graph_pattern_fusion.md) | ||
| 380 | - [融合算子接入指南](./fused_ops.md) | 332 | - [融合算子接入指南](./fused_ops.md) |
| 381 | - [软件安装](../user-guides/installation.md) | 333 | - [软件安装](../user-guides/installation.md) |
| @@ -1,87 +0,0 @@ | |||
| 1 | -# 片段融合算子接入 | ||
| 2 | - | ||
| 3 | -当融合算子只替换 `forward()` 中的一段连续计算时,使用 pre-AOT pattern 可以避免复制 | ||
| 4 | -整个 Module 或修改模型代码。 | ||
| 5 | - | ||
| 6 | -## 什么时候使用 | ||
| 7 | - | ||
| 8 | -适合:原始片段结构稳定、可被 `torch.compile` 捕获,融合算子位于 Module 内部。 | ||
| 9 | - | ||
| 10 | -不适合:需要替换完整 Module、包含数据依赖控制流,或融合算子没有 Fake/Meta 实现。训练 | ||
| 11 | -算子还必须支持 Autograd。 | ||
| 12 | - | ||
| 13 | -## 怎么接入 | ||
| 14 | - | ||
| 15 | -以 DeepSeek-V4 的 `split -> complex RoPE -> cat` 替换为 | ||
| 16 | -`inplace_partial_rotary_mul` 为例,核心结构如下。`original_rope_fragment` 和 | ||
| 17 | -`fused_partial_rope` 分别表示原始计算片段和融合算子调用: | ||
| 18 | - | ||
| 19 | -```python | ||
| 20 | -from torchtitan_npu.compile import PatternReplacement, register_pre_aot_patterns | ||
| 21 | - | ||
| 22 | - | ||
| 23 | -def make_pattern(*, inverse): | ||
| 24 | - def search_fn(x, cos, sin): | ||
| 25 | - return original_rope_fragment(x, cos, sin, inverse=inverse) | ||
| 26 | - | ||
| 27 | - def replacement_fn(x, cos, sin): | ||
| 28 | - return fused_partial_rope(x, cos, sin, inverse=inverse) | ||
| 29 | - | ||
| 30 | - return PatternReplacement( | ||
| 31 | - search_fn=search_fn, | ||
| 32 | - replacement_fn=replacement_fn, | ||
| 33 | - ignore_literals=True, | ||
| 34 | - ) | ||
| 35 | - | ||
| 36 | - | ||
| 37 | -register_pre_aot_patterns( | ||
| 38 | - { | ||
| 39 | - "dsv4_parent_rope_inverse": make_pattern(inverse=True), | ||
| 40 | - "dsv4_parent_rope_forward": make_pattern(inverse=False), | ||
| 41 | - } | ||
| 42 | -) | ||
| 43 | -``` | ||
| 44 | - | ||
| 45 | -将接入代码放在独立模块中,并在模块导入时完成注册。启动训练前显式设置模块路径: | ||
| 46 | - | ||
| 47 | -```bash | ||
| 48 | -export TORCHTITAN_NPU_PATTERN_IMPORTS=\ | ||
| 49 | -torchtitan_npu.compile.patterns.deepseek_v4.inplace_partial_rope | ||
| 50 | -``` | ||
| 51 | - | ||
| 52 | -多个模块使用逗号分隔。该入口只注册编译图 pattern,不占用 `override.imports` 中的 | ||
| 53 | -`Config` 节点。 | ||
| 54 | - | ||
| 55 | -接入时只需注意: | ||
| 56 | - | ||
| 57 | -- `search_fn` 必须与模型中的原始片段一致; | ||
| 58 | -- 仅当字面量(如 `split` 尺寸)应作为通配符时设置 `ignore_literals=True`; | ||
| 59 | -- `replacement_fn` 必须保持相同的输出、dtype、layout 和 alias 语义; | ||
| 60 | -- 可复用的 cache 前处理应在 cache 初始化时完成,避免每步重复计算; | ||
| 61 | -- 不希望 FX 展开的算子调用可以使用 `torch.fx.wrap` 包装; | ||
| 62 | -- 算子已注册 Autograd 时直接调用,不要在 override 中重复实现正反向; | ||
| 63 | -- 多个结构变体用一个 factory 生成多个 `PatternReplacement`,然后一次注册。 | ||
| 64 | - | ||
| 65 | -完整实现参考 | ||
| 66 | -`torchtitan_npu/compile/patterns/deepseek_v4/inplace_partial_rope.py`。 | ||
| 67 | - | ||
| 68 | -## 启用和验证 | ||
| 69 | - | ||
| 70 | -```bash | ||
| 71 | -# 只开启快速调试,不注册 pattern | ||
| 72 | -TORCHINDUCTOR_NPU_EXT_DEBUG=allfallback \ | ||
| 73 | -COMPILE_BACKEND=inductor ./scripts/run_train.sh | ||
| 74 | - | ||
| 75 | -# 开启快速调试,并注册 inplace partial RoPE pattern | ||
| 76 | -TORCHINDUCTOR_NPU_EXT_DEBUG=allfallback \ | ||
| 77 | -PATTERN_IMPORTS=torchtitan_npu.compile.patterns.deepseek_v4.inplace_partial_rope \ | ||
| 78 | -COMPILE_BACKEND=inductor ./scripts/run_train.sh | ||
| 79 | -``` | ||
| 80 | - | ||
| 81 | -验证时确认 pattern 匹配数量、正反向数值、loss/grad norm,并通过 profiling 检查融合算子 | ||
| 82 | -是否生效以及是否新增 clone、copy 或 TensorMove。性能验证时不设置 | ||
| 83 | -`TORCHINDUCTOR_NPU_EXT_DEBUG=allfallback`。 | ||
| 84 | - | ||
| 85 | -> 注:当前 DeepSeek-V4 golden attention 不支持启用 inplace partial RoPE pattern。 | ||
| 86 | - | ||
| 87 | -> 注:`torchtitan_npu.compile.patterns.deepseek_v4.inplace_partial_rope` 的使能依赖 `torchtitan_npu.override.common.rope.workaround`,启用 pattern 时应一并注入该 override。 | ||
| @@ -168,6 +168,7 @@ LI Q/K 量化可通过以下参数单独选择,必须同时启用低精度训 | |||
| 168 | - `--extension.quantization.enable-mxfp4-qat` 与 `--extension.quantization.no-enable-mxfp4-qat`:控制 routed expert 的 Block FP8 weight 是否增加 MXFP4 QAT fake quant 数值约束,默认关闭,仅对包含 Block FP8 的 recipe 生效。该选项不是持久化 4-bit 参数训练,也不会把算子替换为原生 A8W4 GEMM。 | 168 | - `--extension.quantization.enable-mxfp4-qat` 与 `--extension.quantization.no-enable-mxfp4-qat`:控制 routed expert 的 Block FP8 weight 是否增加 MXFP4 QAT fake quant 数值约束,默认关闭,仅对包含 Block FP8 的 recipe 生效。该选项不是持久化 4-bit 参数训练,也不会把算子替换为原生 A8W4 GEMM。 |
| 169 | - `--extension.quantization.li-quantization`:选择 LI Q/K 量化类型,可选 `mxfp4`、`mxfp8`、`fp8` 或 `hif8`;需要同时启用 `enable-quantized-training`。 | 169 | - `--extension.quantization.li-quantization`:选择 LI Q/K 量化类型,可选 `mxfp4`、`mxfp8`、`fp8` 或 `hif8`;需要同时启用 `enable-quantized-training`。 |
| 170 | - `--extension.quantization.dst-type-max`:量化目标数据类型最大值,用于 MXFP4 fake quant 和 HiF8 LI 量化时,默认值为 `0.0`;HiF8 支持 `0`、`15`、`56`、`224` 和 `32768`。 | 170 | - `--extension.quantization.dst-type-max`:量化目标数据类型最大值,用于 MXFP4 fake quant 和 HiF8 LI 量化时,默认值为 `0.0`;HiF8 支持 `0`、`15`、`56`、`224` 和 `32768`。 |
| 171 | +- `--extension.quantization.fsdp-prequantize`:将 Block FP8 权重的量化提前到 FSDP all-gather 之前,默认关闭。开启后权重在 `fsdp_pre_all_gather` 中量化为 block MX,all-gather 传输量化后的 FP8 权重与 scale,前向和反向复用该数据,减少通信量和重复量化计算;用 `--extension.quantization.no-fsdp-prequantize` 可显式关闭。该选项只对 recipe 中包含 Block FP8 的部分生效(`mix` 的 routed expert 与 `all_block_fp8`),对 `all_mxfp8` 无效果;需要同时启用 `enable-quantized-training`。当分片未按 32 对齐或不存在 FSDP 分片(如 EFSDP=1 的 MoE)时,自动回退为高精度通信加运行时量化。 | ||
| 171 | - `--profiler.enable-profiling`:启用性能分析。 | 172 | - `--profiler.enable-profiling`:启用性能分析。 |
| 172 | - `USE_GOLDEN`:设为 `1` 时选择 golden attention override;默认使用 Ascend 融合算子路径。 | 173 | - `USE_GOLDEN`:设为 `1` 时选择 golden attention override;默认使用 Ascend 融合算子路径。 |
| 173 | 174 | ||
| @@ -12,9 +12,6 @@ | |||
| 12 | 12 | ||
| 13 | set -euo pipefail | 13 | set -euo pipefail |
| 14 | 14 | ||
| 15 | -# Enable model compilation by default; callers can override the backend. | ||
| 16 | -export COMPILE_BACKEND="${COMPILE_BACKEND:-aot_eager}" | ||
| 17 | - | ||
| 18 | NGPU="${NGPU:-8}" | 15 | NGPU="${NGPU:-8}" |
| 19 | WORLD_SIZE="${NGPU}" | 16 | WORLD_SIZE="${NGPU}" |
| 20 | 17 | ||
| @@ -72,6 +69,13 @@ PARALLELISM_ARGS=" | |||
| 72 | --parallelism.pipeline-parallel-degree ${PP} | 69 | --parallelism.pipeline-parallel-degree ${PP} |
| 73 | " | 70 | " |
| 74 | 71 | ||
| 72 | +# Compile | ||
| 73 | +COMPILE_ARGS=" | ||
| 74 | + --compile.enable | ||
| 75 | + --compile.components model | ||
| 76 | + --compile.backend inductor | ||
| 77 | +" | ||
| 78 | + | ||
| 75 | # Training | 79 | # Training |
| 76 | TRAINING_ARGS=" | 80 | TRAINING_ARGS=" |
| 77 | --training.local-batch-size ${MBS} | 81 | --training.local-batch-size ${MBS} |
| @@ -120,9 +124,7 @@ OPTIMIZER_ARGS=" | |||
| 120 | --optimizer.muon_ns_steps 10 | 124 | --optimizer.muon_ns_steps 10 |
| 121 | --optimizer.muon_adjust_lr_fn match_rms_adamw | 125 | --optimizer.muon_adjust_lr_fn match_rms_adamw |
| 122 | " | 126 | " |
| 123 | -OPTIMIZER_OVERRIDES=" | 127 | +OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}" |
| 124 | - torchtitan_npu.override.common.optimizer.swap_optimizer | ||
| 125 | -" | ||
| 126 | 128 | ||
| 127 | if [[ "${USE_GOLDEN}" == "1" ]]; then | 129 | if [[ "${USE_GOLDEN}" == "1" ]]; then |
| 128 | NPU_OPS_OVERRIDES=( | 130 | NPU_OPS_OVERRIDES=( |
| @@ -156,6 +158,7 @@ CONFIG="${CONFIG}" \ | |||
| 156 | NGPU="${NGPU}" \ | 158 | NGPU="${NGPU}" \ |
| 157 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | 159 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ |
| 158 | bash scripts/run_train.sh \ | 160 | bash scripts/run_train.sh \ |
| 161 | + $COMPILE_ARGS \ | ||
| 159 | $HF_ASSETS_ARGS \ | 162 | $HF_ASSETS_ARGS \ |
| 160 | $DATALOADER_ARGS \ | 163 | $DATALOADER_ARGS \ |
| 161 | $PARALLELISM_ARGS \ | 164 | $PARALLELISM_ARGS \ |
| @@ -18,18 +18,25 @@ SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | |||
| 18 | # NPU cards for configuration. | 18 | # NPU cards for configuration. |
| 19 | export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" | 19 | export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" |
| 20 | 20 | ||
| 21 | -# A5 defaults to Inductor with the DeepSeek-V4 pre-AOT pattern. | 21 | +export MBS=2 |
| 22 | -export COMPILE_BACKEND="${COMPILE_BACKEND:-inductor}" | 22 | +# A5 defaults to Inductor; partial RoPE fuses through the asc_partial override. |
| 23 | -export TORCHTITAN_NPU_PATTERN_IMPORTS="${TORCHTITAN_NPU_PATTERN_IMPORTS:-torchtitan_npu.compile.patterns.deepseek_v4.inplace_partial_rope}" | 23 | +# swiglu_group fuses SwiGLU for routed and shared experts. |
| 24 | -export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.workaround}" | 24 | +export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \ |
| 25 | + torchtitan_npu.override.common.swiglu_group.asc \ | ||
| 26 | + torchtitan_npu.override.common.swiglu_group.asc_shared_experts}" | ||
| 25 | 27 | ||
| 26 | # A5 defaults to block-FP8 quantized training. Append | 28 | # A5 defaults to block-FP8 quantized training. Append |
| 27 | # --extension.quantization.no-enable-quantized-training for BF16 training. | 29 | # --extension.quantization.no-enable-quantized-training for BF16 training. |
| 28 | QUANTIZATION_ARGS=( | 30 | QUANTIZATION_ARGS=( |
| 29 | --extension.quantization.enable-quantized-training | 31 | --extension.quantization.enable-quantized-training |
| 30 | --extension.quantization.recipe all_block_fp8 | 32 | --extension.quantization.recipe all_block_fp8 |
| 33 | + --extension.quantization.fsdp-prequantize | ||
| 34 | + --extension.quantization.li-quantization fp8 | ||
| 31 | ) | 35 | ) |
| 32 | 36 | ||
| 37 | +# Disable swap optimizer for better performance | ||
| 38 | +export OPTIMIZER_OVERRIDES="" | ||
| 39 | + | ||
| 33 | # Tyro treats activation-checkpoint:selective as a subcommand, so it must be | 40 | # Tyro treats activation-checkpoint:selective as a subcommand, so it must be |
| 34 | # the final token after all regular options and override targets. | 41 | # the final token after all regular options and override targets. |
| 35 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \ | 42 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \ |
| @@ -0,0 +1,22 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 3 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 4 | +# SPDX-License-Identifier: BSD-3-Clause | ||
| 5 | +# | ||
| 6 | +# This source code is licensed under the BSD-style license found in the | ||
| 7 | +# LICENSE file in the root directory of this source tree. | ||
| 8 | + | ||
| 9 | +# SFT wrapper around the 8p CPT launcher in this directory. | ||
| 10 | +set -euo pipefail | ||
| 11 | + | ||
| 12 | +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | ||
| 13 | +SFT_OVERRIDE="${SFT_OVERRIDE:-torchtitan_npu.override.deepseek_v4.chat_dataloader.sft}" | ||
| 14 | +DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}" | ||
| 15 | + | ||
| 16 | +exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \ | ||
| 17 | + "${SFT_OVERRIDE}" \ | ||
| 18 | + --dataloader.dataset json \ | ||
| 19 | + --dataloader.dataset-path "${DATASET_PATH}" \ | ||
| 20 | + --checkpoint.enable \ | ||
| 21 | + --checkpoint.no-load-only \ | ||
| 22 | + "$@" | ||
| @@ -0,0 +1,19 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 3 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 4 | +# SPDX-License-Identifier: BSD-3-Clause | ||
| 5 | +# | ||
| 6 | +# This source code is licensed under the BSD-style license found in the | ||
| 7 | +# LICENSE file in the root directory of this source tree. | ||
| 8 | + | ||
| 9 | +# Eight-node SFT wrapper around the common DeepSeek-V4 Flash SFT launcher. | ||
| 10 | +set -euo pipefail | ||
| 11 | + | ||
| 12 | +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | ||
| 13 | + | ||
| 14 | +NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, \ | ||
| 15 | + xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}" | ||
| 16 | +NGPU="${NGPU:-16}" | ||
| 17 | +export NODE_IPS NGPU | ||
| 18 | + | ||
| 19 | +exec bash "${SCRIPT_DIR}/deepseek_v4_flash_sft_4k_a3.sh" "$@" | ||
| @@ -14,9 +14,6 @@ | |||
| 14 | 14 | ||
| 15 | set -euo pipefail | 15 | set -euo pipefail |
| 16 | 16 | ||
| 17 | -# Enable model compilation by default; callers can override the backend. | ||
| 18 | -export COMPILE_BACKEND="${COMPILE_BACKEND:-aot_eager}" | ||
| 19 | - | ||
| 20 | NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, \ | 17 | NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, \ |
| 21 | xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}" | 18 | xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}" |
| 22 | NGPU="${NGPU:-16}" | 19 | NGPU="${NGPU:-16}" |
| @@ -45,7 +42,7 @@ SPMD_BACKEND="spmd_types" | |||
| 45 | 42 | ||
| 46 | # Training | 43 | # Training |
| 47 | SEQ_LEN=4096 | 44 | SEQ_LEN=4096 |
| 48 | -MBS=1 | 45 | +MBS="${MBS:-1}" |
| 49 | GBS=1024 | 46 | GBS=1024 |
| 50 | STEPS=100 | 47 | STEPS=100 |
| 51 | 48 | ||
| @@ -78,6 +75,13 @@ PARALLELISM_ARGS=" | |||
| 78 | --parallelism.pipeline-parallel-degree ${PP} | 75 | --parallelism.pipeline-parallel-degree ${PP} |
| 79 | " | 76 | " |
| 80 | 77 | ||
| 78 | +# Compile | ||
| 79 | +COMPILE_ARGS=" | ||
| 80 | + --compile.enable | ||
| 81 | + --compile.components model | ||
| 82 | + --compile.backend inductor | ||
| 83 | +" | ||
| 84 | + | ||
| 81 | # Training | 85 | # Training |
| 82 | TRAINING_ARGS=" | 86 | TRAINING_ARGS=" |
| 83 | --training.local-batch-size ${MBS} | 87 | --training.local-batch-size ${MBS} |
| @@ -129,9 +133,7 @@ OPTIMIZER_ARGS=" | |||
| 129 | --optimizer.muon_ns_steps 10 | 133 | --optimizer.muon_ns_steps 10 |
| 130 | --optimizer.muon_adjust_lr_fn match_rms_adamw | 134 | --optimizer.muon_adjust_lr_fn match_rms_adamw |
| 131 | " | 135 | " |
| 132 | -OPTIMIZER_OVERRIDES=" | 136 | +OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}" |
| 133 | - torchtitan_npu.override.common.optimizer.swap_optimizer | ||
| 134 | -" | ||
| 135 | 137 | ||
| 136 | if [[ "${USE_GOLDEN}" == "1" ]]; then | 138 | if [[ "${USE_GOLDEN}" == "1" ]]; then |
| 137 | NPU_OPS_OVERRIDES=( | 139 | NPU_OPS_OVERRIDES=( |
| @@ -166,6 +168,7 @@ NODE_IPS="${NODE_IPS}" \ | |||
| 166 | NGPU="${NGPU}" \ | 168 | NGPU="${NGPU}" \ |
| 167 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | 169 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ |
| 168 | bash scripts/run_train_multinodes.sh \ | 170 | bash scripts/run_train_multinodes.sh \ |
| 171 | + $COMPILE_ARGS \ | ||
| 169 | $HF_ASSETS_ARGS \ | 172 | $HF_ASSETS_ARGS \ |
| 170 | $DATALOADER_ARGS \ | 173 | $DATALOADER_ARGS \ |
| 171 | $PARALLELISM_ARGS \ | 174 | $PARALLELISM_ARGS \ |
| @@ -21,22 +21,30 @@ export HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}" | |||
| 21 | # Override this for the host topology reported by `npu-smi info -t topo`. | 21 | # Override this for the host topology reported by `npu-smi info -t topo`. |
| 22 | export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" | 22 | export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" |
| 23 | 23 | ||
| 24 | -export COMPILE_BACKEND="${COMPILE_BACKEND:-inductor}" | 24 | +# Partial RoPE fuses through the asc_partial override. |
| 25 | -export TORCHTITAN_NPU_PATTERN_IMPORTS="${TORCHTITAN_NPU_PATTERN_IMPORTS:-torchtitan_npu.compile.patterns.deepseek_v4.inplace_partial_rope}" | 25 | +# swiglu_group fuses SwiGLU for routed and shared experts. |
| 26 | -export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.workaround}" | 26 | +export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \ |
| 27 | + torchtitan_npu.override.common.swiglu_group.asc \ | ||
| 28 | + torchtitan_npu.override.common.swiglu_group.asc_shared_experts}" | ||
| 27 | 29 | ||
| 28 | NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, \ | 30 | NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, \ |
| 29 | xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}" | 31 | xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}" |
| 30 | NGPU="${NGPU:-8}" | 32 | NGPU="${NGPU:-8}" |
| 31 | export NODE_IPS NGPU | 33 | export NODE_IPS NGPU |
| 34 | +export MBS="${MBS:-2}" | ||
| 32 | 35 | ||
| 33 | # A5 defaults to block-FP8 quantized training. A trailing | 36 | # A5 defaults to block-FP8 quantized training. A trailing |
| 34 | # --extension.quantization.no-enable-quantized-training selects BF16 instead. | 37 | # --extension.quantization.no-enable-quantized-training selects BF16 instead. |
| 35 | QUANTIZATION_ARGS=( | 38 | QUANTIZATION_ARGS=( |
| 36 | --extension.quantization.enable-quantized-training | 39 | --extension.quantization.enable-quantized-training |
| 37 | --extension.quantization.recipe all_block_fp8 | 40 | --extension.quantization.recipe all_block_fp8 |
| 41 | + --extension.quantization.fsdp-prequantize | ||
| 42 | + --extension.quantization.li-quantization fp8 | ||
| 38 | ) | 43 | ) |
| 39 | 44 | ||
| 45 | +# Disable swap optimizer for better performance | ||
| 46 | +export OPTIMIZER_OVERRIDES="" | ||
| 47 | + | ||
| 40 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh" \ | 48 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh" \ |
| 41 | "${QUANTIZATION_ARGS[@]}" \ | 49 | "${QUANTIZATION_ARGS[@]}" \ |
| 42 | "$@" \ | 50 | "$@" \ |
| @@ -16,15 +16,19 @@ NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx. | |||
| 16 | xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}" | 16 | xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}" |
| 17 | NGPU="${NGPU:-8}" | 17 | NGPU="${NGPU:-8}" |
| 18 | export NODE_IPS NGPU | 18 | export NODE_IPS NGPU |
| 19 | +export MBS="${MBS:-2}" | ||
| 19 | 20 | ||
| 20 | #Introduction of relevant parameters, please refer to docs/user-guides/quickstart.md. | 21 | #Introduction of relevant parameters, please refer to docs/user-guides/quickstart.md. |
| 21 | QUANTIZATION_ARGS=( | 22 | QUANTIZATION_ARGS=( |
| 22 | --extension.quantization.enable-quantized-training | 23 | --extension.quantization.enable-quantized-training |
| 23 | --extension.quantization.recipe all_block_fp8 | 24 | --extension.quantization.recipe all_block_fp8 |
| 24 | --extension.quantization.enable-mxfp4-qat | 25 | --extension.quantization.enable-mxfp4-qat |
| 25 | - --extension.quantization.li-quantization fp8 | 26 | + --extension.quantization.li-quantization mxfp4 |
| 26 | ) | 27 | ) |
| 27 | 28 | ||
| 29 | +# Disable swap optimizer for better performance | ||
| 30 | +export OPTIMIZER_OVERRIDES="" | ||
| 31 | + | ||
| 28 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \ | 32 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \ |
| 29 | "${QUANTIZATION_ARGS[@]}" \ | 33 | "${QUANTIZATION_ARGS[@]}" \ |
| 30 | "$@" | 34 | "$@" |
| @@ -0,0 +1,23 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 3 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 4 | +# SPDX-License-Identifier: BSD-3-Clause | ||
| 5 | +# | ||
| 6 | +# This source code is licensed under the BSD-style license found in the | ||
| 7 | +# LICENSE file in the root directory of this source tree. | ||
| 8 | + | ||
| 9 | +# Reuse the CPT launcher with an SFT JSONL or JSON file. | ||
| 10 | +set -euo pipefail | ||
| 11 | + | ||
| 12 | +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | ||
| 13 | +CPT_SCRIPT="${CPT_SCRIPT:-${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh}" | ||
| 14 | +SFT_OVERRIDE="${SFT_OVERRIDE:-torchtitan_npu.override.deepseek_v4.chat_dataloader.sft}" | ||
| 15 | +DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}" | ||
| 16 | + | ||
| 17 | +exec bash "${CPT_SCRIPT}" \ | ||
| 18 | + "${SFT_OVERRIDE}" \ | ||
| 19 | + --dataloader.dataset json \ | ||
| 20 | + --dataloader.dataset-path "${DATASET_PATH}" \ | ||
| 21 | + --checkpoint.enable \ | ||
| 22 | + --checkpoint.no-load-only \ | ||
| 23 | + "$@" | ||
| @@ -12,10 +12,16 @@ deepseek_v4_flash_cpt_4k_a3.sh | |||
| 12 | └── deepseek_v4_flash_cpt_1024k_a5.sh | 12 | └── deepseek_v4_flash_cpt_1024k_a5.sh |
| 13 | ``` | 13 | ``` |
| 14 | 14 | ||
| 15 | -- `deepseek_v4_flash_cpt_4k_a3.sh`:公共训练参数、override、checkpoint、optimizer 等基线配置,默认启用 `COMPILE_BACKEND=aot_eager`。 | 15 | +- `deepseek_v4_flash_cpt_4k_a3.sh`:公共训练参数、override、checkpoint、optimizer 等基线配置,默认通过 CLI 启用 model 编译,backend 为 `inductor`。 |
| 16 | -- `deepseek_v4_flash_cpt_4k_a5.sh`:只增加 A5 运行环境和默认 block-FP8 量化,其他配置复用 A3 基线。 | 16 | +- `deepseek_v4_flash_cpt_4k_a5.sh`:增加 A5 运行环境和默认 block-FP8 量化,其他配置复用 A3 基线。 |
| 17 | - `deepseek_v4_flash_cpt_1024k_a5.sh`:继续复用 A5 4K 入口,只通过 CLI 覆盖 1M 所需的 CP、DP、序列长度和 global batch size,量化默认随 A5 4K 入口继承。 | 17 | - `deepseek_v4_flash_cpt_1024k_a5.sh`:继续复用 A5 4K 入口,只通过 CLI 覆盖 1M 所需的 CP、DP、序列长度和 global batch size,量化默认随 A5 4K 入口继承。 |
| 18 | -- 用户传入的 `"$@"` 始终位于最后,因此可以覆盖脚本中的默认 CLI 参数,包括使用 `--extension.quantization.no-enable-quantized-training` 切换到 BF16。 | 18 | +- 用户普通 CLI 参数位于默认选项之后,因此可以覆盖默认值(A5 的 activation-checkpoint 子命令仍在末尾),包括使用 `--extension.quantization.no-enable-quantized-training` 切换到 BF16。 |
| 19 | + | ||
| 20 | +## 编译配置 | ||
| 21 | + | ||
| 22 | +编译通过 CLI 配置。Flash A3/A5 默认使用 `inductor`,只编译 `model`。在示例命令末尾追加 | ||
| 23 | +`--compile.backend inductor` 可显式指定 backend,追加 `--compile.no-enable` 可关闭编译。 | ||
| 24 | +独立入口若未默认启用编译,需同时传入 `--compile.enable --compile.components model`。 | ||
| 19 | 25 | ||
| 20 | ## 常用环境变量 | 26 | ## 常用环境变量 |
| 21 | 27 | ||
| @@ -62,8 +68,10 @@ Pro 32-expert 是独立的裁剪模型 debug/performance 入口,不与 8P Flas | |||
| 62 | 68 | ||
| 63 | ```sh | 69 | ```sh |
| 64 | NODE_IPS="${NODE_IPS}" \ | 70 | NODE_IPS="${NODE_IPS}" \ |
| 65 | -COMPILE_BACKEND=aot_eager \ | ||
| 66 | bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \ | 71 | bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \ |
| 72 | + --compile.enable \ | ||
| 73 | + --compile.components model \ | ||
| 74 | + --compile.backend inductor \ | ||
| 67 | --debug.moe-force-load-balance \ | 75 | --debug.moe-force-load-balance \ |
| 68 | --training.steps 20 | 76 | --training.steps 20 |
| 69 | ``` | 77 | ``` |
| @@ -72,8 +80,10 @@ bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \ | |||
| 72 | 80 | ||
| 73 | ```sh | 81 | ```sh |
| 74 | NODE_IPS="${NODE_IPS}" \ | 82 | NODE_IPS="${NODE_IPS}" \ |
| 75 | -COMPILE_BACKEND=aot_eager \ | ||
| 76 | bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \ | 83 | bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \ |
| 84 | + --compile.enable \ | ||
| 85 | + --compile.components model \ | ||
| 86 | + --compile.backend inductor \ | ||
| 77 | --parallelism.context-parallel-degree 32 \ | 87 | --parallelism.context-parallel-degree 32 \ |
| 78 | --parallelism.data-parallel-shard-degree 1 \ | 88 | --parallelism.data-parallel-shard-degree 1 \ |
| 79 | --parallelism.data-parallel-replicate-degree 1 \ | 89 | --parallelism.data-parallel-replicate-degree 1 \ |
| @@ -127,8 +137,10 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \ | |||
| 127 | 137 | ||
| 128 | ```sh | 138 | ```sh |
| 129 | NODE_IPS="${NODE_IPS}" \ | 139 | NODE_IPS="${NODE_IPS}" \ |
| 130 | -COMPILE_BACKEND=aot_eager \ | ||
| 131 | bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \ | 140 | bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \ |
| 141 | + --compile.enable \ | ||
| 142 | + --compile.components model \ | ||
| 143 | + --compile.backend inductor \ | ||
| 132 | --debug.moe-force-load-balance \ | 144 | --debug.moe-force-load-balance \ |
| 133 | --training.steps 20 | 145 | --training.steps 20 |
| 134 | ``` | 146 | ``` |
| @@ -139,8 +151,10 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \ | |||
| 139 | 151 | ||
| 140 | ```sh | 152 | ```sh |
| 141 | NODE_IPS="${NODE_IPS}" \ | 153 | NODE_IPS="${NODE_IPS}" \ |
| 142 | -COMPILE_BACKEND=aot_eager \ | ||
| 143 | bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \ | 154 | bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \ |
| 155 | + --compile.enable \ | ||
| 156 | + --compile.components model \ | ||
| 157 | + --compile.backend inductor \ | ||
| 144 | --parallelism.context-parallel-degree 8 \ | 158 | --parallelism.context-parallel-degree 8 \ |
| 145 | --parallelism.data-parallel-shard-degree 16 \ | 159 | --parallelism.data-parallel-shard-degree 16 \ |
| 146 | --parallelism.data-parallel-replicate-degree 1 \ | 160 | --parallelism.data-parallel-replicate-degree 1 \ |
| @@ -156,8 +170,10 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \ | |||
| 156 | 170 | ||
| 157 | ```sh | 171 | ```sh |
| 158 | NODE_IPS="${NODE_IPS}" \ | 172 | NODE_IPS="${NODE_IPS}" \ |
| 159 | -COMPILE_BACKEND=aot_eager \ | ||
| 160 | bash examples/deepseek_v4/deepseek_v4_flash_cpt_1024k_a5.sh \ | 173 | bash examples/deepseek_v4/deepseek_v4_flash_cpt_1024k_a5.sh \ |
| 174 | + --compile.enable \ | ||
| 175 | + --compile.components model \ | ||
| 176 | + --compile.backend inductor \ | ||
| 161 | --debug.moe-force-load-balance \ | 177 | --debug.moe-force-load-balance \ |
| 162 | --training.steps 20 | 178 | --training.steps 20 |
| 163 | ``` | 179 | ``` |
| @@ -1,18 +0,0 @@ | |||
| 1 | -### V4.1 独立 reference 训练基线 | ||
| 2 | - | ||
| 3 | -V4.1 的模型、图像路由、压缩 attention、metadata 和并行化均由 `torchtitan_npu/models/deepseek_v41` 持有,不依赖 V4 模型或其专属 override。 | ||
| 4 | - | ||
| 5 | -当前只支持 **FSDP + EP、TP1 / CP1 / PP1、eager/reference**,保留 FullAC 与图文输入。不支持量化、ngram、MTP、GraphTrainer 或融合 attention;不支持的 TP、CP、PP 和 compile 配置在入口拒绝。 | ||
| 6 | - | ||
| 7 | -单机 8 卡、40 层、16 专家的入口: | ||
| 8 | - | ||
| 9 | -```sh | ||
| 10 | -bash examples/deepseek_v41/debug/deepseek_v41_flash_8p_cpt_4k_a3.sh | ||
| 11 | -bash examples/deepseek_v41/debug/deepseek_v41_flash_8p_cpt_4k_a3.sh --training.steps 5 | ||
| 12 | -``` | ||
| 13 | - | ||
| 14 | -`USE_GOLDEN=1` 是唯一支持的模式,launcher 默认启用;显式设置为 0 会报错。reference sparse attention 和专家算术已经是模型默认实现,只保留通用 RoPE workaround 与 virtual optimizer override,不再加载 V4 sparse attention 或 V4.1 Golden MoE 类替换。 | ||
| 15 | - | ||
| 16 | -CI 使用 `dsv41_golden_2p_ep2_fsdp2`:2 卡 FSDP2/EP2、30 步,逐步精确比较固定 loss 锚。8 卡形状用于手动 A/B。两种并行形状各自比较对应参照,不混用锚。 | ||
| 17 | - | ||
| 18 | -入口默认关闭 checkpoint;需要保存/加载时显式配置。图像与 tokenizer 的内容保持现有测试资源;V4.1 tokenizer 环境变量为 `DSV41_TOKENIZER_PATH`,兼容旧 `DSV4_TOKENIZER_PATH` 的处理集中在配置入口。 | ||
Rexamples/deepseek_v41/debug/deepseek_v41_flash_8p_cpt_4k_a3.sh→examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh+72-79
| @@ -1,32 +1,26 @@ | |||
| 1 | #!/usr/bin/env bash | 1 | #!/usr/bin/env bash |
| 2 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. |
| 3 | # | 3 | # |
| 4 | # This source code is licensed under the BSD-style license found in the | 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. | 5 | # LICENSE file in the root directory of this source tree. |
| 6 | 6 | ||
| 7 | -# Run this script on a single node. | 7 | +# Run from the repository root; append CLI arguments to override defaults. |
| 8 | -# Append CLI arguments to override the defaults below: | 8 | +# USE_GOLDEN=1 selects reference operators on either A3 or A5. |
| 9 | -# ./examples/deepseek_v41/debug/deepseek_v41_flash_8p_cpt_4k_a3.sh --training.steps 5 | 9 | +# For precision comparisons, append --debug.seed 42 --debug.deterministic. |
| 10 | -# USE_GOLDEN=1 is the only currently supported operator path. USE_GOLDEN=0 | ||
| 11 | -# (AscendC) is rejected until the ratio-1 shared/global-KV contract is | ||
| 12 | -# implemented by the fused sparse-attention kernels. | ||
| 13 | 10 | ||
| 14 | set -euo pipefail | 11 | set -euo pipefail |
| 15 | 12 | ||
| 16 | -# V4.1 currently supports eager execution only; keep compile disabled. | ||
| 17 | -export COMPILE_BACKEND="" | ||
| 18 | - | ||
| 19 | NGPU="${NGPU:-8}" | 13 | NGPU="${NGPU:-8}" |
| 20 | WORLD_SIZE="${NGPU}" | 14 | WORLD_SIZE="${NGPU}" |
| 21 | 15 | ||
| 22 | # Model | 16 | # Model |
| 23 | -MODULE="${MODULE:-torchtitan_npu.models.deepseek_v41}" | 17 | +MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4_1}" |
| 24 | -CONFIG="${CONFIG:-deepseek_v41_flash_40layers_16experts_vision}" | 18 | +CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_16experts_multimodal}" |
| 25 | 19 | ||
| 26 | # Dataloader & Checkpoint | 20 | # Dataloader & Checkpoint |
| 27 | -DATASET="${DATASET:-c4_test}" | 21 | +DATASET="${DATASET:-cc12m-test}" |
| 28 | -DATASET_PATH="${DATASET_PATH:-tests/assets/c4_test}" # your data path | 22 | +HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV41_tokenizer}" |
| 29 | -HF_ASSETS_PATH="${HF_ASSETS_PATH:-/data/tokenizer/dsv4_tokenizer}" # your tokenizer path | 23 | +CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-checkpoint}" |
| 30 | 24 | ||
| 31 | # Parallelism | 25 | # Parallelism |
| 32 | TP=1 | 26 | TP=1 |
| @@ -37,45 +31,24 @@ DP_SHARD=8 | |||
| 37 | DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP))) | 31 | DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP))) |
| 38 | SPMD_BACKEND="spmd_types" | 32 | SPMD_BACKEND="spmd_types" |
| 39 | 33 | ||
| 40 | -# Training | 34 | +# Training (retain the validated eager / AdamW / FullAC resource crop) |
| 41 | -# The reference fallback is intentionally kept at seq_len=512 for the 8-card | ||
| 42 | -# validation recipe. | ||
| 43 | SEQ_LEN=512 | 35 | SEQ_LEN=512 |
| 44 | MBS=1 | 36 | MBS=1 |
| 45 | GBS=8 | 37 | GBS=8 |
| 46 | STEPS=40 | 38 | STEPS=40 |
| 47 | 39 | ||
| 48 | -# Debug | 40 | +USE_GOLDEN="${USE_GOLDEN:-0}" |
| 49 | -export USE_GOLDEN="${USE_GOLDEN:-1}" | ||
| 50 | -if [[ "${USE_GOLDEN}" != "1" ]]; then | ||
| 51 | - echo "FATAL: DeepSeek-V4.1 currently supports the golden/reference path only." | ||
| 52 | - echo "The AscendC sparse-attention path does not yet accept the V4.1" | ||
| 53 | - echo "ratio-1 shared global KV contract (CSA2 layer 20-39)." | ||
| 54 | - echo "Set USE_GOLDEN=1 (default) or unset USE_GOLDEN." | ||
| 55 | - exit 2 | ||
| 56 | -fi | ||
| 57 | DEBUG_ARGS=" | 41 | DEBUG_ARGS=" |
| 58 | - --debug.no-moe-force-load-balance | ||
| 59 | --debug.print-config | 42 | --debug.print-config |
| 43 | + --debug.moe-force-load-balance | ||
| 60 | " | 44 | " |
| 61 | -if [[ "${DETERMINISTIC:-1}" == "1" ]]; then | 45 | + |
| 62 | - DEBUG_ARGS="${DEBUG_ARGS} | 46 | +DATALOADER_ARGS=(--dataloader.dataset "${DATASET}") |
| 63 | - --debug.seed 42 | 47 | +# Leave the path unset so each upstream dataset registration keeps its source. |
| 64 | - --debug.deterministic" | 48 | +if [[ -n "${DATASET_PATH:-}" ]]; then |
| 49 | + DATALOADER_ARGS+=(--dataloader.dataset-path "${DATASET_PATH}") | ||
| 65 | fi | 50 | fi |
| 66 | 51 | ||
| 67 | -# HF assets | ||
| 68 | -HF_ASSETS_ARGS=" | ||
| 69 | - --hf-assets-path ${HF_ASSETS_PATH} | ||
| 70 | -" | ||
| 71 | - | ||
| 72 | -# Dataloader | ||
| 73 | -DATALOADER_ARGS=" | ||
| 74 | - --dataloader.dataset ${DATASET} | ||
| 75 | - --dataloader.dataset-path ${DATASET_PATH} | ||
| 76 | -" | ||
| 77 | - | ||
| 78 | -# Parallelism | ||
| 79 | PARALLELISM_ARGS=" | 52 | PARALLELISM_ARGS=" |
| 80 | --parallelism.spmd-backend ${SPMD_BACKEND} | 53 | --parallelism.spmd-backend ${SPMD_BACKEND} |
| 81 | --parallelism.data-parallel-shard-degree ${DP_SHARD} | 54 | --parallelism.data-parallel-shard-degree ${DP_SHARD} |
| @@ -84,78 +57,98 @@ PARALLELISM_ARGS=" | |||
| 84 | --parallelism.tensor-parallel-degree ${TP} | 57 | --parallelism.tensor-parallel-degree ${TP} |
| 85 | --parallelism.context-parallel-degree ${CP} | 58 | --parallelism.context-parallel-degree ${CP} |
| 86 | --parallelism.pipeline-parallel-degree ${PP} | 59 | --parallelism.pipeline-parallel-degree ${PP} |
| 60 | + --parallelism.fsdp-reshard-after-forward always | ||
| 87 | --parallelism.context-parallel-load-balancer None | 61 | --parallelism.context-parallel-load-balancer None |
| 62 | + --parallelism.enable-sequence-parallel | ||
| 88 | " | 63 | " |
| 89 | 64 | ||
| 90 | -# Training | ||
| 91 | TRAINING_ARGS=" | 65 | TRAINING_ARGS=" |
| 66 | + --compile.no-enable | ||
| 92 | --training.local-batch-size ${MBS} | 67 | --training.local-batch-size ${MBS} |
| 93 | --training.global-batch-size ${GBS} | 68 | --training.global-batch-size ${GBS} |
| 94 | --training.seq-len ${SEQ_LEN} | 69 | --training.seq-len ${SEQ_LEN} |
| 95 | --training.steps ${STEPS} | 70 | --training.steps ${STEPS} |
| 96 | --training.disable-cuda-graphs | 71 | --training.disable-cuda-graphs |
| 72 | + --metrics.log-freq 1 | ||
| 97 | " | 73 | " |
| 98 | 74 | ||
| 99 | -# Checkpoint | 75 | +LR_SCHEDULER_ARGS=" |
| 76 | + --lr-scheduler.warmup-steps 2 | ||
| 77 | + --lr-scheduler.total-steps ${STEPS} | ||
| 78 | + --lr-scheduler.decay-ratio 1.0 | ||
| 79 | + --lr-scheduler.decay-type cosine | ||
| 80 | + --lr-scheduler.min-lr-factor 0.01 | ||
| 81 | +" | ||
| 82 | + | ||
| 83 | +# AdamW keeps its model recipe's param_groups (eps=1e-6). The scalar fields | ||
| 84 | +# below configure the explicit --optimizer.name Muon selection. | ||
| 85 | +OPTIMIZER_ARGS=" | ||
| 86 | + --optimizer.name AdamW | ||
| 87 | + --optimizer.implementation fused | ||
| 88 | + --optimizer.lr 1.0e-5 | ||
| 89 | + --optimizer.beta1 0.9 | ||
| 90 | + --optimizer.beta2 0.95 | ||
| 91 | + --optimizer.eps 1.0e-8 | ||
| 92 | + --optimizer.weight-decay 1.0e-1 | ||
| 93 | + --optimizer.muon-momentum 0.95 | ||
| 94 | + --optimizer.muon-enable-nesterov | ||
| 95 | + --optimizer.muon-ns-steps 10 | ||
| 96 | + --optimizer.muon-adjust-lr-fn match_rms_adamw | ||
| 97 | +" | ||
| 98 | +OPTIMIZER_OVERRIDES="torchtitan_npu.override.common.optimizer.swap_optimizer" | ||
| 99 | + | ||
| 100 | CHECKPOINT_ARGS=" | 100 | CHECKPOINT_ARGS=" |
| 101 | --checkpoint.no-enable | 101 | --checkpoint.no-enable |
| 102 | + --checkpoint.load-only | ||
| 103 | + --checkpoint.interval 10 | ||
| 102 | " | 104 | " |
| 103 | 105 | ||
| 104 | -# Profiler | ||
| 105 | PROFILER_ARGS=" | 106 | PROFILER_ARGS=" |
| 106 | --profiler.no-enable-profiling | 107 | --profiler.no-enable-profiling |
| 107 | - --profiler.profile-freq 1 | 108 | + --profiler.profile-freq 10 |
| 109 | + --profiler.profiler-active 10 | ||
| 108 | --profiler.profiler-warmup 0 | 110 | --profiler.profiler-warmup 0 |
| 109 | - --profiler.profiler-active 1 | ||
| 110 | - --profiler.profiler-repeat 1 | ||
| 111 | - --profiler.profiler-skip-first 4 | ||
| 112 | - --profiler.extension.profile-ranks 0 | ||
| 113 | - --profiler.extension.no-enable-online-parse | ||
| 114 | " | 111 | " |
| 115 | 112 | ||
| 116 | -# Communication | ||
| 117 | COMM_ARGS=" | 113 | COMM_ARGS=" |
| 118 | --comm.init-timeout-seconds 7200 | 114 | --comm.init-timeout-seconds 7200 |
| 119 | --comm.train-timeout-seconds 600 | 115 | --comm.train-timeout-seconds 600 |
| 120 | " | 116 | " |
| 121 | 117 | ||
| 122 | -# Optimizer & LR scheduler | 118 | +# The text-rope entry is a hardware choice: A3 defaults to asc_complex; the A5 |
| 123 | -OPTIMIZER_ARGS=" | 119 | +# wrapper supplies asc_partial through the same CLI_OVERRIDES channel. |
| 124 | - --optimizer.implementation fused | 120 | +if [[ "${USE_GOLDEN}" == "1" ]]; then |
| 125 | - --optimizer.param-groups.0.optimizer-name AdamW | 121 | + NPU_OPS_OVERRIDES=(torchtitan_npu.override.common.rope.workaround) |
| 126 | - --optimizer.param-groups.0.optimizer-kwargs.lr 1.0e-5 | 122 | + DEFAULT_TEXT_ROPE_OVERRIDE="" |
| 127 | - --optimizer.param-groups.0.optimizer-kwargs.betas 0.9 0.95 | 123 | +else |
| 128 | - --optimizer.param-groups.0.optimizer-kwargs.eps 1.0e-6 | 124 | + NPU_OPS_OVERRIDES=( |
| 129 | - --optimizer.param-groups.0.optimizer-kwargs.weight-decay 1.0e-1 | 125 | + torchtitan_npu.override.common.rms_norm.asc |
| 130 | - --lr-scheduler.warmup-steps 25 | 126 | + torchtitan_npu.override.common.rope.asc_half_rotation |
| 131 | - --lr-scheduler.decay-type cosine | 127 | + torchtitan_npu.override.common.token_dispatcher.asc |
| 132 | - --lr-scheduler.decay-ratio 1.0 | 128 | + torchtitan_npu.override.deepseek_v4_1.mhc.asc_hc_post |
| 133 | - --lr-scheduler.min-lr-factor 1.0e-2 | 129 | + ) |
| 134 | - --lr-scheduler.total-steps 40 | 130 | + DEFAULT_TEXT_ROPE_OVERRIDE="torchtitan_npu.override.common.rope.asc_complex" |
| 135 | -" | 131 | +fi |
| 136 | -# The upstream scheduler clamps warmup to training.steps, so a short comparison | ||
| 137 | -# run would silently get a different LR curve; total-steps above pins the | ||
| 138 | -# schedule length to the validation recipe instead. | ||
| 139 | -OPTIMIZER_OVERRIDES=" | ||
| 140 | - torchtitan_npu.override.common.optimizer.virtual | ||
| 141 | -" | ||
| 142 | 132 | ||
| 143 | -NPU_OPS_OVERRIDES=( | 133 | +# Wrapper defaults extend the same override.imports list, as in DSV4. |
| 144 | - torchtitan_npu.override.common.rope.workaround | 134 | +CLI_OVERRIDES="${CLI_OVERRIDES:-${DEFAULT_TEXT_ROPE_OVERRIDE}}" |
| 145 | -) | ||
| 146 | 135 | ||
| 147 | MODULE="${MODULE}" \ | 136 | MODULE="${MODULE}" \ |
| 148 | CONFIG="${CONFIG}" \ | 137 | CONFIG="${CONFIG}" \ |
| 149 | NGPU="${NGPU}" \ | 138 | NGPU="${NGPU}" \ |
| 139 | +LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | ||
| 150 | bash scripts/run_train.sh \ | 140 | bash scripts/run_train.sh \ |
| 151 | - $HF_ASSETS_ARGS \ | 141 | + --hf-assets-path "${HF_ASSETS_PATH}" \ |
| 152 | - $DATALOADER_ARGS \ | 142 | + "${DATALOADER_ARGS[@]}" \ |
| 153 | $PARALLELISM_ARGS \ | 143 | $PARALLELISM_ARGS \ |
| 154 | $TRAINING_ARGS \ | 144 | $TRAINING_ARGS \ |
| 155 | $DEBUG_ARGS \ | 145 | $DEBUG_ARGS \ |
| 156 | $OPTIMIZER_ARGS \ | 146 | $OPTIMIZER_ARGS \ |
| 147 | + $LR_SCHEDULER_ARGS \ | ||
| 157 | $PROFILER_ARGS \ | 148 | $PROFILER_ARGS \ |
| 158 | $COMM_ARGS \ | 149 | $COMM_ARGS \ |
| 159 | $CHECKPOINT_ARGS \ | 150 | $CHECKPOINT_ARGS \ |
| 151 | + --checkpoint.folder "${CKPT_SAVE_LOAD_PATH}" \ | ||
| 160 | --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \ | 152 | --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \ |
| 153 | + $CLI_OVERRIDES \ | ||
| 161 | "$@" | 154 | "$@" |
| @@ -0,0 +1,27 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +# A5 adds CPU affinity, partial text RoPE, SwiGLUGroup experts, sparse | ||
| 8 | +# attention and mHC Sinkhorn to A3; USE_GOLDEN=1 keeps the pure reference list. | ||
| 9 | + | ||
| 10 | +set -euo pipefail | ||
| 11 | + | ||
| 12 | +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | ||
| 13 | + | ||
| 14 | +# Use npu-smi info -t topo to check CPU affinity on the target host. | ||
| 15 | +export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" | ||
| 16 | + | ||
| 17 | +if [[ "${USE_GOLDEN:-0}" != "1" ]]; then | ||
| 18 | + # asc_partial replaces the A3 text-rope choice (asc_complex); both claim | ||
| 19 | + # the same public ComplexRoPE.Config, so only one may be active. | ||
| 20 | + export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \ | ||
| 21 | + torchtitan_npu.override.common.swiglu_group.asc \ | ||
| 22 | + torchtitan_npu.override.common.swiglu_group.asc_shared_experts \ | ||
| 23 | + torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc \ | ||
| 24 | + torchtitan_npu.override.deepseek_v4_1.mhc.asc_sinkhorn}" | ||
| 25 | +fi | ||
| 26 | + | ||
| 27 | +exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a3.sh" "$@" | ||
| @@ -0,0 +1,109 @@ | |||
| 1 | +### V4.1 独立训练基线与融合栈 | ||
| 2 | + | ||
| 3 | +V4.1 的模型、图像路由、压缩 attention、metadata 和并行化均由 `torchtitan_npu/models/deepseek_v4_1` 持有,不依赖 V4 模型或其专属 override。模型默认算子是 Attention Gym 的 eager `selected_attention`(`CompressedSparseInnerAttention2`)、公共 MoE 工厂与上游默认的 indexer 蒸馏损失 `IndexerDistillLoss`(coeff=0.01)。 | ||
| 4 | + | ||
| 5 | +当前支持 **FSDP + EP、TP1 / CP1 / PP1、eager 执行**,保留 FullAC 与图文输入。启动方式与 DSV4 一致:A3 脚本组织公共实验参数与融合列表,A5 调用 A3 并追加 CPU 亲和性、partial 文本 RoPE、两项 SwiGLUGroup、sparse attention 与 mHC Sinkhorn;两种入口均通过 `USE_GOLDEN=1` 选择 reference。A3 默认融合包含 RMSNorm、文本(`asc_complex`)与视觉 RoPE、MoE token dispatcher 和 mHC post;A5 将文本 RoPE 换为 `asc_partial` 并追加 routed/shared SwiGLUGroup、sparse 与 Sinkhorn。routed experts 的 grouped GEMM 是 reference 与融合共用的公共路径,不再作为独立融合开关。不支持量化、ngram、MTP、GraphTrainer;不支持的 TP、CP、PP 和 compile 配置在入口拒绝。 | ||
| 6 | + | ||
| 7 | +单机 8 卡入口(默认读取仓内上游 CC12M 测试 tar;数据源可通过标准 CLI 覆盖): | ||
| 8 | + | ||
| 9 | +```sh | ||
| 10 | +# A3 融合栈(默认) | ||
| 11 | +bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \ | ||
| 12 | + --hf-assets-path <v41_tokenizer_dir> | ||
| 13 | + | ||
| 14 | +# A5(A3 融合栈 + A5 专属算子) | ||
| 15 | +bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a5.sh \ | ||
| 16 | + --hf-assets-path <v41_tokenizer_dir> | ||
| 17 | + | ||
| 18 | +# 纯 reference 对照(同一数据与并行形状) | ||
| 19 | +USE_GOLDEN=1 \ | ||
| 20 | + bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \ | ||
| 21 | + --hf-assets-path <v41_tokenizer_dir> | ||
| 22 | + | ||
| 23 | +# 短跑(如 3 步):显式同步步数与 LR 调度 | ||
| 24 | +bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \ | ||
| 25 | + --hf-assets-path <v41_tokenizer_dir> \ | ||
| 26 | + --training.steps 3 --lr-scheduler.total-steps 3 --lr-scheduler.warmup-steps 2 | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +默认实验为 40 层 / 16 专家、seq512、local/global batch 1/8、FSDP8/EP8、AdamW、eager、FullAC,训练与调度均为 40 步。Python 配方保留模型结构、数据协议和优化器参数布局;实验参数由脚本组织,末尾 CLI 参数覆盖脚本默认值。`CONFIG` 可选择 `deepseek_v4_1_debugmodel_multimodal` 调试宽度,硬件选择仍由脚本负责。 | ||
| 30 | + | ||
| 31 | +A5 的 `CPU_AFFINITY_CONF` 应按主机拓扑覆盖。`CLI_OVERRIDES` 沿用 DSV4 的列表扩展方式:A3 基础列表之外,文本 RoPE 经该通道按硬件选择(A3 默认 `asc_complex`,A5 换为 `asc_partial`),A5 默认追加 SwiGLUGroup、sparse attention 与 Sinkhorn,不重复传入 `--override.imports`。显式传 `--override.imports` 会替换整个集合,需自行包含所需的 RoPE 与 virtual optimizer。最终选择随 Trainer Config 打印。 | ||
| 32 | + | ||
| 33 | +普通运行不强制随机种子和确定性;精度对照须在双方命令中追加 `--debug.seed 42 --debug.deterministic`。默认关闭 checkpoint 且设置 `load_only=True`;保存时同时传 `--checkpoint.enable --checkpoint.no-load-only`。`load_only` 表示禁止保存,与 model-only 加载不同。tokenizer 统一经 `--hf-assets-path` 提供(测试可用仓内 `tests/assets/deepseek_v3` mini tokenizer),该参数本身不加载模型权重。 | ||
| 34 | + | ||
| 35 | +indexer 蒸馏损失由 `IndexerDistillLoss` 实现(上游默认 `coeff=0.01`):每层只要消费了 selection 就挂一个损失,教师用该层自身 attention 的完整 softmax 分母(窗口 + 压缩条目 + sink)重建,按压缩切片的边际质量加权;梯度经 `_AuxLossInjection` 注入,只训练 indexer 自身参数,训练指标为 `indexer_distill_loss/mean`。打包 loader 标记的结构 padding 行不参与蒸馏(真实图像 token 保留训练资格)。 | ||
| 36 | + | ||
| 37 | +### 真实 CC12M 数据入口(图像条件 caption 预测) | ||
| 38 | + | ||
| 39 | +数据入口与 GitHub TorchTitan 的 Qwen/Kimi 多模态训练一致,使用 CC12M WebDataset tar(同名 `.jpg` / `.txt` 样本对)。默认 `dataset=cc12m-test`,读取仓内 `tests/assets/cc12m_test/`,无需传入 dataloader 参数;其他本地 tar 目录通过 `--dataloader.dataset-path <cc12m_tar_dir>` 指定。不提供 manifest、离线准备或 digest 专用脚本。 | ||
| 40 | + | ||
| 41 | +数据准备沿用上游的两种方式: | ||
| 42 | + | ||
| 43 | +- 在线:选择 `--dataloader.dataset cc12m`,不指定 `dataset-path`,从 Hugging Face 流式读取,无需预先下载完整数据集。 | ||
| 44 | +- 本地:下载包含图片和 caption 的 WebDataset tar 分片,使用 `--dataloader.dataset-path <cc12m_tar_dir>`。不解压、不生成 manifest,不预先 tokenize 或计算 ViT 特征;图片预处理在数据加载时执行,ViT 在模型前向中执行。 | ||
| 45 | + | ||
| 46 | +`cc12m-train-0000.tar` 原样复用 [GitHub TorchTitan v0.3.0 测试资产](https://github.com/pytorch/torchtitan/blob/v0.3.0/tests/assets/cc12m_test/cc12m-train-0000.tar),包含 32 条图文样本,仅用于测试。完整在线数据源通过 `--dataloader.dataset cc12m` 选择;指定本地目录后,读取的是该目录的数据,而非仓内测试资产。 | ||
| 47 | + | ||
| 48 | +直接复用上游 `HuggingFaceMultiModalDataset` 的 DP 分片、`MMSamplePacker` 和状态恢复,以及 `ParallelAwareDataloader`。针对 TorchTitan 0.3.0 的 HF 恢复起点跨 epoch 重放问题,按上游文本 loader 的方式补齐 `set_epoch`;packing 缓冲满时调用上游 `flush()`。DSV4.1 只适配协议层:`BOS + 完整图片协议 + caption + EOS`、每篇文档按模型压缩比的最小公倍数对齐(当前为 2,至多在 EOS 后补 1 个不监督的 pad)、`valid_tokens` 标记随 pack 消费并穿过 packer;只有 caption 与 EOS 参与监督,图片特征索引按 pack 中的图片顺序连续编号,每篇文档的位置从零开始,注意力和压缩块隔离文档边界。 | ||
| 49 | + | ||
| 50 | +与上游一致,`--dataloader.packing-buffer-size 0` 默认关闭 packing;设置正值(例如 `128`)启用。一个 rank 的 local batch 仍为 1,但一个 packed 序列可以包含多篇图文样本。装箱和合并仍调用上游实现;缓冲量还包括待输出的 packed 队列及 loader 预取,不是进程内存的硬上限。 | ||
| 51 | + | ||
| 52 | +A/B 必须固定 tar 内容及顺序、tokenizer、序列长度、packing buffer、DP/全局 batch、seed 和初始权重。旧模型结构的 manifest/合成轨迹与新入口、新 LI 训练目标的轨迹互不可比;迁移后的对照统一使用新 reference 起点或同一份完整 checkpoint。精确续训使用完整 checkpoint 恢复 loader 状态;model-only 加载只复用权重(新旧结构需按参数名对账后映射,不做静默兼容)。 | ||
| 53 | + | ||
| 54 | +上游多模态模块需要与 PyTorch 匹配的 `torchvision`(CPU 图像预处理);按运行环境安装对应版本。数据路径支持 `DATASET_PATH` 环境变量或标准 CLI;不指定路径时使用所选数据集的上游注册源。 | ||
| 55 | + | ||
| 56 | +### 相同初始权重(生成与加载) | ||
| 57 | + | ||
| 58 | +baseline 与融合组要从同一份显式权重出发时,先生成再加载(dcp 格式,model-only): | ||
| 59 | + | ||
| 60 | +```sh | ||
| 61 | +# 生成:跑 3 步保存训练 checkpoint(后续仅加载其中的模型权重) | ||
| 62 | +bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \ | ||
| 63 | + --hf-assets-path <v41_tokenizer_dir> \ | ||
| 64 | + --training.steps 3 --lr-scheduler.total-steps 3 --lr-scheduler.warmup-steps 2 \ | ||
| 65 | + --checkpoint.enable --checkpoint.no-load-only \ | ||
| 66 | + --checkpoint.folder <ckpt_dir> | ||
| 67 | + | ||
| 68 | +# 加载同一份权重起跑(--checkpoint.load-only 禁用后续保存) | ||
| 69 | +bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \ | ||
| 70 | + --hf-assets-path <v41_tokenizer_dir> \ | ||
| 71 | + --checkpoint.enable \ | ||
| 72 | + --checkpoint.initial-load-path <ckpt_dir>/step-3 \ | ||
| 73 | + --checkpoint.initial-load-model-only | ||
| 74 | +``` | ||
| 75 | + | ||
| 76 | +两个要点:`--checkpoint.enable` 是加载生效的前提(不传时 CheckpointManager 未激活,会静默 fresh start,日志中只有一条 warning);`initial-load-path` 指向 `step-N` 子目录。输出 `checkpoint.folder` 中已有有效 checkpoint 时会优先恢复它;从 `initial-load-path` 起跑应使用新的输出目录。加载后应核对 checkpoint 日志与实际数据配置,再比较训练轨迹;单凭首步 loss 接近不能证明权重和数据一致。 | ||
| 77 | + | ||
| 78 | +### 融合算子逐项说明 | ||
| 79 | + | ||
| 80 | +融合栈由 A3/A5 脚本默认启用,reference 使用同一入口的 `USE_GOLDEN=1`。逐项语义: | ||
| 81 | + | ||
| 82 | +| override | 替换范围 | 实现 | | ||
| 83 | +|---|---|---| | ||
| 84 | +| `common.rms_norm.asc` | decoder、compressor、indexer 与视觉塔的公共 RMSNorm(保留各位置原有 epsilon) | Ascend RMSNorm | | ||
| 85 | +| `common.rope.asc_complex`(A3 文本) | attention/compressor/indexer 的 split-aware 文本旋转(公共 `ComplexRoPE.Config`,保留 split/theta/YaRN) | Ascend rotary mul(interleave) | | ||
| 86 | +| `common.rope.asc_partial`(A5 文本) | 同上三处文本位点;单个 `inplace_partial_rotary_mul` 只旋转尾部 `dim` 通道 | AscendC partial rotary | | ||
| 87 | +| `common.rope.asc_half_rotation` | 视觉塔 2D 位置表的 half 旋转(半宽 cos/sin,融合前复制为全宽表,逐 batch 折叠保位置) | 同上 | | ||
| 88 | +| `sparse_attn.asc`(仅 A5) | `CompressedSparseInnerAttention2._compute_attention`:A5 TND kernel 返回完整 softmax 的输出与 LSE,蒸馏损失仍由模型注入 | Ascend sparse flash MLA | | ||
| 89 | +| `common.swiglu_group.asc`(仅 A5) | `*.moe.routed_experts.inner_experts` 的 grouped SwiGLU(FQN 限定) | cann_ops_nn.swiglu_group | | ||
| 90 | +| `common.swiglu_group.asc_shared_experts`(仅 A5) | `*.moe.shared_experts` 的 SwiGLU(FQN 限定,不替换视觉 MLP) | 同上 | | ||
| 91 | +| `common.token_dispatcher.asc` | 公共 MoE 的 permute / re-routing / unpermute;reference 不启用 | Ascend token dispatcher | | ||
| 92 | +| `mhc.asc_hc_post` | mHC post 变换 | Ascend mHC post | | ||
| 93 | +| `mhc.asc_sinkhorn`(仅 A5) | `HcPre._split_sinkhorn`(新接口,`hc_eps` 字段) | npu_mhc_sinkhorn | | ||
| 94 | + | ||
| 95 | +routed experts 已走公共 grouped GEMM(`_ClampGroupedExperts` → 仓内 NPU `_grouped_mm`),reference 与融合共用,不改变模型参数名称、FSDP/EP 或 checkpoint 格式。融合输出、输入/权重梯度与训练轨迹的误差需与迁移后同配置 reference 对照验收;仅运行成功不代表数值或性能验收完成。 | ||
| 96 | + | ||
| 97 | +### RoPE seam 说明 | ||
| 98 | + | ||
| 99 | +文本旋转由主干构造公共 `ComplexRoPE.Config`(带 split 前缀宽度):reference 通过 `common.rope.workaround` 用展开实数表;A3 融合选 `asc_complex`,A5 融合选 `asc_partial`,三者精确匹配同一配置类,同一列表只能出现一个(override 框架对同节点双 claim 直接报错)。视觉塔的二维位置表使用 `HalfRotation` / `asc_half_rotation`,与文本 interleaved 布局不同,不能互换。inverse(attention o_rope 路径)经 `-sin` 支持。 | ||
| 100 | + | ||
| 101 | +CPU 测试覆盖两类 seam 的输出/梯度、partial 非连续输入、逐 batch 位置与配置隔离;CPU mock 不代表 NPU kernel 验证通过。 | ||
| 102 | + | ||
| 103 | +### Muon 优化器注意事项 | ||
| 104 | + | ||
| 105 | +`--optimizer.name Muon` 启用 DistMuon 时,`materialize()` 会整体替换 `param_groups` 为 `[DistMuon(pattern), AdamW(.*)]`,launcher 传入的 `--optimizer.param-groups.0.*` 参数静默失效。学习率等超参请使用顶层字段:`--optimizer.lr`、`--optimizer.weight-decay`、`--optimizer.muon-momentum` 等。indexer 参数在 LI 下有梯度,但仍留在 AdamW fallback 组,不因迁移改变参数策略。 | ||
| 106 | + | ||
| 107 | +### 验证范围 | ||
| 108 | + | ||
| 109 | +CPU 单测覆盖模型与融合配置选择、RoPE 输出/梯度等核心行为;不保留专用的 V4.1 两卡手动冒烟 suite。真实训练通过上述 A3/A5 入口执行。历史 A3 的 50 步对照见 PR 845;该证据不代表当前 HEAD 或 A5 新 CANN 已完成重验。 | ||
| @@ -0,0 +1,96 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +# Run this script on a single node. | ||
| 8 | +# Append CLI arguments to override the defaults below: | ||
| 9 | +# ./examples/qwen3_5/qwen3_5_debugmodel_1p_cpt_512.sh | ||
| 10 | +# ENABLE_NPU_MOE_DISPATCHER=1 opts in the ASC MoE token dispatcher. | ||
| 11 | +# Set ASCEND_SET_ENV_PATH to select a specific CANN toolkit. | ||
| 12 | + | ||
| 13 | +set -euo pipefail | ||
| 14 | + | ||
| 15 | +NGPU="${NGPU:-1}" | ||
| 16 | + | ||
| 17 | +# Model | ||
| 18 | +MODULE="${MODULE:-torchtitan_npu.models.qwen3_5}" | ||
| 19 | +CONFIG="${CONFIG:-qwen35_debugmodel}" | ||
| 20 | + | ||
| 21 | +# Dataloader: the multimodal test assets live in the TorchTitan checkout; | ||
| 22 | +# TORCHTITAN_DIR (exported by .ci/smoke_test.sh) or a sibling checkout | ||
| 23 | +# provides the tokenizer and cc12m-test data. | ||
| 24 | +TORCHTITAN_REPO="${TORCHTITAN_REPO:-${TORCHTITAN_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/../torchtitan}}" | ||
| 25 | +DATASET="${DATASET:-cc12m-test}" | ||
| 26 | +DATASET_PATH="${DATASET_PATH:-${TORCHTITAN_REPO}/tests/assets/cc12m_test}" # your data path | ||
| 27 | +HF_ASSETS_PATH="${HF_ASSETS_PATH:-${TORCHTITAN_REPO}/tests/assets/tokenizer}" # your tokenizer path | ||
| 28 | + | ||
| 29 | +# Training (smoke-sized defaults) | ||
| 30 | +SEQ_LEN=512 | ||
| 31 | +MBS=1 | ||
| 32 | +GBS=1 | ||
| 33 | +STEPS=10 | ||
| 34 | +SPMD_BACKEND="spmd_types" | ||
| 35 | + | ||
| 36 | +# NPU overrides: the Triton GDN kernel is always imported; the MoE token | ||
| 37 | +# dispatcher is a performance option enabled via ENABLE_NPU_MOE_DISPATCHER=1. | ||
| 38 | +# An explicitly set (possibly empty) OVERRIDE_IMPORTS wins verbatim. | ||
| 39 | +if [[ ${OVERRIDE_IMPORTS+x} ]]; then | ||
| 40 | + : | ||
| 41 | +else | ||
| 42 | + OVERRIDE_IMPORTS="torchtitan_npu.override.qwen3_5.gated_delta.npu" | ||
| 43 | + if [[ "${ENABLE_NPU_MOE_DISPATCHER:-0}" == "1" ]]; then | ||
| 44 | + OVERRIDE_IMPORTS="${OVERRIDE_IMPORTS},torchtitan_npu.override.common.token_dispatcher.asc" | ||
| 45 | + fi | ||
| 46 | +fi | ||
| 47 | + | ||
| 48 | +DEBUG_ARGS=" | ||
| 49 | + --debug.print-config | ||
| 50 | +" | ||
| 51 | + | ||
| 52 | +# HF assets | ||
| 53 | +HF_ASSETS_ARGS=" | ||
| 54 | + --hf-assets-path ${HF_ASSETS_PATH} | ||
| 55 | +" | ||
| 56 | + | ||
| 57 | +# Dataloader | ||
| 58 | +DATALOADER_ARGS=" | ||
| 59 | + --dataloader.dataset ${DATASET} | ||
| 60 | + --dataloader.dataset-path ${DATASET_PATH} | ||
| 61 | +" | ||
| 62 | + | ||
| 63 | +# Parallelism | ||
| 64 | +PARALLELISM_ARGS=" | ||
| 65 | + --parallelism.spmd-backend ${SPMD_BACKEND} | ||
| 66 | +" | ||
| 67 | + | ||
| 68 | +# Compile | ||
| 69 | +COMPILE_ARGS=" | ||
| 70 | + --compile.no_enable | ||
| 71 | + --compile.components model | ||
| 72 | + --compile.backend aot_eager | ||
| 73 | +" | ||
| 74 | + | ||
| 75 | +# Training | ||
| 76 | +TRAINING_ARGS=" | ||
| 77 | + --training.local-batch-size ${MBS} | ||
| 78 | + --training.global-batch-size ${GBS} | ||
| 79 | + --training.seq-len ${SEQ_LEN} | ||
| 80 | + --training.steps ${STEPS} | ||
| 81 | + --training.disable-cuda-graphs | ||
| 82 | +" | ||
| 83 | + | ||
| 84 | +MODULE="${MODULE}" \ | ||
| 85 | +CONFIG="${CONFIG}" \ | ||
| 86 | +NGPU="${NGPU}" \ | ||
| 87 | +LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | ||
| 88 | +bash scripts/run_train.sh \ | ||
| 89 | + $COMPILE_ARGS \ | ||
| 90 | + $HF_ASSETS_ARGS \ | ||
| 91 | + $DATALOADER_ARGS \ | ||
| 92 | + $PARALLELISM_ARGS \ | ||
| 93 | + $TRAINING_ARGS \ | ||
| 94 | + $DEBUG_ARGS \ | ||
| 95 | + --override.imports "${OVERRIDE_IMPORTS}" \ | ||
| 96 | + "$@" | ||
| @@ -0,0 +1,111 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +# Run this script on a single node. | ||
| 8 | +# Append CLI arguments to override the defaults below: | ||
| 9 | +# ./examples/qwen3_5/qwen3_5_debugmodel_moe_8p_cpt_512.sh | ||
| 10 | +# ENABLE_NPU_MOE_DISPATCHER=1 opts in the ASC MoE token dispatcher. | ||
| 11 | +# Set ASCEND_SET_ENV_PATH to select a specific CANN toolkit. | ||
| 12 | + | ||
| 13 | +set -euo pipefail | ||
| 14 | + | ||
| 15 | +NGPU="${NGPU:-8}" | ||
| 16 | +WORLD_SIZE="${NGPU}" | ||
| 17 | + | ||
| 18 | +# Model | ||
| 19 | +MODULE="${MODULE:-torchtitan_npu.models.qwen3_5}" | ||
| 20 | +CONFIG="${CONFIG:-qwen35_debugmodel_moe}" | ||
| 21 | + | ||
| 22 | +# Dataloader: the multimodal test assets live in the TorchTitan checkout; | ||
| 23 | +# TORCHTITAN_DIR (exported by .ci/smoke_test.sh) or a sibling checkout | ||
| 24 | +# provides the tokenizer and cc12m-test data. | ||
| 25 | +TORCHTITAN_REPO="${TORCHTITAN_REPO:-${TORCHTITAN_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/../torchtitan}}" | ||
| 26 | +DATASET="${DATASET:-cc12m-test}" | ||
| 27 | +DATASET_PATH="${DATASET_PATH:-${TORCHTITAN_REPO}/tests/assets/cc12m_test}" # your data path | ||
| 28 | +HF_ASSETS_PATH="${HF_ASSETS_PATH:-${TORCHTITAN_REPO}/tests/assets/tokenizer}" # your tokenizer path | ||
| 29 | + | ||
| 30 | +# Parallelism | ||
| 31 | +TP=1 | ||
| 32 | +PP=1 | ||
| 33 | +EP=8 | ||
| 34 | +CP=1 | ||
| 35 | +DP_SHARD=8 | ||
| 36 | +DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP))) | ||
| 37 | +SPMD_BACKEND="spmd_types" | ||
| 38 | + | ||
| 39 | +# Training (smoke-sized defaults) | ||
| 40 | +SEQ_LEN=512 | ||
| 41 | +MBS=2 | ||
| 42 | +GBS=-1 | ||
| 43 | +STEPS=10 | ||
| 44 | + | ||
| 45 | +# NPU overrides: the Triton GDN kernel is always imported; the MoE token | ||
| 46 | +# dispatcher is a performance option enabled via ENABLE_NPU_MOE_DISPATCHER=1. | ||
| 47 | +# An explicitly set (possibly empty) OVERRIDE_IMPORTS wins verbatim. | ||
| 48 | +if [[ ${OVERRIDE_IMPORTS+x} ]]; then | ||
| 49 | + : | ||
| 50 | +else | ||
| 51 | + OVERRIDE_IMPORTS="torchtitan_npu.override.qwen3_5.gated_delta.npu" | ||
| 52 | + if [[ "${ENABLE_NPU_MOE_DISPATCHER:-0}" == "1" ]]; then | ||
| 53 | + OVERRIDE_IMPORTS="${OVERRIDE_IMPORTS},torchtitan_npu.override.common.token_dispatcher.asc" | ||
| 54 | + fi | ||
| 55 | +fi | ||
| 56 | + | ||
| 57 | +DEBUG_ARGS=" | ||
| 58 | + --debug.print-config | ||
| 59 | +" | ||
| 60 | + | ||
| 61 | +# HF assets | ||
| 62 | +HF_ASSETS_ARGS=" | ||
| 63 | + --hf-assets-path ${HF_ASSETS_PATH} | ||
| 64 | +" | ||
| 65 | + | ||
| 66 | +# Dataloader | ||
| 67 | +DATALOADER_ARGS=" | ||
| 68 | + --dataloader.dataset ${DATASET} | ||
| 69 | + --dataloader.dataset-path ${DATASET_PATH} | ||
| 70 | +" | ||
| 71 | + | ||
| 72 | +# Parallelism | ||
| 73 | +PARALLELISM_ARGS=" | ||
| 74 | + --parallelism.spmd-backend ${SPMD_BACKEND} | ||
| 75 | + --parallelism.data-parallel-shard-degree ${DP_SHARD} | ||
| 76 | + --parallelism.data-parallel-replicate-degree ${DP_REPLICATE} | ||
| 77 | + --parallelism.expert-parallel-degree ${EP} | ||
| 78 | + --parallelism.tensor-parallel-degree ${TP} | ||
| 79 | + --parallelism.context-parallel-degree ${CP} | ||
| 80 | + --parallelism.pipeline-parallel-degree ${PP} | ||
| 81 | +" | ||
| 82 | + | ||
| 83 | +# Compile | ||
| 84 | +COMPILE_ARGS=" | ||
| 85 | + --compile.no_enable | ||
| 86 | + --compile.components model | ||
| 87 | + --compile.backend aot_eager | ||
| 88 | +" | ||
| 89 | + | ||
| 90 | +# Training | ||
| 91 | +TRAINING_ARGS=" | ||
| 92 | + --training.local-batch-size ${MBS} | ||
| 93 | + --training.global-batch-size ${GBS} | ||
| 94 | + --training.seq-len ${SEQ_LEN} | ||
| 95 | + --training.steps ${STEPS} | ||
| 96 | + --training.disable-cuda-graphs | ||
| 97 | +" | ||
| 98 | + | ||
| 99 | +MODULE="${MODULE}" \ | ||
| 100 | +CONFIG="${CONFIG}" \ | ||
| 101 | +NGPU="${NGPU}" \ | ||
| 102 | +LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | ||
| 103 | +bash scripts/run_train.sh \ | ||
| 104 | + $COMPILE_ARGS \ | ||
| 105 | + $HF_ASSETS_ARGS \ | ||
| 106 | + $DATALOADER_ARGS \ | ||
| 107 | + $PARALLELISM_ARGS \ | ||
| 108 | + $TRAINING_ARGS \ | ||
| 109 | + $DEBUG_ARGS \ | ||
| 110 | + --override.imports "${OVERRIDE_IMPORTS}" \ | ||
| 111 | + "$@" | ||
| @@ -0,0 +1,120 @@ | |||
| 1 | +# Qwen3.5 NPU training examples | ||
| 2 | + | ||
| 3 | +本目录提供 Qwen3.5 在 NPU 上的训练入口: | ||
| 4 | + | ||
| 5 | +- `qwen3_5_debugmodel_1p_cpt_512.sh`:Qwen3.5 多模态 debugmodel 1 卡冒烟入口, | ||
| 6 | + 复用 `scripts/run_train.sh`,默认 `qwen35_debugmodel` 配置、cc12m-test 数据、 | ||
| 7 | + 512 序列 10 步。`ENABLE_NPU_MOE_DISPATCHER=1` 可选启用 ASC MoE dispatcher。 | ||
| 8 | +- `qwen3_5_debugmodel_moe_8p_cpt_512.sh`:Qwen3.5 MoE debugmodel 8 卡入口, | ||
| 9 | + 默认 `qwen35_debugmodel_moe` 配置,EP=8/DP_SHARD=8(spmd_types 后端)。 | ||
| 10 | + | ||
| 11 | +## Qwen3.5 multimodal dependencies | ||
| 12 | + | ||
| 13 | +The Qwen3.5 adapter reuses TorchTitan's upstream image and video preprocessing. | ||
| 14 | +Install the torchvision nightly that declares compatibility with the container's | ||
| 15 | +Torch build, then install this repository without resolving the container's | ||
| 16 | +custom Torch/torch_npu pair: | ||
| 17 | + | ||
| 18 | +```bash | ||
| 19 | +python -m pip install av einops pillow | ||
| 20 | +python -m pip install --no-deps \ | ||
| 21 | + --index-url https://download.pytorch.org/whl/nightly/cpu \ | ||
| 22 | + torchvision==0.29.0.dev20260719+cpu | ||
| 23 | +python -m pip install --no-deps -e ../torchtitan | ||
| 24 | +python -m pip install --no-deps -e . | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +This pairing targets `torch==2.14.0.dev20260719+cpu` on Python 3.12/aarch64. | ||
| 28 | +`--no-deps` is intentional because the custom torch_npu wheel declares the | ||
| 29 | +stable `torch==2.14.0` version even though the validated runtime uses a nightly | ||
| 30 | +Torch build. Fresh environments that install `requirements.txt` instead resolve | ||
| 31 | +`torchvision==0.29.0.dev20260720`: that nightly build declares | ||
| 32 | +`torch==2.14.0.dev20260719` exactly, so plain pip resolution accepts it beside | ||
| 33 | +the pinned Torch. Both builds belong to the validated 0.29.0.dev line. | ||
| 34 | + | ||
| 35 | +## Qwen3.5 NPU override 开关 | ||
| 36 | + | ||
| 37 | +默认启用 Triton GDN override。配置工厂保持与上游完全一致,不会静默注入 NPU | ||
| 38 | +实现;视觉 mask、视频 MRoPE 和 FLA 兼容补丁由 `torchtitan_npu.models.qwen3_5` | ||
| 39 | +导入时按上游接口自动安装。 | ||
| 40 | + | ||
| 41 | +MoE token dispatcher 是性能选项(`ENABLE_NPU_MOE_DISPATCHER` 缺省值为 `0`), | ||
| 42 | +默认关闭。可通过以下任一方式显式启用: | ||
| 43 | + | ||
| 44 | +```bash | ||
| 45 | +ENABLE_NPU_MOE_DISPATCHER=1 bash examples/qwen3_5/qwen3_5_debugmodel_1p_cpt_512.sh | ||
| 46 | + | ||
| 47 | +OVERRIDE_IMPORTS="torchtitan_npu.override.qwen3_5.gated_delta.npu,torchtitan_npu.override.common.token_dispatcher.asc" \ | ||
| 48 | + bash examples/qwen3_5/qwen3_5_debugmodel_1p_cpt_512.sh | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +用户设置的 `OVERRIDE_IMPORTS` 始终优先;显式设置为空字符串可禁用全部默认 | ||
| 52 | +override,用于消融或定位问题。 | ||
| 53 | + | ||
| 54 | +### 启动参数与路径 | ||
| 55 | + | ||
| 56 | +本目录的入口脚本与仓库通用的 `scripts/run_train.sh` 使用相同的参数透传方式: | ||
| 57 | +脚本只设置模型、数据和多模态参数默认值,所有训练参数继续交给 | ||
| 58 | +`torchtitan.train`。上游目录按以下优先级解析: | ||
| 59 | + | ||
| 60 | +1. `TORCHTITAN_REPO`; | ||
| 61 | +2. `TORCHTITAN_DIR`(`.ci/smoke_test.sh` 会导出此变量指向 third_party 克隆); | ||
| 62 | +3. 仓库同级的 `../torchtitan`。 | ||
| 63 | + | ||
| 64 | +数据和路径也可以覆盖:`HF_ASSETS_PATH` 默认为 | ||
| 65 | +`${TORCHTITAN_REPO}/tests/assets/tokenizer`,`DATASET_PATH` 默认为 | ||
| 66 | +`${TORCHTITAN_REPO}/tests/assets/cc12m_test`。如需使用 torch.compile,可在 | ||
| 67 | +脚本中修改 `COMPILE_ARGS` 或通过 `COMPILE_BACKEND` 环境变量控制。 | ||
| 68 | + | ||
| 69 | +示例(单机 8 卡 MoE): | ||
| 70 | + | ||
| 71 | +```bash | ||
| 72 | +TORCHTITAN_DIR=/path/to/torchtitan \ | ||
| 73 | +NGPU=8 CONFIG=qwen35_debugmodel_moe LOG_RANK=5 \ | ||
| 74 | + bash examples/qwen3_5/qwen3_5_debugmodel_moe_8p_cpt_512.sh --training.steps 2 | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +### Qwen3.5-VL 适配链路 | ||
| 78 | + | ||
| 79 | +运行时调用关系如下,NPU 适配只替换必要边界,上游 recipe 和模型主体仍由 | ||
| 80 | +TorchTitan 提供: | ||
| 81 | + | ||
| 82 | +```text | ||
| 83 | +qwen3_5_debugmodel_1p_cpt_512.sh | ||
| 84 | + ÚÄ 组装 tokenizer、cc12m-test、override.imports 和用户参数 | ||
| 85 | + ÚÄ scripts/run_train.sh -> torchrun -m torchtitan_npu.train | ||
| 86 | + ÚÄ torchtitan_npu.models.qwen3_5 导入时安装视觉/MRoPE/FLA patch | ||
| 87 | + ÚÄ 上游 config_registry 构造 qwen35_debugmodel(_moe) | ||
| 88 | + ÚÄ GDN override 替换 delta kernel;可选 dispatcher 替换 MoE dispatch | ||
| 89 | + ÚÄ parallelize_qwen3_5_npu 建立 TP/EP/FSDP;CP 使用序列元数据与 mesh resolver | ||
| 90 | + ÚÄ upstream multimodal collator 读取文本、图像/视频并生成 MRoPE | ||
| 91 | + ÚÄ vision encoder + language decoder 前向,执行 GDN/MoE/CP 数据交换 | ||
| 92 | + ÚÄ backward、优化器更新与 TensorBoard/JSONL 日志 | ||
| 93 | + ä 进程组销毁 | ||
| 94 | +``` | ||
| 95 | + | ||
| 96 | +`spmd_types` 使用 TorchTitan v0.3 的 `resolve_fsdp_mesh`/ | ||
| 97 | +`resolve_sparse_fsdp_mesh`,而旧 backend 保留 `fsdp/efsdp` 名称;因此同一套 | ||
| 98 | +parallelizer 可兼容当前主线和旧 NPU 运行环境。当前 Qwen3.5-VL 多模态视觉 mask | ||
| 99 | +尚未完成 CP 序列元数据适配;VL 配置启用 CP 时会在并行化入口明确失败,避免 | ||
| 100 | +运行到错误的 dict-mask 路径。纯文本长上下文配置仍可使用专用 CP recipe。 | ||
| 101 | + | ||
| 102 | +集成测试通过以下命令运行 Qwen3.5 的 1-rank 冒烟用例: | ||
| 103 | + | ||
| 104 | +```bash | ||
| 105 | +python -m tests.integration_tests.run_tests /tmp/qwen3_5-tests \ | ||
| 106 | + --test_suite qwen3_5 --test_name all --ngpu 2 | ||
| 107 | +``` | ||
| 108 | + | ||
| 109 | +## Qwen3.5 视觉 mask 边界 | ||
| 110 | + | ||
| 111 | +当前 NPU eager Flex 兼容层只处理 Qwen3.5 vision patch 显式标记的、等长且 | ||
| 112 | +各 attention head 共享的 self-attention mask;其他模型和其他 Flex 语义继续走 | ||
| 113 | +原生路径。dense bool mask 在一次 vision forward 内缓存并由所有 vision block | ||
| 114 | +复用;aot_eager 等编译追踪期间,满足同样条件的 NPU Flex mask(即使未被 | ||
| 115 | +vision patch 显式标记)也会走该有界 dense SDPA 路径,eager 执行仍以显式 | ||
| 116 | +标记为界。 | ||
| 117 | + | ||
| 118 | +为避免合法的大图或长视频直接触发 NPU OOM,物化上限为 `16,777,216` 个 bool | ||
| 119 | +元素(单样本等长输入约为 4096 个 merged vision token)。超过上限会在算子下发 | ||
| 120 | +前 fail-fast;请通过数据配置降低图片最大像素、视频帧数或视觉序列长度。 | ||
| @@ -54,29 +54,36 @@ def test_mxfp4_dequantize_rejects_partial_blocks(): | |||
| 54 | 54 | ||
| 55 | 55 | ||
| 56 | @pytest.mark.parametrize( | 56 | @pytest.mark.parametrize( |
| 57 | - "tensor, axis", | 57 | + "layout", |
| 58 | - [ | 58 | + ["dense", "strided_axis", "perm_view", "non_pure", "cat_gate", "cat_up", "single_row"], |
| 59 | - # 1. Dense (is_contiguous() True) -> if branch, no transpose. | ||
| 60 | - (torch.randn(256, 128, device="npu", dtype=torch.bfloat16), -1), | ||
| 61 | - # 2. Quant axis strided (stride(axis) != 1): a transposed 2D tensor. | ||
| 62 | - (torch.randn(128, 256, device="npu", dtype=torch.bfloat16).transpose(0, 1), 1), | ||
| 63 | - # 3. Pure perm view with innermost-contiguous quant axis (like wo_a). | ||
| 64 | - (torch.randn(4, 128, 256, device="npu", dtype=torch.bfloat16).transpose(1, 2), 1), | ||
| 65 | - # 4. Non-pure strided view, stride(axis) == 1 but permute stays non-dense. | ||
| 66 | - (torch.as_strided(torch.randn(4, 4, device="npu", dtype=torch.bfloat16), (2, 4), (2, 1)), 1), | ||
| 67 | - ], | ||
| 68 | - ids=["dense", "strided_axis", "perm_view", "non_pure"], | ||
| 69 | ) | 59 | ) |
| 70 | @pytest.mark.parametrize("elem_dtype", [torch.float8_e4m3fn, torch.float8_e5m2]) | 60 | @pytest.mark.parametrize("elem_dtype", [torch.float8_e4m3fn, torch.float8_e5m2]) |
| 71 | -def test_mx_quantize_matches_raw_op_for_all_layouts(tensor, axis, elem_dtype): | 61 | +def test_mx_quantize_matches_raw_op_for_all_layouts(layout, elem_dtype): |
| 72 | - """mx_quantize matches npu_dynamic_mx_quant on all four input layouts. | 62 | + """Compare wrapper values/scales with the raw NPU op, including cat gradients. |
| 73 | 63 | ||
| 74 | These are value-equivalence checks: they verify correctness, not that a real | 64 | These are value-equivalence checks: they verify correctness, not that a real |
| 75 | - transpose was avoided (that would require profiling). The point is each of | 65 | + transpose was avoided (that would require profiling). Each tested input |
| 76 | - the four branch inputs must produce identical y/scale to the raw op. | 66 | + layout must produce identical y/scale to the raw op. |
| 77 | """ | 67 | """ |
| 78 | from torchao_npu.quantization.quant_primitives.mx import mx_quantize | 68 | from torchao_npu.quantization.quant_primitives.mx import mx_quantize |
| 79 | 69 | ||
| 70 | + # Allocate within the test so RNG/device state is managed by the fixture. | ||
| 71 | + axis = -1 | ||
| 72 | + if layout == "dense": | ||
| 73 | + tensor = torch.randn(256, 128, device="npu", dtype=torch.bfloat16) | ||
| 74 | + elif layout == "strided_axis": | ||
| 75 | + tensor = torch.randn(128, 256, device="npu", dtype=torch.bfloat16).T | ||
| 76 | + elif layout == "perm_view": | ||
| 77 | + tensor = torch.randn(4, 128, 256, device="npu", dtype=torch.bfloat16).transpose(1, 2) | ||
| 78 | + axis = 1 | ||
| 79 | + elif layout == "non_pure": | ||
| 80 | + tensor = torch.randn(4, 256, 129, device="npu", dtype=torch.bfloat16)[..., :128] | ||
| 81 | + else: | ||
| 82 | + rows = 1 if layout == "single_row" else 3 | ||
| 83 | + packed = torch.randn(rows, 256, device="npu", dtype=torch.bfloat16) | ||
| 84 | + tensor = packed[:, 128:] if layout == "cat_up" else packed[:, :128] | ||
| 85 | + assert tensor.stride() == (256, 1) | ||
| 86 | + | ||
| 80 | def as_uint8(t): | 87 | def as_uint8(t): |
| 81 | # FP8 tensors can't be compared element-wise with torch.equal on NPU; | 88 | # FP8 tensors can't be compared element-wise with torch.equal on NPU; |
| 82 | # compare exact bytes instead. Each value is at most 1 byte (FP8, or FP4 | 89 | # compare exact bytes instead. Each value is at most 1 byte (FP8, or FP4 |
| @@ -317,3 +324,82 @@ def test_mx_quantize_dual_axis_quant_matmul_matches_raw_op(elem_dtype, case_a, c | |||
| 317 | 324 | ||
| 318 | assert y.shape == y_ref.shape | 325 | assert y.shape == y_ref.shape |
| 319 | assert torch.equal(y, y_ref), "npu_quant_matmul result differs between mx_quantize_dual_axis and raw op" | 326 | assert torch.equal(y, y_ref), "npu_quant_matmul result differs between mx_quantize_dual_axis and raw op" |
| 327 | + | ||
| 328 | + | ||
| 329 | +# ========================================================================= | ||
| 330 | +# Tests for mx_fake_quantize (quantize then dequantize round trip) | ||
| 331 | +# ========================================================================= | ||
| 332 | + | ||
| 333 | + | ||
| 334 | +@pytest.mark.parametrize( | ||
| 335 | + "tensor, axis", | ||
| 336 | + [ | ||
| 337 | + # 1. Dense (is_contiguous() True) -> if branch, the ops see the tensor as-is. | ||
| 338 | + (torch.randn(256, 128, device="npu", dtype=torch.bfloat16), -1), | ||
| 339 | + # 2. Quant axis strided (stride(axis) != 1): a transposed 2D tensor, which | ||
| 340 | + # no view can undo, so the ops see the tensor as-is. | ||
| 341 | + (torch.randn(128, 256, device="npu", dtype=torch.bfloat16).transpose(0, 1), 1), | ||
| 342 | + # 3. Pure perm view with innermost-contiguous quant axis (like wo_a): the | ||
| 343 | + # permuting branch, where FP4 packs a different dim than the raw ops' call. | ||
| 344 | + (torch.randn(4, 128, 256, device="npu", dtype=torch.bfloat16).transpose(1, 2), 1), | ||
| 345 | + # 4. Non-pure strided view, stride(axis) == 1 but no permutation makes it | ||
| 346 | + # dense, so the permuting branch's permutation is the identity and the | ||
| 347 | + # op copies internally. The quant dim is a whole number of blocks, which | ||
| 348 | + # the dequantize helper the reference uses requires. | ||
| 349 | + (torch.as_strided(torch.randn(2, 65, device="npu", dtype=torch.bfloat16), (2, 64), (65, 1)), 1), | ||
| 350 | + ], | ||
| 351 | + ids=["dense", "strided_axis", "perm_view", "non_pure"], | ||
| 352 | +) | ||
| 353 | +@pytest.mark.parametrize("elem_dtype", [torch.float8_e4m3fn, torch.float8_e5m2, torch.float4_e2m1fn_x2]) | ||
| 354 | +def test_mx_fake_quantize_matches_quantize_then_dequantize_for_all_layouts(tensor, axis, elem_dtype): | ||
| 355 | + """mx_fake_quantize reproduces quantize-then-dequantize on all four layouts. | ||
| 356 | + | ||
| 357 | + The reference quantizes with the raw ``npu_dynamic_mx_quant`` and dequantizes | ||
| 358 | + with ``mxfp8_dequantize``/``mxfp4_dequantize``, the helpers training's fake | ||
| 359 | + quantization has used so far (``MXFP4FakeQuantize.forward``). The raw | ||
| 360 | + ``npu_anti_mx_quant`` cannot serve as the reference: it only consumes quantized | ||
| 361 | + data whose quant axis is trailing, which the ``perm_view`` layout breaks. | ||
| 362 | + | ||
| 363 | + These are value-equivalence checks: they verify correctness, not that a real | ||
| 364 | + transpose was avoided (that would require profiling). The point is each of the | ||
| 365 | + four branch inputs must dequantize to what the raw ops produce for the original | ||
| 366 | + tensor. Values are compared rather than quantized bytes: for FP4 the two calls | ||
| 367 | + may pack different dims (two values per byte), which does not change what each | ||
| 368 | + value dequantizes to. | ||
| 369 | + | ||
| 370 | + The result is then fake quantized a second time: the dequantized tensor's layout | ||
| 371 | + need not match the original's (``non_pure`` comes back dense), so the second call | ||
| 372 | + may take the other branch, and it must still reproduce the values exactly. | ||
| 373 | + """ | ||
| 374 | + from torchao_npu.ops.mx_ops import mxfp4_dequantize, mxfp8_dequantize | ||
| 375 | + from torchao_npu.quantization.quant_primitives.mx import mx_fake_quantize | ||
| 376 | + | ||
| 377 | + config = MXQuantizeConfig(elem_dtype=elem_dtype) | ||
| 378 | + | ||
| 379 | + y = mx_fake_quantize(tensor, axis, config) | ||
| 380 | + y_q, scale = torch_npu.npu_dynamic_mx_quant( | ||
| 381 | + tensor, | ||
| 382 | + axis=axis, | ||
| 383 | + dst_type=config.npu_elem_dtype, | ||
| 384 | + block_size=config.block_size, | ||
| 385 | + round_mode=config.round_mode, | ||
| 386 | + scale_alg=config.scale_alg, | ||
| 387 | + dst_type_max=config.dst_type_max, | ||
| 388 | + ) | ||
| 389 | + dequantize = mxfp4_dequantize if elem_dtype is torch.float4_e2m1fn_x2 else mxfp8_dequantize | ||
| 390 | + y_ref = dequantize( | ||
| 391 | + y_q, | ||
| 392 | + scale, | ||
| 393 | + axis=axis, | ||
| 394 | + block_size=config.block_size, | ||
| 395 | + output_shape=tensor.shape, | ||
| 396 | + output_dtype=tensor.dtype, | ||
| 397 | + ) | ||
| 398 | + | ||
| 399 | + assert y.shape == tensor.shape, f"shape mismatch: {y.shape} vs {tensor.shape}" | ||
| 400 | + assert y.dtype == tensor.dtype, f"dtype mismatch: {y.dtype} vs {tensor.dtype}" | ||
| 401 | + assert torch.equal(y, y_ref), "fake quantized values differ from the reference dequantize" | ||
| 402 | + | ||
| 403 | + # Idempotency: quantize -> dequantize -> quantize -> dequantize is a no-op. | ||
| 404 | + y2 = mx_fake_quantize(y, axis, config) | ||
| 405 | + assert torch.equal(y, y2), "fake quantization is not idempotent" | ||
| @@ -168,3 +168,17 @@ def test_block_mx_config_accepts_only_fp4_nested_fake_quantization(): | |||
| 168 | 168 | ||
| 169 | with pytest.raises(AssertionError, match="must be FP4"): | 169 | with pytest.raises(AssertionError, match="must be FP4"): |
| 170 | BlockMXQuantizeConfig(mxfp4_fake_quantize_config=MXQuantizeConfig()) | 170 | BlockMXQuantizeConfig(mxfp4_fake_quantize_config=MXQuantizeConfig()) |
| 171 | + | ||
| 172 | + | ||
| 173 | +def test_block_mx_config_fsdp_prequantize_defaults_to_false(): | ||
| 174 | + """fsdp_prequantize defaults to False (on-the-fly quantization baseline).""" | ||
| 175 | + config = BlockMXQuantizeConfig() | ||
| 176 | + assert config.fsdp_prequantize is False | ||
| 177 | + | ||
| 178 | + | ||
| 179 | +def test_block_mx_config_fsdp_prequantize_can_be_enabled(): | ||
| 180 | + """fsdp_prequantize can be enabled and is excluded from equality comparison.""" | ||
| 181 | + config = BlockMXQuantizeConfig(fsdp_prequantize=True) | ||
| 182 | + assert config.fsdp_prequantize is True | ||
| 183 | + # compare=False: two configs differing only in fsdp_prequantize are equal. | ||
| 184 | + assert BlockMXQuantizeConfig(fsdp_prequantize=True) == BlockMXQuantizeConfig(fsdp_prequantize=False) | ||
| @@ -0,0 +1,158 @@ | |||
| 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 | +"""Tests for the helpers shared by the quantized tensor classes.""" | ||
| 7 | + | ||
| 8 | +import itertools | ||
| 9 | + | ||
| 10 | +import pytest | ||
| 11 | +import torch | ||
| 12 | +import torch_npu # noqa: F401 | ||
| 13 | +from torchao_npu.quantized_tensors import ( | ||
| 14 | + logical_qdata_shape, | ||
| 15 | + permutation_from_transpose, | ||
| 16 | + resolve_pack_axis, | ||
| 17 | +) | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +@pytest.mark.parametrize( | ||
| 21 | + "dim0, dim1, ndim, expected", | ||
| 22 | + [ | ||
| 23 | + (0, 1, 3, [1, 0, 2]), | ||
| 24 | + (1, 2, 3, [0, 2, 1]), | ||
| 25 | + (-1, -2, 3, [0, 2, 1]), | ||
| 26 | + (0, 1, 5, [1, 0, 2, 3, 4]), | ||
| 27 | + (1, 3, 5, [0, 3, 2, 1, 4]), | ||
| 28 | + (-1, -3, 5, [0, 1, 4, 3, 2]), | ||
| 29 | + ], | ||
| 30 | +) | ||
| 31 | +def test_permutation_from_transpose(dim0, dim1, ndim, expected): | ||
| 32 | + perm = permutation_from_transpose(dim0, dim1, ndim) | ||
| 33 | + | ||
| 34 | + assert perm == expected, ( | ||
| 35 | + f"permutation_from_transpose(dim0={dim0}, dim1={dim1}, ndim={ndim}) returned {perm}, expected {expected}" | ||
| 36 | + ) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +@pytest.mark.parametrize("ndim", [2, 3, 5]) | ||
| 40 | +def test_permutation_from_transpose_is_its_own_inverse(ndim): | ||
| 41 | + """A dims list produced by a swap is its own inverse: applying it twice is the identity.""" | ||
| 42 | + identity = list(range(ndim)) | ||
| 43 | + | ||
| 44 | + for dim0, dim1 in itertools.combinations(range(ndim), 2): | ||
| 45 | + perm = permutation_from_transpose(dim0, dim1, ndim) | ||
| 46 | + composed = [perm[i] for i in perm] | ||
| 47 | + | ||
| 48 | + assert composed == identity, ( | ||
| 49 | + f"permutation_from_transpose(dim0={dim0}, dim1={dim1}, ndim={ndim}) " | ||
| 50 | + f"returned {perm}; applying it twice gives {composed}, expected {identity}" | ||
| 51 | + ) | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def test_permutation_from_transpose_out_of_range(): | ||
| 55 | + with pytest.raises(IndexError): | ||
| 56 | + permutation_from_transpose(0, 3, 3) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +@pytest.mark.parametrize("shape", [(64,), (4, 64), (2, 4, 64)]) | ||
| 60 | +def test_logical_qdata_shape_fp8_is_the_stored_shape(shape): | ||
| 61 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 62 | + | ||
| 63 | + assert logical_qdata_shape(qdata, None) == shape | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +@pytest.mark.parametrize( | ||
| 67 | + "qdata_shape, pack_axis, expected", | ||
| 68 | + [ | ||
| 69 | + ((32,), -1, (64,)), | ||
| 70 | + ((4, 32), 1, (4, 64)), | ||
| 71 | + ((4, 32), -1, (4, 64)), | ||
| 72 | + ((2, 4, 32), -1, (2, 4, 64)), | ||
| 73 | + ], | ||
| 74 | +) | ||
| 75 | +def test_logical_qdata_shape_fp4_doubles_the_pack_axis(qdata_shape, pack_axis, expected): | ||
| 76 | + qdata = torch.randint(0, 256, qdata_shape, dtype=torch.uint8).view(torch.float4_e2m1fn_x2) | ||
| 77 | + | ||
| 78 | + assert logical_qdata_shape(qdata, pack_axis) == expected | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +@pytest.mark.parametrize("qdata_shape", [(32,), (4, 32), (2, 4, 32)]) | ||
| 82 | +def test_logical_qdata_shape_fp4_requires_a_pack_axis(qdata_shape): | ||
| 83 | + qdata = torch.randint(0, 256, qdata_shape, dtype=torch.uint8).view(torch.float4_e2m1fn_x2) | ||
| 84 | + | ||
| 85 | + with pytest.raises(ValueError, match="pack_axis should be set"): | ||
| 86 | + logical_qdata_shape(qdata, None) | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +@pytest.mark.parametrize( | ||
| 90 | + "qdata_shape, pack_axis", | ||
| 91 | + [ | ||
| 92 | + ((4, 32), 0), | ||
| 93 | + ((2, 4, 32), 0), | ||
| 94 | + ((2, 4, 32), 1), | ||
| 95 | + ], | ||
| 96 | +) | ||
| 97 | +def test_logical_qdata_shape_rejects_non_unit_stride_pack_axis(qdata_shape, pack_axis): | ||
| 98 | + """Doubling a dim only describes packing if that dim is the unit-stride one.""" | ||
| 99 | + qdata = torch.randint(0, 256, qdata_shape, dtype=torch.uint8).view(torch.float4_e2m1fn_x2) | ||
| 100 | + | ||
| 101 | + with pytest.raises(ValueError, match="unit-stride pack_axis is expected"): | ||
| 102 | + logical_qdata_shape(qdata, pack_axis) | ||
| 103 | + | ||
| 104 | + | ||
| 105 | +@pytest.mark.parametrize( | ||
| 106 | + "qdata_shape, pack_axis", | ||
| 107 | + [ | ||
| 108 | + ((32,), 1), | ||
| 109 | + ((4, 32), 2), | ||
| 110 | + ((2, 4, 32), 3), | ||
| 111 | + ], | ||
| 112 | +) | ||
| 113 | +def test_logical_qdata_shape_rejects_out_of_range_pack_axis(qdata_shape, pack_axis): | ||
| 114 | + qdata = torch.randint(0, 256, qdata_shape, dtype=torch.uint8).view(torch.float4_e2m1fn_x2) | ||
| 115 | + | ||
| 116 | + with pytest.raises(IndexError): | ||
| 117 | + logical_qdata_shape(qdata, pack_axis) | ||
| 118 | + | ||
| 119 | + | ||
| 120 | +@pytest.mark.parametrize("shape", [(4, 64), (2, 4, 64)]) | ||
| 121 | +def test_logical_qdata_shape_ignores_pack_axis_for_fp8(shape): | ||
| 122 | + """FP8 stores one value per element, so a set pack_axis only has to be valid.""" | ||
| 123 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 124 | + | ||
| 125 | + assert logical_qdata_shape(qdata, -1) == shape | ||
| 126 | + with pytest.raises(ValueError, match="unit-stride pack_axis is expected"): | ||
| 127 | + logical_qdata_shape(qdata, 0) | ||
| 128 | + | ||
| 129 | + | ||
| 130 | +@pytest.mark.parametrize( | ||
| 131 | + "qdata_shape, expected", | ||
| 132 | + [ | ||
| 133 | + ((32,), 0), | ||
| 134 | + ((4, 32), 1), | ||
| 135 | + ((2, 4, 32), 2), | ||
| 136 | + ], | ||
| 137 | +) | ||
| 138 | +def test_resolve_pack_axis_finds_the_unit_stride_dim(qdata_shape, expected): | ||
| 139 | + qdata = torch.randint(0, 256, qdata_shape, dtype=torch.uint8).view(torch.float4_e2m1fn_x2) | ||
| 140 | + | ||
| 141 | + assert resolve_pack_axis(qdata) == expected | ||
| 142 | + | ||
| 143 | + | ||
| 144 | +@pytest.mark.parametrize("qdata_shape", [(4, 32), (2, 4, 32)]) | ||
| 145 | +def test_resolve_pack_axis_honors_candidate_axes(qdata_shape): | ||
| 146 | + qdata = torch.randint(0, 256, qdata_shape, dtype=torch.uint8).view(torch.float4_e2m1fn_x2) | ||
| 147 | + | ||
| 148 | + assert resolve_pack_axis(qdata, -1) == qdata.ndim - 1 | ||
| 149 | + with pytest.raises(ValueError, match="expected one of them to be 1"): | ||
| 150 | + resolve_pack_axis(qdata, 0) | ||
| 151 | + | ||
| 152 | + | ||
| 153 | +@pytest.mark.parametrize("shape", [(64,), (4, 64), (2, 4, 64)]) | ||
| 154 | +def test_resolve_pack_axis_requires_fp4(shape): | ||
| 155 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 156 | + | ||
| 157 | + with pytest.raises(AssertionError, match="must be"): | ||
| 158 | + resolve_pack_axis(qdata) | ||
| @@ -0,0 +1,207 @@ | |||
| 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 | +"""Tests for the behavior :class:`BaseQuantizedTensor` gives every subclass.""" | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | +import torch_npu # noqa: F401 | ||
| 11 | +from torchao_npu.quantization.quant_configs import MXQuantizeConfig | ||
| 12 | +from torchao_npu.quantized_tensors.mx_tensor import MXTensor | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +def test_torch_function_layer_is_disabled(): | ||
| 16 | + """Ops must bypass the function layer and reach ``__torch_dispatch__``.""" | ||
| 17 | + assert MXTensor.__torch_function__ is torch._C._disabled_torch_function_impl | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +@pytest.mark.parametrize("shape", [(4, 64), (2, 4, 64)]) | ||
| 21 | +@pytest.mark.parametrize( | ||
| 22 | + "call", | ||
| 23 | + [ | ||
| 24 | + lambda x: x.view(-1), | ||
| 25 | + lambda x: x.sum(), | ||
| 26 | + lambda x: x + 1, | ||
| 27 | + lambda x: x[0], | ||
| 28 | + ], | ||
| 29 | +) | ||
| 30 | +def test_unimplemented_ops_raise_not_implemented(shape, call): | ||
| 31 | + """Op support is a whitelist: anything outside it raises, naming the class.""" | ||
| 32 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 33 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 34 | + scale = torch.full((*shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 35 | + x = MXTensor(qdata, scale, torch.bfloat16, -1, config) | ||
| 36 | + | ||
| 37 | + with pytest.raises(NotImplementedError, match=type(x).__name__): | ||
| 38 | + call(x) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +@pytest.mark.parametrize("shape", [(4, 64), (2, 4, 64)]) | ||
| 42 | +@pytest.mark.parametrize("op", ["add_", "mul_", "div_"]) | ||
| 43 | +def test_in_place_ops_are_rejected(shape, op): | ||
| 44 | + """Values are frozen: every mutable-schema op is rejected.""" | ||
| 45 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 46 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 47 | + scale = torch.full((*shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 48 | + x = MXTensor(qdata, scale, torch.bfloat16, -1, config) | ||
| 49 | + qdata_before = x.qdata.clone() | ||
| 50 | + | ||
| 51 | + with pytest.raises(RuntimeError, match="immutable"): | ||
| 52 | + getattr(x, op)(2.0) | ||
| 53 | + | ||
| 54 | + assert x.qdata.shape == qdata_before.shape, ( | ||
| 55 | + f"qdata shape changed after {op}: {tuple(x.qdata.shape)} != {tuple(qdata_before.shape)}" | ||
| 56 | + ) | ||
| 57 | + assert torch.equal(x.qdata.view(torch.uint8), qdata_before.view(torch.uint8)), f"qdata values changed after {op}" | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +@pytest.mark.parametrize("shape", [(4, 64), (2, 4, 64)]) | ||
| 61 | +def test_clone_and_detach_preserve_class_and_metadata(shape): | ||
| 62 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 63 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 64 | + scale = torch.full((*shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 65 | + x = MXTensor(qdata, scale, torch.bfloat16, -1, config) | ||
| 66 | + | ||
| 67 | + for name, y in (("clone", x.clone()), ("detach", x.detach())): | ||
| 68 | + assert type(y) is type(x) | ||
| 69 | + | ||
| 70 | + assert y.qdata.shape == x.qdata.shape, ( | ||
| 71 | + f"{name} changed the qdata shape: {tuple(y.qdata.shape)} != {tuple(x.qdata.shape)}" | ||
| 72 | + ) | ||
| 73 | + assert torch.equal(y.qdata.view(torch.uint8), x.qdata.view(torch.uint8)), f"{name} changed the qdata values" | ||
| 74 | + | ||
| 75 | + assert y.scale.shape == x.scale.shape, ( | ||
| 76 | + f"{name} changed the scale shape: {tuple(y.scale.shape)} != {tuple(x.scale.shape)}" | ||
| 77 | + ) | ||
| 78 | + assert torch.equal(y.scale.view(torch.uint8), x.scale.view(torch.uint8)), f"{name} changed the scale values" | ||
| 79 | + | ||
| 80 | + assert y.quant_axis == x.quant_axis | ||
| 81 | + assert y.quant_config is x.quant_config | ||
| 82 | + assert y.orig_dtype is x.orig_dtype | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def test_flatten_unflatten_round_trip(): | ||
| 86 | + """The declared name lists are the serialization contract DCP relies on.""" | ||
| 87 | + config = MXQuantizeConfig(elem_dtype=torch.float4_e2m1fn_x2) | ||
| 88 | + act_config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 89 | + qdata = torch.randint(0, 256, (4, 32), dtype=torch.uint8).view(torch.float4_e2m1fn_x2) | ||
| 90 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 91 | + x = MXTensor(qdata, scale, torch.bfloat16, -1, config, act_quant_config=act_config, pack_axis=-1) | ||
| 92 | + | ||
| 93 | + data_names, attributes = x.__tensor_flatten__() | ||
| 94 | + data = {name: getattr(x, name) for name in data_names} | ||
| 95 | + y = type(x).__tensor_unflatten__(data, attributes, None, None) | ||
| 96 | + | ||
| 97 | + assert data_names == ["qdata", "scale"] | ||
| 98 | + assert set(attributes) == {"orig_dtype", "quant_axis", "quant_config", "act_quant_config", "pack_axis"} | ||
| 99 | + assert y.qdata.shape == x.qdata.shape, ( | ||
| 100 | + f"unflattened qdata shape {tuple(y.qdata.shape)} != the original {tuple(x.qdata.shape)}" | ||
| 101 | + ) | ||
| 102 | + assert torch.equal(y.qdata.view(torch.uint8), x.qdata.view(torch.uint8)), ( | ||
| 103 | + "unflattened qdata values differ from the original" | ||
| 104 | + ) | ||
| 105 | + | ||
| 106 | + assert y.scale.shape == x.scale.shape, ( | ||
| 107 | + f"unflattened scale shape {tuple(y.scale.shape)} != the original {tuple(x.scale.shape)}" | ||
| 108 | + ) | ||
| 109 | + assert torch.equal(y.scale.view(torch.uint8), x.scale.view(torch.uint8)), ( | ||
| 110 | + "unflattened scale values differ from the original" | ||
| 111 | + ) | ||
| 112 | + | ||
| 113 | + assert y.quant_axis == x.quant_axis | ||
| 114 | + assert y.pack_axis == x.pack_axis | ||
| 115 | + assert y.act_quant_config is x.act_quant_config | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +@pytest.mark.parametrize("shape", [(4, 64), (2, 4, 64)]) | ||
| 119 | +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32]) | ||
| 120 | +def test_to_dtype_changes_only_the_logical_dtype(shape, dtype): | ||
| 121 | + """``.to(dtype)`` retags the tensor; the stored quantization is shared, not cast.""" | ||
| 122 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 123 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 124 | + scale = torch.full((*shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 125 | + x = MXTensor(qdata, scale, torch.bfloat16, -1, config) | ||
| 126 | + | ||
| 127 | + y = x.to(dtype) | ||
| 128 | + | ||
| 129 | + assert y.dtype is dtype, f".to({dtype}) left the logical dtype at {y.dtype}" | ||
| 130 | + assert y.orig_dtype is dtype, f".to({dtype}) left orig_dtype at {y.orig_dtype}" | ||
| 131 | + assert y.qdata is x.qdata, f".to({dtype}) cast the stored qdata" | ||
| 132 | + assert y.scale is x.scale, f".to({dtype}) cast the stored scale" | ||
| 133 | + assert x.dtype is torch.bfloat16, f".to({dtype}) changed the original's dtype to {x.dtype}" | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +@pytest.mark.parametrize("shape", [(4, 64), (2, 4, 64)]) | ||
| 137 | +def test_to_dtype_chains(shape): | ||
| 138 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 139 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 140 | + scale = torch.full((*shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 141 | + x = MXTensor(qdata, scale, torch.bfloat16, -1, config) | ||
| 142 | + | ||
| 143 | + y = x.to(torch.float32).to(torch.float16) | ||
| 144 | + | ||
| 145 | + assert y.dtype is torch.float16, f"chained .to calls ended at {y.dtype}, expected torch.float16" | ||
| 146 | + | ||
| 147 | + | ||
| 148 | +@pytest.mark.parametrize("dtype", [torch.float64, torch.int64, torch.float8_e4m3fn]) | ||
| 149 | +def test_to_unsupported_dtype_raises(dtype): | ||
| 150 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 151 | + qdata = torch.randn((4, 64)).to(torch.float8_e4m3fn) | ||
| 152 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 153 | + x = MXTensor(qdata, scale, torch.bfloat16, -1, config) | ||
| 154 | + | ||
| 155 | + with pytest.raises(ValueError, match="only supports the logical dtypes"): | ||
| 156 | + x.to(dtype) | ||
| 157 | + | ||
| 158 | + | ||
| 159 | +@pytest.mark.parametrize("shape", [(4, 64), (2, 4, 64)]) | ||
| 160 | +def test_to_same_dtype_is_a_no_op(shape): | ||
| 161 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 162 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 163 | + scale = torch.full((*shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 164 | + x = MXTensor(qdata, scale, torch.bfloat16, -1, config) | ||
| 165 | + | ||
| 166 | + y = x.to(torch.bfloat16) | ||
| 167 | + | ||
| 168 | + assert y.dtype is torch.bfloat16, f".to(same dtype) ended at {y.dtype}" | ||
| 169 | + | ||
| 170 | + | ||
| 171 | +@pytest.mark.parametrize("shape", [(4, 64), (2, 4, 64)]) | ||
| 172 | +def test_to_device_moves_the_components(shape): | ||
| 173 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 174 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 175 | + scale = torch.full((*shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 176 | + x = MXTensor(qdata, scale, torch.bfloat16, -1, config) | ||
| 177 | + | ||
| 178 | + y = x.to("npu") | ||
| 179 | + | ||
| 180 | + assert y.qdata.device.type == "npu", f".to('npu') left qdata on {y.qdata.device}" | ||
| 181 | + assert y.scale.device.type == "npu", f".to('npu') left scale on {y.scale.device}" | ||
| 182 | + assert y.dtype is x.dtype, f".to('npu') changed the logical dtype to {y.dtype}" | ||
| 183 | + assert x.qdata.device.type == "cpu", f".to('npu') moved the original's qdata to {x.qdata.device}" | ||
| 184 | + | ||
| 185 | + # the move must not alter the values: moving the plain components ourselves | ||
| 186 | + # (bypassing MXTensor's handler) has to reproduce y's components exactly | ||
| 187 | + moved_qdata = qdata.to(y.qdata.device) | ||
| 188 | + assert torch.equal(y.qdata.view(torch.uint8), moved_qdata.view(torch.uint8)), ".to('npu') changed the qdata values" | ||
| 189 | + | ||
| 190 | + moved_scale = scale.to(y.scale.device) | ||
| 191 | + assert torch.equal(y.scale.view(torch.uint8), moved_scale.view(torch.uint8)), ".to('npu') changed the scale values" | ||
| 192 | + | ||
| 193 | + | ||
| 194 | +@pytest.mark.parametrize("shape", [(4, 64), (2, 4, 64)]) | ||
| 195 | +def test_to_dtype_requires_the_class_to_declare_orig_dtype(shape): | ||
| 196 | + """``.to(dtype)`` swaps ``orig_dtype``, so a subclass has to declare it.""" | ||
| 197 | + | ||
| 198 | + class _NoOrigDtype(MXTensor): | ||
| 199 | + tensor_attribute_names = ["quant_axis", "quant_config", "act_quant_config"] | ||
| 200 | + | ||
| 201 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 202 | + qdata = torch.randn(shape).to(torch.float8_e4m3fn) | ||
| 203 | + scale = torch.full((*shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 204 | + x = _NoOrigDtype(qdata, scale, torch.bfloat16, -1, config) | ||
| 205 | + | ||
| 206 | + with pytest.raises(RuntimeError, match="must declare"): | ||
| 207 | + x.to(torch.float32) | ||
| @@ -0,0 +1,357 @@ | |||
| 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 | +"""Tests for :class:`torchao_npu.quantized_tensors.block_mx_tensor.BlockMXTensor`.""" | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | +import torch_npu # noqa: F401 | ||
| 11 | +from torchao_npu.quantization.quant_configs import BlockMXQuantizeConfig, MXQuantizeConfig | ||
| 12 | +from torchao_npu.quantization.quant_primitives.block_mx import block_mx_quantize | ||
| 13 | +from torchao_npu.quantized_tensors.block_mx_tensor import BlockMXTensor | ||
| 14 | + | ||
| 15 | +# ========================================================================= | ||
| 16 | +# Construction and validation | ||
| 17 | +# ========================================================================= | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def test_construction(): | ||
| 21 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 22 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 23 | + scale1 = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) # [..., R, R_blocks, 2] | ||
| 24 | + scale2 = torch.full((1, 64, 2), 4.0, dtype=torch.float8_e8m0fnu) # [..., C_blocks, C, 2] | ||
| 25 | + | ||
| 26 | + x = BlockMXTensor(qdata, scale1, scale2, torch.bfloat16, config) | ||
| 27 | + | ||
| 28 | + assert x.shape == torch.Size([4, 64]) | ||
| 29 | + assert x.dtype is torch.bfloat16 | ||
| 30 | + assert x.pack_axis is None | ||
| 31 | + assert x.quant_config is config | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +@pytest.mark.parametrize( | ||
| 35 | + "qdata, pack_axis, expected_shape, expected_pack_axis", | ||
| 36 | + [ | ||
| 37 | + ( | ||
| 38 | + torch.randint(0, 256, (4, 32), dtype=torch.uint8).view(torch.float4_e2m1fn_x2), | ||
| 39 | + -1, | ||
| 40 | + (4, 64), | ||
| 41 | + 1, | ||
| 42 | + ), | ||
| 43 | + ( | ||
| 44 | + torch.randint(0, 256, (128, 8), dtype=torch.uint8).view(torch.float4_e2m1fn_x2).t(), | ||
| 45 | + 0, | ||
| 46 | + (16, 128), | ||
| 47 | + 0, | ||
| 48 | + ), | ||
| 49 | + ], | ||
| 50 | + ids=["packed-on-the-last-dim", "packed-on-the-first-dim"], | ||
| 51 | +) | ||
| 52 | +def test_fp4_construction_doubles_the_packed_dim(qdata, pack_axis, expected_shape, expected_pack_axis): | ||
| 53 | + """The packed dim is whichever the qdata is unit-stride on, not necessarily the last one.""" | ||
| 54 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float4_e2m1fn_x2) | ||
| 55 | + scale1 = torch.full((*qdata.shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 56 | + scale2 = torch.full((*qdata.shape[:-2], 1, qdata.shape[-1], 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 57 | + | ||
| 58 | + x = BlockMXTensor(qdata, scale1, scale2, torch.bfloat16, config, pack_axis=pack_axis) | ||
| 59 | + | ||
| 60 | + assert x.shape == torch.Size(expected_shape), f"logical shape {tuple(x.shape)} != {tuple(expected_shape)}" | ||
| 61 | + assert x.pack_axis == expected_pack_axis, f"pack axis tracked as {x.pack_axis}, expected {expected_pack_axis}" | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def test_construction_rejects_scale_with_wrong_ndim(): | ||
| 65 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 66 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 67 | + scale1 = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 68 | + scale2 = torch.full((1, 64, 1, 2), 4.0, dtype=torch.float8_e8m0fnu) # one rank too deep | ||
| 69 | + | ||
| 70 | + with pytest.raises(ValueError, match="scale1/scale2 ndim must be"): | ||
| 71 | + BlockMXTensor(qdata, scale1, scale2, torch.bfloat16, config) | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +def test_construction_rejects_1d_qdata(): | ||
| 75 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 76 | + qdata = torch.randn(64).to(torch.float8_e4m3fn) | ||
| 77 | + scale = torch.full((64, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 78 | + | ||
| 79 | + with pytest.raises(ValueError, match=r"requires qdata.ndim >= 2"): | ||
| 80 | + BlockMXTensor(qdata, scale, scale, torch.bfloat16, config) | ||
| 81 | + | ||
| 82 | + | ||
| 83 | +@pytest.mark.parametrize( | ||
| 84 | + "qdata_dtype, config_dtype, expected_error, expected_message", | ||
| 85 | + [ | ||
| 86 | + # qdata dtypes this class does not store | ||
| 87 | + (torch.bfloat16, torch.float8_e4m3fn, ValueError, "supports FP8 or FP4 qdata"), | ||
| 88 | + (torch.float32, torch.float4_e2m1fn_x2, ValueError, "supports FP8 or FP4 qdata"), | ||
| 89 | + # supported dtypes that disagree with the config | ||
| 90 | + (torch.float8_e4m3fn, torch.float8_e5m2, AssertionError, "is not consistent with"), | ||
| 91 | + (torch.float8_e4m3fn, torch.float4_e2m1fn_x2, AssertionError, "is not consistent with"), | ||
| 92 | + (torch.float8_e5m2, torch.float8_e4m3fn, AssertionError, "is not consistent with"), | ||
| 93 | + (torch.float8_e5m2, torch.float4_e2m1fn_x2, AssertionError, "is not consistent with"), | ||
| 94 | + (torch.float4_e2m1fn_x2, torch.float8_e4m3fn, AssertionError, "is not consistent with"), | ||
| 95 | + (torch.float4_e2m1fn_x2, torch.float8_e5m2, AssertionError, "is not consistent with"), | ||
| 96 | + ], | ||
| 97 | +) | ||
| 98 | +def test_construction_rejects_qdata_dtype_mismatch(qdata_dtype, config_dtype, expected_error, expected_message): | ||
| 99 | + """Every (qdata dtype, config elem_dtype) pair outside the three matching ones.""" | ||
| 100 | + if qdata_dtype is torch.float4_e2m1fn_x2: | ||
| 101 | + qdata = torch.randint(0, 256, (4, 32), dtype=torch.uint8).view(torch.float4_e2m1fn_x2) | ||
| 102 | + pack_axis = -1 # FP4 data cannot even be described without its pack axis | ||
| 103 | + else: | ||
| 104 | + qdata = torch.randn(4, 64).to(qdata_dtype) | ||
| 105 | + pack_axis = None | ||
| 106 | + config = BlockMXQuantizeConfig(elem_dtype=config_dtype) | ||
| 107 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 108 | + | ||
| 109 | + with pytest.raises(expected_error, match=expected_message): | ||
| 110 | + BlockMXTensor(qdata, scale, scale, torch.bfloat16, config, pack_axis=pack_axis) | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def test_construction_rejects_pack_axis_on_non_fp4(): | ||
| 114 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 115 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 116 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 117 | + | ||
| 118 | + with pytest.raises(ValueError, match="non-FP4 tensor are not packed"): | ||
| 119 | + BlockMXTensor(qdata, scale, scale, torch.bfloat16, config, pack_axis=1) | ||
| 120 | + | ||
| 121 | + | ||
| 122 | +# ========================================================================= | ||
| 123 | +# Axis-preserving shape ops | ||
| 124 | +# ========================================================================= | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +def test_permute_keeps_content_and_leading_dims(): | ||
| 128 | + """Leading dims permute freely; the trailing two stay trailing.""" | ||
| 129 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 130 | + qdata = torch.randn(2, 3, 4, 64).to(torch.float8_e4m3fn) | ||
| 131 | + scale1 = torch.full((2, 3, 4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 132 | + scale2 = torch.full((2, 3, 1, 64, 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 133 | + x = BlockMXTensor(qdata, scale1, scale2, torch.bfloat16, config) | ||
| 134 | + perm = [1, 0, 2, 3] | ||
| 135 | + | ||
| 136 | + y = x.permute(perm) | ||
| 137 | + | ||
| 138 | + expected_qdata = x.qdata.permute(perm) | ||
| 139 | + assert y.qdata.shape == expected_qdata.shape, ( | ||
| 140 | + f"permuted qdata shape {tuple(y.qdata.shape)} != the expected {tuple(expected_qdata.shape)}" | ||
| 141 | + ) | ||
| 142 | + assert torch.equal(y.qdata.view(torch.uint8), expected_qdata.view(torch.uint8)), ( | ||
| 143 | + "permuted qdata values differ from the permuted original" | ||
| 144 | + ) | ||
| 145 | + | ||
| 146 | + expected_scale1 = x.scale1.permute([*perm, x.scale1.ndim - 1]) | ||
| 147 | + assert y.scale1.shape == expected_scale1.shape, ( | ||
| 148 | + f"permuted scale1 shape {tuple(y.scale1.shape)} != the expected {tuple(expected_scale1.shape)}" | ||
| 149 | + ) | ||
| 150 | + assert torch.equal(y.scale1.view(torch.uint8), expected_scale1.view(torch.uint8)), ( | ||
| 151 | + "permuted scale1 values differ from the permuted original" | ||
| 152 | + ) | ||
| 153 | + | ||
| 154 | + expected_scale2 = x.scale2.permute([*perm, x.scale2.ndim - 1]) | ||
| 155 | + assert y.scale2.shape == expected_scale2.shape, ( | ||
| 156 | + f"permuted scale2 shape {tuple(y.scale2.shape)} != the expected {tuple(expected_scale2.shape)}" | ||
| 157 | + ) | ||
| 158 | + assert torch.equal(y.scale2.view(torch.uint8), expected_scale2.view(torch.uint8)), ( | ||
| 159 | + "permuted scale2 values differ from the permuted original" | ||
| 160 | + ) | ||
| 161 | + | ||
| 162 | + | ||
| 163 | +def test_swap_transposes_qdata_and_exchanges_the_two_scales(): | ||
| 164 | + """A swap transposes qdata and swaps the scales' roles -- content, not just shape.""" | ||
| 165 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 166 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 167 | + scale1 = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 168 | + scale2 = torch.full((1, 64, 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 169 | + x = BlockMXTensor(qdata, scale1, scale2, torch.bfloat16, config) | ||
| 170 | + | ||
| 171 | + y = x.transpose(-1, -2) | ||
| 172 | + | ||
| 173 | + assert y.shape == torch.Size([64, 4]), f"swapped shape {tuple(y.shape)} != torch.Size([64, 4])" | ||
| 174 | + | ||
| 175 | + expected_qdata = x.qdata.transpose(-1, -2) | ||
| 176 | + assert y.qdata.shape == expected_qdata.shape, ( | ||
| 177 | + f"swapped qdata shape {tuple(y.qdata.shape)} != the expected {tuple(expected_qdata.shape)}" | ||
| 178 | + ) | ||
| 179 | + assert torch.equal(y.qdata.view(torch.uint8), expected_qdata.view(torch.uint8)), ( | ||
| 180 | + "swapped qdata values differ from the transposed original" | ||
| 181 | + ) | ||
| 182 | + | ||
| 183 | + expected_scale1 = x.scale2.transpose(0, 1) # the two scales trade roles | ||
| 184 | + assert y.scale1.shape == expected_scale1.shape, ( | ||
| 185 | + f"swapped scale1 shape {tuple(y.scale1.shape)} != the original scale2's {tuple(expected_scale1.shape)}" | ||
| 186 | + ) | ||
| 187 | + assert torch.equal(y.scale1.view(torch.uint8), expected_scale1.view(torch.uint8)), ( | ||
| 188 | + "swapped scale1 values differ from the original scale2" | ||
| 189 | + ) | ||
| 190 | + | ||
| 191 | + expected_scale2 = x.scale1.transpose(0, 1) | ||
| 192 | + assert y.scale2.shape == expected_scale2.shape, ( | ||
| 193 | + f"swapped scale2 shape {tuple(y.scale2.shape)} != the original scale1's {tuple(expected_scale2.shape)}" | ||
| 194 | + ) | ||
| 195 | + assert torch.equal(y.scale2.view(torch.uint8), expected_scale2.view(torch.uint8)), ( | ||
| 196 | + "swapped scale2 values differ from the original scale1" | ||
| 197 | + ) | ||
| 198 | + | ||
| 199 | + | ||
| 200 | +def test_permute_rejects_moving_the_last_two_dims_away(): | ||
| 201 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 202 | + qdata = torch.randn(2, 4, 64).to(torch.float8_e4m3fn) | ||
| 203 | + scale = torch.full((2, 4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 204 | + x = BlockMXTensor(qdata, scale, scale, torch.bfloat16, config) | ||
| 205 | + | ||
| 206 | + with pytest.raises(ValueError, match="keep the last two dims trailing"): | ||
| 207 | + x.permute([2, 0, 1]) | ||
| 208 | + | ||
| 209 | + | ||
| 210 | +def test_t_is_a_swap_on_2d(): | ||
| 211 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 212 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 213 | + scale1 = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 214 | + scale2 = torch.full((1, 64, 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 215 | + x = BlockMXTensor(qdata, scale1, scale2, torch.bfloat16, config) | ||
| 216 | + | ||
| 217 | + y = x.t() | ||
| 218 | + expected = x.transpose(0, 1) | ||
| 219 | + | ||
| 220 | + assert y.qdata.shape == expected.qdata.shape, ( | ||
| 221 | + f"t() gave qdata shape {tuple(y.qdata.shape)}, transpose(0, 1) gave {tuple(expected.qdata.shape)}" | ||
| 222 | + ) | ||
| 223 | + assert torch.equal(y.qdata.view(torch.uint8), expected.qdata.view(torch.uint8)), ( | ||
| 224 | + "t() and transpose(0, 1) produced different qdata values" | ||
| 225 | + ) | ||
| 226 | + | ||
| 227 | + assert y.scale1.shape == expected.scale1.shape, ( | ||
| 228 | + f"t() gave scale1 shape {tuple(y.scale1.shape)}, transpose(0, 1) gave {tuple(expected.scale1.shape)}" | ||
| 229 | + ) | ||
| 230 | + assert torch.equal(y.scale1.view(torch.uint8), expected.scale1.view(torch.uint8)), ( | ||
| 231 | + "t() and transpose(0, 1) produced different scale1 values" | ||
| 232 | + ) | ||
| 233 | + | ||
| 234 | + | ||
| 235 | +def test_t_rejects_more_than_2d(): | ||
| 236 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 237 | + qdata = torch.randn(2, 4, 64).to(torch.float8_e4m3fn) | ||
| 238 | + scale = torch.full((2, 4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 239 | + x = BlockMXTensor(qdata, scale, scale, torch.bfloat16, config) | ||
| 240 | + | ||
| 241 | + with pytest.raises(RuntimeError, match="expects a tensor with <= 2 dimensions"): | ||
| 242 | + x.t() | ||
| 243 | + | ||
| 244 | + | ||
| 245 | +# ========================================================================= | ||
| 246 | +# Conversion to the single-axis MXTensor | ||
| 247 | +# ========================================================================= | ||
| 248 | + | ||
| 249 | + | ||
| 250 | +@pytest.mark.parametrize( | ||
| 251 | + "qdata, pack_axis", | ||
| 252 | + [ | ||
| 253 | + (torch.randn(4, 64).to(torch.float8_e4m3fn), None), | ||
| 254 | + (torch.randint(0, 256, (4, 32), dtype=torch.uint8).view(torch.float4_e2m1fn_x2), -1), | ||
| 255 | + ], | ||
| 256 | + ids=["fp8", "fp4"], | ||
| 257 | +) | ||
| 258 | +@pytest.mark.parametrize("quant_axis, use_scale1", [(1, True), (0, False)]) | ||
| 259 | +def test_to_mx_tensor_shares_components(qdata, pack_axis, quant_axis, use_scale1): | ||
| 260 | + config = BlockMXQuantizeConfig(elem_dtype=qdata.dtype) | ||
| 261 | + scale1 = torch.full((*qdata.shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 262 | + scale2 = torch.full((*qdata.shape[:-2], 1, qdata.shape[-1], 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 263 | + x = BlockMXTensor(qdata, scale1, scale2, torch.bfloat16, config, pack_axis=pack_axis) | ||
| 264 | + | ||
| 265 | + y = x.to_mx_tensor(quant_axis) | ||
| 266 | + | ||
| 267 | + assert y.quant_axis == quant_axis, f"quantized along {y.quant_axis}, expected {quant_axis}" | ||
| 268 | + assert y.pack_axis == x.pack_axis, f"pack axis {y.pack_axis} != the source's {x.pack_axis}" | ||
| 269 | + assert y.qdata is x.qdata, "the converted tensor must share qdata, not copy it" | ||
| 270 | + | ||
| 271 | + expected_scale = x.scale1 if use_scale1 else x.scale2 | ||
| 272 | + assert y.scale is expected_scale, f"quantized along {quant_axis} must use the matching scale" | ||
| 273 | + | ||
| 274 | + assert type(y.quant_config) is MXQuantizeConfig, ( | ||
| 275 | + f"quant_config type {type(y.quant_config).__name__}, expected MXQuantizeConfig" | ||
| 276 | + ) | ||
| 277 | + | ||
| 278 | + | ||
| 279 | +def test_to_mx_tensor_rejects_other_axes(): | ||
| 280 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 281 | + qdata = torch.randn(2, 4, 64).to(torch.float8_e4m3fn) | ||
| 282 | + scale = torch.full((2, 4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 283 | + x = BlockMXTensor(qdata, scale, scale, torch.bfloat16, config) | ||
| 284 | + | ||
| 285 | + with pytest.raises(ValueError, match="Only the last two dims are supported"): | ||
| 286 | + x.to_mx_tensor(0) | ||
| 287 | + | ||
| 288 | + | ||
| 289 | +# ========================================================================= | ||
| 290 | +# Inherited behavior | ||
| 291 | +# ========================================================================= | ||
| 292 | + | ||
| 293 | + | ||
| 294 | +def test_to_dtype_changes_only_the_logical_dtype(): | ||
| 295 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 296 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 297 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 298 | + x = BlockMXTensor(qdata, scale, scale, torch.bfloat16, config) | ||
| 299 | + | ||
| 300 | + y = x.to(torch.float32) | ||
| 301 | + | ||
| 302 | + assert y.dtype is torch.float32, f".to(torch.float32) left the logical dtype at {y.dtype}" | ||
| 303 | + assert y.qdata is x.qdata, ".to(dtype) cast the stored qdata" | ||
| 304 | + | ||
| 305 | + | ||
| 306 | +def test_values_are_frozen(): | ||
| 307 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 308 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 309 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 310 | + x = BlockMXTensor(qdata, scale, scale, torch.bfloat16, config) | ||
| 311 | + | ||
| 312 | + with pytest.raises(RuntimeError, match="immutable"): | ||
| 313 | + x.zero_() | ||
| 314 | + | ||
| 315 | + | ||
| 316 | +def test_matmul_is_not_supported(): | ||
| 317 | + """Matmul is whitelisted for MXTensor only.""" | ||
| 318 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 319 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 320 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 321 | + x = BlockMXTensor(qdata, scale, scale, torch.bfloat16, config) | ||
| 322 | + | ||
| 323 | + with pytest.raises(NotImplementedError): | ||
| 324 | + torch.mm(x, x) | ||
| 325 | + | ||
| 326 | + | ||
| 327 | +# ========================================================================= | ||
| 328 | +# Quantization against the primitive (NPU kernels) | ||
| 329 | +# ========================================================================= | ||
| 330 | + | ||
| 331 | + | ||
| 332 | +def test_from_hp_matches_block_mx_quantize(): | ||
| 333 | + config = BlockMXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 334 | + x = torch.randn(64, 128, device="npu", dtype=torch.bfloat16) | ||
| 335 | + | ||
| 336 | + y = BlockMXTensor.from_hp(x, config) | ||
| 337 | + qdata, scale1, scale2 = block_mx_quantize(x, config) | ||
| 338 | + | ||
| 339 | + assert y.shape == x.shape, f"quantized shape {tuple(y.shape)} != the input's {tuple(x.shape)}" | ||
| 340 | + assert y.pack_axis is None, f"FP8 needs no pack axis, got {y.pack_axis}" | ||
| 341 | + | ||
| 342 | + assert y.qdata.shape == qdata.shape, f"qdata shape {tuple(y.qdata.shape)} != the primitive's {tuple(qdata.shape)}" | ||
| 343 | + assert torch.equal(y.qdata.view(torch.uint8), qdata.view(torch.uint8)), "qdata values differ from the primitive's" | ||
| 344 | + | ||
| 345 | + assert y.scale1.shape == scale1.shape, ( | ||
| 346 | + f"scale1 shape {tuple(y.scale1.shape)} != the primitive's {tuple(scale1.shape)}" | ||
| 347 | + ) | ||
| 348 | + assert torch.equal(y.scale1.view(torch.uint8), scale1.view(torch.uint8)), ( | ||
| 349 | + "scale1 values differ from the primitive's" | ||
| 350 | + ) | ||
| 351 | + | ||
| 352 | + assert y.scale2.shape == scale2.shape, ( | ||
| 353 | + f"scale2 shape {tuple(y.scale2.shape)} != the primitive's {tuple(scale2.shape)}" | ||
| 354 | + ) | ||
| 355 | + assert torch.equal(y.scale2.view(torch.uint8), scale2.view(torch.uint8)), ( | ||
| 356 | + "scale2 values differ from the primitive's" | ||
| 357 | + ) | ||
| @@ -0,0 +1,456 @@ | |||
| 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 | +"""Tests for :class:`torchao_npu.quantized_tensors.dual_axis_mx_tensor.DualAxisMXTensor`.""" | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | +import torch_npu # noqa: F401 | ||
| 11 | +from torchao_npu import normalize_dim | ||
| 12 | +from torchao_npu.quantization.quant_configs import MXQuantizeConfig | ||
| 13 | +from torchao_npu.quantization.quant_primitives.mx import mx_quantize_dual_axis | ||
| 14 | +from torchao_npu.quantized_tensors.dual_axis_mx_tensor import DualAxisMXTensor | ||
| 15 | +from torchao_npu.quantized_tensors.mx_tensor import MXTensor | ||
| 16 | + | ||
| 17 | +# ========================================================================= | ||
| 18 | +# Construction and validation | ||
| 19 | +# ========================================================================= | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +@pytest.mark.parametrize( | ||
| 23 | + "qdata1, qdata2, pack_axis", | ||
| 24 | + [ | ||
| 25 | + # distinguishable content: the two pairs trade roles on a swap | ||
| 26 | + ( | ||
| 27 | + torch.full((4, 64), 1.0, dtype=torch.bfloat16).to(torch.float8_e4m3fn), | ||
| 28 | + torch.full((4, 64), 2.0, dtype=torch.bfloat16).to(torch.float8_e4m3fn), | ||
| 29 | + None, | ||
| 30 | + ), | ||
| 31 | + ( | ||
| 32 | + torch.randint(0, 256, (4, 32), dtype=torch.uint8).view(torch.float4_e2m1fn_x2), | ||
| 33 | + torch.randint(0, 256, (4, 32), dtype=torch.uint8).view(torch.float4_e2m1fn_x2), | ||
| 34 | + -1, | ||
| 35 | + ), | ||
| 36 | + ], | ||
| 37 | + ids=["fp8", "fp4"], | ||
| 38 | +) | ||
| 39 | +def test_construction(qdata1, qdata2, pack_axis): | ||
| 40 | + config = MXQuantizeConfig(elem_dtype=qdata1.dtype) | ||
| 41 | + scale1 = torch.full((*qdata1.shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) # [..., R, R_blocks, 2] | ||
| 42 | + scale2 = torch.full((*qdata1.shape[:-2], 1, qdata1.shape[-1], 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 43 | + | ||
| 44 | + expected_pack_axis = normalize_dim(pack_axis, qdata1.ndim) if pack_axis is not None else None | ||
| 45 | + | ||
| 46 | + x = DualAxisMXTensor(qdata1, scale1, qdata2, scale2, torch.bfloat16, config, pack_axis=pack_axis) | ||
| 47 | + | ||
| 48 | + assert x.shape == torch.Size([4, 64]), f"logical shape {tuple(x.shape)} != (4, 64)" | ||
| 49 | + assert x.dtype is torch.bfloat16, f"logical dtype {x.dtype} != torch.bfloat16" | ||
| 50 | + assert x.pack_axis == expected_pack_axis, f"pack axis tracked as {x.pack_axis}, expected {expected_pack_axis}" | ||
| 51 | + assert x.quant_config is config, "the config must be stored as passed" | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +@pytest.mark.parametrize( | ||
| 55 | + "qdata1, qdata2, pack_axis, expected_shape, expected_pack_axis", | ||
| 56 | + [ | ||
| 57 | + ( | ||
| 58 | + torch.randint(0, 256, (4, 32), dtype=torch.uint8).view(torch.float4_e2m1fn_x2), | ||
| 59 | + torch.randint(0, 256, (4, 32), dtype=torch.uint8).view(torch.float4_e2m1fn_x2), | ||
| 60 | + -1, | ||
| 61 | + (4, 64), | ||
| 62 | + 1, | ||
| 63 | + ), | ||
| 64 | + ( | ||
| 65 | + torch.randint(0, 256, (128, 8), dtype=torch.uint8).view(torch.float4_e2m1fn_x2).t(), | ||
| 66 | + torch.randint(0, 256, (128, 8), dtype=torch.uint8).view(torch.float4_e2m1fn_x2).t(), | ||
| 67 | + 0, | ||
| 68 | + (16, 128), | ||
| 69 | + 0, | ||
| 70 | + ), | ||
| 71 | + ], | ||
| 72 | + ids=["packed-on-the-last-dim", "packed-on-the-first-dim"], | ||
| 73 | +) | ||
| 74 | +def test_fp4_construction_doubles_the_packed_dim(qdata1, qdata2, pack_axis, expected_shape, expected_pack_axis): | ||
| 75 | + """Both qdata pack the same dim, which need not be the last one.""" | ||
| 76 | + config = MXQuantizeConfig(elem_dtype=torch.float4_e2m1fn_x2) | ||
| 77 | + scale1 = torch.full((*qdata1.shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 78 | + scale2 = torch.full((*qdata1.shape[:-2], 1, qdata1.shape[-1], 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 79 | + | ||
| 80 | + x = DualAxisMXTensor(qdata1, scale1, qdata2, scale2, torch.bfloat16, config, pack_axis=pack_axis) | ||
| 81 | + | ||
| 82 | + assert x.shape == torch.Size(expected_shape), f"logical shape {tuple(x.shape)} != {tuple(expected_shape)}" | ||
| 83 | + assert x.pack_axis == expected_pack_axis, f"pack axis tracked as {x.pack_axis}, expected {expected_pack_axis}" | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +def test_construction_rejects_mismatched_qdata_dtypes(): | ||
| 87 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 88 | + qdata1 = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 89 | + qdata2 = qdata1.to(torch.float8_e5m2) | ||
| 90 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 91 | + | ||
| 92 | + with pytest.raises(ValueError, match="must share a dtype"): | ||
| 93 | + DualAxisMXTensor(qdata1, scale, qdata2, scale, torch.bfloat16, config) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def test_construction_requires_qdata_to_agree_on_the_logical_shape(): | ||
| 97 | + """Both qdata describe one logical tensor, so their shapes must match.""" | ||
| 98 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 99 | + qdata1 = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 100 | + qdata2 = torch.randn(4, 32).to(torch.float8_e4m3fn) | ||
| 101 | + scale1 = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 102 | + scale2 = torch.full((4, 1, 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 103 | + | ||
| 104 | + with pytest.raises(ValueError, match="same logical shape"): | ||
| 105 | + DualAxisMXTensor(qdata1, scale1, qdata2, scale2, torch.bfloat16, config) | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def test_construction_rejects_scale_with_wrong_ndim(): | ||
| 109 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 110 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 111 | + scale1 = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 112 | + scale2 = torch.full((1, 64, 1, 2), 4.0, dtype=torch.float8_e8m0fnu) # one rank too deep | ||
| 113 | + | ||
| 114 | + with pytest.raises(ValueError, match="scale1/scale2 ndim must be"): | ||
| 115 | + DualAxisMXTensor(qdata, scale1, qdata, scale2, torch.bfloat16, config) | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +def test_construction_rejects_1d_qdata(): | ||
| 119 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 120 | + qdata = torch.randn(64).to(torch.float8_e4m3fn) | ||
| 121 | + scale = torch.full((64, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 122 | + | ||
| 123 | + with pytest.raises(ValueError, match=r"requires qdata.ndim >= 2"): | ||
| 124 | + DualAxisMXTensor(qdata, scale, qdata, scale, torch.bfloat16, config) | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +def test_construction_rejects_pack_axis_on_non_fp4(): | ||
| 128 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 129 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 130 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 131 | + | ||
| 132 | + with pytest.raises(ValueError, match="non-FP4 tensor are not packed"): | ||
| 133 | + DualAxisMXTensor(qdata, scale, qdata, scale, torch.bfloat16, config, pack_axis=1) | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +# ========================================================================= | ||
| 137 | +# Axis-preserving shape ops | ||
| 138 | +# ========================================================================= | ||
| 139 | + | ||
| 140 | + | ||
| 141 | +def test_permute_keeps_content_and_leading_dims(): | ||
| 142 | + """Leading dims permute freely; the trailing two stay trailing.""" | ||
| 143 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 144 | + qdata1 = torch.randn(2, 3, 4, 64).to(torch.float8_e4m3fn) | ||
| 145 | + qdata2 = torch.randn(2, 3, 4, 64).to(torch.float8_e4m3fn) | ||
| 146 | + scale1 = torch.full((2, 3, 4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 147 | + scale2 = torch.full((2, 3, 1, 64, 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 148 | + x = DualAxisMXTensor(qdata1, scale1, qdata2, scale2, torch.bfloat16, config) | ||
| 149 | + perm = [1, 0, 2, 3] | ||
| 150 | + | ||
| 151 | + y = x.permute(perm) | ||
| 152 | + | ||
| 153 | + expected_qdata1 = x.qdata1.permute(perm) | ||
| 154 | + assert y.qdata1.shape == expected_qdata1.shape, ( | ||
| 155 | + f"permuted qdata1 shape {tuple(y.qdata1.shape)} != the expected {tuple(expected_qdata1.shape)}" | ||
| 156 | + ) | ||
| 157 | + assert torch.equal(y.qdata1.view(torch.uint8), expected_qdata1.view(torch.uint8)), ( | ||
| 158 | + "permuted qdata1 values differ from the permuted original" | ||
| 159 | + ) | ||
| 160 | + | ||
| 161 | + expected_qdata2 = x.qdata2.permute(perm) | ||
| 162 | + assert y.qdata2.shape == expected_qdata2.shape, ( | ||
| 163 | + f"permuted qdata2 shape {tuple(y.qdata2.shape)} != the expected {tuple(expected_qdata2.shape)}" | ||
| 164 | + ) | ||
| 165 | + assert torch.equal(y.qdata2.view(torch.uint8), expected_qdata2.view(torch.uint8)), ( | ||
| 166 | + "permuted qdata2 values differ from the permuted original" | ||
| 167 | + ) | ||
| 168 | + | ||
| 169 | + expected_scale1 = x.scale1.permute([*perm, x.scale1.ndim - 1]) | ||
| 170 | + assert y.scale1.shape == expected_scale1.shape, ( | ||
| 171 | + f"permuted scale1 shape {tuple(y.scale1.shape)} != the expected {tuple(expected_scale1.shape)}" | ||
| 172 | + ) | ||
| 173 | + assert torch.equal(y.scale1.view(torch.uint8), expected_scale1.view(torch.uint8)), ( | ||
| 174 | + "permuted scale1 values differ from the permuted original" | ||
| 175 | + ) | ||
| 176 | + | ||
| 177 | + expected_scale2 = x.scale2.permute([*perm, x.scale2.ndim - 1]) | ||
| 178 | + assert y.scale2.shape == expected_scale2.shape, ( | ||
| 179 | + f"permuted scale2 shape {tuple(y.scale2.shape)} != the expected {tuple(expected_scale2.shape)}" | ||
| 180 | + ) | ||
| 181 | + assert torch.equal(y.scale2.view(torch.uint8), expected_scale2.view(torch.uint8)), ( | ||
| 182 | + "permuted scale2 values differ from the permuted original" | ||
| 183 | + ) | ||
| 184 | + | ||
| 185 | + | ||
| 186 | +def test_swap_exchanges_the_two_pairs(): | ||
| 187 | + """A swap trades the (qdata, scale) pairs so each keeps the dim it was quantized along.""" | ||
| 188 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 189 | + qdata1 = torch.full((4, 64), 1.0, dtype=torch.bfloat16).to(torch.float8_e4m3fn) | ||
| 190 | + qdata2 = torch.full((4, 64), 2.0, dtype=torch.bfloat16).to(torch.float8_e4m3fn) | ||
| 191 | + scale1 = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 192 | + scale2 = torch.full((1, 64, 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 193 | + x = DualAxisMXTensor(qdata1, scale1, qdata2, scale2, torch.bfloat16, config) | ||
| 194 | + | ||
| 195 | + y = x.transpose(-1, -2) | ||
| 196 | + | ||
| 197 | + assert y.shape == torch.Size([64, 4]), f"swapped shape {tuple(y.shape)} != torch.Size([64, 4])" | ||
| 198 | + | ||
| 199 | + expected_qdata1 = x.qdata2.transpose(-1, -2) | ||
| 200 | + assert y.qdata1.shape == expected_qdata1.shape, ( | ||
| 201 | + f"swapped qdata1 shape {tuple(y.qdata1.shape)} != the original qdata2's {tuple(expected_qdata1.shape)}" | ||
| 202 | + ) | ||
| 203 | + assert torch.equal(y.qdata1.view(torch.uint8), expected_qdata1.view(torch.uint8)), ( | ||
| 204 | + "swapped qdata1 values differ from the original qdata2" | ||
| 205 | + ) | ||
| 206 | + | ||
| 207 | + expected_scale1 = x.scale2.transpose(0, 1) | ||
| 208 | + assert y.scale1.shape == expected_scale1.shape, ( | ||
| 209 | + f"swapped scale1 shape {tuple(y.scale1.shape)} != the original scale2's {tuple(expected_scale1.shape)}" | ||
| 210 | + ) | ||
| 211 | + assert torch.equal(y.scale1.view(torch.uint8), expected_scale1.view(torch.uint8)), ( | ||
| 212 | + "swapped scale1 values differ from the original scale2" | ||
| 213 | + ) | ||
| 214 | + | ||
| 215 | + expected_qdata2 = x.qdata1.transpose(-1, -2) | ||
| 216 | + assert y.qdata2.shape == expected_qdata2.shape, ( | ||
| 217 | + f"swapped qdata2 shape {tuple(y.qdata2.shape)} != the original qdata1's {tuple(expected_qdata2.shape)}" | ||
| 218 | + ) | ||
| 219 | + assert torch.equal(y.qdata2.view(torch.uint8), expected_qdata2.view(torch.uint8)), ( | ||
| 220 | + "swapped qdata2 values differ from the original qdata1" | ||
| 221 | + ) | ||
| 222 | + | ||
| 223 | + expected_scale2 = x.scale1.transpose(0, 1) | ||
| 224 | + assert y.scale2.shape == expected_scale2.shape, ( | ||
| 225 | + f"swapped scale2 shape {tuple(y.scale2.shape)} != the original scale1's {tuple(expected_scale2.shape)}" | ||
| 226 | + ) | ||
| 227 | + assert torch.equal(y.scale2.view(torch.uint8), expected_scale2.view(torch.uint8)), ( | ||
| 228 | + "swapped scale2 values differ from the original scale1" | ||
| 229 | + ) | ||
| 230 | + | ||
| 231 | + | ||
| 232 | +def test_swap_then_to_mx_tensor_pairs_the_quantized_dims(): | ||
| 233 | + """After a swap the pairs must still match the dims they were quantized on.""" | ||
| 234 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 235 | + qdata1 = torch.full((4, 64), 1.0, dtype=torch.bfloat16).to(torch.float8_e4m3fn) | ||
| 236 | + qdata2 = torch.full((4, 64), 2.0, dtype=torch.bfloat16).to(torch.float8_e4m3fn) | ||
| 237 | + scale1 = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 238 | + scale2 = torch.full((1, 64, 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 239 | + x = DualAxisMXTensor(qdata1, scale1, qdata2, scale2, torch.bfloat16, config) | ||
| 240 | + | ||
| 241 | + y = x.transpose(-1, -2) | ||
| 242 | + | ||
| 243 | + # axis -1 of the swapped tensor is the original -2, which qdata2 covered | ||
| 244 | + expected = x.qdata2.transpose(-1, -2) | ||
| 245 | + assert y.to_mx_tensor(-1).qdata.shape == expected.shape, ( | ||
| 246 | + f"swapped to_mx_tensor(-1) qdata shape {tuple(y.to_mx_tensor(-1).qdata.shape)} != {tuple(expected.shape)}" | ||
| 247 | + ) | ||
| 248 | + assert torch.equal(y.to_mx_tensor(-1).qdata.view(torch.uint8), expected.view(torch.uint8)), ( | ||
| 249 | + "swapped to_mx_tensor(-1) must pair with the original qdata2" | ||
| 250 | + ) | ||
| 251 | + | ||
| 252 | + expected = x.qdata1.transpose(-1, -2) | ||
| 253 | + assert y.to_mx_tensor(-2).qdata.shape == expected.shape, ( | ||
| 254 | + f"swapped to_mx_tensor(-2) qdata shape {tuple(y.to_mx_tensor(-2).qdata.shape)} != {tuple(expected.shape)}" | ||
| 255 | + ) | ||
| 256 | + assert torch.equal(y.to_mx_tensor(-2).qdata.view(torch.uint8), expected.view(torch.uint8)), ( | ||
| 257 | + "swapped to_mx_tensor(-2) must pair with the original qdata1" | ||
| 258 | + ) | ||
| 259 | + | ||
| 260 | + | ||
| 261 | +def test_permute_rejects_moving_the_last_two_dims_away(): | ||
| 262 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 263 | + qdata = torch.randn(2, 4, 64).to(torch.float8_e4m3fn) | ||
| 264 | + scale = torch.full((2, 4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 265 | + x = DualAxisMXTensor(qdata, scale, qdata, scale, torch.bfloat16, config) | ||
| 266 | + | ||
| 267 | + with pytest.raises(ValueError, match="keep the last two dims trailing"): | ||
| 268 | + x.permute([2, 0, 1]) | ||
| 269 | + | ||
| 270 | + | ||
| 271 | +def test_t_is_a_swap_on_2d(): | ||
| 272 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 273 | + qdata1 = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 274 | + qdata2 = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 275 | + scale1 = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 276 | + scale2 = torch.full((1, 64, 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 277 | + x = DualAxisMXTensor(qdata1, scale1, qdata2, scale2, torch.bfloat16, config) | ||
| 278 | + | ||
| 279 | + y = x.t() | ||
| 280 | + expected = x.transpose(0, 1) | ||
| 281 | + | ||
| 282 | + assert y.qdata1.shape == expected.qdata1.shape, ( | ||
| 283 | + f"t() gave qdata1 shape {tuple(y.qdata1.shape)}, transpose(0, 1) gave {tuple(expected.qdata1.shape)}" | ||
| 284 | + ) | ||
| 285 | + assert torch.equal(y.qdata1.view(torch.uint8), expected.qdata1.view(torch.uint8)), ( | ||
| 286 | + "t() and transpose(0, 1) produced different qdata1 values" | ||
| 287 | + ) | ||
| 288 | + | ||
| 289 | + assert y.qdata2.shape == expected.qdata2.shape, ( | ||
| 290 | + f"t() gave qdata2 shape {tuple(y.qdata2.shape)}, transpose(0, 1) gave {tuple(expected.qdata2.shape)}" | ||
| 291 | + ) | ||
| 292 | + assert torch.equal(y.qdata2.view(torch.uint8), expected.qdata2.view(torch.uint8)), ( | ||
| 293 | + "t() and transpose(0, 1) produced different qdata2 values" | ||
| 294 | + ) | ||
| 295 | + | ||
| 296 | + | ||
| 297 | +def test_t_rejects_more_than_2d(): | ||
| 298 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 299 | + qdata = torch.randn(2, 4, 64).to(torch.float8_e4m3fn) | ||
| 300 | + scale = torch.full((2, 4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 301 | + x = DualAxisMXTensor(qdata, scale, qdata, scale, torch.bfloat16, config) | ||
| 302 | + | ||
| 303 | + with pytest.raises(RuntimeError, match="expects a tensor with <= 2 dimensions"): | ||
| 304 | + x.t() | ||
| 305 | + | ||
| 306 | + | ||
| 307 | +# ========================================================================= | ||
| 308 | +# Conversion to the single-axis MXTensor | ||
| 309 | +# ========================================================================= | ||
| 310 | + | ||
| 311 | + | ||
| 312 | +@pytest.mark.parametrize( | ||
| 313 | + "qdata, pack_axis", | ||
| 314 | + [ | ||
| 315 | + (torch.randn(4, 64).to(torch.float8_e4m3fn), None), | ||
| 316 | + (torch.randint(0, 256, (4, 32), dtype=torch.uint8).view(torch.float4_e2m1fn_x2), -1), | ||
| 317 | + ], | ||
| 318 | + ids=["fp8", "fp4"], | ||
| 319 | +) | ||
| 320 | +@pytest.mark.parametrize("quant_axis, qdata_name", [(1, "qdata1"), (0, "qdata2")]) | ||
| 321 | +def test_to_mx_tensor_shares_components(qdata, pack_axis, quant_axis, qdata_name): | ||
| 322 | + config = MXQuantizeConfig(elem_dtype=qdata.dtype) | ||
| 323 | + scale1 = torch.full((*qdata.shape[:-1], 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 324 | + scale2 = torch.full((*qdata.shape[:-2], 1, qdata.shape[-1], 2), 4.0, dtype=torch.float8_e8m0fnu) | ||
| 325 | + x = DualAxisMXTensor(qdata, scale1, qdata, scale2, torch.bfloat16, config, pack_axis=pack_axis) | ||
| 326 | + | ||
| 327 | + y = x.to_mx_tensor(quant_axis) | ||
| 328 | + | ||
| 329 | + assert y.quant_axis == quant_axis, f"quantized along {y.quant_axis}, expected {quant_axis}" | ||
| 330 | + assert y.pack_axis == x.pack_axis, f"pack axis {y.pack_axis} != the source's {x.pack_axis}" | ||
| 331 | + assert y.qdata is getattr(x, qdata_name), f"quantized along {quant_axis} must reuse {qdata_name}" | ||
| 332 | + assert y.orig_dtype is x.orig_dtype, f"orig_dtype {y.orig_dtype} != the source's {x.orig_dtype}" | ||
| 333 | + | ||
| 334 | + | ||
| 335 | +def test_to_mx_tensor_rejects_other_axes(): | ||
| 336 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 337 | + qdata = torch.randn(2, 4, 64).to(torch.float8_e4m3fn) | ||
| 338 | + scale = torch.full((2, 4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 339 | + x = DualAxisMXTensor(qdata, scale, qdata, scale, torch.bfloat16, config) | ||
| 340 | + | ||
| 341 | + with pytest.raises(ValueError, match="Only the last two dims are supported"): | ||
| 342 | + x.to_mx_tensor(0) | ||
| 343 | + | ||
| 344 | + | ||
| 345 | +# ========================================================================= | ||
| 346 | +# Inherited behavior | ||
| 347 | +# ========================================================================= | ||
| 348 | + | ||
| 349 | + | ||
| 350 | +def test_to_dtype_changes_only_the_logical_dtype(): | ||
| 351 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 352 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 353 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 354 | + x = DualAxisMXTensor(qdata, scale, qdata, scale, torch.bfloat16, config) | ||
| 355 | + | ||
| 356 | + y = x.to(torch.float16) | ||
| 357 | + | ||
| 358 | + assert y.dtype is torch.float16, f".to(torch.float16) left the logical dtype at {y.dtype}" | ||
| 359 | + assert y.qdata1 is x.qdata1, ".to(dtype) cast the stored qdata1" | ||
| 360 | + | ||
| 361 | + | ||
| 362 | +def test_values_are_frozen(): | ||
| 363 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 364 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 365 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 366 | + x = DualAxisMXTensor(qdata, scale, qdata, scale, torch.bfloat16, config) | ||
| 367 | + | ||
| 368 | + with pytest.raises(RuntimeError, match="immutable"): | ||
| 369 | + x.zero_() | ||
| 370 | + | ||
| 371 | + | ||
| 372 | +def test_matmul_is_not_supported(): | ||
| 373 | + """Matmul is whitelisted for MXTensor only.""" | ||
| 374 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 375 | + qdata = torch.randn(4, 64).to(torch.float8_e4m3fn) | ||
| 376 | + scale = torch.full((4, 1, 2), 2.0, dtype=torch.float8_e8m0fnu) | ||
| 377 | + x = DualAxisMXTensor(qdata, scale, qdata, scale, torch.bfloat16, config) | ||
| 378 | + | ||
| 379 | + with pytest.raises(NotImplementedError): | ||
| 380 | + torch.mm(x, x) | ||
| 381 | + | ||
| 382 | + | ||
| 383 | +# ========================================================================= | ||
| 384 | +# Quantization against the primitives (NPU kernels) | ||
| 385 | +# ========================================================================= | ||
| 386 | + | ||
| 387 | + | ||
| 388 | +@pytest.mark.parametrize("elem_dtype", [torch.float8_e4m3fn, torch.float4_e2m1fn_x2]) | ||
| 389 | +def test_from_hp_matches_mx_quantize_dual_axis(elem_dtype): | ||
| 390 | + config = MXQuantizeConfig(elem_dtype=elem_dtype) | ||
| 391 | + x = torch.randn(64, 128, device="npu", dtype=torch.bfloat16) | ||
| 392 | + | ||
| 393 | + y = DualAxisMXTensor.from_hp(x, config) | ||
| 394 | + qdata1, scale1, qdata2, scale2 = mx_quantize_dual_axis(x, config) | ||
| 395 | + | ||
| 396 | + assert y.shape == x.shape, f"quantized shape {tuple(y.shape)} != the input's {tuple(x.shape)}" | ||
| 397 | + | ||
| 398 | + # the op packs both qdata along the input's last dim; FP8 has no packing at all | ||
| 399 | + expected_pack_axis = y.ndim - 1 if elem_dtype is torch.float4_e2m1fn_x2 else None | ||
| 400 | + assert y.pack_axis == expected_pack_axis, f"pack axis {y.pack_axis}, expected {expected_pack_axis}" | ||
| 401 | + | ||
| 402 | + assert y.qdata1.shape == qdata1.shape, ( | ||
| 403 | + f"qdata1 shape {tuple(y.qdata1.shape)} != the primitive's {tuple(qdata1.shape)}" | ||
| 404 | + ) | ||
| 405 | + assert torch.equal(y.qdata1.view(torch.uint8), qdata1.view(torch.uint8)), ( | ||
| 406 | + "qdata1 values differ from the primitive's" | ||
| 407 | + ) | ||
| 408 | + | ||
| 409 | + assert y.scale1.shape == scale1.shape, ( | ||
| 410 | + f"scale1 shape {tuple(y.scale1.shape)} != the primitive's {tuple(scale1.shape)}" | ||
| 411 | + ) | ||
| 412 | + assert torch.equal(y.scale1.view(torch.uint8), scale1.view(torch.uint8)), ( | ||
| 413 | + "scale1 values differ from the primitive's" | ||
| 414 | + ) | ||
| 415 | + | ||
| 416 | + assert y.qdata2.shape == qdata2.shape, ( | ||
| 417 | + f"qdata2 shape {tuple(y.qdata2.shape)} != the primitive's {tuple(qdata2.shape)}" | ||
| 418 | + ) | ||
| 419 | + assert torch.equal(y.qdata2.view(torch.uint8), qdata2.view(torch.uint8)), ( | ||
| 420 | + "qdata2 values differ from the primitive's" | ||
| 421 | + ) | ||
| 422 | + | ||
| 423 | + assert y.scale2.shape == scale2.shape, ( | ||
| 424 | + f"scale2 shape {tuple(y.scale2.shape)} != the primitive's {tuple(scale2.shape)}" | ||
| 425 | + ) | ||
| 426 | + assert torch.equal(y.scale2.view(torch.uint8), scale2.view(torch.uint8)), ( | ||
| 427 | + "scale2 values differ from the primitive's" | ||
| 428 | + ) | ||
| 429 | + | ||
| 430 | + | ||
| 431 | +@pytest.mark.parametrize("elem_dtype", [torch.float8_e4m3fn, torch.float4_e2m1fn_x2]) | ||
| 432 | +def test_to_mx_tensor_equals_single_axis_from_hp(elem_dtype): | ||
| 433 | + """The pair stored for one quant axis must match a single-axis quantization.""" | ||
| 434 | + config = MXQuantizeConfig(elem_dtype=elem_dtype) | ||
| 435 | + x = torch.randn(64, 128, device="npu", dtype=torch.bfloat16) | ||
| 436 | + | ||
| 437 | + y = DualAxisMXTensor.from_hp(x, config).to_mx_tensor(-2) | ||
| 438 | + y_ref = MXTensor.from_hp(x, config, axis=-2) | ||
| 439 | + | ||
| 440 | + assert y.pack_axis == y_ref.pack_axis, ( | ||
| 441 | + f"pack axis {y.pack_axis} != the single-axis quantization's {y_ref.pack_axis}" | ||
| 442 | + ) | ||
| 443 | + | ||
| 444 | + assert y.qdata.shape == y_ref.qdata.shape, ( | ||
| 445 | + f"qdata shape {tuple(y.qdata.shape)} != the single-axis quantization's {tuple(y_ref.qdata.shape)}" | ||
| 446 | + ) | ||
| 447 | + assert torch.equal(y.qdata.view(torch.uint8), y_ref.qdata.view(torch.uint8)), ( | ||
| 448 | + "qdata values differ from the single-axis quantization's" | ||
| 449 | + ) | ||
| 450 | + | ||
| 451 | + assert y.scale.shape == y_ref.scale.shape, ( | ||
| 452 | + f"scale shape {tuple(y.scale.shape)} != the single-axis quantization's {tuple(y_ref.scale.shape)}" | ||
| 453 | + ) | ||
| 454 | + assert torch.equal(y.scale.view(torch.uint8), y_ref.scale.view(torch.uint8)), ( | ||
| 455 | + "scale values differ from the single-axis quantization's" | ||
| 456 | + ) | ||
| @@ -279,6 +279,20 @@ def test_wrapper_to_tensor(wrapper_cls, weight_config, act_config, device): | |||
| 279 | assert result is w | 279 | assert result is w |
| 280 | 280 | ||
| 281 | 281 | ||
| 282 | +# ========================================================================= | ||
| 283 | +# to_inference_weight | ||
| 284 | +# ========================================================================= | ||
| 285 | + | ||
| 286 | + | ||
| 287 | +@pytest.mark.parametrize("wrapper_cls, weight_config, act_config", _BASE_WRAPPER_CASES) | ||
| 288 | +def test_base_to_inference_weight_is_not_implemented(wrapper_cls, weight_config, act_config): | ||
| 289 | + """The base class serves no quantized inference weight: subclasses have to implement it.""" | ||
| 290 | + wrapper = wrapper_cls(torch.randn(2, 4), weight_config=weight_config, activation_config=act_config) | ||
| 291 | + | ||
| 292 | + with pytest.raises(NotImplementedError, match="to_inference_weight"): | ||
| 293 | + wrapper.to_inference_weight() | ||
| 294 | + | ||
| 295 | + | ||
| 282 | # ========================================================================= | 296 | # ========================================================================= |
| 283 | # untyped_storage / data_ptr | 297 | # untyped_storage / data_ptr |
| 284 | # ========================================================================= | 298 | # ========================================================================= |
| @@ -3,13 +3,18 @@ | |||
| 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 | +import pytest | ||
| 6 | import torch | 7 | import torch |
| 8 | +import torch.nn.functional as F | ||
| 7 | from torch import nn | 9 | from torch import nn |
| 8 | from torchao_npu import ParamSwapConfig | 10 | from torchao_npu import ParamSwapConfig |
| 9 | from torchao_npu.quantization.quant_configs import BlockMXQuantizeConfig, MXQuantizeConfig | 11 | from torchao_npu.quantization.quant_configs import BlockMXQuantizeConfig, MXQuantizeConfig |
| 10 | from torchao_npu.quantization.transform import _PARAM_SWAP_QUANTIZE_CONFIG_HANDLER | 12 | from torchao_npu.quantization.transform import _PARAM_SWAP_QUANTIZE_CONFIG_HANDLER |
| 13 | +from torchao_npu.quantized_tensors.mx_tensor import MXTensor | ||
| 11 | from torchao_npu.wrapper_tensors.block_mx_wrapper_tensor import BlockMXTrainingWeightWrapperTensor | 14 | from torchao_npu.wrapper_tensors.block_mx_wrapper_tensor import BlockMXTrainingWeightWrapperTensor |
| 12 | 15 | ||
| 16 | +from ..testing_utils import target_devices | ||
| 17 | + | ||
| 13 | 18 | ||
| 14 | def test_block_mx_handler_wraps_parameter_and_preserves_requires_grad(): | 19 | def test_block_mx_handler_wraps_parameter_and_preserves_requires_grad(): |
| 15 | parameter = nn.Parameter(torch.randn(2, 4), requires_grad=True) | 20 | parameter = nn.Parameter(torch.randn(2, 4), requires_grad=True) |
| @@ -25,3 +30,116 @@ def test_block_mx_handler_wraps_parameter_and_preserves_requires_grad(): | |||
| 25 | assert result.data.weight_config is config.weight_config | 30 | assert result.data.weight_config is config.weight_config |
| 26 | assert result.data.activation_config is config.activation_config | 31 | assert result.data.activation_config is config.activation_config |
| 27 | assert result.requires_grad | 32 | assert result.requires_grad |
| 33 | + | ||
| 34 | + | ||
| 35 | +def _make_prequantized_wrapper(shape=(64, 128), fsdp_prequantize=True): | ||
| 36 | + """Build a wrapper carrying pre-quantized FP8 data + scales.""" | ||
| 37 | + weight_config = BlockMXQuantizeConfig(fsdp_prequantize=fsdp_prequantize) | ||
| 38 | + activation_config = MXQuantizeConfig() | ||
| 39 | + # torch.randn does not implement a CPU kernel for FP8 dtypes, so build the | ||
| 40 | + # FP8 tensors by casting from a float source instead. | ||
| 41 | + b_q = torch.randn(*shape).to(torch.float8_e4m3fn) | ||
| 42 | + b_s1 = torch.randn(shape[0], 2, 2).to(torch.float8_e8m0fnu) | ||
| 43 | + b_s2 = torch.randn(2, shape[1], 2).to(torch.float8_e8m0fnu) | ||
| 44 | + return BlockMXTrainingWeightWrapperTensor._from_prequantized(b_q, b_s1, b_s2, weight_config, activation_config) | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +def test_prequantized_wrapper_has_prequantized_data(): | ||
| 48 | + wrapper = _make_prequantized_wrapper() | ||
| 49 | + assert wrapper._has_prequantized_data() | ||
| 50 | + # Logical dtype stays BF16 while _data holds FP8. | ||
| 51 | + assert wrapper.dtype == torch.bfloat16 | ||
| 52 | + assert wrapper._data.dtype == torch.float8_e4m3fn | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def test_prequantized_wrapper_from_prequantized_preserves_configs(): | ||
| 56 | + weight_config = BlockMXQuantizeConfig(fsdp_prequantize=True) | ||
| 57 | + activation_config = MXQuantizeConfig() | ||
| 58 | + b_q = torch.randn(64, 128).to(torch.float8_e4m3fn) | ||
| 59 | + b_s1 = torch.randn(64, 2, 2).to(torch.float8_e8m0fnu) | ||
| 60 | + b_s2 = torch.randn(2, 128, 2).to(torch.float8_e8m0fnu) | ||
| 61 | + wrapper = BlockMXTrainingWeightWrapperTensor._from_prequantized( | ||
| 62 | + b_q, b_s1, b_s2, weight_config, activation_config, requires_grad=True | ||
| 63 | + ) | ||
| 64 | + assert wrapper.weight_config is weight_config | ||
| 65 | + assert wrapper.activation_config is activation_config | ||
| 66 | + assert wrapper.requires_grad | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def test_prequantized_wrapper_transpose_scales(): | ||
| 70 | + """Transposing the last two dims swaps the roles of the two scales.""" | ||
| 71 | + wrapper = _make_prequantized_wrapper(shape=(64, 128)) | ||
| 72 | + b_q, b_s1, b_s2 = ( | ||
| 73 | + wrapper._data, | ||
| 74 | + wrapper._scale_s1, | ||
| 75 | + wrapper._scale_s2, | ||
| 76 | + ) | ||
| 77 | + new_b_q, new_s1, new_s2 = BlockMXTrainingWeightWrapperTensor._transpose_prequantized_scales(b_q, b_s1, b_s2) | ||
| 78 | + assert new_b_q.shape == (128, 64) | ||
| 79 | + # new s1 (N-dim) = old K-dim scale B_s2 transposed: (2, 128, 2) -> (128, 2, 2) | ||
| 80 | + assert new_s1.shape == (128, 2, 2) | ||
| 81 | + # new s2 (K-dim) = old N-dim scale B_s1 transposed: (64, 2, 2) -> (2, 64, 2) | ||
| 82 | + assert new_s2.shape == (2, 64, 2) | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def test_prequantized_wrapper_reshape_scales_2d_to_3d(): | ||
| 86 | + """A 2D->3D view (adding a leading batch dim) reshapes the scales.""" | ||
| 87 | + wrapper = _make_prequantized_wrapper(shape=(64, 128)) | ||
| 88 | + b_s1, b_s2 = wrapper._scale_s1, wrapper._scale_s2 | ||
| 89 | + new_s1, new_s2 = BlockMXTrainingWeightWrapperTensor._reshape_prequantized_scales( | ||
| 90 | + b_s1, b_s2, torch.Size([64, 128]), torch.Size([2, 32, 128]) | ||
| 91 | + ) | ||
| 92 | + assert new_s1.shape == (2, 32, 2, 2) | ||
| 93 | + assert new_s2.shape == (2, 1, 128, 2) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def test_prequantized_wrapper_can_prequantize_falls_back_when_disabled(): | ||
| 97 | + """_can_prequantize returns False when fsdp_prequantize is disabled.""" | ||
| 98 | + wrapper = _make_prequantized_wrapper(fsdp_prequantize=False) | ||
| 99 | + assert wrapper._can_prequantize(None) is False | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +def test_prequantized_wrapper_can_prequantize_requires_block_alignment(): | ||
| 103 | + """_can_prequantize requires 32-aligned trailing dims.""" | ||
| 104 | + wrapper = _make_prequantized_wrapper(shape=(64, 128), fsdp_prequantize=True) | ||
| 105 | + # Non-32-aligned last dim -> cannot prequantize. | ||
| 106 | + wrapper._data = torch.randn(64, 100).to(torch.float8_e4m3fn) | ||
| 107 | + assert wrapper._can_prequantize(None) is False | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +@pytest.mark.parametrize("device", target_devices) | ||
| 111 | +def test_to_inference_weight_matches_the_training_forward(device): | ||
| 112 | + """The converted single-axis weight must multiply the way the block-MX wrapped one does.""" | ||
| 113 | + weight_config = BlockMXQuantizeConfig() | ||
| 114 | + activation_config = MXQuantizeConfig() | ||
| 115 | + A = torch.randn(64, 128, dtype=torch.bfloat16, device=device) # [M, K] | ||
| 116 | + w = torch.randn(256, 128, dtype=torch.bfloat16, device=device) # [N, K] | ||
| 117 | + wrapped = BlockMXTrainingWeightWrapperTensor(w, weight_config=weight_config, activation_config=activation_config) | ||
| 118 | + | ||
| 119 | + inference_weight = wrapped.to_inference_weight() | ||
| 120 | + y_training = F.linear(A, wrapped) | ||
| 121 | + y_inference = F.linear(A, inference_weight) | ||
| 122 | + | ||
| 123 | + assert isinstance(inference_weight, MXTensor), f"got {type(inference_weight).__name__}" | ||
| 124 | + assert torch.equal(y_training, y_inference), "the inference weight does not reproduce training's forward" | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +@pytest.mark.parametrize("device", target_devices) | ||
| 128 | +def test_to_inference_weight_with_mxfp4_matches_the_training_forward(device): | ||
| 129 | + """With mxfp4-QAT the inference weight is FP4, as training's QAT pre-pass produces.""" | ||
| 130 | + weight_config = BlockMXQuantizeConfig( | ||
| 131 | + mxfp4_fake_quantize_config=MXQuantizeConfig(elem_dtype=torch.float4_e2m1fn_x2) | ||
| 132 | + ) | ||
| 133 | + activation_config = MXQuantizeConfig() | ||
| 134 | + A = torch.randn(64, 128, dtype=torch.bfloat16, device=device) # [M, K] | ||
| 135 | + w = torch.randn(256, 128, dtype=torch.bfloat16, device=device) # [N, K] | ||
| 136 | + wrapped = BlockMXTrainingWeightWrapperTensor(w, weight_config=weight_config, activation_config=activation_config) | ||
| 137 | + | ||
| 138 | + inference_weight = wrapped.to_inference_weight() | ||
| 139 | + y_training = F.linear(A, wrapped) | ||
| 140 | + y_inference = F.linear(A, inference_weight) | ||
| 141 | + | ||
| 142 | + assert inference_weight.quant_config.elem_dtype is torch.float4_e2m1fn_x2, ( | ||
| 143 | + f"expected an FP4 inference weight, got {inference_weight.quant_config.elem_dtype}" | ||
| 144 | + ) | ||
| 145 | + assert torch.equal(y_training, y_inference), "the FP4 inference weight does not reproduce training's forward" | ||
| @@ -3,6 +3,7 @@ | |||
| 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 | +import pytest | ||
| 6 | import torch | 7 | import torch |
| 7 | from torch import nn | 8 | from torch import nn |
| 8 | from torchao.quantization.qat.fake_quantize_config import Float8FakeQuantizeConfig | 9 | from torchao.quantization.qat.fake_quantize_config import Float8FakeQuantizeConfig |
| @@ -21,3 +22,11 @@ def test_float8_handler_wraps_parameter_and_preserves_requires_grad(): | |||
| 21 | assert isinstance(result.data, Float8TrainingWeightWrapperTensor) | 22 | assert isinstance(result.data, Float8TrainingWeightWrapperTensor) |
| 22 | assert result.data.weight_config is config.weight_config | 23 | assert result.data.weight_config is config.weight_config |
| 23 | assert result.requires_grad | 24 | assert result.requires_grad |
| 25 | + | ||
| 26 | + | ||
| 27 | +def test_to_inference_weight_is_not_implemented(): | ||
| 28 | + """Float8 has no inference-side quantized tensor yet, so the inherited base method refuses.""" | ||
| 29 | + wrapper = Float8TrainingWeightWrapperTensor(torch.randn(2, 4), weight_config=Float8FakeQuantizeConfig()) | ||
| 30 | + | ||
| 31 | + with pytest.raises(NotImplementedError, match="to_inference_weight"): | ||
| 32 | + wrapper.to_inference_weight() | ||
| @@ -3,13 +3,18 @@ | |||
| 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 | +import pytest | ||
| 6 | import torch | 7 | import torch |
| 8 | +import torch.nn.functional as F | ||
| 7 | from torch import nn | 9 | from torch import nn |
| 8 | from torchao_npu import ParamSwapConfig | 10 | from torchao_npu import ParamSwapConfig |
| 9 | from torchao_npu.quantization.quant_configs import MXQuantizeConfig | 11 | from torchao_npu.quantization.quant_configs import MXQuantizeConfig |
| 10 | from torchao_npu.quantization.transform import _PARAM_SWAP_QUANTIZE_CONFIG_HANDLER | 12 | from torchao_npu.quantization.transform import _PARAM_SWAP_QUANTIZE_CONFIG_HANDLER |
| 13 | +from torchao_npu.quantized_tensors.mx_tensor import MXTensor | ||
| 11 | from torchao_npu.wrapper_tensors.mx_wrapper_tensor import MXTrainingWeightWrapperTensor | 14 | from torchao_npu.wrapper_tensors.mx_wrapper_tensor import MXTrainingWeightWrapperTensor |
| 12 | 15 | ||
| 16 | +from ..testing_utils import target_devices | ||
| 17 | + | ||
| 13 | 18 | ||
| 14 | def test_mx_handler_wraps_parameter_and_preserves_requires_grad(): | 19 | def test_mx_handler_wraps_parameter_and_preserves_requires_grad(): |
| 15 | parameter = nn.Parameter(torch.randn(2, 4), requires_grad=True) | 20 | parameter = nn.Parameter(torch.randn(2, 4), requires_grad=True) |
| @@ -25,3 +30,40 @@ def test_mx_handler_wraps_parameter_and_preserves_requires_grad(): | |||
| 25 | assert result.data.weight_config is config.weight_config | 30 | assert result.data.weight_config is config.weight_config |
| 26 | assert result.data.activation_config is config.activation_config | 31 | assert result.data.activation_config is config.activation_config |
| 27 | assert result.requires_grad | 32 | assert result.requires_grad |
| 33 | + | ||
| 34 | + | ||
| 35 | +@pytest.mark.parametrize("device", target_devices) | ||
| 36 | +def test_to_inference_weight_keeps_the_stored_layout(device): | ||
| 37 | + """The inference weight is the stored ``[N, K]`` weight, quantized along its last axis (K).""" | ||
| 38 | + config = MXQuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 39 | + w = torch.randn(256, 128, dtype=torch.bfloat16, device=device) # [N, K] | ||
| 40 | + | ||
| 41 | + inference_weight = MXTrainingWeightWrapperTensor( | ||
| 42 | + w, weight_config=config, activation_config=config | ||
| 43 | + ).to_inference_weight() | ||
| 44 | + | ||
| 45 | + assert isinstance(inference_weight, MXTensor), f"got {type(inference_weight).__name__}" | ||
| 46 | + assert inference_weight.shape == w.shape, ( | ||
| 47 | + f"inference weight shape {tuple(inference_weight.shape)} != the stored {tuple(w.shape)}" | ||
| 48 | + ) | ||
| 49 | + assert inference_weight.dtype is torch.bfloat16, f"logical dtype {inference_weight.dtype} != torch.bfloat16" | ||
| 50 | + assert inference_weight.quant_axis == w.ndim - 1, ( | ||
| 51 | + f"quantized along dim {inference_weight.quant_axis}, expected {w.ndim - 1} (K in the stored layout)" | ||
| 52 | + ) | ||
| 53 | + assert inference_weight.act_quant_config is config, "the activation config was not carried over" | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +@pytest.mark.parametrize("device", target_devices) | ||
| 57 | +@pytest.mark.parametrize("elem_dtype", [torch.float8_e4m3fn, torch.float4_e2m1fn_x2]) | ||
| 58 | +def test_to_inference_weight_matches_the_training_forward(elem_dtype, device): | ||
| 59 | + """The inference weight has to multiply the way the wrapped one does: that is its purpose.""" | ||
| 60 | + config = MXQuantizeConfig(elem_dtype=elem_dtype) | ||
| 61 | + A = torch.randn(64, 128, dtype=torch.bfloat16, device=device) # [M, K] | ||
| 62 | + w = torch.randn(256, 128, dtype=torch.bfloat16, device=device) # [N, K] | ||
| 63 | + wrapped = MXTrainingWeightWrapperTensor(w, weight_config=config, activation_config=config) | ||
| 64 | + | ||
| 65 | + y_training = F.linear(A, wrapped) | ||
| 66 | + y_inference = F.linear(A, wrapped.to_inference_weight()) | ||
| 67 | + | ||
| 68 | + assert y_inference.dtype is torch.bfloat16, f"output dtype {y_inference.dtype} != torch.bfloat16" | ||
| 69 | + assert torch.equal(y_training, y_inference), "the inference weight does not reproduce training's forward" | ||
Rtests/unit_tests/compile/patterns/deepseek_v4/test_recompute_policy.py→tests/unit_tests/compile/test_recompute_policy.py+0-0
Rtests/unit_tests/models/deepseek_v41/test_baseline_contract.py→tests/unit_tests/models/deepseek_v4_1/test_baseline_contract.py+79-18
Rtests/unit_tests/models/deepseek_v41/test_independence.py→tests/unit_tests/models/deepseek_v4_1/test_independence.py+62-11
Rtests/unit_tests/models/deepseek_v41/test_state_dict_adapter.py→tests/unit_tests/models/deepseek_v4_1/test_state_dict_adapter.py+4-4
Rtests/unit_tests/models/deepseek_v41/test_training_contract.py→tests/unit_tests/models/deepseek_v4_1/test_training_contract.py+8-20
Rtorchtitan_npu/models/deepseek_v41/model_registry.py→torchtitan_npu/models/deepseek_v4_1/__init__.py+310-232
Rtorchtitan_npu/models/deepseek_v41/parallelize.py→torchtitan_npu/models/deepseek_v4_1/parallelize.py+1-1
Rtorchtitan_npu/models/deepseek_v41/sharding.py→torchtitan_npu/models/deepseek_v4_1/sharding.py+13-54
Rtorchtitan_npu/models/deepseek_v41/state_dict_adapter.py→torchtitan_npu/models/deepseek_v4_1/state_dict_adapter.py+3-2
Rtorchtitan_npu/models/deepseek_v41/vision_data.py→torchtitan_npu/models/deepseek_v4_1/vision_data.py+24-8
Rtorchtitan_npu/models/deepseek_v41/vision_state_dict.py→torchtitan_npu/models/deepseek_v4_1/vision_state_dict.py+0-0
Rtorchtitan_npu/patches/torchtitan/graph_trainer/memory_policy.py→torchtitan_npu/patches/torchtitan/experiments/graph_trainer/memory_policy.py+0-0