Merged
[feat] Qwen3.5-VL NPU Context Parallel 适配迁移至 master #694
zhaowei1936Add on Sep 3
[feat] Qwen3.5-VL NPU Context Parallel 适配迁移至 master #694
Merged
Total: 29 files changed+2370-70
| @@ -53,19 +53,23 @@ git -C "${TORCHTITAN_DIR}" checkout --detach --quiet "${TORCHTITAN_COMMIT}" | |||
| 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 | 55 | ||
| 56 | -# The image predates wheels added to requirements.txt; install only the missing wheel, | 56 | +# The image predates wheels added to requirements.txt; install only the missing |
| 57 | -# never the whole file, whose torch/torch_npu pins differ from the image build. | 57 | +# wheels, never the whole file, whose torch/torch_npu pins differ from the image |
| 58 | +# build. | ||
| 58 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir attn-gym==0.0.9 | 59 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir attn-gym==0.0.9 |
| 59 | - | 60 | +# The CI image supplies torch 2.15.0.dev; the matching torchvision nightly |
| 60 | -"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir \ | 61 | +# is installed with --no-deps (resolving its torch pin would fight the image). |
| 61 | - torchvision==0.30.0.dev20260918 --extra-index-url https://download.pytorch.org/whl/nightly/cpu | 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" |
| 62 | -"${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu' | 63 | +"${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu, torchvision' |
| 63 | 64 | ||
| 64 | export MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" | 65 | export MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" |
| 65 | export CONFIG="${CONFIG:-deepseek_v4_debugmodel}" | 66 | export CONFIG="${CONFIG:-deepseek_v4_debugmodel}" |
| 66 | export NGPU | 67 | export NGPU |
| 67 | export LOG_RANK="${LOG_RANK:-0}" | 68 | export LOG_RANK="${LOG_RANK:-0}" |
| 68 | 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 | ||
| 69 | 73 | ||
| 70 | SMOKE_TESTS_START="$(date +%s)" | 74 | SMOKE_TESTS_START="$(date +%s)" |
| 71 | "${PYTHON_BIN}" -m pytest -v --tb=short tests/smoke_tests | 75 | "${PYTHON_BIN}" -m pytest -v --tb=short tests/smoke_tests |
| @@ -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 运行时兼容处理 |
| @@ -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 | ||
文件夹就写qwen3_5吧 不要3.5 3.6混用 ![]() ![]() | |||
| 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;请通过数据配置降低图片最大像素、视频帧数或视觉序列长度。 | ||
| @@ -9,6 +9,14 @@ description = "Ascend NPU overrides for torchtitan" | |||
| 9 | requires-python = ">=3.12" | 9 | requires-python = ">=3.12" |
| 10 | dependencies = ["torchtitan", "torch-npu", "attn-gym==0.0.9", "torchvision"] | 10 | dependencies = ["torchtitan", "torch-npu", "attn-gym==0.0.9", "torchvision"] |
| 11 | 11 | ||
| 12 | +[project.optional-dependencies] | ||
为什么要改这个文件? ![]() ![]() | |||
| 13 | +multimodal = [ | ||
| 14 | + "av", | ||
| 15 | + "einops", | ||
| 16 | + "pillow", | ||
| 17 | + "torchvision==0.29.0.dev20260720+cpu", | ||
| 18 | +] | ||
| 19 | + | ||
| 12 | [tool.setuptools.packages.find] | 20 | [tool.setuptools.packages.find] |
| 13 | include = ["torchtitan_npu*"] | 21 | include = ["torchtitan_npu*"] |
| 14 | exclude = ["tests*", "CI*", "third_party*"] | 22 | exclude = ["tests*", "CI*", "third_party*"] |
| @@ -1,3 +1,7 @@ | |||
| 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. | ||
| 1 | pytest==8.3.2 | 5 | pytest==8.3.2 |
| 2 | pytest-cov | 6 | pytest-cov |
| 3 | pre-commit | 7 | pre-commit |
| @@ -1,3 +1,7 @@ | |||
| 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. | ||
| 1 | --extra-index-url https://download.pytorch.org/whl/nightly/cpu | 5 | --extra-index-url https://download.pytorch.org/whl/nightly/cpu |
| 2 | torch==2.14.0.dev20260719 | 6 | torch==2.14.0.dev20260719 |
| 3 | torchvision==0.29.0.dev20260720 | 7 | torchvision==0.29.0.dev20260720 |
| @@ -30,6 +30,9 @@ class OverrideDefinitions: | |||
| 30 | env_vars: Mapping[str, str] | None = None | 30 | env_vars: Mapping[str, str] | None = None |
| 31 | use_golden: bool = True | 31 | use_golden: bool = True |
| 32 | check_loss: bool = True | 32 | check_loss: bool = True |
| 33 | + # Model-specific launchers may provide their own dataset/assets defaults. | ||
| 34 | + train_script: str = "scripts/run_train.sh" | ||
| 35 | + train_args: Sequence[str] | None = None | ||
| 33 | expected_steps: Sequence[Sequence[int]] | None = None | 36 | expected_steps: Sequence[Sequence[int]] | None = None |
| 34 | check_resume: bool = False | 37 | check_resume: bool = False |
| 35 | verify_ema_checkpoint: bool = False | 38 | verify_ema_checkpoint: bool = False |
| @@ -0,0 +1,64 @@ | |||
| 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 | +from tests.integration_tests import OverrideDefinitions | ||
| 7 | + | ||
| 8 | +# The Qwen3.5 launcher supplies the tokenizer and cc12m-test defaults. Keep | ||
| 9 | +# only the common metrics switches here so the suite exercises that launcher | ||
| 10 | +# exactly as users do. | ||
| 11 | +QWEN3_5_TRAIN_ARGS = ( | ||
| 12 | + "--metrics.enable_tensorboard", | ||
| 13 | + "--metrics.log_freq=1", | ||
| 14 | + "--metrics.save_tb_folder=tb", | ||
| 15 | + "--training.disable-cuda-graphs", | ||
| 16 | +) | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def _build_case( | ||
| 20 | + *, | ||
| 21 | + test_name: str, | ||
| 22 | + test_descr: str, | ||
| 23 | + ngpu: int, | ||
| 24 | + extra_args: tuple[str, ...], | ||
| 25 | + disabled: bool = False, | ||
这里注册了ST,但是不使能的目的是? ![]() ![]() | |||
| 26 | +) -> OverrideDefinitions: | ||
| 27 | + return OverrideDefinitions( | ||
| 28 | + override_args=[extra_args], | ||
| 29 | + test_descr=test_descr, | ||
| 30 | + test_name=test_name, | ||
| 31 | + ngpu=ngpu, | ||
| 32 | + disabled=disabled, | ||
| 33 | + env_vars={ | ||
| 34 | + "MODULE": "torchtitan_npu.models.qwen3_5", | ||
| 35 | + "CONFIG": "qwen35_debugmodel", | ||
| 36 | + }, | ||
| 37 | + use_golden=False, | ||
| 38 | + check_loss=False, | ||
| 39 | + train_script="examples/qwen3_5/qwen3_5_debugmodel_1p_cpt_512.sh", | ||
| 40 | + train_args=QWEN3_5_TRAIN_ARGS, | ||
| 41 | + ) | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +def build_qwen3_5_test_list() -> list[OverrideDefinitions]: | ||
| 45 | + """Return the runnable Qwen3.5 NPU smoke case. | ||
| 46 | + | ||
| 47 | + The multimodal stack (torchvision and the torchtitan tokenizer and | ||
| 48 | + cc12m-test assets) is installed by .ci/smoke_test.sh in the smoke | ||
| 49 | + runner environment. | ||
| 50 | + """ | ||
| 51 | + common = ( | ||
| 52 | + "--training.steps=1", | ||
| 53 | + "--training.local-batch-size=1", | ||
| 54 | + "--training.global-batch-size=1", | ||
| 55 | + "--training.seq-len=512", | ||
| 56 | + ) | ||
| 57 | + return [ | ||
| 58 | + _build_case( | ||
| 59 | + test_name="qwen3_5_debugmodel_1rank", | ||
| 60 | + test_descr="Qwen3.5 debug model 1rank", | ||
| 61 | + ngpu=1, | ||
| 62 | + extra_args=common, | ||
| 63 | + ), | ||
| 64 | + ] | ||
| @@ -36,6 +36,7 @@ from tests.integration_tests.loss_compare import ( | |||
| 36 | log_print, | 36 | log_print, |
| 37 | read_losses_from_file, | 37 | read_losses_from_file, |
| 38 | ) | 38 | ) |
| 39 | +from tests.integration_tests.qwen3_5 import build_qwen3_5_test_list | ||
| 39 | 40 | ||
| 40 | 41 | ||
| 41 | def build_models_test_list() -> list[OverrideDefinitions]: | 42 | def build_models_test_list() -> list[OverrideDefinitions]: |
| @@ -44,6 +45,7 @@ def build_models_test_list() -> list[OverrideDefinitions]: | |||
| 44 | return ( | 45 | return ( |
| 45 | build_deepseek_v4_test_list() | 46 | build_deepseek_v4_test_list() |
| 46 | + build_deepseek_v3_2_test_list() | 47 | + build_deepseek_v3_2_test_list() |
| 48 | + + build_qwen3_5_test_list() | ||
| 47 | ) | 49 | ) |
| 48 | 50 | ||
| 49 | 51 | ||
| @@ -54,6 +56,7 @@ _TEST_SUITES_FUNCTION = { | |||
| 54 | "deepseek_v4": build_deepseek_v4_test_list, | 56 | "deepseek_v4": build_deepseek_v4_test_list, |
| 55 | "deepseek_v4_checkpoint": build_deepseek_v4_checkpoint_resume_test_list, | 57 | "deepseek_v4_checkpoint": build_deepseek_v4_checkpoint_resume_test_list, |
| 56 | "ema": build_ema_test_list, | 58 | "ema": build_ema_test_list, |
| 59 | + "qwen3_5": build_qwen3_5_test_list, | ||
| 57 | } | 60 | } |
| 58 | 61 | ||
| 59 | # Held while a test writes its captured output so concurrent tests do not | 62 | # Held while a test writes its captured output so concurrent tests do not |
| @@ -141,13 +144,8 @@ class GPUPool: | |||
| 141 | conc[holders] = conc.get(holders, 0.0) + duration | 144 | conc[holders] = conc.get(holders, 0.0) + duration |
| 142 | npu_seconds += duration * level | 145 | npu_seconds += duration * level |
| 143 | sequential_seconds += duration * holders | 146 | sequential_seconds += duration * holders |
| 144 | - histogram = ", ".join( | 147 | + histogram = ", ".join(f"{level}/{self.total} busy {busy[level]:.1f}s" for level in sorted(busy, reverse=True)) |
| 145 | - f"{level}/{self.total} busy {busy[level]:.1f}s" | 148 | + allocations = ", ".join(f"{count}x({n} NPU)" for n, count in sorted(self._alloc_counts.items(), reverse=True)) |
| 146 | - for level in sorted(busy, reverse=True) | ||
| 147 | - ) | ||
| 148 | - allocations = ", ".join( | ||
| 149 | - f"{count}x({n} NPU)" for n, count in sorted(self._alloc_counts.items(), reverse=True) | ||
| 150 | - ) | ||
| 151 | capacity = self.total * window | 149 | capacity = self.total * window |
| 152 | pool_line = ( | 150 | pool_line = ( |
| 153 | f"pool: window {window:.1f}s, utilization {100 * npu_seconds / capacity:.0f}% " | 151 | f"pool: window {window:.1f}s, utilization {100 * npu_seconds / capacity:.0f}% " |
| @@ -359,8 +357,7 @@ def _check_phase_results( | |||
| 359 | expected_steps = set(test_flavor.expected_steps[idx]) | 357 | expected_steps = set(test_flavor.expected_steps[idx]) |
| 360 | if set(test_losses) != expected_steps: | 358 | if set(test_losses) != expected_steps: |
| 361 | raise RuntimeError( | 359 | raise RuntimeError( |
| 362 | - f"{test_name} phase {idx}: expected steps {sorted(expected_steps)}, " | 360 | + f"{test_name} phase {idx}: expected steps {sorted(expected_steps)}, got {sorted(test_losses)}" |
| 363 | - f"got {sorted(test_losses)}" | ||
| 364 | ) | 361 | ) |
| 365 | if test_flavor.check_loss: | 362 | if test_flavor.check_loss: |
| 366 | assert golden_losses is not None | 363 | assert golden_losses is not None |
| @@ -369,9 +366,7 @@ def _check_phase_results( | |||
| 369 | try: | 366 | try: |
| 370 | assert_losses_equal(golden_losses, test_losses) | 367 | assert_losses_equal(golden_losses, test_losses) |
| 371 | except AssertionError: | 368 | except AssertionError: |
| 372 | - mismatch_body = "\n".join( | 369 | + mismatch_body = "\n".join(f"[GOLDEN_MISMATCH] {step} {test_losses[step]}" for step in sorted(test_losses)) |
| 373 | - f"[GOLDEN_MISMATCH] {step} {test_losses[step]}" for step in sorted(test_losses) | ||
| 374 | - ) | ||
| 375 | _emit_block( | 370 | _emit_block( |
| 376 | test_name, | 371 | test_name, |
| 377 | f"[GOLDEN_MISMATCH] {test_name} — dumping actual losses for regeneration:\n", | 372 | f"[GOLDEN_MISMATCH] {test_name} — dumping actual losses for regeneration:\n", |
| @@ -397,13 +392,9 @@ def run_single_test( | |||
| 397 | case_dir = Path(output_dir) / test_name | 392 | case_dir = Path(output_dir) / test_name |
| 398 | all_ranks = ",".join(map(str, range(test_flavor.ngpu))) | 393 | all_ranks = ",".join(map(str, range(test_flavor.ngpu))) |
| 399 | 394 | ||
| 400 | - if test_flavor.expected_steps is not None and len(test_flavor.expected_steps) != len( | 395 | + if test_flavor.expected_steps is not None and len(test_flavor.expected_steps) != len(test_flavor.override_args): |
| 401 | - test_flavor.override_args | ||
| 402 | - ): | ||
| 403 | raise ValueError(f"Expected one step sequence per phase for {test_name}") | 396 | raise ValueError(f"Expected one step sequence per phase for {test_name}") |
| 404 | - if test_flavor.check_resume and ( | 397 | + if test_flavor.check_resume and (test_flavor.expected_steps is None or len(test_flavor.override_args) != 2): |
| 405 | - test_flavor.expected_steps is None or len(test_flavor.override_args) != 2 | ||
| 406 | - ): | ||
| 407 | raise ValueError(f"Resume comparison requires two phases with expected steps for {test_name}") | 398 | raise ValueError(f"Resume comparison requires two phases with expected steps for {test_name}") |
| 408 | 399 | ||
| 409 | # When running in parallel, pin each test to a disjoint subset of physical | 400 | # When running in parallel, pin each test to a disjoint subset of physical |
| @@ -433,11 +424,12 @@ def run_single_test( | |||
| 433 | golden_losses = read_losses_from_file(golden_file) | 424 | golden_losses = read_losses_from_file(golden_file) |
| 434 | 425 | ||
| 435 | for idx, override_arg in enumerate(test_flavor.override_args): | 426 | for idx, override_arg in enumerate(test_flavor.override_args): |
| 436 | - # torchtitan-npu override: launch run_train.sh directly with an argv | 427 | + # torchtitan-npu override: launch the case-specific training script |
| 437 | - # list and pass per-case settings through the environment; no shell | 428 | + # directly with an argv list and pass settings through the environment; |
| 438 | - # is involved, so tokens are never re-split or interpolated. | 429 | + # no shell is involved, so tokens are never re-split or interpolated. |
| 439 | - cmd = ["bash", "scripts/run_train.sh", "--dump_folder", str(case_dir / "test_run")] | 430 | + cmd = ["bash", test_flavor.train_script, "--dump_folder", str(case_dir / "test_run")] |
| 440 | - cmd += list(DEFAULT_TRAIN_ARGS) | 431 | + train_args = DEFAULT_TRAIN_ARGS if test_flavor.train_args is None else test_flavor.train_args |
| 432 | + cmd += list(train_args) | ||
| 441 | if test_flavor.check_loss or test_flavor.check_resume: | 433 | if test_flavor.check_loss or test_flavor.check_resume: |
| 442 | cmd += list(DETERMINISTIC_ARGS) | 434 | cmd += list(DETERMINISTIC_ARGS) |
| 443 | if override_arg: | 435 | if override_arg: |
| @@ -0,0 +1,62 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
孤儿文件,CI 无任何入口收集:smoke 的 pytest 只跑 tests/smoke_tests,integration runner 不走 pytest,unit_test.sh 只跑 tests/unit_tests,目前无任何地方使用 ![]() ![]() | |||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +import pytest | ||
| 6 | +import torch | ||
| 7 | + | ||
| 8 | +torch_npu = pytest.importorskip("torch_npu") | ||
| 9 | +pytestmark = [ | ||
| 10 | + pytest.mark.smoke, | ||
| 11 | + pytest.mark.skipif(not torch.npu.is_available(), reason="Ascend NPU is required"), | ||
| 12 | +] | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +def test_merged_gdn_forward_backward(): | ||
| 16 | + from torchtitan_npu.ops.triton.gdn import gated_delta_rule | ||
| 17 | + | ||
| 18 | + torch.npu.set_device(0) | ||
| 19 | + q = torch.randn(1, 64, 1, 64, device="npu", dtype=torch.bfloat16, requires_grad=True) | ||
| 20 | + k = torch.randn_like(q, requires_grad=True) | ||
| 21 | + v = torch.randn_like(q, requires_grad=True) | ||
| 22 | + g = torch.randn(1, 64, 1, device="npu", dtype=torch.float32, requires_grad=True) | ||
| 23 | + beta_logits = torch.randn(1, 64, 1, device="npu", dtype=torch.bfloat16, requires_grad=True) | ||
| 24 | + beta = torch.sigmoid(beta_logits) | ||
| 25 | + | ||
| 26 | + output = gated_delta_rule(q, k, v, g, beta) | ||
| 27 | + output.float().square().mean().backward() | ||
| 28 | + torch.npu.synchronize() | ||
| 29 | + | ||
| 30 | + assert output.shape == v.shape | ||
| 31 | + assert all(tensor.grad is not None and torch.isfinite(tensor.grad).all() for tensor in (q, k, v, g)) | ||
| 32 | + assert beta_logits.grad is not None and torch.isfinite(beta_logits.grad).all() | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def test_qwen3_5_learned_position_embedding_has_npu_backward(): | ||
| 36 | + __import__("torchtitan_npu.models.qwen3_5") | ||
| 37 | + | ||
| 38 | + from torchtitan.models.qwen3_5.vision_encoder import _compute_learned_pos_embeds | ||
| 39 | + | ||
| 40 | + torch.npu.set_device(0) | ||
| 41 | + pos_embed = torch.randn( | ||
| 42 | + 16 * 16, | ||
| 43 | + 8, | ||
| 44 | + device="npu", | ||
| 45 | + dtype=torch.bfloat16, | ||
| 46 | + requires_grad=True, | ||
| 47 | + ) | ||
| 48 | + output = _compute_learned_pos_embeds( | ||
| 49 | + pos_embed, | ||
| 50 | + [[1, 4, 4]], | ||
| 51 | + max_num_patch=16, | ||
| 52 | + num_grid_per_side=16, | ||
| 53 | + spatial_merge_size=2, | ||
| 54 | + dim=8, | ||
| 55 | + ) | ||
| 56 | + output.float().sum().backward() | ||
| 57 | + torch.npu.synchronize() | ||
| 58 | + | ||
| 59 | + assert output.shape == (1, 16, 8) | ||
| 60 | + assert pos_embed.grad is not None | ||
| 61 | + assert torch.isfinite(pos_embed.grad).all() | ||
| 62 | + assert bool(pos_embed.grad.abs().sum() > 0) | ||
| @@ -0,0 +1,12 @@ | |||
| 1 | +from pathlib import Path | ||
| 2 | + | ||
| 3 | + | ||
| 4 | +def test_qwen3_5_cp_adapter_uses_override_refactor_paths(): | ||
| 5 | + root = Path(__file__).resolve().parents[4] | ||
| 6 | + parallelize_source = (root / "torchtitan_npu/override/qwen3_5/parallelize.py").read_text(encoding="utf-8") | ||
| 7 | + gated_delta_source = (root / "torchtitan_npu/override/qwen3_5/gated_delta.py").read_text(encoding="utf-8") | ||
| 8 | + | ||
| 9 | + assert "QwenCPMetadata" in parallelize_source | ||
| 10 | + assert "prepare_sequence_metadata" in parallelize_source | ||
| 11 | + assert "exchange_sequence_heads" in gated_delta_source | ||
| 12 | + assert "context_parallel" in gated_delta_source | ||
| @@ -0,0 +1,466 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +import os | ||
| 6 | +import subprocess | ||
| 7 | +import sys | ||
| 8 | +import textwrap | ||
| 9 | +from pathlib import Path | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +def _run_isolated(source: str, root: Path) -> None: | ||
| 13 | + """Run import-sensitive checks in a child process to avoid global leaks.""" | ||
| 14 | + env = os.environ.copy() | ||
| 15 | + pythonpath = [str(root), *sys.path] | ||
| 16 | + env["PYTHONPATH"] = os.pathsep.join(dict.fromkeys(pythonpath)) | ||
| 17 | + subprocess.run([sys.executable, "-c", textwrap.dedent(source)], check=True, env=env) | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def test_qwen3_5_launcher_delegates_to_run_train_and_uses_current_gdn_override(): | ||
| 21 | + root = Path(__file__).resolve().parents[4] | ||
| 22 | + script = (root / "examples/qwen3_5/qwen3_5_debugmodel_1p_cpt_512.sh").read_text(encoding="utf-8") | ||
| 23 | + eager_flex = (root / "torchtitan_npu/patches/workaround/eager_flex.py").read_text(encoding="utf-8") | ||
| 24 | + | ||
| 25 | + | ||
| 26 | + assert "bash scripts/run_train.sh" in script | ||
| 27 | + assert "TORCHTITAN_REPO:-${TORCHTITAN_DIR:-" in script | ||
| 28 | + assert 'if [[ ${OVERRIDE_IMPORTS+x} ]]' in script | ||
| 29 | + assert "HF_ASSETS_PATH:-${TORCHTITAN_REPO}/tests/assets/tokenizer" in script | ||
| 30 | + assert "DATASET_PATH:-${TORCHTITAN_REPO}/tests/assets/cc12m_test" in script | ||
| 31 | + | ||
| 32 | + assert "torchtitan_npu.models.qwen3_5" in script | ||
| 33 | + assert "torchtitan_npu.override.qwen3_5.gated_delta.npu" in script | ||
| 34 | + assert "override.common.attention" not in script | ||
| 35 | + assert "torchtitan_npu.override.common.token_dispatcher.asc" in script | ||
| 36 | + assert "ENABLE_NPU_MOE_DISPATCHER" in script | ||
| 37 | + assert 'ENABLE_NPU_MOE_DISPATCHER:-0' in script | ||
| 38 | + assert '--override.imports "${OVERRIDE_IMPORTS}"' in script | ||
| 39 | + assert 'if [[ -n "${OVERRIDE_IMPORTS}" ]]' not in script | ||
| 40 | + assert "return_lse=_requests_auxiliary_outputs(return_aux)" in eager_flex | ||
| 41 | + assert "return_aux=_normalize_aux_request(return_aux)" in eager_flex | ||
| 42 | + assert "use_legacy_npu_compile" in eager_flex | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def test_qwen3_5_adapter_applies_only_early_compatibility_patches(): | ||
| 46 | + root = Path(__file__).resolve().parents[4] | ||
| 47 | + _run_isolated( | ||
| 48 | + """ | ||
| 49 | + import torchtitan_npu.models.qwen3_5 | ||
| 50 | + from torchtitan.hf_datasets.multimodal.mm_collator import MultiModalCollator | ||
| 51 | + from torchtitan.models.qwen3_5 import vision_encoder as upstream_vision | ||
| 52 | + from torchtitan_npu.patches.torchtitan.hf_datasets.multimodal.mm_collator import patched_build_mrope_positions | ||
| 53 | + from torchtitan_npu.patches.torchtitan.models.qwen3_5.vision_encoder import ( | ||
| 54 | + eager_create_block_mask, | ||
| 55 | + owning_vision_encoder_forward, | ||
| 56 | + ) | ||
| 57 | + assert MultiModalCollator._build_mrope_positions is patched_build_mrope_positions | ||
| 58 | + assert upstream_vision.compiled_create_block_mask is eager_create_block_mask | ||
| 59 | + assert upstream_vision.Qwen35VisionEncoder.forward is owning_vision_encoder_forward | ||
| 60 | + from torchtitan_npu.patches.workaround import eager_flex | ||
| 61 | + assert callable(eager_flex.mark_dense_sdpa_mask_mod) | ||
| 62 | + assert callable(eager_flex._run_eager_flex_attention) | ||
| 63 | + """, | ||
| 64 | + root, | ||
| 65 | + ) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +def test_qwen3_5_config_registry_forwards_upstream_factories(): | ||
| 69 | + root = Path(__file__).resolve().parents[4] | ||
| 70 | + _run_isolated( | ||
| 71 | + """ | ||
| 72 | + import torchtitan_npu.models.qwen3_5 | ||
| 73 | + from torchtitan.models.qwen3_5 import config_registry as upstream | ||
| 74 | + from torchtitan_npu.models.qwen3_5 import config_registry as adapter | ||
| 75 | + assert adapter.qwen35_debugmodel is upstream.qwen35_debugmodel | ||
| 76 | + assert adapter.qwen35_debugmodel().override.imports == [] | ||
| 77 | + """, | ||
| 78 | + root, | ||
| 79 | + ) | ||
| 80 | + | ||
| 81 | + | ||
| 82 | +def test_qwen3_5_moe_factory_preserves_unpatched_dispatcher_schemas(): | ||
| 83 | + root = Path(__file__).resolve().parents[4] | ||
| 84 | + _run_isolated( | ||
| 85 | + """ | ||
| 86 | + import torchtitan_npu.models.qwen3_5 | ||
| 87 | + from torchtitan.models.common.config_utils import make_routed_experts_config | ||
| 88 | + | ||
| 89 | + for backend in ("standard", "deepep", "hybridep", "minimal_async_ep"): | ||
| 90 | + config = make_routed_experts_config( | ||
| 91 | + dim=8, | ||
| 92 | + hidden_dim=16, | ||
| 93 | + num_experts=4, | ||
| 94 | + top_k=2, | ||
| 95 | + param_init={}, | ||
| 96 | + comm_backend=backend, | ||
| 97 | + ) | ||
| 98 | + has_absorb = hasattr(config.token_dispatcher, "absorb_router_scores") | ||
| 99 | + assert has_absorb is (backend in ("standard", "deepep")), (backend, config.token_dispatcher) | ||
| 100 | + """, | ||
| 101 | + root, | ||
| 102 | + ) | ||
| 103 | + | ||
| 104 | + | ||
| 105 | +def test_qwen3_5_video_mrope_uses_contiguous_temporal_coordinates(): | ||
| 106 | + root = Path(__file__).resolve().parents[4] | ||
| 107 | + _run_isolated( | ||
| 108 | + """ | ||
| 109 | + import torch | ||
| 110 | + import torchtitan_npu.models.qwen3_5 | ||
| 111 | + from torchtitan.hf_datasets.multimodal.mm_collator import MultiModalCollator | ||
| 112 | + collator = MultiModalCollator( | ||
| 113 | + batch_size=1, | ||
| 114 | + seq_len=4, | ||
| 115 | + max_images_per_batch=8, | ||
| 116 | + patch_size=16, | ||
| 117 | + temporal_patch_size=2, | ||
| 118 | + spatial_merge_size=2, | ||
| 119 | + tokenizer=object(), | ||
| 120 | + build_mrope_positions=True, | ||
| 121 | + ) | ||
| 122 | + positions = collator._build_mrope_positions( | ||
| 123 | + torch.tensor([[100, 11, 11, 101]]), | ||
| 124 | + grid_thw=None, | ||
| 125 | + grid_thw_videos=torch.tensor([[2, 2, 2]]), | ||
| 126 | + positions=torch.arange(4).unsqueeze(0), | ||
| 127 | + image_token_id=10, | ||
| 128 | + video_token_id=11, | ||
| 129 | + ) | ||
| 130 | + torch.testing.assert_close(positions, torch.tensor([[[0, 0, 0], [1, 1, 1], [2, 1, 1], [3, 3, 3]]])) | ||
| 131 | + """, | ||
| 132 | + root, | ||
| 133 | + ) | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +def test_qwen3_5_gdn_override_targets_upstream_kernel_config(): | ||
| 137 | + root = Path(__file__).resolve().parents[4] | ||
| 138 | + _run_isolated( | ||
| 139 | + """ | ||
| 140 | + import inspect | ||
| 141 | + from torchtitan.config import apply_overrides | ||
| 142 | + from torchtitan_npu.models.qwen3_5.config_registry import qwen35_debugmodel | ||
| 143 | + from torchtitan_npu.override.qwen3_5.gated_delta import TritonGatedDeltaKernel, npu | ||
| 144 | + config = qwen35_debugmodel() | ||
| 145 | + config.override.imports = ["torchtitan_npu.override.qwen3_5.gated_delta.npu"] | ||
| 146 | + apply_overrides(config.override, config) | ||
| 147 | + delta_layers = [layer.delta_net for layer in config.model_spec.model.layers if layer.delta_net is not None] | ||
| 148 | + assert delta_layers | ||
| 149 | + assert all(isinstance(layer.kernel, TritonGatedDeltaKernel.Config) for layer in delta_layers) | ||
| 150 | + assert inspect.isfunction(npu) | ||
| 151 | + """, | ||
| 152 | + root, | ||
| 153 | + ) | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +def test_qwen3_5_gdn_override_is_directly_importable_without_fla(): | ||
| 157 | + root = Path(__file__).resolve().parents[4] | ||
| 158 | + _run_isolated( | ||
| 159 | + """ | ||
| 160 | + import torchtitan_npu.override.qwen3_5.gated_delta as gated_delta | ||
| 161 | + assert callable(gated_delta._causal_conv1d_varlen) | ||
| 162 | + """, | ||
| 163 | + root, | ||
| 164 | + ) | ||
| 165 | + | ||
| 166 | + | ||
| 167 | +def test_qwen3_5_varlen_conv_rejects_truncated_metadata(): | ||
| 168 | + root = Path(__file__).resolve().parents[4] | ||
| 169 | + _run_isolated( | ||
| 170 | + """ | ||
| 171 | + import torch | ||
| 172 | + from torchtitan_npu.override.qwen3_5.gated_delta import _causal_conv1d_varlen | ||
| 173 | + # The helper must remain traceable inside checkpoint HOP; a disabled | ||
| 174 | + # callable is rejected by the target Torch version. | ||
| 175 | + assert not getattr(_causal_conv1d_varlen, "_torchdynamo_disable", False) | ||
| 176 | + x = torch.ones(1, 3, 2) | ||
| 177 | + weight = torch.ones(2, 3) | ||
| 178 | + try: | ||
| 179 | + _causal_conv1d_varlen(x, weight, torch.tensor([0, 2], dtype=torch.int32)) | ||
| 180 | + except ValueError as error: | ||
| 181 | + assert "sequence_length=3" in str(error) | ||
| 182 | + else: | ||
| 183 | + raise AssertionError("truncated cu_seqlens metadata was accepted") | ||
| 184 | + output = _causal_conv1d_varlen(x, weight, torch.tensor([0, 1, 3], dtype=torch.int32)) | ||
| 185 | + assert output.shape == x.shape | ||
| 186 | + """, | ||
| 187 | + root, | ||
| 188 | + ) | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +def test_qwen3_5_flex_attention_preserves_aux_output_protocol(): | ||
| 192 | + root = Path(__file__).resolve().parents[4] | ||
| 193 | + _run_isolated( | ||
| 194 | + """ | ||
| 195 | + import torch | ||
| 196 | + import torchtitan_npu.models.qwen3_5 | ||
| 197 | + from torch.nn.attention.flex_attention import AuxOutput, AuxRequest, create_block_mask | ||
| 198 | + from torchtitan_npu.patches.workaround.eager_flex import _run_eager_flex_attention | ||
| 199 | + | ||
| 200 | + q = torch.randn(1, 1, 4, 4) | ||
| 201 | + k = torch.randn(1, 1, 4, 4) | ||
| 202 | + v = torch.randn(1, 1, 4, 4) | ||
| 203 | + mask = create_block_mask( | ||
| 204 | + lambda _b, _h, q_idx, _kv_idx: q_idx >= 0, | ||
| 205 | + 1, | ||
| 206 | + 1, | ||
| 207 | + 4, | ||
| 208 | + 4, | ||
| 209 | + device="cpu", | ||
| 210 | + _compile=False, | ||
| 211 | + ) | ||
| 212 | + _, no_lse = _run_eager_flex_attention( | ||
| 213 | + q, | ||
| 214 | + k, | ||
| 215 | + v, | ||
| 216 | + score_mod=None, | ||
| 217 | + block_mask=mask, | ||
| 218 | + scale=None, | ||
| 219 | + enable_gqa=False, | ||
| 220 | + return_aux=AuxRequest(lse=False), | ||
| 221 | + kernel_options={}, | ||
| 222 | + ) | ||
| 223 | + _, with_lse = _run_eager_flex_attention( | ||
| 224 | + q, | ||
| 225 | + k, | ||
| 226 | + v, | ||
| 227 | + score_mod=None, | ||
| 228 | + block_mask=mask, | ||
| 229 | + scale=None, | ||
| 230 | + enable_gqa=False, | ||
| 231 | + return_aux=AuxRequest(lse=True), | ||
| 232 | + kernel_options={}, | ||
| 233 | + ) | ||
| 234 | + assert isinstance(no_lse, AuxOutput) and no_lse.lse is None | ||
| 235 | + assert isinstance(with_lse, AuxOutput) and with_lse.lse is not None | ||
| 236 | + """, | ||
| 237 | + root, | ||
| 238 | + ) | ||
| 239 | + | ||
| 240 | + | ||
| 241 | +def test_qwen3_5_parallelizer_uses_v030_spmd_storage_mesh(): | ||
| 242 | + root = Path(__file__).resolve().parents[4] | ||
| 243 | + _run_isolated( | ||
| 244 | + """ | ||
| 245 | + from types import SimpleNamespace | ||
| 246 | + from unittest.mock import patch | ||
| 247 | + from torchtitan_npu.override.qwen3_5 import parallelize as adapter | ||
| 248 | + class ParallelDims: | ||
| 249 | + cp_enabled = False | ||
| 250 | + tp_enabled = False | ||
| 251 | + ep_enabled = False | ||
| 252 | + dp_replicate_enabled = False | ||
| 253 | + pp_enabled = False | ||
| 254 | + ep = 1 | ||
| 255 | + def get_mesh(self, _dims): | ||
| 256 | + raise AssertionError("spmd_types must use the v0.3.0 storage mesh resolver") | ||
| 257 | + class Model: | ||
| 258 | + vision_encoder = None | ||
| 259 | + def __init__(self): self.parallelized = False | ||
| 260 | + def parallelize(self, _parallel_dims): self.parallelized = True | ||
| 261 | + parallel_dims = ParallelDims() | ||
| 262 | + model = Model() | ||
| 263 | + dense_mesh, dense_dims = object(), object() | ||
| 264 | + training = SimpleNamespace( | ||
| 265 | + mixed_precision_param="bfloat16", | ||
| 266 | + mixed_precision_reduce="float32", | ||
| 267 | + enable_cpu_offload=False, | ||
| 268 | + ) | ||
| 269 | + parallelism = SimpleNamespace(spmd_backend="spmd_types", fsdp_reshard_after_forward="default") | ||
| 270 | + compile_config = SimpleNamespace(enable=False, components=()) | ||
| 271 | + with ( | ||
| 272 | + patch.object(adapter, "resolve_fsdp_mesh", return_value=(dense_mesh, dense_dims)) as resolve_dense, | ||
| 273 | + patch.object(adapter, "resolve_sparse_fsdp_mesh", return_value=(None, None)) as resolve_sparse, | ||
| 274 | + patch.object(adapter, "apply_fsdp_to_decoder") as apply_decoder, | ||
| 275 | + ): | ||
| 276 | + result = adapter.parallelize_qwen3_5_npu( | ||
| 277 | + model, | ||
| 278 | + parallel_dims=parallel_dims, | ||
| 279 | + training=training, | ||
| 280 | + parallelism=parallelism, | ||
| 281 | + compile_config=compile_config, | ||
| 282 | + ac_config=None, | ||
| 283 | + dump_folder="unused", | ||
| 284 | + ) | ||
| 285 | + assert result is model and model.parallelized | ||
| 286 | + resolve_dense.assert_called_once_with(parallel_dims) | ||
| 287 | + resolve_sparse.assert_called_once_with(parallel_dims) | ||
| 288 | + assert apply_decoder.call_args.args[1] is dense_mesh | ||
| 289 | + assert apply_decoder.call_args.kwargs["dp_mesh_dims"] is dense_dims | ||
| 290 | + assert apply_decoder.call_args.kwargs["edp_mesh_dims"] is None | ||
| 291 | + """, | ||
| 292 | + root, | ||
| 293 | + ) | ||
| 294 | + | ||
| 295 | + | ||
| 296 | +def test_qwen3_5_cp_rejects_expert_parallel(): | ||
| 297 | + root = Path(__file__).resolve().parents[4] | ||
| 298 | + _run_isolated( | ||
| 299 | + """ | ||
| 300 | + from types import SimpleNamespace | ||
| 301 | + from unittest.mock import patch | ||
| 302 | + from torchtitan_npu.override.qwen3_5 import parallelize as adapter | ||
| 303 | + | ||
| 304 | + parallel_dims = SimpleNamespace(cp_enabled=True, ep_enabled=True, tp_enabled=False) | ||
| 305 | + parallelism = SimpleNamespace(spmd_backend="spmd_types") | ||
| 306 | + compile_config = SimpleNamespace(enable=False, components=()) | ||
| 307 | + with patch.object(adapter, "parallelize_qwen3_5_cp") as cp: | ||
| 308 | + try: | ||
| 309 | + adapter.parallelize_qwen3_5_npu( | ||
| 310 | + object(), | ||
| 311 | + parallel_dims=parallel_dims, | ||
| 312 | + training=SimpleNamespace(), | ||
| 313 | + parallelism=parallelism, | ||
| 314 | + compile_config=compile_config, | ||
| 315 | + ac_config=None, | ||
| 316 | + dump_folder="unused", | ||
| 317 | + ) | ||
| 318 | + except NotImplementedError as error: | ||
| 319 | + assert "Expert Parallel" in str(error) | ||
| 320 | + else: | ||
| 321 | + raise AssertionError("CP + EP was not rejected") | ||
| 322 | + cp.assert_not_called() | ||
| 323 | + """, | ||
| 324 | + root, | ||
| 325 | + ) | ||
| 326 | + | ||
| 327 | + | ||
| 328 | +def test_qwen3_5_cp_helper_rejects_unsupported_modes_before_mesh_setup(): | ||
| 329 | + root = Path(__file__).resolve().parents[4] | ||
| 330 | + _run_isolated( | ||
| 331 | + """ | ||
| 332 | + from types import SimpleNamespace | ||
| 333 | + from torchtitan_npu.override.qwen3_5 import parallelize as adapter | ||
| 334 | + | ||
| 335 | + common = dict( | ||
| 336 | + training=SimpleNamespace(), | ||
| 337 | + parallelism=SimpleNamespace(), | ||
| 338 | + compile_config=SimpleNamespace(), | ||
| 339 | + ac_config=None, | ||
| 340 | + dump_folder="unused", | ||
| 341 | + ) | ||
| 342 | + for field, message in (("ep_enabled", "Expert Parallel"), ("tp_enabled", "Tensor Parallel")): | ||
| 343 | + dims = SimpleNamespace(cp_enabled=True, ep_enabled=False, tp_enabled=False) | ||
| 344 | + setattr(dims, field, True) | ||
| 345 | + try: | ||
| 346 | + adapter.parallelize_qwen3_5_cp(object(), parallel_dims=dims, **common) | ||
| 347 | + except NotImplementedError as error: | ||
| 348 | + assert message in str(error) | ||
| 349 | + else: | ||
| 350 | + raise AssertionError(f"CP + {field} was not rejected") | ||
| 351 | + | ||
| 352 | + dims = SimpleNamespace(cp_enabled=True, ep_enabled=False, tp_enabled=False) | ||
| 353 | + model = SimpleNamespace(vision_encoder=object()) | ||
| 354 | + try: | ||
| 355 | + adapter.parallelize_qwen3_5_cp(model, parallel_dims=dims, **common) | ||
| 356 | + except NotImplementedError as error: | ||
| 357 | + assert "multimodal" in str(error) | ||
| 358 | + else: | ||
| 359 | + raise AssertionError("VL CP was not rejected") | ||
| 360 | + """, | ||
| 361 | + root, | ||
| 362 | + ) | ||
| 363 | + | ||
| 364 | + | ||
| 365 | +def test_qwen3_5_cp_parallelizer_uses_v030_spmd_storage_mesh(): | ||
| 366 | + root = Path(__file__).resolve().parents[4] | ||
| 367 | + _run_isolated( | ||
| 368 | + """ | ||
| 369 | + from types import SimpleNamespace | ||
| 370 | + from unittest.mock import patch | ||
| 371 | + from torchtitan_npu.override.qwen3_5 import parallelize as adapter | ||
| 372 | + cp_mesh = object() | ||
| 373 | + class ParallelDims: | ||
| 374 | + cp_enabled = True | ||
| 375 | + tp_enabled = False | ||
| 376 | + ep_enabled = False | ||
| 377 | + dp_replicate_enabled = False | ||
| 378 | + pp_enabled = False | ||
| 379 | + ep = 1 | ||
| 380 | + def get_mesh(self, dims): | ||
| 381 | + if dims == "cp": | ||
| 382 | + return cp_mesh | ||
| 383 | + raise AssertionError("spmd_types CP must use the v0.3.0 storage mesh resolver") | ||
| 384 | + class Model: | ||
| 385 | + vision_encoder = None | ||
| 386 | + layers = {} | ||
| 387 | + def register_forward_pre_hook(self, hook, *, with_kwargs): | ||
| 388 | + self.hook = hook | ||
| 389 | + self.with_kwargs = with_kwargs | ||
| 390 | + # torchtitan module protocol: distribute params to DTensors | ||
| 391 | + # before FSDP2 wrapping under the spmd_types backend. | ||
| 392 | + def parallelize(self, parallel_dims): | ||
| 393 | + self.parallelized_dims = parallel_dims | ||
| 394 | + parallel_dims = ParallelDims() | ||
| 395 | + model = Model() | ||
| 396 | + dense_mesh, dense_dims = object(), object() | ||
| 397 | + training = SimpleNamespace( | ||
| 398 | + mixed_precision_param="bfloat16", | ||
| 399 | + mixed_precision_reduce="float32", | ||
| 400 | + enable_cpu_offload=False, | ||
| 401 | + ) | ||
| 402 | + parallelism = SimpleNamespace(spmd_backend="spmd_types", fsdp_reshard_after_forward="default") | ||
| 403 | + compile_config = SimpleNamespace(enable=False, components=()) | ||
| 404 | + with ( | ||
| 405 | + patch.object(adapter, "resolve_fsdp_mesh", return_value=(dense_mesh, dense_dims)) as resolve_dense, | ||
| 406 | + patch.object(adapter, "apply_fsdp_to_decoder") as apply_decoder, | ||
| 407 | + ): | ||
| 408 | + result = adapter.parallelize_qwen3_5_npu( | ||
| 409 | + model, | ||
| 410 | + parallel_dims=parallel_dims, | ||
| 411 | + training=training, | ||
| 412 | + parallelism=parallelism, | ||
| 413 | + compile_config=compile_config, | ||
| 414 | + ac_config=None, | ||
| 415 | + dump_folder="unused", | ||
| 416 | + ) | ||
| 417 | + assert result is model | ||
| 418 | + assert model.context_parallel_mesh is cp_mesh | ||
| 419 | + assert model.hook is adapter.prepare_sequence_metadata and model.with_kwargs | ||
| 420 | + assert model.parallelized_dims is parallel_dims | ||
| 421 | + resolve_dense.assert_called_once_with(parallel_dims) | ||
| 422 | + assert apply_decoder.call_args.args[1] is dense_mesh | ||
| 423 | + assert apply_decoder.call_args.kwargs["dp_mesh_dims"] is dense_dims | ||
| 424 | + assert apply_decoder.call_args.kwargs["edp_mesh_dims"] is None | ||
| 425 | + """, | ||
| 426 | + root, | ||
| 427 | + ) | ||
| 428 | + | ||
| 429 | + | ||
| 430 | +def test_qwen3_5_does_not_vendor_a_second_gdn_implementation(): | ||
| 431 | + root = Path(__file__).resolve().parents[4] | ||
| 432 | + override = (root / "torchtitan_npu/override/qwen3_5/gated_delta.py").read_text(encoding="utf-8") | ||
| 433 | + assert "torchtitan_npu.ops.triton.gdn" in override | ||
| 434 | + assert "torchtitan_npu.ops.triton.gated_delta_rule" not in override | ||
| 435 | + assert (root / "torchtitan_npu/ops/triton/gdn/gated_delta.py").is_file() | ||
| 436 | + old_ops = root / "torchtitan_npu/ops/triton/gated_delta_rule" | ||
| 437 | + assert not any(old_ops.rglob("*.py")) | ||
| 438 | + | ||
| 439 | + | ||
| 440 | +def test_presplit_pipeline_bridge_handles_older_npu_schedule(): | ||
| 441 | + root = Path(__file__).resolve().parents[4] | ||
| 442 | + _run_isolated( | ||
| 443 | + """ | ||
| 444 | + import torch | ||
| 445 | + from torchtitan_npu.patches.torchtitan.trainer import _run_presplit_pipeline_schedule | ||
| 446 | + class Stage: | ||
| 447 | + def __init__(self): self.has_backward = False; self.cleared = 0 | ||
| 448 | + def clear_runtime_states(self): self.cleared += 1 | ||
| 449 | + class Schedule: | ||
| 450 | + _has_backward = True | ||
| 451 | + def __init__(self): self._stage = Stage(); self.received = None | ||
| 452 | + def _step_microbatches(self, **kwargs): self.received = kwargs | ||
| 453 | + schedule = Schedule() | ||
| 454 | + _run_presplit_pipeline_schedule( | ||
| 455 | + schedule, | ||
| 456 | + arg_mbs=[(torch.ones(1),)], | ||
| 457 | + kwarg_mbs=[{}], | ||
| 458 | + target_mbs=[torch.ones(1)], | ||
| 459 | + losses=[], | ||
| 460 | + loss_kwargs={}, | ||
| 461 | + return_outputs=False, | ||
| 462 | + ) | ||
| 463 | + assert schedule._stage.has_backward and schedule._stage.cleared == 1 and schedule.received["arg_mbs"] | ||
| 464 | + """, | ||
| 465 | + root, | ||
| 466 | + ) | ||
| @@ -0,0 +1,104 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +import os | ||
| 6 | +import sys | ||
| 7 | +import tomllib | ||
| 8 | +from io import BytesIO | ||
| 9 | +from pathlib import Path | ||
| 10 | + | ||
| 11 | +import torch | ||
| 12 | +from PIL import Image | ||
| 13 | + | ||
| 14 | +# dev20260720+cpu is the nightly whose metadata requires | ||
| 15 | +# torch==2.14.0.dev20260719 exactly, so plain pip resolution accepts it beside | ||
| 16 | +# the requirements.txt torch pin; dev20260719+cpu stays accepted for the | ||
| 17 | +# containers that installed it with --no-deps per the example readme. | ||
| 18 | +EXPECTED_TORCHVISION = "0.29.0.dev20260720+cpu" | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +def test_multimodal_dependency_and_package_discovery_are_explicit(): | ||
| 22 | + root = Path(__file__).resolve().parents[4] | ||
| 23 | + project = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8")) | ||
| 24 | + | ||
| 25 | + dependencies = project["project"]["optional-dependencies"]["multimodal"] | ||
| 26 | + assert f"torchvision=={EXPECTED_TORCHVISION}" in dependencies | ||
| 27 | + requirements = (root / "requirements.txt").read_text(encoding="utf-8") | ||
| 28 | + torchvision_requirement = f"torchvision=={EXPECTED_TORCHVISION.removesuffix('+cpu')}" | ||
| 29 | + assert f"{torchvision_requirement}\n" in requirements | ||
| 30 | + | ||
| 31 | + # The UT runner installs requirements-dev.txt directly, so the runtime | ||
| 32 | + # dependency must be declared there as well as in the base requirements. | ||
| 33 | + package_find = project.get("tool", {}).get("setuptools", {}).get("packages", {}).get("find") | ||
| 34 | + assert package_find["include"] == ["torchtitan_npu*"] | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def test_qwen3_5_uses_the_merged_gdn_override(): | ||
| 38 | + root = Path(__file__).resolve().parents[4] | ||
| 39 | + override = (root / "torchtitan_npu/override/qwen3_5/gated_delta.py").read_text(encoding="utf-8") | ||
| 40 | + assert "torchtitan_npu.ops.triton.gdn" in override | ||
| 41 | + assert "gated_delta_rule" not in override.split("torchtitan_npu.ops.triton.gdn", 1)[0] | ||
| 42 | + assert (root / "torchtitan_npu/ops/triton/gdn/gated_delta.py").is_file() | ||
| 43 | + old_ops = root / "torchtitan_npu/ops/triton/gated_delta_rule" | ||
| 44 | + assert not any(old_ops.rglob("*.py")) | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +def test_qwen3_5_launcher_selects_the_current_gdn_override(): | ||
| 48 | + script = (Path(__file__).resolve().parents[4] / "examples" / "qwen3_5" / "qwen3_5_debugmodel_1p_cpt_512.sh").read_text(encoding="utf-8") | ||
| 49 | + assert "bash scripts/run_train.sh" in script | ||
| 50 | + assert "torchtitan_npu.override.qwen3_5.gated_delta.npu" in script | ||
| 51 | + assert "override.common.attention" not in script | ||
| 52 | + assert "triton_gated_delta_override" not in script | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def test_torchvision_native_image_ops_and_v2_transforms_are_available(): | ||
| 56 | + import torchvision | ||
| 57 | + import torchvision.transforms.v2.functional as TVF | ||
| 58 | + | ||
| 59 | + assert torchvision.extension._has_ops() | ||
| 60 | + buffer = BytesIO() | ||
| 61 | + Image.new("RGB", (16, 12), color=(64, 128, 192)).save(buffer, format="JPEG") | ||
| 62 | + encoded = torch.frombuffer(bytearray(buffer.getvalue()), dtype=torch.uint8) | ||
| 63 | + decoded = torchvision.io.decode_image( | ||
| 64 | + encoded, | ||
| 65 | + mode=torchvision.io.ImageReadMode.RGB, | ||
| 66 | + ) | ||
| 67 | + resized = TVF.resize( | ||
| 68 | + decoded, | ||
| 69 | + [8, 8], | ||
| 70 | + interpolation=TVF.InterpolationMode.BICUBIC, | ||
| 71 | + antialias=True, | ||
| 72 | + ) | ||
| 73 | + assert decoded.shape == (3, 12, 16) | ||
| 74 | + assert resized.shape == (3, 8, 8) | ||
| 75 | + assert resized.dtype == torch.uint8 | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def test_qwen3_5_adapter_uses_real_torchvision_without_compat_modules(): | ||
| 79 | + import subprocess | ||
| 80 | + | ||
| 81 | + root = Path(__file__).resolve().parents[4] | ||
| 82 | + subprocess.run( | ||
| 83 | + [ | ||
| 84 | + sys.executable, | ||
| 85 | + "-c", | ||
| 86 | + """ | ||
| 87 | +import importlib.util | ||
| 88 | +import sys | ||
| 89 | +import torchvision | ||
| 90 | +from pathlib import Path | ||
| 91 | +assert torchvision.__version__ in ('0.29.0.dev20260719+cpu', '0.29.0.dev20260720+cpu', '0.30.0.dev20260918+cpu') | ||
| 92 | +assert torchvision.__file__ is not None and Path(torchvision.__file__).is_file() | ||
| 93 | +from torchtitan_npu.models.qwen3_5.config_registry import qwen35_debugmodel | ||
| 94 | +qwen35_debugmodel() | ||
| 95 | +assert sys.modules['torchvision'] is torchvision | ||
| 96 | +assert 'torchtitan_npu.models.qwen3_5._torchvision_compat' not in sys.modules | ||
| 97 | +# FLA is imported normally when installed; the placeholder cleanup | ||
| 98 | +# is only observable in environments without FLA (e.g. the CI runner). | ||
| 99 | +assert 'fla.ops.gated_delta_rule' not in sys.modules or importlib.util.find_spec('fla') is not None | ||
| 100 | +""", | ||
| 101 | + ], | ||
| 102 | + check=True, | ||
| 103 | + env={**os.environ, "PYTHONPATH": os.pathsep.join(dict.fromkeys([str(root), *sys.path]))}, | ||
| 104 | + ) | ||
| @@ -0,0 +1,21 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | + | ||
| 3 | +from pathlib import Path | ||
| 4 | + | ||
| 5 | + | ||
| 6 | +def test_qwen_gdn_uses_the_override_refactor_kernel(): | ||
| 7 | + root = Path(__file__).resolve().parents[4] | ||
| 8 | + gdn = root / "torchtitan_npu/ops/triton/gdn" | ||
| 9 | + override = root / "torchtitan_npu/override/qwen3_5/gated_delta.py" | ||
| 10 | + | ||
| 11 | + assert (gdn / "gated_delta.py").is_file() | ||
| 12 | + assert (gdn / "__init__.py").is_file() | ||
| 13 | + text = override.read_text(encoding="utf-8") | ||
| 14 | + assert "torchtitan_npu.ops.triton.gdn" in text | ||
| 15 | + assert "torchtitan_npu.ops.triton.gated_delta_rule" not in text | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def test_qwen_gdn_legacy_vendor_tree_is_not_tracked(): | ||
| 19 | + root = Path(__file__).resolve().parents[4] | ||
| 20 | + legacy = root / "torchtitan_npu/ops/triton/gated_delta_rule" | ||
| 21 | + assert not any(legacy.rglob("*.py")) | ||
| @@ -6,4 +6,31 @@ | |||
| 6 | 6 | ||
| 7 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | 7 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. |
| 8 | 8 | ||
| 9 | -from torchtitan.models.qwen3_5 import model_registry as model_registry | 9 | +from torchtitan_npu.models.qwen3_5._fla_compat import ensure_qwen3_5_importable |
| 10 | + | ||
| 11 | +ensure_qwen3_5_importable() | ||
| 12 | + | ||
| 13 | +from torchtitan_npu.patches.torchtitan.hf_datasets.multimodal import ( | ||
| 14 | + mm_collator as _mm_collator_patch, | ||
| 15 | +) | ||
| 16 | +from torchtitan_npu.patches.torchtitan.models.qwen3_5 import ( | ||
| 17 | + vision_encoder as _vision_patch, | ||
| 18 | +) | ||
| 19 | + | ||
| 20 | +_mm_collator_patch.apply() | ||
| 21 | +_vision_patch.apply() | ||
| 22 | + | ||
| 23 | +import torchtitan.models.qwen3_5.config_registry as _upstream_config_registry | ||
| 24 | +from torchtitan.models.qwen3_5 import model_registry as _upstream_model_registry | ||
| 25 | + | ||
| 26 | +from torchtitan_npu.override.qwen3_5.parallelize import parallelize_qwen3_5_npu | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def model_registry(*args, **kwargs): | ||
| 30 | + """Return upstream Qwen3.5 specs with the NPU parallelizer.""" | ||
| 31 | + spec = _upstream_model_registry(*args, **kwargs) | ||
| 32 | + spec.parallelize_fn = parallelize_qwen3_5_npu | ||
| 33 | + return spec | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +_upstream_config_registry.model_registry = model_registry | ||
| @@ -0,0 +1,131 @@ | |||
| 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 | +"""Make the optional FLA imports in TorchTitan Qwen3.5 lazy and explicit. | ||
| 7 | + | ||
| 8 | +TorchTitan keeps the Qwen3.5 model in the upstream package, but importing that | ||
| 9 | +module imports Flash Linear Attention (FLA) unconditionally. The NPU adapter | ||
| 10 | +uses its own Triton kernel, so FLA is not required for that path. These small | ||
| 11 | +placeholder modules let the upstream model be imported without pretending that | ||
| 12 | +the FLA kernels are available at runtime. | ||
| 13 | +""" | ||
| 14 | + | ||
| 15 | +# Dynamic module attributes are intentional: these modules only exist as | ||
| 16 | +# import-time placeholders when the optional FLA dependency is unavailable. | ||
| 17 | +# ruff: noqa: B010 | ||
| 18 | + | ||
| 19 | +from __future__ import annotations | ||
| 20 | + | ||
| 21 | +import importlib | ||
| 22 | +import importlib.util | ||
| 23 | +import sys | ||
| 24 | +import types | ||
| 25 | +from typing import Any | ||
| 26 | + | ||
| 27 | +import torch | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def _unavailable_fla_kernel(*args: Any, **kwargs: Any) -> Any: | ||
| 31 | + del args, kwargs | ||
| 32 | + raise RuntimeError( | ||
| 33 | + "Qwen3.5 FLA kernels are unavailable. Use the NPU override " | ||
| 34 | + "torchtitan_npu.override.qwen3_5.gated_delta.npu or install FLA." | ||
| 35 | + ) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +class _UnavailableFlaAutogradFunction(torch.autograd.Function): | ||
| 39 | + """Autograd-compatible placeholder for FLA Function classes.""" | ||
| 40 | + | ||
| 41 | + @staticmethod | ||
| 42 | + def forward(*args: Any, **kwargs: Any) -> Any: | ||
| 43 | + return _unavailable_fla_kernel(*args, **kwargs) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _has_fla() -> bool: | ||
| 47 | + required_modules = ( | ||
| 48 | + "fla.modules.conv.triton.ops", | ||
| 49 | + "fla.modules.conv.causal_conv1d", | ||
| 50 | + "fla.ops.gated_delta_rule", | ||
| 51 | + "fla.ops.gated_delta_rule.chunk", | ||
| 52 | + "fla.ops.gated_delta_rule.fused_recurrent", | ||
| 53 | + ) | ||
| 54 | + try: | ||
| 55 | + return all(importlib.util.find_spec(name) is not None for name in required_modules) | ||
| 56 | + except (ImportError, ModuleNotFoundError, ValueError): | ||
| 57 | + return False | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def _temporary_fla_modules() -> dict[str, types.ModuleType]: | ||
| 61 | + fla = types.ModuleType("fla") | ||
| 62 | + fla.__path__ = [] | ||
| 63 | + modules = types.ModuleType("fla.modules") | ||
| 64 | + modules.__path__ = [] | ||
| 65 | + conv = types.ModuleType("fla.modules.conv") | ||
| 66 | + conv.__path__ = [] | ||
| 67 | + conv_triton = types.ModuleType("fla.modules.conv.triton") | ||
| 68 | + conv_triton.__path__ = [] | ||
| 69 | + conv_triton_ops = types.ModuleType("fla.modules.conv.triton.ops") | ||
| 70 | + setattr(conv_triton_ops, "CausalConv1dFunction", _UnavailableFlaAutogradFunction) | ||
| 71 | + causal_conv1d = types.ModuleType("fla.modules.conv.causal_conv1d") | ||
| 72 | + setattr(causal_conv1d, "causal_conv1d", _unavailable_fla_kernel) | ||
| 73 | + ops = types.ModuleType("fla.ops") | ||
| 74 | + ops.__path__ = [] | ||
| 75 | + gated_delta_rule = types.ModuleType("fla.ops.gated_delta_rule") | ||
| 76 | + setattr(gated_delta_rule, "chunk_gated_delta_rule", _unavailable_fla_kernel) | ||
| 77 | + setattr(gated_delta_rule, "fused_recurrent_gated_delta_rule", _unavailable_fla_kernel) | ||
| 78 | + gated_delta_rule_chunk = types.ModuleType("fla.ops.gated_delta_rule.chunk") | ||
| 79 | + setattr(gated_delta_rule_chunk, "ChunkGatedDeltaRuleFunction", _UnavailableFlaAutogradFunction) | ||
| 80 | + gated_delta_rule_fused_recurrent = types.ModuleType("fla.ops.gated_delta_rule.fused_recurrent") | ||
| 81 | + setattr( | ||
| 82 | + gated_delta_rule_fused_recurrent, | ||
| 83 | + "FusedRecurrentFunction", | ||
| 84 | + _UnavailableFlaAutogradFunction, | ||
| 85 | + ) | ||
| 86 | + | ||
| 87 | + setattr(fla, "modules", modules) | ||
| 88 | + setattr(modules, "conv", conv) | ||
| 89 | + setattr(conv, "triton", conv_triton) | ||
| 90 | + setattr(conv, "causal_conv1d", causal_conv1d) | ||
| 91 | + setattr(conv_triton, "ops", conv_triton_ops) | ||
| 92 | + setattr(fla, "ops", ops) | ||
| 93 | + setattr(ops, "gated_delta_rule", gated_delta_rule) | ||
| 94 | + setattr(gated_delta_rule, "chunk", gated_delta_rule_chunk) | ||
| 95 | + setattr(gated_delta_rule, "fused_recurrent", gated_delta_rule_fused_recurrent) | ||
| 96 | + return { | ||
| 97 | + "fla": fla, | ||
| 98 | + "fla.modules": modules, | ||
| 99 | + "fla.modules.conv": conv, | ||
| 100 | + "fla.modules.conv.triton": conv_triton, | ||
| 101 | + "fla.modules.conv.triton.ops": conv_triton_ops, | ||
| 102 | + "fla.modules.conv.causal_conv1d": causal_conv1d, | ||
| 103 | + "fla.ops": ops, | ||
| 104 | + "fla.ops.gated_delta_rule": gated_delta_rule, | ||
| 105 | + "fla.ops.gated_delta_rule.chunk": gated_delta_rule_chunk, | ||
| 106 | + "fla.ops.gated_delta_rule.fused_recurrent": gated_delta_rule_fused_recurrent, | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +def ensure_qwen3_5_importable(): | ||
| 111 | + """Import upstream Qwen3.5, isolating optional FLA placeholders.""" | ||
| 112 | + module_name = "torchtitan.models.qwen3_5" | ||
| 113 | + if module_name in sys.modules: | ||
| 114 | + return sys.modules[module_name] | ||
| 115 | + if _has_fla(): | ||
| 116 | + return importlib.import_module(module_name) | ||
| 117 | + | ||
| 118 | + created: dict[str, types.ModuleType] = {} | ||
| 119 | + for name, module in _temporary_fla_modules().items(): | ||
| 120 | + if name not in sys.modules: | ||
| 121 | + sys.modules[name] = module | ||
| 122 | + created[name] = module | ||
| 123 | + try: | ||
| 124 | + return importlib.import_module(module_name) | ||
| 125 | + finally: | ||
| 126 | + for name, module in reversed(tuple(created.items())): | ||
| 127 | + if sys.modules.get(name) is module: | ||
| 128 | + del sys.modules[name] | ||
| 129 | + | ||
| 130 | + | ||
| 131 | +__all__ = ["ensure_qwen3_5_importable"] | ||
| @@ -11,6 +11,7 @@ from dataclasses import replace | |||
| 11 | 11 | ||
| 12 | from torchtitan.components.optimizer import LRSchedulersContainer, default_adamw | 12 | from torchtitan.components.optimizer import LRSchedulersContainer, default_adamw |
| 13 | from torchtitan.hf_datasets.text_datasets import ChatDataLoader | 13 | from torchtitan.hf_datasets.text_datasets import ChatDataLoader |
| 14 | +from torchtitan.models.qwen3_5 import config_registry as _upstream_config_registry | ||
| 14 | from torchtitan.models.qwen3_5 import model_registry | 15 | from torchtitan.models.qwen3_5 import model_registry |
| 15 | from torchtitan.models.qwen3_5.config_registry import qwen35_27b | 16 | from torchtitan.models.qwen3_5.config_registry import qwen35_27b |
| 16 | from torchtitan.models.qwen3_5.parallelize import parallelize_qwen3_5 | 17 | from torchtitan.models.qwen3_5.parallelize import parallelize_qwen3_5 |
| @@ -21,6 +22,14 @@ from torchtitan_npu.override.qwen3_5.parallelize import parallelize_qwen3_5_cp | |||
| 21 | _TEXT_SPECIAL_TOKEN_IDS = {"image_id": -1, "video_id": -1} | 22 | _TEXT_SPECIAL_TOKEN_IDS = {"image_id": -1, "video_id": -1} |
| 22 | 23 | ||
| 23 | 24 | ||
| 25 | +# Keep upstream debug and benchmark recipes available through the NPU module. | ||
| 26 | +# The recipe objects remain upstream-owned; NPU-specific behavior is selected | ||
| 27 | +# explicitly through ``override.imports`` or the launcher defaults. | ||
| 28 | +for _name, _factory in vars(_upstream_config_registry).items(): | ||
| 29 | + if _name.startswith("qwen35_") and callable(_factory) and _name not in globals(): | ||
| 30 | + globals()[_name] = _factory | ||
| 31 | + | ||
| 32 | + | ||
| 24 | def _messages(sample): | 33 | def _messages(sample): |
| 25 | return sample["messages"] | 34 | return sample["messages"] |
| 26 | 35 | ||
| @@ -48,6 +57,9 @@ def _parallelize_text(model, **kwargs): | |||
| 48 | 57 | ||
| 49 | def _parallelize_long_text(model, **kwargs): | 58 | def _parallelize_long_text(model, **kwargs): |
| 50 | model.register_forward_pre_hook(_text_inputs, with_kwargs=True) | 59 | model.register_forward_pre_hook(_text_inputs, with_kwargs=True) |
| 60 | + # Long-text SFT is text-only: detach the VL vision encoder so the CP | ||
| 61 | + # sequence-metadata adapter only ever sees pure-text varlen masks. | ||
| 62 | + model.vision_encoder = None | ||
| 51 | return parallelize_qwen3_5_cp(model, **kwargs) | 63 | return parallelize_qwen3_5_cp(model, **kwargs) |
| 52 | 64 | ||
| 53 | 65 | ||
| @@ -9,14 +9,21 @@ | |||
| 9 | # pylint: disable=huawei-invalid-name | 9 | # pylint: disable=huawei-invalid-name |
| 10 | 10 | ||
| 11 | from dataclasses import dataclass | 11 | from dataclasses import dataclass |
| 12 | +from itertools import pairwise | ||
| 12 | from typing import cast | 13 | from typing import cast |
| 13 | 14 | ||
| 14 | import torch | 15 | import torch |
| 15 | import torch.nn.functional as F | 16 | import torch.nn.functional as F |
| 16 | from torch.distributed.device_mesh import DeviceMesh | 17 | from torch.distributed.device_mesh import DeviceMesh |
| 18 | +from torch.distributed.tensor import DTensor | ||
| 17 | from torchtitan.config import derive, override | 19 | from torchtitan.config import derive, override |
| 18 | -from torchtitan.models import qwen3_5 | ||
| 19 | from torchtitan.models.common.attention import AttentionMasksType | 20 | from torchtitan.models.common.attention import AttentionMasksType |
| 21 | + | ||
| 22 | +from torchtitan_npu.models.qwen3_5._fla_compat import ensure_qwen3_5_importable | ||
| 23 | + | ||
| 24 | +ensure_qwen3_5_importable() | ||
| 25 | + | ||
| 26 | +from torchtitan.models import qwen3_5 | ||
| 20 | from torchtitan.models.qwen3_5.model import GatedDeltaKernel | 27 | from torchtitan.models.qwen3_5.model import GatedDeltaKernel |
| 21 | 28 | ||
| 22 | from torchtitan_npu.ops.triton.gdn import gated_delta_rule as run_gdn | 29 | from torchtitan_npu.ops.triton.gdn import gated_delta_rule as run_gdn |
| @@ -56,6 +63,188 @@ def triton(cfg: GatedDeltaKernel.Config) -> TritonGatedDeltaKernel.Config: | |||
| 56 | return derive(cfg, TritonGatedDeltaKernel.Config) | 63 | return derive(cfg, TritonGatedDeltaKernel.Config) |
| 57 | 64 | ||
| 58 | 65 | ||
| 66 | +def _causal_conv1d( | ||
| 67 | + x_BTD: torch.Tensor, | ||
| 68 | + weight: torch.Tensor, | ||
| 69 | + *, | ||
| 70 | + stride=1, | ||
| 71 | + padding=0, | ||
| 72 | + dilation=1, | ||
| 73 | +) -> torch.Tensor: | ||
| 74 | + """Depthwise causal convolution used when FLA is not installed.""" | ||
| 75 | + if weight.ndim == 3: | ||
| 76 | + weight = weight.squeeze(1) | ||
| 77 | + if weight.ndim != 2: | ||
| 78 | + raise ValueError(f"Expected depthwise conv weight [channels, kernel], got {weight.shape}") | ||
| 79 | + dilation_value = dilation[0] if isinstance(dilation, tuple) else dilation | ||
| 80 | + x_BDL = F.pad(x_BTD.transpose(1, 2), ((weight.shape[-1] - 1) * dilation_value, 0)) | ||
| 81 | + out_BDL = F.conv1d( | ||
| 82 | + x_BDL, | ||
| 83 | + weight.unsqueeze(1), | ||
| 84 | + None, | ||
| 85 | + stride, | ||
| 86 | + padding, | ||
| 87 | + dilation, | ||
| 88 | + weight.size(0), | ||
| 89 | + ) | ||
| 90 | + return F.silu(out_BDL).transpose(1, 2) | ||
| 91 | + | ||
| 92 | + | ||
| 93 | +_QWEN3_5_CONV_KERNEL_SIZE = 4 | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def _causal_conv1d_varlen_tensor( | ||
| 97 | + x_BTD: torch.Tensor, | ||
| 98 | + weight: torch.Tensor, | ||
| 99 | + cu_seqlens: torch.Tensor, | ||
| 100 | + *, | ||
| 101 | + stride=1, | ||
| 102 | + padding=0, | ||
| 103 | + dilation=1, | ||
| 104 | +) -> torch.Tensor: | ||
| 105 | + """Compile-safe packed causal convolution using device-side offsets.""" | ||
| 106 | + if weight.ndim == 3: | ||
| 107 | + weight = weight.squeeze(1) | ||
| 108 | + if weight.ndim != 2: | ||
| 109 | + raise ValueError(f"Expected depthwise conv weight [channels, kernel], got {weight.shape}") | ||
| 110 | + stride_value = stride[0] if isinstance(stride, tuple) else stride | ||
| 111 | + padding_value = padding[0] if isinstance(padding, tuple) else padding | ||
| 112 | + dilation_value = dilation[0] if isinstance(dilation, tuple) else dilation | ||
| 113 | + if stride_value != 1 or padding_value != 0 or dilation_value != 1 or weight.shape[-1] != _QWEN3_5_CONV_KERNEL_SIZE: | ||
| 114 | + raise ValueError("Qwen3.5 compiled varlen convolution requires kernel=4, stride=1, padding=0, dilation=1") | ||
| 115 | + | ||
| 116 | + boundary_indices = cu_seqlens[1:-1].to(device=x_BTD.device, dtype=torch.long) | ||
| 117 | + boundary_mask = torch.zeros(x_BTD.shape[1], dtype=torch.bool, device=x_BTD.device) | ||
| 118 | + boundary_mask = boundary_mask.scatter( | ||
| 119 | + 0, | ||
| 120 | + boundary_indices, | ||
| 121 | + torch.ones_like(boundary_indices, dtype=torch.bool), | ||
| 122 | + ) | ||
| 123 | + segment_ids = boundary_mask.cumsum(dim=0) | ||
| 124 | + | ||
| 125 | + output = x_BTD * weight[:, -1].view(1, 1, -1) | ||
| 126 | + for delay in range(1, _QWEN3_5_CONV_KERNEL_SIZE): | ||
| 127 | + same_segment = (segment_ids[delay:] == segment_ids[:-delay]).to(x_BTD.dtype).view(1, -1, 1) | ||
| 128 | + term = x_BTD[:, :-delay, :] * weight[:, -1 - delay].view(1, 1, -1) | ||
| 129 | + output = output + F.pad(term * same_segment, (0, 0, delay, 0)) | ||
| 130 | + return F.silu(output) | ||
| 131 | + | ||
| 132 | + | ||
| 133 | +def _causal_conv1d_varlen( | ||
| 134 | + x_BTD: torch.Tensor, | ||
| 135 | + weight: torch.Tensor, | ||
| 136 | + cu_seqlens_cpu: torch.Tensor | None, | ||
| 137 | + *, | ||
| 138 | + cu_seqlens: torch.Tensor | None = None, | ||
| 139 | + stride=1, | ||
| 140 | + padding=0, | ||
| 141 | + dilation=1, | ||
| 142 | +) -> torch.Tensor: | ||
| 143 | + """Apply causal convolution independently to each packed document. | ||
| 144 | + | ||
| 145 | + Compiled execution consumes device-side offsets so checkpoint HOP can trace | ||
| 146 | + the operation; eager execution retains strict host-metadata validation. | ||
| 147 | + """ | ||
| 148 | + if torch.compiler.is_compiling(): | ||
| 149 | + if cu_seqlens is None: | ||
| 150 | + raise ValueError("Qwen3.5 compiled varlen convolution requires device cu_seqlens metadata.") | ||
| 151 | + return _causal_conv1d_varlen_tensor( | ||
| 152 | + x_BTD, | ||
| 153 | + weight, | ||
| 154 | + cu_seqlens, | ||
| 155 | + stride=stride, | ||
| 156 | + padding=padding, | ||
| 157 | + dilation=dilation, | ||
| 158 | + ) | ||
| 159 | + if cu_seqlens_cpu is None: | ||
| 160 | + raise ValueError("Qwen3.5 varlen causal convolution requires CPU cu_seqlens metadata.") | ||
| 161 | + offsets = [int(offset) for offset in cu_seqlens_cpu.detach().cpu().tolist()] | ||
| 162 | + if len(offsets) < 2 or offsets[0] != 0 or offsets[-1] != x_BTD.shape[1]: | ||
| 163 | + raise ValueError(f"Invalid Qwen3.5 cu_seqlens metadata: offsets={offsets}, sequence_length={x_BTD.shape[1]}") | ||
| 164 | + outputs = [] | ||
| 165 | + for start, end in pairwise(offsets): | ||
| 166 | + if start < 0 or end <= start: | ||
| 167 | + raise ValueError(f"Qwen3.5 cu_seqlens must be monotonic: {offsets}") | ||
| 168 | + outputs.append( | ||
| 169 | + _causal_conv1d( | ||
| 170 | + x_BTD[:, start:end, :], | ||
| 171 | + weight, | ||
| 172 | + stride=stride, | ||
| 173 | + padding=padding, | ||
| 174 | + dilation=dilation, | ||
| 175 | + ) | ||
| 176 | + ) | ||
| 177 | + return torch.cat(outputs, dim=1) if outputs else x_BTD[:, :0, :] | ||
| 178 | + | ||
| 179 | + | ||
| 180 | +def _npu_causal_conv( | ||
| 181 | + self, | ||
| 182 | + x_BLD: torch.Tensor, | ||
| 183 | + conv, | ||
| 184 | + cu_seqlens: torch.Tensor | None = None, | ||
| 185 | + cu_seqlens_cpu: torch.Tensor | None = None, | ||
| 186 | +) -> torch.Tensor: | ||
| 187 | + """Use the NPU-safe reference convolution instead of lazy FLA imports.""" | ||
| 188 | + stride = conv.stride | ||
| 189 | + padding = conv.padding | ||
| 190 | + dilation = conv.dilation | ||
| 191 | + if cu_seqlens is not None: | ||
| 192 | + if isinstance(x_BLD, DTensor): | ||
| 193 | + | ||
| 194 | + def _conv_varlen(x_local_BLD, w_local, cu_seqlens_local): | ||
| 195 | + return _causal_conv1d_varlen( | ||
| 196 | + x_local_BLD, | ||
| 197 | + w_local, | ||
| 198 | + cu_seqlens_cpu, | ||
| 199 | + cu_seqlens=cu_seqlens_local, | ||
| 200 | + stride=stride, | ||
| 201 | + padding=padding, | ||
| 202 | + dilation=dilation, | ||
| 203 | + ) | ||
| 204 | + | ||
| 205 | + return self._local_map_conv(x_BLD, conv, _conv_varlen, cu_seqlens) | ||
| 206 | + return _causal_conv1d_varlen( | ||
| 207 | + x_BLD, | ||
| 208 | + conv.weight, | ||
| 209 | + cu_seqlens_cpu, | ||
| 210 | + cu_seqlens=cu_seqlens, | ||
| 211 | + stride=stride, | ||
| 212 | + padding=padding, | ||
| 213 | + dilation=dilation, | ||
| 214 | + ) | ||
| 215 | + | ||
| 216 | + if isinstance(x_BLD, DTensor): | ||
| 217 | + | ||
| 218 | + def _conv_fixed(x_local_BLD, w_local): | ||
| 219 | + return _causal_conv1d( | ||
| 220 | + x_local_BLD, | ||
| 221 | + w_local, | ||
| 222 | + stride=stride, | ||
| 223 | + padding=padding, | ||
| 224 | + dilation=dilation, | ||
| 225 | + ) | ||
| 226 | + | ||
| 227 | + return self._local_map_conv(x_BLD, conv, _conv_fixed) | ||
| 228 | + return _causal_conv1d( | ||
| 229 | + x_BLD, | ||
| 230 | + conv.weight, | ||
| 231 | + stride=stride, | ||
| 232 | + padding=padding, | ||
| 233 | + dilation=dilation, | ||
| 234 | + ) | ||
| 235 | + | ||
| 236 | + | ||
| 237 | +@override(target=GatedDeltaKernel.Config, exact=True, description="Use the NPU GDN kernel without FLA") | ||
| 238 | +def npu(cfg: GatedDeltaKernel.Config) -> TritonGatedDeltaKernel.Config: | ||
| 239 | + # The upstream GatedDeltaNet config remains the owner of the module. Only | ||
| 240 | + # its kernel config and convolution implementation are replaced, matching | ||
| 241 | + # the upstream build contract and keeping pipeline stage metadata unchanged. | ||
| 242 | + # FLA availability is not used as a backend selector because its | ||
| 243 | + # convolution is not an NPU implementation. | ||
| 244 | + qwen3_5.GatedDeltaNet._causal_conv = _npu_causal_conv # pyrefly: ignore [bad-assignment] | ||
| 245 | + return derive(cfg, TritonGatedDeltaKernel.Config) | ||
| 246 | + | ||
| 247 | + | ||
| 59 | class ContextParallelGatedDeltaNet(qwen3_5.GatedDeltaNet): | 248 | class ContextParallelGatedDeltaNet(qwen3_5.GatedDeltaNet): |
| 60 | context_parallel_mesh: DeviceMesh | 249 | context_parallel_mesh: DeviceMesh |
| 61 | 250 | ||
| @@ -3,6 +3,8 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 3 | # This source code is licensed under the BSD-style license found in the |
| 4 | # LICENSE file in the root directory of this source tree. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | +import inspect | ||
| 7 | +from contextlib import contextmanager | ||
| 6 | from dataclasses import dataclass | 8 | from dataclasses import dataclass |
| 7 | 9 | ||
| 8 | import torch | 10 | import torch |
| @@ -10,6 +12,58 @@ from torch.distributed.tensor import DTensor, Replicate, Shard | |||
| 10 | from torchtitan.config import TORCH_DTYPE_MAP | 12 | from torchtitan.config import TORCH_DTYPE_MAP |
| 11 | from torchtitan.distributed.compile import apply_compile | 13 | from torchtitan.distributed.compile import apply_compile |
| 12 | from torchtitan.distributed.fsdp import apply_fsdp_to_decoder, apply_fsdp_to_vision_encoder | 14 | from torchtitan.distributed.fsdp import apply_fsdp_to_decoder, apply_fsdp_to_vision_encoder |
| 15 | +from torchtitan.distributed.full_dtensor import ( | ||
| 16 | + resolve_fsdp_mesh, | ||
| 17 | + resolve_sparse_fsdp_mesh, | ||
| 18 | +) | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +@contextmanager | ||
| 22 | +def _qwen_aot_eager_compile_options(backend: str): | ||
| 23 | + """Isolate Qwen3.5 recompilation caches for dynamic multimodal inputs. | ||
| 24 | + | ||
| 25 | + The upstream compiler applies fullgraph=True to every transformer block. | ||
| 26 | + Qwen3.5 multimodal batches legitimately vary in vision-token and | ||
| 27 | + packed-document metadata shapes, so one shared checkpoint-wrapper code | ||
| 28 | + object can exceed Dynamo's recompilation cache. Keep this policy local to | ||
| 29 | + the Qwen3.5 adapter and only for aot_eager; other models and backends | ||
| 30 | + retain the upstream compile contract. | ||
| 31 | + """ | ||
| 32 | + if backend != "aot_eager": | ||
| 33 | + yield | ||
| 34 | + return | ||
| 35 | + | ||
| 36 | + original_compile = torch.nn.Module.compile | ||
| 37 | + try: | ||
| 38 | + compile_parameters = inspect.signature(torch.compile).parameters | ||
| 39 | + except (TypeError, ValueError): | ||
| 40 | + compile_parameters = {} | ||
| 41 | + | ||
| 42 | + def _compile_qwen_block(self, *args, **kwargs): | ||
| 43 | + # Isolate per-call cache entries when supported; heterogeneous Qwen | ||
| 44 | + # blocks otherwise share checkpoint-wrapper recompilation counters. | ||
| 45 | + # Keep upstream fullgraph=True so each block remains an aot_eager | ||
| 46 | + # graph; isolation prevents unrelated block variants exhausting the | ||
| 47 | + # shared Dynamo cache. | ||
| 48 | + if "isolate_recompiles" in compile_parameters: | ||
| 49 | + kwargs.setdefault("isolate_recompiles", True) | ||
| 50 | + return original_compile(self, *args, **kwargs) | ||
| 51 | + | ||
| 52 | + torch.nn.Module.compile = _compile_qwen_block | ||
| 53 | + try: | ||
| 54 | + yield | ||
| 55 | + finally: | ||
| 56 | + torch.nn.Module.compile = original_compile | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def _apply_qwen_compile(module, *, parallel_dims, compile_config): | ||
| 60 | + """Apply upstream compilation with a Qwen3.5-specific shape policy.""" | ||
| 61 | + with _qwen_aot_eager_compile_options(compile_config.backend): | ||
| 62 | + return apply_compile( | ||
| 63 | + module, | ||
| 64 | + parallel_dims=parallel_dims, | ||
| 65 | + compile_config=compile_config, | ||
| 66 | + ) | ||
| 13 | 67 | ||
| 14 | 68 | ||
| 15 | @dataclass(frozen=True, slots=True) | 69 | @dataclass(frozen=True, slots=True) |
| @@ -19,6 +73,91 @@ class QwenCPMetadata: | |||
| 19 | actual_seq_qlen: torch.Tensor | 73 | actual_seq_qlen: torch.Tensor |
| 20 | 74 | ||
| 21 | 75 | ||
| 76 | +def parallelize_qwen3_5_npu(model, *, parallel_dims, **kwargs): | ||
| 77 | + """Apply the standard Qwen3.5 sharding path with NPU vision handling. | ||
| 78 | + | ||
| 79 | + The pinned upstream parallelizer enables pipeline partitioning for the | ||
| 80 | + vision encoder. Its multimodal inputs are assembled before pipeline | ||
| 81 | + stages, so the encoder must remain replicated while the decoder keeps the | ||
| 82 | + configured pipeline setting. Context-parallel recipes use the dedicated | ||
| 83 | + function below. | ||
| 84 | + """ | ||
| 85 | + training, parallelism = kwargs["training"], kwargs["parallelism"] | ||
| 86 | + compile_config, ac_config = kwargs["compile_config"], kwargs["ac_config"] | ||
| 87 | + if parallelism.spmd_backend == "full_dtensor": | ||
| 88 | + raise NotImplementedError("full_dtensor is not supported yet.") | ||
| 89 | + | ||
| 90 | + model_compile_enabled = compile_config.enable and "model" in compile_config.components | ||
| 91 | + if parallel_dims.cp_enabled: | ||
| 92 | + if parallel_dims.ep_enabled: | ||
| 93 | + raise NotImplementedError("Qwen3.5 NPU Context Parallel does not support Expert Parallel yet.") | ||
| 94 | + if parallel_dims.tp_enabled: | ||
| 95 | + raise NotImplementedError("Qwen3.5 NPU Context Parallel does not support Tensor Parallel yet.") | ||
| 96 | + if getattr(model, "vision_encoder", None) is not None: | ||
| 97 | + raise NotImplementedError( | ||
| 98 | + "Qwen3.5-VL NPU Context Parallel is not supported for multimodal attention masks yet." | ||
| 99 | + ) | ||
| 100 | + return parallelize_qwen3_5_cp(model, parallel_dims=parallel_dims, **kwargs) | ||
| 101 | + | ||
| 102 | + if parallelism.spmd_backend == "spmd_types" or parallel_dims.tp_enabled or parallel_dims.ep_enabled: | ||
| 103 | + model.parallelize(parallel_dims) | ||
| 104 | + | ||
| 105 | + if ac_config is not None: | ||
| 106 | + ac_policy = ac_config.build(dump_folder=kwargs["dump_folder"]) | ||
| 107 | + ac_policy.apply(model) | ||
| 108 | + if model.vision_encoder is not None: | ||
| 109 | + ac_policy.apply(model.vision_encoder) | ||
| 110 | + | ||
| 111 | + if model_compile_enabled: | ||
| 112 | + _apply_qwen_compile(model, parallel_dims=parallel_dims, compile_config=compile_config) | ||
| 113 | + if model.vision_encoder is not None: | ||
| 114 | + _apply_qwen_compile( | ||
| 115 | + model.vision_encoder, | ||
| 116 | + parallel_dims=parallel_dims, | ||
| 117 | + compile_config=compile_config, | ||
| 118 | + ) | ||
| 119 | + | ||
| 120 | + if parallelism.spmd_backend == "spmd_types": | ||
| 121 | + dp_mesh, dp_mesh_dims = resolve_fsdp_mesh(parallel_dims) | ||
| 122 | + edp_mesh, edp_mesh_dims = resolve_sparse_fsdp_mesh(parallel_dims) | ||
| 123 | + else: | ||
| 124 | + dp_mesh_names = ["dp_replicate", "fsdp"] if parallel_dims.dp_replicate_enabled else ["fsdp"] | ||
| 125 | + dp_mesh = parallel_dims.get_mesh(dp_mesh_names) | ||
| 126 | + dp_mesh_dims = None | ||
| 127 | + edp_mesh = None | ||
| 128 | + edp_mesh_dims = None | ||
| 129 | + if parallel_dims.ep_enabled: | ||
| 130 | + edp_mesh_names = ["dp_replicate", "efsdp"] if parallel_dims.dp_replicate_enabled else ["efsdp"] | ||
| 131 | + edp_mesh = parallel_dims.get_optional_mesh(edp_mesh_names) | ||
| 132 | + | ||
| 133 | + param_dtype = TORCH_DTYPE_MAP[training.mixed_precision_param] | ||
| 134 | + reduce_dtype = TORCH_DTYPE_MAP[training.mixed_precision_reduce] | ||
| 135 | + if model.vision_encoder is not None: | ||
| 136 | + apply_fsdp_to_vision_encoder( | ||
| 137 | + model.vision_encoder, | ||
| 138 | + dp_mesh, | ||
| 139 | + param_dtype=param_dtype, | ||
| 140 | + reduce_dtype=reduce_dtype, | ||
| 141 | + reshard_after_forward_policy=parallelism.fsdp_reshard_after_forward, | ||
| 142 | + pp_enabled=False, | ||
| 143 | + dp_mesh_dims=dp_mesh_dims, | ||
| 144 | + ) | ||
| 145 | + apply_fsdp_to_decoder( | ||
| 146 | + model, | ||
| 147 | + dp_mesh, | ||
| 148 | + param_dtype=param_dtype, | ||
| 149 | + reduce_dtype=reduce_dtype, | ||
| 150 | + pp_enabled=parallel_dims.pp_enabled, | ||
| 151 | + cpu_offload=training.enable_cpu_offload, | ||
| 152 | + reshard_after_forward_policy=parallelism.fsdp_reshard_after_forward, | ||
| 153 | + ep_degree=parallel_dims.ep, | ||
| 154 | + edp_mesh=edp_mesh, | ||
| 155 | + dp_mesh_dims=dp_mesh_dims, | ||
| 156 | + edp_mesh_dims=edp_mesh_dims, | ||
| 157 | + ) | ||
| 158 | + return model | ||
| 159 | + | ||
| 160 | + | ||
| 22 | def shard_local_heads(tensor, mesh): | 161 | def shard_local_heads(tensor, mesh): |
| 23 | return tensor.chunk(mesh.size(), 0)[mesh.get_local_rank()].contiguous() | 162 | return tensor.chunk(mesh.size(), 0)[mesh.get_local_rank()].contiguous() |
| 24 | 163 | ||
| @@ -57,15 +196,41 @@ def build_sequence_metadata(varlen, mesh, batch, length): | |||
| 57 | return QwenCPMetadata(cu, cu_cpu, cu_cpu[1:]) | 196 | return QwenCPMetadata(cu, cu_cpu, cu_cpu[1:]) |
| 58 | 197 | ||
| 59 | 198 | ||
| 199 | +def _to_qwen_cp_metadata(mask, mesh, batch, length): | ||
| 200 | + if mask is None or isinstance(mask, QwenCPMetadata) or not hasattr(mask, "cu_seq_q"): | ||
| 201 | + return mask | ||
| 202 | + return build_sequence_metadata(mask, mesh, batch, length) | ||
| 203 | + | ||
| 204 | + | ||
| 60 | def prepare_sequence_metadata(module, args, kwargs): | 205 | def prepare_sequence_metadata(module, args, kwargs): |
| 61 | - varlen = kwargs.get("attention_masks") | 206 | + masks = kwargs.get("attention_masks") |
| 62 | - if varlen is not None and not isinstance(varlen, QwenCPMetadata): | 207 | + if masks is None: |
| 63 | - batch, length = args[0].shape[:2] | 208 | + return args, kwargs |
| 64 | - kwargs["attention_masks"] = build_sequence_metadata(varlen, module.context_parallel_mesh, batch, length) | 209 | + mesh = module.context_parallel_mesh |
| 210 | + batch, length = args[0].shape[:2] | ||
| 211 | + if isinstance(masks, dict): | ||
| 212 | + # Qwen3.5 hybrid attention passes one mask dict per consumer key; | ||
| 213 | + # convert each varlen entry to rank-local QwenCPMetadata in place. | ||
| 214 | + kwargs["attention_masks"] = { | ||
| 215 | + key: _to_qwen_cp_metadata(value, mesh, batch, length) for key, value in masks.items() | ||
| 216 | + } | ||
| 217 | + elif not isinstance(masks, QwenCPMetadata): | ||
| 218 | + kwargs["attention_masks"] = build_sequence_metadata(masks, mesh, batch, length) | ||
| 65 | return args, kwargs | 219 | return args, kwargs |
| 66 | 220 | ||
| 67 | 221 | ||
| 68 | def parallelize_qwen3_5_cp(model, *, parallel_dims, **kwargs): | 222 | def parallelize_qwen3_5_cp(model, *, parallel_dims, **kwargs): |
| 223 | + # Keep this guard here as well as in the public dispatcher: recipes may | ||
| 224 | + # call the CP helper directly, and VL's mixed multimodal mask path is not | ||
| 225 | + # compatible with the sequence-metadata adapter yet. | ||
| 226 | + if parallel_dims.ep_enabled: | ||
| 227 | + raise NotImplementedError("Qwen3.5 NPU Context Parallel does not support Expert Parallel yet.") | ||
| 228 | + if parallel_dims.tp_enabled: | ||
| 229 | + raise NotImplementedError("Qwen3.5 NPU Context Parallel does not support Tensor Parallel yet.") | ||
| 230 | + if getattr(model, "vision_encoder", None) is not None: | ||
| 231 | + raise NotImplementedError( | ||
| 232 | + "Qwen3.5-VL NPU Context Parallel is not supported for multimodal attention masks yet." | ||
| 233 | + ) | ||
| 69 | mesh = parallel_dims.get_mesh("cp") | 234 | mesh = parallel_dims.get_mesh("cp") |
| 70 | model.context_parallel_mesh = mesh | 235 | model.context_parallel_mesh = mesh |
| 71 | model.register_forward_pre_hook(prepare_sequence_metadata, with_kwargs=True) | 236 | model.register_forward_pre_hook(prepare_sequence_metadata, with_kwargs=True) |
| @@ -74,6 +239,11 @@ def parallelize_qwen3_5_cp(model, *, parallel_dims, **kwargs): | |||
| 74 | module.context_parallel_mesh = mesh | 239 | module.context_parallel_mesh = mesh |
| 75 | 240 | ||
| 76 | training, parallelism = kwargs["training"], kwargs["parallelism"] | 241 | training, parallelism = kwargs["training"], kwargs["parallelism"] |
| 242 | + if parallelism.spmd_backend == "spmd_types": | ||
| 243 | + # FSDP2 with dp_mesh_dims (cp axis included when CP is enabled) | ||
| 244 | + # requires params to be DTensors on the dense storage mesh; | ||
| 245 | + # distribute them before wrapping, mirroring the dispatcher. | ||
| 246 | + model.parallelize(parallel_dims) | ||
| 77 | compile_config, ac_config = kwargs["compile_config"], kwargs["ac_config"] | 247 | compile_config, ac_config = kwargs["compile_config"], kwargs["ac_config"] |
| 78 | model_compile_enabled = compile_config.enable and "model" in compile_config.components | 248 | model_compile_enabled = compile_config.enable and "model" in compile_config.components |
| 79 | ac_policy = None if ac_config is None else ac_config.build(dump_folder=kwargs["dump_folder"]) | 249 | ac_policy = None if ac_config is None else ac_config.build(dump_folder=kwargs["dump_folder"]) |
| @@ -82,22 +252,28 @@ def parallelize_qwen3_5_cp(model, *, parallel_dims, **kwargs): | |||
| 82 | if ac_policy is not None: | 252 | if ac_policy is not None: |
| 83 | ac_policy.apply(module) | 253 | ac_policy.apply(module) |
| 84 | if model_compile_enabled: | 254 | if model_compile_enabled: |
| 85 | - apply_compile(module, parallel_dims=parallel_dims, compile_config=compile_config) | 255 | + _apply_qwen_compile(module, parallel_dims=parallel_dims, compile_config=compile_config) |
| 86 | - fsdp_mesh = parallel_dims.get_mesh("fsdp") | 256 | + if parallelism.spmd_backend == "spmd_types": |
| 257 | + dp_mesh, dp_mesh_dims = resolve_fsdp_mesh(parallel_dims) | ||
| 258 | + else: | ||
| 259 | + dp_mesh_names = ["dp_replicate", "fsdp"] if parallel_dims.dp_replicate_enabled else ["fsdp"] | ||
| 260 | + dp_mesh = parallel_dims.get_mesh(dp_mesh_names) | ||
| 261 | + dp_mesh_dims = None | ||
| 87 | param_dtype = TORCH_DTYPE_MAP[training.mixed_precision_param] | 262 | param_dtype = TORCH_DTYPE_MAP[training.mixed_precision_param] |
| 88 | reduce_dtype = TORCH_DTYPE_MAP[training.mixed_precision_reduce] | 263 | reduce_dtype = TORCH_DTYPE_MAP[training.mixed_precision_reduce] |
| 89 | if model.vision_encoder is not None: | 264 | if model.vision_encoder is not None: |
| 90 | apply_fsdp_to_vision_encoder( | 265 | apply_fsdp_to_vision_encoder( |
| 91 | model.vision_encoder, | 266 | model.vision_encoder, |
| 92 | - fsdp_mesh, | 267 | + dp_mesh, |
| 93 | param_dtype=param_dtype, | 268 | param_dtype=param_dtype, |
| 94 | reduce_dtype=reduce_dtype, | 269 | reduce_dtype=reduce_dtype, |
| 95 | reshard_after_forward_policy=parallelism.fsdp_reshard_after_forward, | 270 | reshard_after_forward_policy=parallelism.fsdp_reshard_after_forward, |
| 96 | pp_enabled=False, | 271 | pp_enabled=False, |
| 272 | + dp_mesh_dims=dp_mesh_dims, | ||
| 97 | ) | 273 | ) |
| 98 | apply_fsdp_to_decoder( | 274 | apply_fsdp_to_decoder( |
| 99 | model, | 275 | model, |
| 100 | - fsdp_mesh, | 276 | + dp_mesh, |
| 101 | param_dtype=param_dtype, | 277 | param_dtype=param_dtype, |
| 102 | reduce_dtype=reduce_dtype, | 278 | reduce_dtype=reduce_dtype, |
| 103 | pp_enabled=False, | 279 | pp_enabled=False, |
| @@ -105,5 +281,54 @@ def parallelize_qwen3_5_cp(model, *, parallel_dims, **kwargs): | |||
| 105 | reshard_after_forward_policy=parallelism.fsdp_reshard_after_forward, | 281 | reshard_after_forward_policy=parallelism.fsdp_reshard_after_forward, |
| 106 | ep_degree=1, | 282 | ep_degree=1, |
| 107 | edp_mesh=None, | 283 | edp_mesh=None, |
| 284 | + dp_mesh_dims=dp_mesh_dims, | ||
| 285 | + edp_mesh_dims=None, | ||
| 108 | ) | 286 | ) |
| 109 | return model | 287 | return model |
| 288 | + | ||
| 289 | + | ||
| 290 | +def _patch_spmd_type_annotation() -> None: | ||
| 291 | + """Let rank-local CP masks pass the spmd_types input annotation. | ||
| 292 | + | ||
| 293 | + ``annotate_qwen35_input_spmd_types`` asserts the "deltanet" mask is the | ||
| 294 | + global VarlenMetadata; under CP the model pre-hook already replaced the | ||
| 295 | + dict entries with rank-local QwenCPMetadata, whose cu_seqlens are ragged | ||
| 296 | + across cp ranks and carry no global SPMD type. Strip them (only for the | ||
| 297 | + annotation call) instead of failing the assert. | ||
| 298 | + """ | ||
| 299 | + import functools | ||
| 300 | + | ||
| 301 | + try: | ||
| 302 | + from torchtitan.models.qwen3_5 import model as qwen3_5_model | ||
| 303 | + from torchtitan.models.qwen3_5 import sharding as qwen3_5_sharding | ||
| 304 | + except ImportError: | ||
| 305 | + return | ||
| 306 | + | ||
| 307 | + original = getattr( | ||
| 308 | + qwen3_5_sharding, | ||
| 309 | + "_annotate_qwen35_input_spmd_types_original", | ||
| 310 | + qwen3_5_sharding.annotate_qwen35_input_spmd_types, | ||
| 311 | + ) | ||
| 312 | + if getattr(qwen3_5_sharding.annotate_qwen35_input_spmd_types, "_cp_patched", False): | ||
| 313 | + return | ||
| 314 | + qwen3_5_sharding._annotate_qwen35_input_spmd_types_original = original # pyrefly: ignore [missing-attribute] | ||
| 315 | + | ||
| 316 | + @functools.wraps(original) | ||
| 317 | + def _annotated(*args, **kwargs): | ||
| 318 | + masks = kwargs.get("attention_masks") | ||
| 319 | + if isinstance(masks, dict) and any(isinstance(v, QwenCPMetadata) for v in masks.values()): | ||
| 320 | + local = {k: None if isinstance(v, QwenCPMetadata) else v for k, v in masks.items()} | ||
| 321 | + kwargs = dict(kwargs) | ||
| 322 | + kwargs["attention_masks"] = None if all(v is None for v in local.values()) else local | ||
| 323 | + return original(*args, **kwargs) | ||
| 324 | + | ||
| 325 | + _annotated._cp_patched = True # pyrefly: ignore [missing-attribute] | ||
| 326 | + qwen3_5_sharding.annotate_qwen35_input_spmd_types = _annotated | ||
| 327 | + if getattr(qwen3_5_model, "annotate_qwen35_input_spmd_types", None) is original: | ||
| 328 | + qwen3_5_model.annotate_qwen35_input_spmd_types = _annotated | ||
| 329 | + | ||
| 330 | + | ||
| 331 | +_patch_spmd_type_annotation() | ||
| 332 | + | ||
| 333 | + | ||
| 334 | +__all__ = ["QwenCPMetadata", "parallelize_qwen3_5_cp", "parallelize_qwen3_5_npu"] | ||
| @@ -34,7 +34,16 @@ class AscVarlenAttention(VarlenAttention): | |||
| 34 | repeats = q_BLNH.size(2) // k_BLNH.size(2) | 34 | repeats = q_BLNH.size(2) // k_BLNH.size(2) |
| 35 | k_BLNH, v_BLNH = (tensor.repeat_interleave(repeats, 2) for tensor in (k_BLNH, v_BLNH)) | 35 | k_BLNH, v_BLNH = (tensor.repeat_interleave(repeats, 2) for tensor in (k_BLNH, v_BLNH)) |
| 36 | actual_seq = attention_masks.actual_seq_qlen | 36 | actual_seq = attention_masks.actual_seq_qlen |
| 37 | - q_BLNH, k_BLNH, v_BLNH = exchange_sequence_heads((q_BLNH, k_BLNH, v_BLNH), mesh, 2) | 37 | + if k_BLNH.size(1) == q_BLNH.size(1): |
| 38 | + q_BLNH, k_BLNH, v_BLNH = exchange_sequence_heads((q_BLNH, k_BLNH, v_BLNH), mesh, 2) | ||
| 39 | + else: | ||
| 40 | + # spmd local_map contract: q stays sequence-sharded on the cp axis | ||
| 41 | + # while k/v arrive all-gathered (Replicate on cp) with all heads | ||
| 42 | + # local. Exchange only q to the head-sharded view and take this | ||
| 43 | + # rank's head slice of k/v without extra collectives. | ||
| 44 | + q_BLNH = exchange_sequence_heads((q_BLNH,), mesh, 2)[0] | ||
| 45 | + k_BLNH = k_BLNH.chunk(mesh.size(), 2)[mesh.get_local_rank()].contiguous() | ||
| 46 | + v_BLNH = v_BLNH.chunk(mesh.size(), 2)[mesh.get_local_rank()].contiguous() | ||
| 38 | batch, length, heads, head_dim = q_BLNH.shape | 47 | batch, length, heads, head_dim = q_BLNH.shape |
| 39 | dtype = q_BLNH.dtype | 48 | dtype = q_BLNH.dtype |
| 40 | query, key, value = ( | 49 | query, key, value = ( |
| @@ -21,6 +21,17 @@ from torchtitan_npu.patches.torchtitan.distributed.varlen_cp import ( | |||
| 21 | logger = logging.getLogger(__name__) | 21 | logger = logging.getLogger(__name__) |
| 22 | 22 | ||
| 23 | 23 | ||
| 24 | +def _varlen_from_masks(masks): | ||
| 25 | + """Return the shared VarlenMetadata behind a bare mask or an all-varlen dict.""" | ||
| 26 | + if isinstance(masks, VarlenMetadata): | ||
| 27 | + return masks | ||
| 28 | + if isinstance(masks, dict): | ||
| 29 | + values = [value for value in masks.values() if value is not None] | ||
| 30 | + if values and all(isinstance(value, VarlenMetadata) for value in values): | ||
| 31 | + return values[0] | ||
| 32 | + return None | ||
| 33 | + | ||
| 34 | + | ||
| 24 | @functools.wraps(original_cp_shard) | 35 | @functools.wraps(original_cp_shard) |
| 25 | def patched_cp_shard( | 36 | def patched_cp_shard( |
| 26 | cp_mesh: DeviceMesh, | 37 | cp_mesh: DeviceMesh, |
| @@ -32,7 +43,8 @@ def patched_cp_shard( | |||
| 32 | """Build rank-local varlen metadata after sharding inputs for CP.""" | 43 | """Build rank-local varlen metadata after sharding inputs for CP.""" |
| 33 | load_balancer_type = args[0] if args else kwargs.get("load_balancer_type", "headtail") | 44 | load_balancer_type = args[0] if args else kwargs.get("load_balancer_type", "headtail") |
| 34 | input_seq_dim = args[1] if len(args) > 1 else kwargs.get("input_seq_dim", 1) | 45 | input_seq_dim = args[1] if len(args) > 1 else kwargs.get("input_seq_dim", 1) |
| 35 | - is_varlen = isinstance(attention_masks, VarlenMetadata) | 46 | + varlen_metadata = _varlen_from_masks(attention_masks) |
| 47 | + is_varlen = varlen_metadata is not None | ||
| 36 | batch_size = inputs[0].size(0) | 48 | batch_size = inputs[0].size(0) |
| 37 | seq_len = inputs[0].size(input_seq_dim) | 49 | seq_len = inputs[0].size(input_seq_dim) |
| 38 | 50 | ||
| @@ -44,14 +56,14 @@ def patched_cp_shard( | |||
| 44 | **kwargs, | 56 | **kwargs, |
| 45 | ) | 57 | ) |
| 46 | 58 | ||
| 47 | - if is_varlen: | 59 | + if varlen_metadata is not None: |
| 48 | assert load_balancer_type in ( | 60 | assert load_balancer_type in ( |
| 49 | None, | 61 | None, |
| 50 | "headtail", | 62 | "headtail", |
| 51 | ), f"varlen only support headtail as load balancer, got ({load_balancer_type})" | 63 | ), f"varlen only support headtail as load balancer, got ({load_balancer_type})" |
| 52 | 64 | ||
| 53 | - output_masks = CPVarlenMetadata.from_global( | 65 | + cp_metadata = CPVarlenMetadata.from_global( |
| 54 | - attention_masks, | 66 | + varlen_metadata, |
| 55 | cp_mesh, | 67 | cp_mesh, |
| 56 | batch_size, | 68 | batch_size, |
| 57 | seq_len, | 69 | seq_len, |
| @@ -61,15 +73,51 @@ def patched_cp_shard( | |||
| 61 | else None | 73 | else None |
| 62 | ), | 74 | ), |
| 63 | ) | 75 | ) |
| 76 | + if isinstance(attention_masks, dict): | ||
| 77 | + # Hybrid attention stacks carry one shared varlen metadata under | ||
| 78 | + # multiple mask keys; keep the dict shape so each block can still | ||
| 79 | + # select its mask by key after CP sharding. | ||
| 80 | + output_masks = { | ||
| 81 | + key: cp_metadata if isinstance(value, VarlenMetadata) else value | ||
| 82 | + for key, value in attention_masks.items() | ||
| 83 | + } | ||
| 84 | + else: | ||
| 85 | + output_masks = cp_metadata | ||
| 64 | 86 | ||
| 65 | - return inputs, output_masks | 87 | + return inputs, output_masks # pyrefly: ignore [bad-return] |
| 66 | 88 | ||
| 67 | 89 | ||
| 68 | def apply() -> None: | 90 | def apply() -> None: |
| 69 | - import torchtitan.distributed.context_parallel.api as context_parallel_api | 91 | + try: |
| 92 | + import torchtitan.distributed.context_parallel.api as context_parallel_api | ||
| 93 | + except ImportError: | ||
| 94 | + import torchtitan.distributed.context_parallel as context_parallel_api | ||
| 95 | + | ||
| 96 | + # Qwen3.5 vision masks are created after NPU initialization. Torch's | ||
| 97 | + # compiled helper starts a worker process, which cannot reinitialize NPU; | ||
| 98 | + # use the eager helper for this CP path. | ||
| 99 | + try: | ||
| 100 | + import torch.distributed.tensor.experimental._context_parallel._attention as cp_attention | ||
| 101 | + from torch.nn.attention.flex_attention import create_block_mask | ||
| 102 | + | ||
| 103 | + def _eager_create_block_mask(*args, **kwargs): | ||
| 104 | + kwargs.pop("separate_full_blocks", None) | ||
| 105 | + kwargs["_compile"] = False | ||
| 106 | + return create_block_mask(*args, **kwargs) | ||
| 107 | + | ||
| 108 | + cp_attention._compiled_create_block_mask = _eager_create_block_mask # pyrefly: ignore [bad-assignment] | ||
| 109 | + except (ImportError, AttributeError): | ||
| 110 | + logger.debug("CP eager block-mask workaround is unavailable", exc_info=True) | ||
| 70 | 111 | ||
| 71 | logger.info("[PATCH] torchtitan.distributed.context_parallel.api.cp_shard -> patched_cp_shard") | 112 | logger.info("[PATCH] torchtitan.distributed.context_parallel.api.cp_shard -> patched_cp_shard") |
| 72 | context_parallel_api.cp_shard = patched_cp_shard # pyrefly: ignore [bad-assignment] | 113 | context_parallel_api.cp_shard = patched_cp_shard # pyrefly: ignore [bad-assignment] |
| 73 | 114 | ||
| 115 | + try: | ||
| 116 | + import torchtitan.distributed.context_parallel as context_parallel_root | ||
| 117 | + | ||
| 118 | + context_parallel_root.cp_shard = patched_cp_shard # pyrefly: ignore [bad-assignment] | ||
| 119 | + except ImportError: | ||
| 120 | + pass | ||
| 121 | + | ||
| 74 | 122 | ||
| 75 | apply() | 123 | apply() |
| @@ -0,0 +1,151 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""Backport contiguous-video MRoPE positions to the pinned upstream. | ||
| 8 | + | ||
| 9 | +Upstream PR: pending publication of the Qwen3.5 contiguous video-MRoPE fix. | ||
| 10 | +Upstream base: ``b175497ea3502388bb9513391810a86ca46dbfa8``. | ||
| 11 | + | ||
| 12 | +The collator builds positions before the model Config exists, so a late Config | ||
| 13 | +override cannot repair this behavior. Remove when the pinned upstream revision | ||
| 14 | +contains the contiguous-video MRoPE fix. | ||
| 15 | +""" | ||
| 16 | + | ||
| 17 | +from __future__ import annotations | ||
| 18 | + | ||
| 19 | +import inspect | ||
| 20 | + | ||
| 21 | +import torch | ||
| 22 | +from torchtitan.hf_datasets.multimodal.mm_collator import MultiModalCollator | ||
| 23 | + | ||
| 24 | +_ORIGINAL = MultiModalCollator._build_mrope_positions | ||
| 25 | +_EXPECTED_PARAMETERS = ( | ||
| 26 | + ("self", inspect.Parameter.POSITIONAL_OR_KEYWORD), | ||
| 27 | + ("tokens", inspect.Parameter.POSITIONAL_OR_KEYWORD), | ||
| 28 | + ("grid_thw", inspect.Parameter.POSITIONAL_OR_KEYWORD), | ||
| 29 | + ("grid_thw_videos", inspect.Parameter.POSITIONAL_OR_KEYWORD), | ||
| 30 | + ("positions", inspect.Parameter.POSITIONAL_OR_KEYWORD), | ||
| 31 | + ("image_token_id", inspect.Parameter.KEYWORD_ONLY), | ||
| 32 | + ("video_token_id", inspect.Parameter.KEYWORD_ONLY), | ||
| 33 | +) | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def _parameter_contract(fn): | ||
| 37 | + return tuple((parameter.name, parameter.kind) for parameter in inspect.signature(fn).parameters.values()) | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def patched_build_mrope_positions( | ||
| 41 | + self, | ||
| 42 | + tokens: torch.Tensor, | ||
| 43 | + grid_thw: torch.Tensor | None, | ||
| 44 | + grid_thw_videos: torch.Tensor | None, | ||
| 45 | + positions: torch.Tensor | None, | ||
| 46 | + *, | ||
| 47 | + image_token_id: int, | ||
| 48 | + video_token_id: int, | ||
| 49 | +) -> torch.Tensor: | ||
| 50 | + """Build 3D MRoPE positions without flattening a video into frame grids.""" | ||
| 51 | + if self.patch_order != "block": | ||
| 52 | + raise ValueError(f"MRoPE requires patch_order='block', got {self.patch_order!r}.") | ||
| 53 | + | ||
| 54 | + spatial_merge_size = self.spatial_merge_size | ||
| 55 | + batch_size, seq_len = tokens.shape | ||
| 56 | + mrope_positions = torch.zeros(batch_size, seq_len, 3, dtype=tokens.dtype, device=tokens.device) | ||
| 57 | + | ||
| 58 | + resets = torch.zeros( | ||
| 59 | + batch_size, | ||
| 60 | + max(seq_len - 1, 0), | ||
| 61 | + dtype=torch.bool, | ||
| 62 | + device=tokens.device, | ||
| 63 | + ) | ||
| 64 | + if positions is not None: | ||
| 65 | + resets = positions[:, 1:] < positions[:, :-1] | ||
| 66 | + grid_thw_images = grid_thw if grid_thw is not None else tokens.new_empty((0, 3)) | ||
| 67 | + grid_thw_video = grid_thw_videos if grid_thw_videos is not None else tokens.new_empty((0, 3)) | ||
| 68 | + vision_mask = (tokens == image_token_id) | (tokens == video_token_id) | ||
| 69 | + prev_vision = torch.cat([torch.zeros_like(vision_mask[:, :1]), vision_mask[:, :-1]], dim=1) | ||
| 70 | + batch_vision_starts = vision_mask & ~prev_vision | ||
| 71 | + grid_cache: dict[tuple[int, int, int], torch.Tensor] = {} | ||
| 72 | + | ||
| 73 | + image_index, video_index = 0, 0 | ||
| 74 | + for sample_i in range(batch_size): | ||
| 75 | + llm_pos_ids_list: list[torch.Tensor] = [] | ||
| 76 | + | ||
| 77 | + if positions is not None: | ||
| 78 | + reset_indices = torch.where(resets[sample_i])[0] + 1 | ||
| 79 | + doc_starts = [0, *reset_indices.tolist()] | ||
| 80 | + doc_ranges = [ | ||
| 81 | + ( | ||
| 82 | + doc_starts[d], | ||
| 83 | + doc_starts[d + 1] if d + 1 < len(doc_starts) else seq_len, | ||
| 84 | + ) | ||
| 85 | + for d in range(len(doc_starts)) | ||
| 86 | + ] | ||
| 87 | + else: | ||
| 88 | + doc_ranges = [(0, seq_len)] | ||
| 89 | + | ||
| 90 | + sample_tokens = tokens[sample_i] | ||
| 91 | + sample_vision_starts = torch.where(batch_vision_starts[sample_i])[0].tolist() | ||
| 92 | + vision_start_index = 0 | ||
| 93 | + | ||
| 94 | + for doc_start, doc_end in doc_ranges: | ||
| 95 | + doc_pos_ids_list: list[torch.Tensor] = [] | ||
| 96 | + doc_vision_starts: list[int] = [] | ||
| 97 | + while vision_start_index < len(sample_vision_starts) and sample_vision_starts[vision_start_index] < doc_end: | ||
| 98 | + doc_vision_starts.append(sample_vision_starts[vision_start_index]) | ||
| 99 | + vision_start_index += 1 | ||
| 100 | + | ||
| 101 | + pair_cursor = doc_start | ||
| 102 | + for vision_start in doc_vision_starts: | ||
| 103 | + if sample_tokens[vision_start] == image_token_id: | ||
| 104 | + t, h, w = grid_thw_images[image_index] | ||
| 105 | + image_index += 1 | ||
| 106 | + else: | ||
| 107 | + t, h, w = grid_thw_video[video_index] | ||
| 108 | + video_index += 1 | ||
| 109 | + | ||
| 110 | + llm_grid_t, llm_grid_h, llm_grid_w = ( | ||
| 111 | + int(t.item()), | ||
| 112 | + int(h.item()) // spatial_merge_size, | ||
| 113 | + int(w.item()) // spatial_merge_size, | ||
| 114 | + ) | ||
| 115 | + text_len = vision_start - pair_cursor | ||
| 116 | + pos_id_offset = doc_pos_ids_list[-1].max() + 1 if len(doc_pos_ids_list) > 0 else 0 | ||
| 117 | + doc_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + pos_id_offset) | ||
| 118 | + | ||
| 119 | + grid_key = (llm_grid_t, llm_grid_h, llm_grid_w) | ||
| 120 | + if grid_key not in grid_cache: | ||
| 121 | + hw = llm_grid_h * llm_grid_w | ||
| 122 | + t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, hw).flatten() | ||
| 123 | + h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() | ||
| 124 | + w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() | ||
| 125 | + grid_cache[grid_key] = torch.stack([t_index, h_index, w_index]) | ||
| 126 | + doc_pos_ids_list.append(grid_cache[grid_key] + text_len + pos_id_offset) | ||
| 127 | + pair_cursor = vision_start + llm_grid_t * llm_grid_h * llm_grid_w | ||
| 128 | + | ||
| 129 | + if pair_cursor < doc_end: | ||
| 130 | + pos_id_offset = doc_pos_ids_list[-1].max() + 1 if len(doc_pos_ids_list) > 0 else 0 | ||
| 131 | + text_len = doc_end - pair_cursor | ||
| 132 | + doc_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + pos_id_offset) | ||
| 133 | + | ||
| 134 | + llm_pos_ids_list.extend(doc_pos_ids_list) | ||
| 135 | + | ||
| 136 | + mrope_positions[sample_i] = torch.cat(llm_pos_ids_list, dim=1).T | ||
| 137 | + | ||
| 138 | + return mrope_positions | ||
| 139 | + | ||
| 140 | + | ||
| 141 | +def apply() -> None: | ||
| 142 | + """Install the backport once, rejecting an unknown upstream contract.""" | ||
| 143 | + current = MultiModalCollator._build_mrope_positions | ||
| 144 | + if current is patched_build_mrope_positions: | ||
| 145 | + return | ||
| 146 | + if current is not _ORIGINAL or _parameter_contract(current) != _EXPECTED_PARAMETERS: | ||
| 147 | + raise RuntimeError("Unsupported upstream MultiModalCollator signature") | ||
| 148 | + MultiModalCollator._build_mrope_positions = patched_build_mrope_positions | ||
| 149 | + | ||
| 150 | + | ||
| 151 | +__all__ = ["apply"] | ||
| @@ -127,6 +127,11 @@ class HashRouter(TokenChoiceTopKRouter): | |||
| 127 | # (torchtitan TokenChoiceTopKRouter pattern). | 127 | # (torchtitan TokenChoiceTopKRouter pattern). |
| 128 | with torch.autocast(device_type=x_BLD.device.type, dtype=torch.float32): | 128 | with torch.autocast(device_type=x_BLD.device.type, dtype=torch.float32): |
| 129 | scores = self.gate(x_BLD) | 129 | scores = self.gate(x_BLD) |
| 130 | + if isinstance(scores, DTensor): | ||
| 131 | + scores = scores.to_local() | ||
| 132 | + if isinstance(expert_bias_E, DTensor): | ||
| 133 | + expert_bias_E = expert_bias_E.to_local() | ||
| 134 | + | ||
| 130 | # scores is already float32 from the autocast above. | 135 | # scores is already float32 from the autocast above. |
| 131 | if self.score_func == "sigmoid": | 136 | if self.score_func == "sigmoid": |
| 132 | scores = torch.sigmoid(scores) | 137 | scores = torch.sigmoid(scores) |
| @@ -201,15 +206,30 @@ class HashMoE(MoE): | |||
| 201 | """ | 206 | """ |
| 202 | _B, L, _D = x_BLD.shape | 207 | _B, L, _D = x_BLD.shape |
| 203 | sp_size = getattr(self.routed_experts.token_dispatcher, "sp_size", 1) | 208 | sp_size = getattr(self.routed_experts.token_dispatcher, "sp_size", 1) |
| 209 | + # Older TorchTitan dispatchers reconstruct the sequence after SP. Keep | ||
| 210 | + # the padded local length explicit so the combine operation can restore | ||
| 211 | + # the same shape; newer dispatchers ignore these optional arguments. | ||
| 212 | + legacy_seq_padding = hasattr(self, "seq_dim_tp_sharded") | ||
| 213 | + num_local_tokens_after_seq_dim_padding = None | ||
| 204 | if not isinstance(x_BLD, DTensor) and getattr(self, "seq_dim_tp_sharded", False): | 214 | if not isinstance(x_BLD, DTensor) and getattr(self, "seq_dim_tp_sharded", False): |
| 205 | seq_pad = 0 | 215 | seq_pad = 0 |
| 206 | seq_dim_pad_tokens = 0 | 216 | seq_dim_pad_tokens = 0 |
| 217 | + if legacy_seq_padding: | ||
| 218 | + num_local_tokens_after_seq_dim_padding = _B * L | ||
| 207 | else: | 219 | else: |
| 208 | seq_pad = sp_size - L if sp_size > L else 0 | 220 | seq_pad = sp_size - L if sp_size > L else 0 |
| 209 | if seq_pad: | 221 | if seq_pad: |
| 210 | x_BLD = F.pad(x_BLD, (0, 0, 0, seq_pad)) | 222 | x_BLD = F.pad(x_BLD, (0, 0, 0, seq_pad)) |
| 211 | L = L + seq_pad | 223 | L = L + seq_pad |
| 212 | seq_dim_pad_tokens = (-L) % sp_size | 224 | seq_dim_pad_tokens = (-L) % sp_size |
| 225 | + if legacy_seq_padding: | ||
| 226 | + local_batch_size = x_BLD._local_tensor.shape[0] if isinstance(x_BLD, DTensor) else _B | ||
| 227 | + if local_batch_size != _B: | ||
| 228 | + raise NotImplementedError( | ||
| 229 | + "Legacy sequence-dimension padding requires an unsharded batch; " | ||
| 230 | + "DP-sharded DTensor batches are not supported." | ||
| 231 | + ) | ||
| 232 | + num_local_tokens_after_seq_dim_padding = local_batch_size * (L + seq_dim_pad_tokens) // sp_size | ||
| 213 | 233 | ||
| 214 | ( | 234 | ( |
| 215 | topk_scores_BLK, | 235 | topk_scores_BLK, |
| @@ -231,13 +251,25 @@ class HashMoE(MoE): | |||
| 231 | 251 | ||
| 232 | if self.training: | 252 | if self.training: |
| 233 | with torch.no_grad(): | 253 | with torch.no_grad(): |
| 234 | - self.tokens_per_expert_E.add_(num_local_tokens_per_expert_E) | 254 | + token_count = num_local_tokens_per_expert_E |
| 255 | + if isinstance(self.tokens_per_expert_E, DTensor) and not isinstance(token_count, DTensor): | ||
| 256 | + token_count = DTensor.from_local( | ||
| 257 | + token_count, | ||
| 258 | + self.tokens_per_expert_E.device_mesh, | ||
| 259 | + self.tokens_per_expert_E.placements, | ||
| 260 | + run_check=False, | ||
| 261 | + ) | ||
| 262 | + self.tokens_per_expert_E.add_(token_count) | ||
| 235 | 263 | ||
| 264 | + routed_expert_kwargs = {} | ||
| 265 | + if num_local_tokens_after_seq_dim_padding is not None: | ||
| 266 | + routed_expert_kwargs["num_local_tokens_after_seq_dim_padding"] = num_local_tokens_after_seq_dim_padding | ||
| 236 | out_BLD = self.routed_experts( | 267 | out_BLD = self.routed_experts( |
| 237 | x_BLD, | 268 | x_BLD, |
| 238 | topk_scores_BLK, | 269 | topk_scores_BLK, |
| 239 | topk_expert_ids_BLK, | 270 | topk_expert_ids_BLK, |
| 240 | num_local_tokens_per_expert_E, | 271 | num_local_tokens_per_expert_E, |
| 272 | + **routed_expert_kwargs, | ||
| 241 | ) | 273 | ) |
| 242 | 274 | ||
| 243 | shared_out_BLD = self.shared_experts(x_BLD) if self.shared_experts is not None else None | 275 | shared_out_BLD = self.shared_experts(x_BLD) if self.shared_experts is not None else None |
| @@ -267,6 +299,8 @@ class _RouterScoreAbsorbingRoutedExperts(RoutedExperts): | |||
| 267 | topk_scores_BLK: torch.Tensor, | 299 | topk_scores_BLK: torch.Tensor, |
| 268 | topk_expert_ids_BLK: torch.Tensor, | 300 | topk_expert_ids_BLK: torch.Tensor, |
| 269 | num_local_tokens_per_expert_E: torch.Tensor, | 301 | num_local_tokens_per_expert_E: torch.Tensor, |
| 302 | + *, | ||
| 303 | + num_local_tokens_after_seq_dim_padding: int | None = None, | ||
| 270 | ) -> torch.Tensor: | 304 | ) -> torch.Tensor: |
| 271 | B, L, D = x_BLD.shape | 305 | B, L, D = x_BLD.shape |
| 272 | K = topk_scores_BLK.size(-1) | 306 | K = topk_scores_BLK.size(-1) |
| @@ -297,7 +331,13 @@ class _RouterScoreAbsorbingRoutedExperts(RoutedExperts): | |||
| 297 | routed_scores_R=routed_scores_R, | 331 | routed_scores_R=routed_scores_R, |
| 298 | ) | 332 | ) |
| 299 | 333 | ||
| 300 | - out_TD = dispatcher.combine(routed_output_RD, metadata, x_TD) | 334 | + combine_kwargs = {} |
| 335 | + if num_local_tokens_after_seq_dim_padding is not None: | ||
| 336 | + combine_kwargs = { | ||
| 337 | + "num_local_tokens_after_padding": num_local_tokens_after_seq_dim_padding, | ||
| 338 | + "local_seq_len_after_padding": num_local_tokens_after_seq_dim_padding // B, | ||
| 339 | + } | ||
| 340 | + out_TD = dispatcher.combine(routed_output_RD, metadata, x_TD, **combine_kwargs) | ||
| 301 | return out_TD.view(B, -1, D) | 341 | return out_TD.view(B, -1, D) |
| 302 | 342 | ||
| 303 | 343 | ||
| @@ -384,6 +424,14 @@ class _ClampFeedForward(FeedForward): | |||
| 384 | return self.w2(F.silu(gate) * up) | 424 | return self.w2(F.silu(gate) * up) |
| 385 | 425 | ||
| 386 | 426 | ||
| 427 | +def _as_config(config, config_type, **overrides): | ||
| 428 | + """Rebuild a config while retaining fields shared across upstream schemas.""" | ||
| 429 | + field_names = {config_field.name for config_field in dataclasses.fields(config_type)} | ||
| 430 | + values = {name: getattr(config, name) for name in field_names if hasattr(config, name)} | ||
| 431 | + values.update(overrides) | ||
| 432 | + return config_type(**values) | ||
| 433 | + | ||
| 434 | + | ||
| 387 | def _clamp_make_routed_experts_config( | 435 | def _clamp_make_routed_experts_config( |
| 388 | *, | 436 | *, |
| 389 | swiglu_limit: float = 0.0, | 437 | swiglu_limit: float = 0.0, |
| @@ -393,21 +441,30 @@ def _clamp_make_routed_experts_config( | |||
| 393 | """``make_routed_experts_config`` with the clamp passthrough.""" | 441 | """``make_routed_experts_config`` with the clamp passthrough.""" |
| 394 | cfg = _original_make_routed_experts_config(**kwargs) | 442 | cfg = _original_make_routed_experts_config(**kwargs) |
| 395 | dispatcher_config = cfg.token_dispatcher | 443 | dispatcher_config = cfg.token_dispatcher |
| 396 | - dispatcher_config = dataclasses.replace( | 444 | + # Only the dispatcher configs extended by the NPU patch understand this |
| 397 | - dispatcher_config, | 445 | + # option. HybridEP and MinimalAsyncEP intentionally retain upstream |
| 398 | - absorb_router_scores=absorb_router_scores, | 446 | + # schemas, so passing the field to them would fail during config |
| 399 | - ) | 447 | + # construction before a model can report which backend is unsupported. |
| 400 | - return dataclasses.replace( | 448 | + dispatcher_fields = {field.name for field in dataclasses.fields(dispatcher_config)} |
| 401 | - cfg, | 449 | + if "absorb_router_scores" in dispatcher_fields: |
| 402 | - inner_experts=dataclasses.replace(cfg.inner_experts, swiglu_limit=swiglu_limit), | 450 | + dispatcher_config = dataclasses.replace( |
| 403 | - token_dispatcher=dispatcher_config, | 451 | + dispatcher_config, |
| 404 | - ) | 452 | + absorb_router_scores=absorb_router_scores, |
| 453 | + ) | ||
| 454 | + inner_experts = cfg.inner_experts | ||
| 455 | + if isinstance(inner_experts, _ClampGroupedExperts.Config): | ||
| 456 | + inner_experts = dataclasses.replace(inner_experts, swiglu_limit=swiglu_limit) | ||
| 457 | + else: | ||
| 458 | + inner_experts = _as_config(inner_experts, _ClampGroupedExperts.Config, swiglu_limit=swiglu_limit) | ||
| 459 | + return dataclasses.replace(cfg, inner_experts=inner_experts, token_dispatcher=dispatcher_config) | ||
| 405 | 460 | ||
| 406 | 461 | ||
| 407 | def _clamp_make_ffn_config(*, swiglu_limit: float = 0.0, **kwargs): | 462 | def _clamp_make_ffn_config(*, swiglu_limit: float = 0.0, **kwargs): |
| 408 | """``make_ffn_config`` with the clamp passthrough.""" | 463 | """``make_ffn_config`` with the clamp passthrough.""" |
| 409 | cfg = _original_make_ffn_config(**kwargs) | 464 | cfg = _original_make_ffn_config(**kwargs) |
| 410 | - return dataclasses.replace(cfg, swiglu_limit=swiglu_limit) | 465 | + if isinstance(cfg, _ClampFeedForward.Config): |
| 466 | + return dataclasses.replace(cfg, swiglu_limit=swiglu_limit) | ||
| 467 | + return _as_config(cfg, _ClampFeedForward.Config, swiglu_limit=swiglu_limit) | ||
| 411 | 468 | ||
| 412 | 469 | ||
| 413 | # Assigned in ``apply()`` before the clamp factories are ever called; declared | 470 | # Assigned in ``apply()`` before the clamp factories are ever called; declared |
| @@ -97,7 +97,13 @@ class LocalTokenDispatcher(TorchTitanLocalTokenDispatcher): | |||
| 97 | routed_output_RD: torch.Tensor, | 97 | routed_output_RD: torch.Tensor, |
| 98 | metadata: LocalDispatchMetadata, | 98 | metadata: LocalDispatchMetadata, |
| 99 | x_TD: torch.Tensor, | 99 | x_TD: torch.Tensor, |
| 100 | + *, | ||
| 101 | + num_local_tokens_after_padding: int | None = None, | ||
| 102 | + local_seq_len_after_padding: int | None = None, | ||
| 100 | ) -> torch.Tensor: | 103 | ) -> torch.Tensor: |
| 104 | + # Local dispatch has no SP all-gather. Accept the legacy arguments so | ||
| 105 | + # the shared MoE compatibility path can call both dispatcher variants. | ||
| 106 | + del num_local_tokens_after_padding, local_seq_len_after_padding | ||
| 101 | out_TD = torch.zeros_like(x_TD) | 107 | out_TD = torch.zeros_like(x_TD) |
| 102 | # Patch override: the config is the single source of truth; skip the | 108 | # Patch override: the config is the single source of truth; skip the |
| 103 | # multiply when grouped experts applied scores before down projection. | 109 | # multiply when grouped experts applied scores before down projection. |
| @@ -253,6 +259,9 @@ class AllToAllTokenDispatcher(TorchTitanAllToAllTokenDispatcher): | |||
| 253 | routed_output_RD: torch.Tensor, | 259 | routed_output_RD: torch.Tensor, |
| 254 | metadata: AllToAllDispatchMetadata | LocalDispatchMetadata, | 260 | metadata: AllToAllDispatchMetadata | LocalDispatchMetadata, |
| 255 | x_TD: torch.Tensor, | 261 | x_TD: torch.Tensor, |
| 262 | + *, | ||
| 263 | + num_local_tokens_after_padding: int | None = None, | ||
| 264 | + local_seq_len_after_padding: int | None = None, | ||
| 256 | ) -> torch.Tensor: | 265 | ) -> torch.Tensor: |
| 257 | if self.ep_mesh is None: | 266 | if self.ep_mesh is None: |
| 258 | assert isinstance(metadata, LocalDispatchMetadata) | 267 | assert isinstance(metadata, LocalDispatchMetadata) |
| @@ -280,7 +289,23 @@ class AllToAllTokenDispatcher(TorchTitanAllToAllTokenDispatcher): | |||
| 280 | if get_spmd_backend() == "spmd_types" and spmd.is_type_checking(): | 289 | if get_spmd_backend() == "spmd_types" and spmd.is_type_checking(): |
| 281 | routed_output_RD = spmd.reinterpret_mesh(routed_output_RD, spmd.current_mesh()) | 290 | routed_output_RD = spmd.reinterpret_mesh(routed_output_RD, spmd.current_mesh()) |
| 282 | 291 | ||
| 283 | - out_TD = torch.zeros_like(x_TD) | 292 | + legacy_seq_padding = num_local_tokens_after_padding is not None |
| 293 | + if legacy_seq_padding: | ||
| 294 | + if local_seq_len_after_padding is None: | ||
| 295 | + raise ValueError("local_seq_len_after_padding is required with legacy SP padding") | ||
| 296 | + out_TD = torch.zeros( | ||
| 297 | + num_local_tokens_after_padding * getattr(self, "sp_size", 1), | ||
| 298 | + x_TD.shape[-1], | ||
| 299 | + device=x_TD.device, | ||
| 300 | + dtype=x_TD.dtype, | ||
| 301 | + ) | ||
| 302 | + token_indices_experts_sorted_N = self._sp_global_token_indices( # pyrefly: ignore [missing-attribute] | ||
| 303 | + metadata.token_indices_experts_sorted_N, | ||
| 304 | + local_seq_len_after_padding, | ||
| 305 | + ) | ||
| 306 | + else: | ||
| 307 | + out_TD = torch.zeros_like(x_TD) | ||
| 308 | + token_indices_experts_sorted_N = metadata.token_indices_experts_sorted_N | ||
| 284 | # Patch override: use the dispatcher config instead of a per-call flag; | 309 | # Patch override: use the dispatcher config instead of a per-call flag; |
| 285 | # grouped experts may have absorbed scores before the down projection. | 310 | # grouped experts may have absorbed scores before the down projection. |
| 286 | if not self.absorb_router_scores: | 311 | if not self.absorb_router_scores: |
| @@ -288,7 +313,6 @@ class AllToAllTokenDispatcher(TorchTitanAllToAllTokenDispatcher): | |||
| 288 | routed_output_RD.to(torch.float32) * metadata.topk_scores_experts_sorted_N.reshape(-1, 1) | 313 | routed_output_RD.to(torch.float32) * metadata.topk_scores_experts_sorted_N.reshape(-1, 1) |
| 289 | ).to(routed_output_RD.dtype) | 314 | ).to(routed_output_RD.dtype) |
| 290 | 315 | ||
| 291 | - token_indices_experts_sorted_N = metadata.token_indices_experts_sorted_N | ||
| 292 | assert isinstance(token_indices_experts_sorted_N, torch.Tensor) | 316 | assert isinstance(token_indices_experts_sorted_N, torch.Tensor) |
| 293 | return deterministic_scatter_add( | 317 | return deterministic_scatter_add( |
| 294 | out_TD, | 318 | out_TD, |
| @@ -0,0 +1,70 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
按照仓库规范,需要附上上游PR ![]() ![]() | |||
| 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 | +"""Backport the NPU-safe Qwen3.5 vision boundaries to pinned TorchTitan. | ||
| 7 | + | ||
| 8 | +Upstream PR: pending publication of the Qwen3.5 vision-mask fix. | ||
| 9 | +Upstream base: ``b175497ea3502388bb9513391810a86ca46dbfa8``. | ||
| 10 | + | ||
| 11 | +The mask builder and FSDP module boundary are fixed before a model Config can | ||
| 12 | +replace them, so a late Config override is insufficient. Remove when the | ||
| 13 | +pinned upstream revision builds masks eagerly off CUDA and returns an owning | ||
| 14 | +vision-encoder output. | ||
| 15 | + | ||
| 16 | +Still required as of 2026-09-16: upstream wires vision mask creation through | ||
| 17 | +``torch.compile(create_block_mask)`` even in eager runs, and under CANN 9.0.0 | ||
| 18 | +(what ``/usr/local/Ascend/cann`` resolves to on the dev container, selected | ||
| 19 | +first by the launcher env chain) that compiled wrapper fails to build while | ||
| 20 | +the eager path works. Only mask creation bypasses compile here; model-body | ||
| 21 | +compilation (aot_eager / inductor-ascendc) is unaffected. | ||
| 22 | +""" | ||
| 23 | + | ||
| 24 | +from __future__ import annotations | ||
| 25 | + | ||
| 26 | +from functools import wraps | ||
| 27 | + | ||
| 28 | +from torch.nn.attention.flex_attention import create_block_mask | ||
| 29 | +from torchtitan.models.qwen3_5 import vision_encoder as upstream_vision | ||
| 30 | + | ||
| 31 | +from torchtitan_npu.patches.workaround.eager_flex import ( | ||
| 32 | + mark_dense_sdpa_mask_mod, | ||
| 33 | +) | ||
| 34 | + | ||
| 35 | +_ORIGINAL_MASK_BUILDER = upstream_vision.compiled_create_block_mask | ||
| 36 | +_ORIGINAL_VISION_FORWARD = upstream_vision.Qwen35VisionEncoder.forward | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def eager_create_block_mask(mask_mod, *args, **kwargs): | ||
| 40 | + """Use the upstream block-mask implementation without Inductor workers.""" | ||
| 41 | + mark_dense_sdpa_mask_mod(mask_mod) | ||
| 42 | + kwargs["_compile"] = False | ||
| 43 | + return create_block_mask(mask_mod, *args, **kwargs) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +@wraps(_ORIGINAL_VISION_FORWARD) | ||
| 47 | +def owning_vision_encoder_forward(self, *args, **kwargs): | ||
| 48 | + """Return an owning tensor so FSDP keeps its pre-backward hook.""" | ||
| 49 | + return _ORIGINAL_VISION_FORWARD(self, *args, **kwargs).clone() | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def apply() -> None: | ||
| 53 | + """Install the two narrow vision fixes, rejecting an unknown API.""" | ||
| 54 | + mask_builder = upstream_vision.compiled_create_block_mask | ||
| 55 | + vision_forward = upstream_vision.Qwen35VisionEncoder.forward | ||
| 56 | + if mask_builder not in (eager_create_block_mask, _ORIGINAL_MASK_BUILDER): | ||
| 57 | + raise RuntimeError("Unsupported upstream Qwen3.5 vision mask builder") | ||
| 58 | + if vision_forward not in ( | ||
| 59 | + owning_vision_encoder_forward, | ||
| 60 | + _ORIGINAL_VISION_FORWARD, | ||
| 61 | + ): | ||
| 62 | + raise RuntimeError("Unsupported upstream Qwen3.5 vision forward") | ||
| 63 | + | ||
| 64 | + if mask_builder is _ORIGINAL_MASK_BUILDER: | ||
| 65 | + upstream_vision.compiled_create_block_mask = eager_create_block_mask | ||
| 66 | + if vision_forward is _ORIGINAL_VISION_FORWARD: | ||
| 67 | + upstream_vision.Qwen35VisionEncoder.forward = owning_vision_encoder_forward | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +__all__ = ["apply", "eager_create_block_mask", "owning_vision_encoder_forward"] | ||
| @@ -1,17 +1,19 @@ | |||
| 1 | +# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/3634 | ||
| 2 | +# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/3985 | ||
| 3 | + | ||
| 1 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | 4 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. |
| 2 | # Copyright (c) Meta Platforms, Inc. and affiliates. | 5 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | # | 6 | # |
| 4 | # This source code is licensed under the BSD-style license found in the | 7 | # This source code is licensed under the BSD-style license found in the |
| 5 | # LICENSE file in the root directory of this source tree. | 8 | # LICENSE file in the root directory of this source tree. |
| 6 | 9 | ||
| 7 | -# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/3634 | ||
| 8 | -# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/3985 | ||
| 9 | - | ||
| 10 | import functools | 10 | import functools |
| 11 | +import inspect | ||
| 11 | import logging | 12 | import logging |
| 12 | from dataclasses import dataclass, field | 13 | from dataclasses import dataclass, field |
| 13 | from typing import Any, cast | 14 | from typing import Any, cast |
| 14 | 15 | ||
| 16 | +import torch | ||
| 15 | import torchtitan.trainer | 17 | import torchtitan.trainer |
| 16 | from torchtitan.distributed import full_dtensor | 18 | from torchtitan.distributed import full_dtensor |
| 17 | from torchtitan.distributed.spmd_types import annotate_input_spmd_types | 19 | from torchtitan.distributed.spmd_types import annotate_input_spmd_types |
| @@ -23,6 +25,7 @@ from torchtitan_npu.patches.torchtitan.components.ema import EMAOptimizersContai | |||
| 23 | logger = logging.getLogger(__name__) | 25 | logger = logging.getLogger(__name__) |
| 24 | 26 | ||
| 25 | original_post_dataloading_process = Trainer.post_dataloading_process | 27 | original_post_dataloading_process = Trainer.post_dataloading_process |
| 28 | +original_pp_forward_backward_step = Trainer.pp_forward_backward_step | ||
| 26 | 29 | ||
| 27 | 30 | ||
| 28 | @functools.wraps(original_post_dataloading_process) | 31 | @functools.wraps(original_post_dataloading_process) |
| @@ -68,6 +71,62 @@ def patched_post_dataloading_process(self, input_dict, labels): | |||
| 68 | return original_post_dataloading_process(self, input_dict, labels) | 71 | return original_post_dataloading_process(self, input_dict, labels) |
| 69 | 72 | ||
| 70 | 73 | ||
| 74 | +def _run_presplit_pipeline_schedule( | ||
| 75 | + schedule, | ||
| 76 | + *, | ||
| 77 | + arg_mbs, | ||
| 78 | + kwarg_mbs, | ||
| 79 | + target_mbs, | ||
| 80 | + losses, | ||
| 81 | + loss_kwargs, | ||
| 82 | + return_outputs, | ||
| 83 | +): | ||
| 84 | + """Bridge the NPU Torch pipeline schedule's private microbatch API.""" | ||
| 85 | + if ( | ||
| 86 | + schedule._has_backward | ||
| 87 | + and getattr(schedule, "_backward_requires_autograd", True) | ||
| 88 | + and not torch.is_grad_enabled() | ||
| 89 | + ): | ||
| 90 | + raise RuntimeError("pipeline backward requires gradients") | ||
| 91 | + | ||
| 92 | + stages = getattr(schedule, "_stages", None) | ||
| 93 | + if stages is None: | ||
| 94 | + stages = [schedule._stage] | ||
| 95 | + for stage in stages: | ||
| 96 | + stage.has_backward = schedule._has_backward | ||
| 97 | + stage.clear_runtime_states() | ||
| 98 | + return schedule._step_microbatches( | ||
| 99 | + arg_mbs=arg_mbs, | ||
| 100 | + kwarg_mbs=kwarg_mbs, | ||
| 101 | + target_mbs=target_mbs, | ||
| 102 | + losses=losses, | ||
| 103 | + loss_kwargs=loss_kwargs, | ||
| 104 | + return_outputs=return_outputs, | ||
| 105 | + ) | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +@functools.wraps(original_pp_forward_backward_step) | ||
| 109 | +def patched_pp_forward_backward_step(self, *args, **kwargs): | ||
| 110 | + """Adapt older NPU pipeline schedules without changing Trainer semantics.""" | ||
| 111 | + schedule = self.pp_schedule | ||
| 112 | + parameters = inspect.signature(schedule.step).parameters | ||
| 113 | + if {"arg_mbs", "kwarg_mbs", "target_mbs"}.issubset(parameters): | ||
| 114 | + return original_pp_forward_backward_step(self, *args, **kwargs) | ||
| 115 | + if not hasattr(schedule, "_step_microbatches"): | ||
| 116 | + raise RuntimeError("installed pipeline schedule has no pre-split API") | ||
| 117 | + | ||
| 118 | + original_step = schedule.step | ||
| 119 | + had_instance_step = "step" in vars(schedule) | ||
| 120 | + schedule.step = functools.partial(_run_presplit_pipeline_schedule, schedule) | ||
| 121 | + try: | ||
| 122 | + return original_pp_forward_backward_step(self, *args, **kwargs) | ||
| 123 | + finally: | ||
| 124 | + if had_instance_step: | ||
| 125 | + schedule.step = original_step | ||
| 126 | + else: | ||
| 127 | + del schedule.step | ||
| 128 | + | ||
| 129 | + | ||
| 71 | class EMATrainer(Trainer): | 130 | class EMATrainer(Trainer): |
| 72 | """Trainer with upstream EMA configuration and optimizer wiring.""" | 131 | """Trainer with upstream EMA configuration and optimizer wiring.""" |
| 73 | 132 | ||
| @@ -90,6 +149,8 @@ class EMATrainer(Trainer): | |||
| 90 | def apply() -> None: | 149 | def apply() -> None: |
| 91 | logger.info("[PATCH] Trainer.post_dataloading_process -> patched_post_dataloading_process") | 150 | logger.info("[PATCH] Trainer.post_dataloading_process -> patched_post_dataloading_process") |
| 92 | Trainer.post_dataloading_process = patched_post_dataloading_process | 151 | Trainer.post_dataloading_process = patched_post_dataloading_process |
| 152 | + logger.info("[PATCH] Trainer.pp_forward_backward_step -> patched_pp_forward_backward_step") | ||
| 153 | + Trainer.pp_forward_backward_step = patched_pp_forward_backward_step | ||
| 93 | torchtitan.trainer.Trainer = EMATrainer | 154 | torchtitan.trainer.Trainer = EMATrainer |
| 94 | 155 | ||
| 95 | 156 | ||
| @@ -1,4 +1,4 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. |
| 2 | # | 2 | # |
| 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. |
| @@ -8,22 +8,246 @@ | |||
| 8 | Importing this module applies the workaround. | 8 | Importing this module applies the workaround. |
| 9 | """ | 9 | """ |
| 10 | 10 | ||
| 11 | +import functools | ||
| 12 | +import inspect | ||
| 13 | +from typing import Any, NamedTuple | ||
| 14 | + | ||
| 11 | import torch | 15 | import torch |
| 16 | +import torch.nn.functional as F | ||
| 12 | import torchtitan | 17 | import torchtitan |
| 18 | +from torch.nn.attention.flex_attention import ( | ||
| 19 | + BlockMask, | ||
| 20 | + create_mask, | ||
| 21 | +) | ||
| 13 | from torch.nn.attention.flex_attention import ( | 22 | from torch.nn.attention.flex_attention import ( |
| 14 | create_block_mask as eager_create_block_mask, | 23 | create_block_mask as eager_create_block_mask, |
| 15 | ) | 24 | ) |
| 16 | from torch.nn.attention.flex_attention import ( | 25 | from torch.nn.attention.flex_attention import ( |
| 17 | flex_attention as eager_flex_attention, | 26 | flex_attention as eager_flex_attention, |
| 18 | ) | 27 | ) |
| 28 | +from torchtitan.distributed import utils as dist_utils | ||
| 29 | + | ||
| 30 | +try: | ||
| 31 | + from torch.nn.attention.flex_attention import AuxOutput as _TorchAuxOutput | ||
| 32 | + from torch.nn.attention.flex_attention import AuxRequest as _TorchAuxRequest | ||
| 33 | +except ImportError: | ||
这个临时规避文件,非必要不允许再新增了 ![]() ![]() | |||
| 34 | + _TorchAuxOutput = None | ||
| 35 | + _TorchAuxRequest = None | ||
| 36 | + | ||
| 37 | +_DENSE_SDPA_OPT_IN = "_torchtitan_npu_dense_sdpa" | ||
| 38 | +_DENSE_SDPA_CACHE = "_torchtitan_npu_dense_mask_cache" | ||
| 39 | +_MAX_DENSE_MASK_ELEMENTS = 16 * 1024 * 1024 | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +class _CompatAuxOutput(NamedTuple): | ||
| 43 | + """Auxiliary-output shape for older Torch versions.""" | ||
| 44 | + | ||
| 45 | + lse: torch.Tensor | None = None | ||
| 46 | + max_scores: torch.Tensor | None = None | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +_EAGER_SUPPORTS_RETURN_AUX = "return_aux" in inspect.signature(eager_flex_attention).parameters | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def _requests_auxiliary_outputs(return_aux: Any) -> bool: | ||
| 53 | + if return_aux is None: | ||
| 54 | + return False | ||
| 55 | + if isinstance(return_aux, bool): | ||
| 56 | + return return_aux | ||
| 57 | + return bool(getattr(return_aux, "lse", False) or getattr(return_aux, "max_scores", False)) | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def _normalize_aux_request(return_aux: Any) -> Any: | ||
| 61 | + """Convert legacy bool/None requests to the current AuxRequest protocol.""" | ||
| 62 | + if _TorchAuxRequest is None: | ||
| 63 | + return return_aux | ||
| 64 | + if isinstance(return_aux, _TorchAuxRequest): | ||
| 65 | + return return_aux | ||
| 66 | + return _TorchAuxRequest( | ||
| 67 | + lse=bool(getattr(return_aux, "lse", return_aux) if return_aux is not None else False), | ||
| 68 | + max_scores=bool(getattr(return_aux, "max_scores", False)), | ||
| 69 | + ) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def _make_aux_output( | ||
| 73 | + *, | ||
| 74 | + lse: torch.Tensor | None = None, | ||
| 75 | + max_scores: torch.Tensor | None = None, | ||
| 76 | +) -> Any: | ||
| 77 | + if _TorchAuxOutput is not None: | ||
| 78 | + return _TorchAuxOutput(lse=lse, max_scores=max_scores) | ||
| 79 | + return _CompatAuxOutput(lse=lse, max_scores=max_scores) | ||
| 80 | + | ||
| 81 | + | ||
| 82 | +def _normalize_flex_result(result: Any) -> tuple[torch.Tensor, Any]: | ||
| 83 | + """Keep the (output, AuxOutput) contract across Torch API versions.""" | ||
| 84 | + if not isinstance(result, tuple) or len(result) != 2: | ||
| 85 | + return result, _make_aux_output() | ||
| 86 | + output, auxiliary = result | ||
| 87 | + if hasattr(auxiliary, "lse") and hasattr(auxiliary, "max_scores"): | ||
| 88 | + return output, auxiliary | ||
| 89 | + if isinstance(auxiliary, torch.Tensor): | ||
| 90 | + return output, _make_aux_output(lse=auxiliary) | ||
| 91 | + return output, _make_aux_output() | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def mark_dense_sdpa_mask_mod(mask_mod): | ||
| 95 | + """Opt one mask closure into the bounded NPU dense-SDPA fallback.""" | ||
| 96 | + setattr(mask_mod, _DENSE_SDPA_OPT_IN, True) | ||
| 97 | + setattr(mask_mod, _DENSE_SDPA_CACHE, {}) | ||
| 98 | + return mask_mod | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +def _validate_dense_mask_size( | ||
| 102 | + batch_size: int, | ||
| 103 | + query_len: int, | ||
| 104 | + key_len: int, | ||
| 105 | +) -> None: | ||
| 106 | + elements = batch_size * query_len * key_len | ||
| 107 | + if elements > _MAX_DENSE_MASK_ELEMENTS: | ||
| 108 | + raise RuntimeError( | ||
| 109 | + "NPU dense Flex fallback would materialize " | ||
| 110 | + f"{elements:,} boolean mask elements; the supported limit is " | ||
| 111 | + f"{_MAX_DENSE_MASK_ELEMENTS:,}. Reduce image/video resolution " | ||
| 112 | + "or sequence length." | ||
| 113 | + ) | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +def _dense_block_mask( | ||
| 117 | + block_mask: BlockMask, | ||
| 118 | + *, | ||
| 119 | + batch_size: int, | ||
| 120 | + query_len: int, | ||
| 121 | + key_len: int, | ||
| 122 | + device: torch.device, | ||
| 123 | +) -> torch.Tensor: | ||
| 124 | + _validate_dense_mask_size(batch_size, query_len, key_len) | ||
| 125 | + mask_mod = block_mask.mask_mod | ||
| 126 | + # Compile-time implicit NPU fallback masks are not marked by the vision | ||
| 127 | + # patch, so they may not carry the eager cache attribute. | ||
| 128 | + cache = getattr(mask_mod, _DENSE_SDPA_CACHE, None) | ||
| 129 | + if cache is None: | ||
| 130 | + cache = {} | ||
| 131 | + cache_key = (batch_size, query_len, key_len, device.type, device.index) | ||
| 132 | + if cache_key in cache: | ||
| 133 | + return cache[cache_key] | ||
| 134 | + | ||
| 135 | + mask = create_mask( | ||
| 136 | + mask_mod, | ||
| 137 | + batch_size, | ||
| 138 | + 1, | ||
| 139 | + query_len, | ||
| 140 | + key_len, | ||
| 141 | + device=device, | ||
| 142 | + ) | ||
| 143 | + diagonal = torch.eye(query_len, key_len, dtype=torch.bool, device=device)[None, None] | ||
| 144 | + mask = mask | (~mask.any(dim=-1, keepdim=True) & diagonal) | ||
| 145 | + cache[cache_key] = mask | ||
| 146 | + return mask | ||
| 147 | + | ||
| 148 | + | ||
| 149 | +def _run_eager_flex_attention( | ||
| 150 | + q: torch.Tensor, | ||
| 151 | + k: torch.Tensor, | ||
| 152 | + v: torch.Tensor, | ||
| 153 | + *, | ||
| 154 | + score_mod, | ||
| 155 | + block_mask, | ||
| 156 | + scale, | ||
| 157 | + enable_gqa, | ||
| 158 | + return_aux, | ||
| 159 | + kernel_options, | ||
| 160 | +): | ||
| 161 | + # During aot_eager, TorchTitan wraps FlexAttention in a regional | ||
| 162 | + # Inductor subcompile. The NPU flex lowering then selects CUDA Triton | ||
| 163 | + # templates; use the bounded dense SDPA path for eligible NPU masks only | ||
| 164 | + # while tracing. Eager execution remains explicitly opt-in via the marker. | ||
| 165 | + if ( | ||
| 166 | + score_mod is None | ||
| 167 | + and isinstance(block_mask, BlockMask) | ||
| 168 | + and block_mask.mask_mod is not None | ||
| 169 | + and ( | ||
| 170 | + getattr(block_mask.mask_mod, _DENSE_SDPA_OPT_IN, False) | ||
| 171 | + or (torch.compiler.is_compiling() and q.device.type == "npu") | ||
| 172 | + ) | ||
| 173 | + and block_mask.kv_num_blocks.shape[1] == 1 | ||
| 174 | + and q.shape[2] == k.shape[2] | ||
| 175 | + and not _requests_auxiliary_outputs(return_aux) | ||
| 176 | + ): | ||
| 177 | + del kernel_options | ||
| 178 | + dense_mask = _dense_block_mask( | ||
| 179 | + block_mask, | ||
| 180 | + batch_size=q.shape[0], | ||
| 181 | + query_len=q.shape[2], | ||
| 182 | + key_len=k.shape[2], | ||
| 183 | + device=q.device, | ||
| 184 | + ) | ||
| 185 | + return _normalize_flex_result( | ||
| 186 | + ( | ||
| 187 | + F.scaled_dot_product_attention( | ||
| 188 | + q, | ||
| 189 | + k, | ||
| 190 | + v, | ||
| 191 | + attn_mask=dense_mask, | ||
| 192 | + scale=scale, | ||
| 193 | + enable_gqa=enable_gqa, | ||
| 194 | + ), | ||
| 195 | + _make_aux_output(), | ||
| 196 | + ) | ||
| 197 | + ) | ||
| 198 | + | ||
| 199 | + # The pinned torch_npu build advertises return_aux, but its NPU flex | ||
| 200 | + # lowering sends that form through the CUDA Triton regional path while | ||
| 201 | + # tracing. Keep the protocol-preserving return_aux path for eager/CPU | ||
| 202 | + # callers; use the compatible legacy return_lse entry point only for the | ||
| 203 | + # NPU compile path. | ||
| 204 | + use_legacy_npu_compile = q.device.type == "npu" and torch.compiler.is_compiling() | ||
| 205 | + if _EAGER_SUPPORTS_RETURN_AUX and not use_legacy_npu_compile: | ||
| 206 | + result = eager_flex_attention( | ||
| 207 | + q, | ||
| 208 | + k, | ||
| 209 | + v, | ||
| 210 | + score_mod=score_mod, | ||
| 211 | + block_mask=block_mask, | ||
| 212 | + scale=scale, | ||
| 213 | + enable_gqa=enable_gqa, | ||
| 214 | + return_aux=_normalize_aux_request(return_aux), | ||
| 215 | + kernel_options=kernel_options, | ||
| 216 | + ) | ||
| 217 | + else: | ||
| 218 | + result = eager_flex_attention( | ||
| 219 | + q, | ||
| 220 | + k, | ||
| 221 | + v, | ||
| 222 | + score_mod=score_mod, | ||
| 223 | + block_mask=block_mask, | ||
| 224 | + scale=scale, | ||
| 225 | + enable_gqa=enable_gqa, | ||
| 226 | + return_lse=_requests_auxiliary_outputs(return_aux), | ||
| 227 | + kernel_options=kernel_options, | ||
| 228 | + ) | ||
| 229 | + return _normalize_flex_result(result) | ||
| 230 | + | ||
| 231 | + | ||
| 232 | +def _install_eager_flex_attention() -> None: | ||
| 233 | + torchtitan.models.common.attention.FlexAttention._compiled_flex_attn = staticmethod(_run_eager_flex_attention) | ||
| 234 | + | ||
| 235 | + | ||
| 236 | +_original_set_determinism = dist_utils.set_determinism | ||
| 237 | + | ||
| 238 | + | ||
| 239 | +@functools.wraps(_original_set_determinism) | ||
| 240 | +def _set_determinism_preserving_eager_flex(*args, **kwargs): | ||
| 241 | + result = _original_set_determinism(*args, **kwargs) | ||
| 242 | + _install_eager_flex_attention() | ||
| 243 | + return result | ||
| 19 | 244 | ||
| 20 | 245 | ||
| 21 | def apply() -> None: | 246 | def apply() -> None: |
| 22 | torch.nn.attention.flex_attention._FLEX_ATTENTION_DISABLE_COMPILE_DEBUG = True # pyrefly: ignore [bad-assignment] | 247 | torch.nn.attention.flex_attention._FLEX_ATTENTION_DISABLE_COMPILE_DEBUG = True # pyrefly: ignore [bad-assignment] |
| 23 | 248 | ||
| 24 | - torchtitan.models.common.attention.FlexAttention._compiled_flex_attn = staticmethod( | 249 | + _install_eager_flex_attention() |
| 25 | - lambda *args, **kwargs: eager_flex_attention(*args, **kwargs) | 250 | + dist_utils.set_determinism = _set_determinism_preserving_eager_flex |
| 26 | - ) | ||
| 27 | 251 | ||
| 28 | def _eager_create_block_mask(*args, **kwargs): | 252 | def _eager_create_block_mask(*args, **kwargs): |
| 29 | kwargs.pop("separate_full_blocks", None) | 253 | kwargs.pop("separate_full_blocks", None) |
| @@ -33,8 +257,8 @@ def apply() -> None: | |||
| 33 | torchtitan.models.common.attention._compiled_create_block_mask = _eager_create_block_mask | 257 | torchtitan.models.common.attention._compiled_create_block_mask = _eager_create_block_mask |
| 34 | 258 | ||
| 35 | if hasattr(torch.nn.attention.flex_attention, "_validate_device"): | 259 | if hasattr(torch.nn.attention.flex_attention, "_validate_device"): |
| 36 | - torch.nn.attention.flex_attention._validate_device = ( | 260 | + torch.nn.attention.flex_attention._validate_device = ( # pyrefly: ignore [bad-assignment] |
| 37 | - lambda q, k, v: None # pyrefly: ignore [bad-assignment] | 261 | + lambda query, key, value: None |
| 38 | ) | 262 | ) |
| 39 | 263 | ||
| 40 | 264 | ||


统一命名qwen35吧,统一不加下划线,文件名和编码也统一一下