Merged
refactor(dsv3.2): remove the varlen-CP capability, keep the model #1150
hanboyouAdd on Oct 31
refactor(dsv3.2): remove the varlen-CP capability, keep the model #1150
Merged
Total: 20 files changed+134-762
| @@ -34,7 +34,7 @@ rank-local)。0.3.0 三者皆无(无 `InnerAttention` / `ParallelismContext` | |||
| 34 | provider 节点; | 34 | provider 节点; |
| 35 | 2. per-batch metadata 由 backend config 构建(每 microbatch 每 backend 一次、同几何共享),CP 下由 **metadata 自己**的 | 35 | 2. per-batch metadata 由 backend config 构建(每 microbatch 每 backend 一次、同几何共享),CP 下由 **metadata 自己**的 |
| 36 | `prepare_cp_metadata` 产出 rank-local 副本(几何由 `cp_shard_context` 发布)(V4/V4.1 的记录在 CP 后**重建**)。 | 36 | `prepare_cp_metadata` 产出 rank-local 副本(几何由 `cp_shard_context` 发布)(V4/V4.1 的记录在 CP 后**重建**)。 |
| 37 | - 宿主是 metadata 而不是 backend 类:被重建的就是它,key 因此退化成纯寻址(V3.2 三栈均如此); | 37 | + 宿主是 metadata 而不是 backend 类:被重建的就是它,key 因此退化成纯寻址(V4/V4.1 如此;V3.2 的 CP 已退场); |
| 38 | 3. `.ci/architecture_import_baseline.json` 不再有 metadata 相关的 `extensions → models` 债务边:metadata dataclass | 38 | 3. `.ci/architecture_import_baseline.json` 不再有 metadata 相关的 `extensions → models` 债务边:metadata dataclass |
| 39 | 直接用 `torch.utils._pytree.register_dataclass` 注册(没有自定义 pytree shim,也没有 patch 目录里的新文件), | 39 | 直接用 `torch.utils._pytree.register_dataclass` 注册(没有自定义 pytree shim,也没有 patch 目录里的新文件), |
| 40 | activation order 不动; | 40 | activation order 不动; |
| @@ -59,10 +59,11 @@ rank-local)。0.3.0 三者皆无(无 `InnerAttention` / `ParallelismContext` | |||
| 59 | 59 | ||
| 60 | ### B. 三个栈迁到接缝(每栈一个 commit,可按同序拆成三个 PR) | 60 | ### B. 三个栈迁到接缝(每栈一个 commit,可按同序拆成三个 PR) |
| 61 | 61 | ||
| 62 | -- **V3.2**:`SparseInnerAttention.Config.build_attention_metadata` 建 packed layout(`ReferenceVarlenMetadata`;参考核 | 62 | +- **V3.2**:`SparseInnerAttention.Config.build_attention_metadata` 建 packed layout(`VarlenMetadata`); |
| 63 | - 不可 CP → `prepare_cp_metadata` 拒绝);`AscSparseInnerAttention.Config` 包成带 TND host 序列长度的 | 63 | + `AscSparseInnerAttention.Config` 包成带 TND host 序列长度的 `AscVarlenMetadata`。删 `metadata_extension` / |
| 64 | - `AscVarlenMetadata`,CP 用 `prepare_cp_varlen_metadata` 得 rank-local 再重读 host 列表。删 `metadata_extension` / | 64 | + `_metadata_extension` / `build_attention_masks` 与 `sparse_attn.asc_metadata`。该栈的 varlen-CP 已整体退场: |
| 65 | - `_metadata_extension` / `build_attention_masks` 与 `sparse_attn.asc_metadata`。 | 65 | + 所有 attention config 都派生自 `VarlenAttention.Config`,pinned decoder 在 CP>1 时于配置阶段报错,不再需要 |
| 66 | + rank-local 的 metadata 变换。 | ||
| 66 | - **V4.1**:参考核只保留自己读的几何(`window_size` / `softmax_scale` / `compress_ratio`),metadata 是**整行的 | 67 | - **V4.1**:参考核只保留自己读的几何(`window_size` / `softmax_scale` / `compress_ratio`),metadata 是**整行的 |
| 67 | document 边界**(`create_varlen_metadata_for_document` 的 `cu_seq_q`)加上后端在同一处按自己的 ratio 折一次的 | 68 | document 边界**(`create_varlen_metadata_for_document` 的 `cu_seq_q`)加上后端在同一处按自己的 ratio 折一次的 |
| 68 | 池化轴 `cu_seq_k`(消费者不再除);kernel 几何与 records | 69 | 池化轴 `cu_seq_k`(消费者不再除);kernel 几何与 records |
| @@ -109,8 +110,9 @@ rank-local)。0.3.0 三者皆无(无 `InnerAttention` / `ParallelismContext` | |||
| 109 | - **map 键默认是 backend 类**(同上游;#4897 自述的限制):一个类多套几何时由 config 用 `attention_metadata_key` 声明 | 110 | - **map 键默认是 backend 类**(同上游;#4897 自述的限制):一个类多套几何时由 config 用 `attention_metadata_key` 声明 |
| 110 | 几何键。0.3.0 无 `InnerAttention.__init__`,键在 `Module.Config.build` 时**无条件**盖到实例上——SimpleFSDP / | 111 | 几何键。0.3.0 无 `InnerAttention.__init__`,键在 `Module.Config.build` 时**无条件**盖到实例上——SimpleFSDP / |
| 111 | GraphTrainer 会改写模块的 `__class__`,条件盖章会让层按运行时类型查找而拿到 `None`。 | 112 | GraphTrainer 会改写模块的 `__class__`,条件盖章会让层按运行时类型查找而拿到 `None`。 |
| 112 | -- **不能切分的栈必须显式拒绝**:无 `prepare_cp_metadata` 的条目原样透传,V3.2 参考核因此在变换里 raise,而不是让层静默读 | 113 | +- **不能切分的栈必须显式拒绝**:无 `prepare_cp_metadata` 的条目原样透传;V3.2 已没有 rank-local CP 变换,其所有 |
| 113 | - 到本 rank 不持有的全局 layout。 | 114 | + attention config 都派生自 `VarlenAttention.Config`,pinned decoder 在 CP>1 时于配置阶段报错,层不会静默读到 |
| 115 | + 本 rank 不持有的全局 layout。 | ||
| 114 | - **V4 的 LI provider 随 metadata 走**(provider config 是该 metadata 上的字段):只带扁平几何时,量化 LI + | 116 | - **V4 的 LI provider 随 metadata 走**(provider config 是该 metadata 上的字段):只带扁平几何时,量化 LI + |
| 115 | CP/batch-chunk 的重新切分会静默产出 BF16 记录。 | 117 | CP/batch-chunk 的重新切分会静默产出 BF16 记录。 |
| 116 | - **本仓无 NPU**:A/B 的等价性依据是逐字段比对(同 frames 输入、同算子参数与顺序、同报错文本)与 CPU UT,数值结论待设备 | 118 | - **本仓无 NPU**:A/B 的等价性依据是逐字段比对(同 frames 输入、同算子参数与顺序、同报错文本)与 CPU UT,数值结论待设备 |
| @@ -136,12 +138,13 @@ CP 变换落在模型的 `Decoder._cp_shard`(与上游同名同职责;0.3.0 | |||
| 136 | 138 | ||
| 137 | | 文件内容 | 性质 | 退出条件 | | 139 | | 文件内容 | 性质 | 退出条件 | |
| 138 | | --- | --- | --- | | 140 | | --- | --- | --- | |
| 139 | -| `_varlen_from_masks` + `patched_cp_shard` | pinned `cp_shard` 不处理 varlen mask | **qwen3.5 迁到接缝之后**。三个 DeepSeek 栈不再往 `extra_kwargs` 放 `attention_masks`(V3.2+asc+CP 下该函数等价于 `original_cp_shard`,只做输入切分;!1099 起它另外承载本仓自己的布局 balancer `doc_chunk`,rank-local metadata 仍由 `_cp_shard` → `prepare_cp_metadata_map` → 各栈 **backend 类**的 `prepare_cp_metadata` 产生),只剩 qwen3.5 的兜底 `get_attention_masks()` 产出 `VarlenMetadata`,由 varlen 分支改写成 `CPVarlenMetadata` 供它的掩码适配器读 `k_global_gather_indices` | | 141 | +| `patched_cp_shard` 的 doc-chunk 布局 balancer | 仓库自有布局:rank `r` 的窗口是每篇文档的第 `r` 段;rank-local metadata 由各栈自己的 `prepare_cp_metadata` 或整行边界重建,shard 只切张量 | 上游 `cp_shard` 提供布局注册点,或 doc-chunk 布局并入上游后删除 | |
| 140 | | `apply()` 里的 `_compiled_create_block_mask` eager 改写 | **NPU 运行时约束**:torch CP helper 内部惰性 `torch.compile(create_block_mask)`(`torch/distributed/tensor/experimental/_context_parallel/_attention.py`)会起 worker 进程、无法再初始化 NPU,「CP + BlockMask」路径必须换成 eager | 搬到 **`patches/torch_npu/`**(它改的是 torch 内部符号,不属于 torchtitan 的 CP 语义补丁;`extensions/torchtitan/eager_flex.py` 里那份改写的是另一个同名符号 `torchtitan.models.common.attention._compiled_create_block_mask`,两者不重复),或等 torch/torch_npu 不再用 worker 进程建 mask | | 142 | | `apply()` 里的 `_compiled_create_block_mask` eager 改写 | **NPU 运行时约束**:torch CP helper 内部惰性 `torch.compile(create_block_mask)`(`torch/distributed/tensor/experimental/_context_parallel/_attention.py`)会起 worker 进程、无法再初始化 NPU,「CP + BlockMask」路径必须换成 eager | 搬到 **`patches/torch_npu/`**(它改的是 torch 内部符号,不属于 torchtitan 的 CP 语义补丁;`extensions/torchtitan/eager_flex.py` 里那份改写的是另一个同名符号 `torchtitan.models.common.attention._compiled_create_block_mask`,两者不重复),或等 torch/torch_npu 不再用 worker 进程建 mask | |
| 141 | 143 | ||
| 142 | -两个条件都满足后该文件整体删除。`varlen_cp.py` 的 `CPVarlenMetadata`/`from_global` **不随之删**:它现在只剩 V3.2 的 | 144 | +DeepSeek-V3.2 的 varlen-CP backport(`patched_cp_shard` 的 varlen 分支、参考核与 AscendC entry 的 |
| 143 | -map 路径在用(V4 在 !1099 之后与 V4.1 共用 doc-chunk 布局、由整行边界重建 metadata,不再走 `from_global`,见 | 145 | +`prepare_cp_metadata`)已整体删除:该栈不再支持 CP,pinned decoder 在配置阶段就拒绝 CP>1,不需要第二道 rank-local |
| 144 | -`./2026-10-28-doc-chunk-layout.md`)。V3.2 的 CP 仍拒绝,`from_global` 随上游 #5071 或 V3.2 同样迁到 doc-chunk 一起退场。 | 146 | +守卫。qwen3.5 的 rank-local 转换仍在其自己的 `override/qwen3_5/parallelize.py` 钩子里(`QwenCPMetadata`),不经过 |
| 147 | +这条分支。 | ||
| 145 | 148 | ||
| 146 | qwen3.5 那一步的核对点:它的 inner attention 要声明 `build_attention_metadata`(+ 需要的 geometry key),并把 rank-local | 149 | qwen3.5 那一步的核对点:它的 inner attention 要声明 `build_attention_metadata`(+ 需要的 geometry key),并把 rank-local |
| 147 | 转换从 forward 的掩码适配器挪进自己的 `prepare_cp_metadata`。这条路径**参与数值**,删前须做 NPU CP=1/CP=2 对齐。 | 150 | 转换从 forward 的掩码适配器挪进自己的 `prepare_cp_metadata`。这条路径**参与数值**,删前须做 NPU CP=1/CP=2 对齐。 |
| @@ -42,8 +42,8 @@ CP 的布局定义为整行的**一个置换**:rank `r` 的窗口是每篇文 | |||
| 42 | ## Consequences | 42 | ## Consequences |
| 43 | 43 | ||
| 44 | - 两栈共用一套 metadata:`cu_seq_q` / `cu_seq_k` / `positions_q` / `exchange` 这类别名一起删掉,改成 | 44 | - 两栈共用一套 metadata:`cu_seq_q` / `cu_seq_k` / `positions_q` / `exchange` 这类别名一起删掉,改成 |
| 45 | - `q` / `swa_k` / `cmp_k` 三个 frame 加 `position_k`(V4.1 另有 `restore`)。`varlen_cp.CPVarlenMetadata.from_global` | 45 | + `q` / `swa_k` / `cmp_k` 三个 frame 加 `position_k`(V4.1 另有 `restore`)。原先 V3.2 专用的 varlen-CP |
| 46 | - 只剩 V3.2 用。 | 46 | + rank-local metadata(`from_global`)已随该栈的 CP 能力退场删除,也没有第二个消费者。 |
| 47 | - CLI 取值 `chunk_r` 改名 `doc_chunk`,示例脚本与数值对齐脚本同步;`parallelize` 侧不再为 CP 准备 batch 维搬移。 | 47 | - CLI 取值 `chunk_r` 改名 `doc_chunk`,示例脚本与数值对齐脚本同步;`parallelize` 侧不再为 CP 准备 batch 维搬移。 |
| 48 | - arch22(910)+ CP>1 不再编译:融合 metadata 带 device 行数(key 压实的 `nonzero`),编译区无法 guard。判为 | 48 | - arch22(910)+ CP>1 不再编译:融合 metadata 带 device 行数(key 压实的 `nonzero`),编译区无法 guard。判为 |
| 49 | 不可编译时告警并跑 eager,训练照常;代价是 arch22 上开编译跑 CP 的作业会变慢。 | 49 | 不可编译时告警并跑 eager,训练照常;代价是 arch22 上开编译跑 CP 的作业会变慢。 |
| @@ -113,9 +113,9 @@ | |||
| 113 | 时标为待决,不能靠改标签宣称兼容性已验证。 | 113 | 时标为待决,不能靠改标签宣称兼容性已验证。 |
| 114 | 114 | ||
| 115 | CI 与 `requirements.txt` 的部分版本和 CANN 路径有意不同:`.ci/unit_test.sh` 与 | 115 | CI 与 `requirements.txt` 的部分版本和 CANN 路径有意不同:`.ci/unit_test.sh` 与 |
| 116 | -`.ci/common.sh` 都改装 nightly 的 `torchvision` 覆盖 requirements 中的正式版,两者的 CANN | 116 | +`.ci/common.sh` 都改装 PyTorch CPU index 的 `torchvision==0.29.0+cpu`,覆盖镜像内按 |
| 117 | -入口也不同(前者 source Jenkins 目录下的 CANN,后者用 | 117 | +requirements 安装的同版本 wheel,两者的 CANN 入口也不同(前者 source Jenkins 目录下的 |
| 118 | -`/usr/local/Ascend/cann/set_env.sh`)。 | 118 | +CANN,后者用 `/usr/local/Ascend/cann/set_env.sh`)。 |
| 119 | 119 | ||
| 120 | CI 通过只能证明其实际软件栈下的检查结果,不能替代另一套 requirements 配置的验证。 | 120 | CI 通过只能证明其实际软件栈下的检查结果,不能替代另一套 requirements 配置的验证。 |
| 121 | 121 | ||
| @@ -74,9 +74,9 @@ _setup_torchtitan "${TORCHTITAN_DIR}" | |||
| 74 | # Grain needs its data-pipeline dependencies (for example etils and array-record). | 74 | # Grain needs its data-pipeline dependencies (for example etils and array-record). |
| 75 | # Its dependency graph does not include torch or torch_npu. | 75 | # Its dependency graph does not include torch or torch_npu. |
| 76 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-cache-dir grain==0.2.18 | 76 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-cache-dir grain==0.2.18 |
| 77 | -# The CI image supplies torch 2.15.0.dev; the matching torchvision nightly | 77 | +# The CI image supplies torch 2.14.0.dev; the matching torchvision CPU wheel |
| 78 | # is installed with --no-deps (resolving its torch pin would fight the image). | 78 | # is installed with --no-deps (resolving its torch pin would fight the image). |
| 79 | -"${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" | 79 | +"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir --index-url https://download.pytorch.org/whl/cpu "torchvision==0.29.0+cpu" |
| 80 | "${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu, torchvision' | 80 | "${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu, torchvision' |
| 81 | 81 | ||
| 82 | export MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" | 82 | export MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" |
| @@ -63,8 +63,9 @@ pip install --no-deps attn-gym==0.0.16 spmd_types==0.2.5 \ | |||
| 63 | # Resolve Grain's own data-pipeline dependencies without changing the torch stack. | 63 | # Resolve Grain's own data-pipeline dependencies without changing the torch stack. |
| 64 | pip install grain==0.2.18 | 64 | pip install grain==0.2.18 |
| 65 | 65 | ||
| 66 | -pip install --no-deps torchvision==0.30.0.dev20260918 \ | 66 | +pip install --no-deps torchvision==0.29.0+cpu \ |
| 67 | - --extra-index-url https://download.pytorch.org/whl/nightly/cpu | 67 | + --index-url https://download.pytorch.org/whl/cpu |
| 68 | +python -c 'import torch, torchvision; print(torch.__version__, torchvision.__version__)' | ||
| 68 | 69 | ||
| 69 | python -c 'from torchtitan.distributed.context_parallel.api import cp_shard; print(cp_shard.__module__)' | 70 | python -c 'from torchtitan.distributed.context_parallel.api import cp_shard; print(cp_shard.__module__)' |
| 70 | python -m pytest -v --tb=short tests/unit_tests | 71 | python -m pytest -v --tb=short tests/unit_tests |
| @@ -74,7 +74,7 @@ MTP 的 future-token shift 不能在 CP rank-local 序列上执行:局部移 | |||
| 74 | 74 | ||
| 75 | 这些张量在 `preprocess_inputs` 中先于基座切分、在全局行上构建;随后 `super().preprocess_inputs()` 完成 `inputs`/`labels`/`positions` 的切分,MTP 三个张量再用**同一把连续切片**单独 `cp_shard`(本地切片,无通信),保证 token、label 和 mask 与 `inputs` 在每个 rank 上严格同位。 | 75 | 这些张量在 `preprocess_inputs` 中先于基座切分、在全局行上构建;随后 `super().preprocess_inputs()` 完成 `inputs`/`labels`/`positions` 的切分,MTP 三个张量再用**同一把连续切片**单独 `cp_shard`(本地切片,无通信),保证 token、label 和 mask 与 `inputs` 在每个 rank 上严格同位。 |
| 76 | 76 | ||
| 77 | -该流程只接入 DeepSeek-V4:继续复用已有压缩 metadata 和 CP plan 构造;MTP 张量的切分是独立的一次 `cp_shard` 调用,与 `inputs`/`labels`/`positions` 的切分使用同一把连续切片。DeepSeek-V3 和 DeepSeek-V3.2 保留社区 MTP 的原有限制,`context_parallel_degree > 1` 时在配置更新阶段报错;两者已有的非 MTP CP 路径不变。 | 77 | +该流程只接入 DeepSeek-V4:继续复用已有压缩 metadata 和 CP plan 构造;MTP 张量的切分是独立的一次 `cp_shard` 调用,与 `inputs`/`labels`/`positions` 的切分使用同一把连续切片。DeepSeek-V3 和 DeepSeek-V3.2 保留社区 MTP 的原有限制,`context_parallel_degree > 1` 时在配置更新阶段报错;DeepSeek-V3.2 的 varlen attention 本身也不支持 CP,DeepSeek-V3 已有的非 MTP CP 路径不变。 |
| 78 | 78 | ||
| 79 | 该处理与 Megatron-LM MTP 在 CP 边界交换 future token/label 的数学目标一致;区别是 TorchTitan 的模型 metadata hook 位于 CP 切分之前,因此可直接在全局序列上生成,再按和输入相同的连续切法单独切分,无需额外点对点通信。 | 79 | 该处理与 Megatron-LM MTP 在 CP 边界交换 future token/label 的数学目标一致;区别是 TorchTitan 的模型 metadata hook 位于 CP 切分之前,因此可直接在全局序列上生成,再按和输入相同的连续切法单独切分,无需额外点对点通信。 |
| 80 | 80 | ||
| @@ -83,7 +83,6 @@ python -m tests.integration_tests.run_tests ./test_reports/v41-reference-mm \ | |||
| 83 | | **`dsv4_mtp_smla_cp2`** | DeepSeek-V4 MTP | CP2(连续切片) | 2 | 否 | 覆盖 MTP forward、chunked loss 及 backward 算子路径 | | 83 | | **`dsv4_mtp_smla_cp2`** | DeepSeek-V4 MTP | CP2(连续切片) | 2 | 否 | 覆盖 MTP forward、chunked loss 及 backward 算子路径 | |
| 84 | | **`dsv3_2_dsa_1rank`** | DeepSeek-V3.2 | 1 Rank,DSA 算子 | 1 | **是** | 校验 DSA attention override 并在 1-rank 下做数值 Loss 比对 | | 84 | | **`dsv3_2_dsa_1rank`** | DeepSeek-V3.2 | 1 Rank,DSA 算子 | 1 | **是** | 校验 DSA attention override 并在 1-rank 下做数值 Loss 比对 | |
| 85 | | **`dsv3_2_dsa_ep2_fsdp2`** | DeepSeek-V3.2 | DSA + EP2/FSDP2 | 2 | **是** | 校验分布式 DSA 算子 30-step 精度对齐 | | 85 | | **`dsv3_2_dsa_ep2_fsdp2`** | DeepSeek-V3.2 | DSA + EP2/FSDP2 | 2 | **是** | 校验分布式 DSA 算子 30-step 精度对齐 | |
| 86 | -| **`dsv3_2_dsa_cp2`** | DeepSeek-V3.2 | DSA + CP2 | 2 | 否 | 校验 DSA 在 CP2 模式下的训练触发与通信 | | ||
| 87 | | **`dsv4_ema_ep2_fsdp2`** | DeepSeek-V4 | Golden + EP2/FSDP2 + EMA CPU Offload | 2 | 否 | 校验 DCP Checkpoint Metadata 完整包含 `ema_optimizer.*` | | 86 | | **`dsv4_ema_ep2_fsdp2`** | DeepSeek-V4 | Golden + EP2/FSDP2 + EMA CPU Offload | 2 | 否 | 校验 DCP Checkpoint Metadata 完整包含 `ema_optimizer.*` | |
| 88 | 87 | ||
| 89 | --- | 88 | --- |
| @@ -11,10 +11,7 @@ NPU does not run in production). | |||
| 11 | 11 | ||
| 12 | from tests.integration_tests import OverrideDefinitions | 12 | from tests.integration_tests import OverrideDefinitions |
| 13 | 13 | ||
| 14 | -_DSA_OVERRIDES = ( | 14 | +_DSA_OVERRIDES = "torchtitan_npu.override.common.rope.workaround,torchtitan_npu.override.deepseek_v3_2.sparse_attn.asc" |
| 15 | - "torchtitan_npu.override.common.rope.workaround," | ||
| 16 | - "torchtitan_npu.override.deepseek_v3_2.sparse_attn.asc" | ||
| 17 | -) | ||
| 18 | 15 | ||
| 19 | 16 | ||
| 20 | def build_deepseek_v3_2_test_list() -> list[OverrideDefinitions]: | 17 | def build_deepseek_v3_2_test_list() -> list[OverrideDefinitions]: |
| @@ -65,30 +62,4 @@ def build_deepseek_v3_2_test_list() -> list[OverrideDefinitions]: | |||
| 65 | "CONFIG": "deepseek_v3_2_debugmodel", | 62 | "CONFIG": "deepseek_v3_2_debugmodel", |
| 66 | }, | 63 | }, |
| 67 | ), | 64 | ), |
| 68 | - OverrideDefinitions( | ||
| 69 | - override_args=[ | ||
| 70 | - ( | ||
| 71 | - "--training.steps=1", | ||
| 72 | - "--parallelism.context-parallel-degree=2", | ||
| 73 | - "--parallelism.context-parallel-load-balancer=headtail", | ||
| 74 | - "--parallelism.spmd-backend=spmd_types", | ||
| 75 | - "--hf-assets-path=tests/assets/deepseek_v3", | ||
| 76 | - "--training.local-batch-size=2", | ||
| 77 | - "--training.global-batch-size=4", | ||
| 78 | - "--training.seq-len=128", | ||
| 79 | - "--optimizer.param-groups.0.optimizer-kwargs.lr=1e-5", | ||
| 80 | - "--override.imports", | ||
| 81 | - _DSA_OVERRIDES, | ||
| 82 | - ) | ||
| 83 | - ], | ||
| 84 | - test_descr="DeepSeek-V3.2 DSA CP2 smoke", | ||
| 85 | - test_name="dsv3_2_dsa_cp2", | ||
| 86 | - ngpu=2, | ||
| 87 | - use_golden=False, | ||
| 88 | - check_loss=False, | ||
| 89 | - env_vars={ | ||
| 90 | - "MODULE": "torchtitan_npu.models.deepseek_v3_2", | ||
| 91 | - "CONFIG": "deepseek_v3_2_debugmodel", | ||
| 92 | - }, | ||
| 93 | - ), | ||
| 94 | ] | 65 | ] |
| @@ -92,13 +92,10 @@ _DEFERRED_VISION_TESTS = { | |||
| 92 | 92 | ||
| 93 | 93 | ||
| 94 | # DeepSeek-V3.2 still forwards the pre-fold ``[B, L, ...]`` layout against the | 94 | # DeepSeek-V3.2 still forwards the pre-fold ``[B, L, ...]`` layout against the |
| 95 | -# folded pinned upstream. These two cross the unmigrated seams: the AscendC CP | 95 | +# folded pinned upstream. This test crosses the unmigrated seam: the decoder |
| 96 | -# entry's positions unpack and the decoder config's context-length knob. Match | 96 | +# config's context-length knob. Match the integration runner's dsv3_2 deferral |
| 97 | -# the integration runner's dsv3_2 deferral until the folded-token migration lands. | 97 | +# until the folded-token migration lands. |
| 98 | _DEFERRED_DSV32_FOLD_TESTS = { | 98 | _DEFERRED_DSV32_FOLD_TESTS = { |
| 99 | - "models/deepseek_v3_2/test_metadata_seam.py": { | ||
| 100 | - "test_the_ascendc_entry_prepares_this_ranks_copy_for_context_parallel", | ||
| 101 | - }, | ||
| 102 | "models/test_mtp_cp_chunk_loss.py": { | 99 | "models/test_mtp_cp_chunk_loss.py": { |
| 103 | "test_dsv32_mtp_keeps_community_cp_restriction", | 100 | "test_dsv32_mtp_keeps_community_cp_restriction", |
| 104 | }, | 101 | }, |
| @@ -317,12 +314,5 @@ def dsv4(): | |||
| 317 | ns.metadata = importlib.import_module("torchtitan_npu.models.deepseek_v4.metadata") | 314 | ns.metadata = importlib.import_module("torchtitan_npu.models.deepseek_v4.metadata") |
| 318 | ns.attention = importlib.import_module("torchtitan_npu.models.deepseek_v4.attention") | 315 | ns.attention = importlib.import_module("torchtitan_npu.models.deepseek_v4.attention") |
| 319 | ns.compressor = importlib.import_module("torchtitan_npu.models.deepseek_v4.compressor") | 316 | ns.compressor = importlib.import_module("torchtitan_npu.models.deepseek_v4.compressor") |
| 320 | - spec = importlib.util.spec_from_file_location( | ||
| 321 | - "varlen_cp_backport", | ||
| 322 | - _REPO / "torchtitan_npu" / "patches" / "torchtitan" / "distributed" / "varlen_cp.py", | ||
| 323 | - ) | ||
| 324 | - varlen_cp = importlib.util.module_from_spec(spec) | ||
| 325 | - spec.loader.exec_module(varlen_cp) | ||
| 326 | - ns.CPVarlenMetadata = varlen_cp.CPVarlenMetadata | ||
| 327 | ns.cann_ops = importlib.import_module("cann_ops_transformer") | 317 | ns.cann_ops = importlib.import_module("cann_ops_transformer") |
| 328 | return ns | 318 | return ns |
| @@ -27,7 +27,6 @@ from torchtitan.models.common.rope import CosSinRoPE | |||
| 27 | 27 | ||
| 28 | from torchtitan_npu.models.deepseek_v3_2 import model_registry | 28 | from torchtitan_npu.models.deepseek_v3_2 import model_registry |
| 29 | from torchtitan_npu.models.deepseek_v3_2.model import DeepSeekV32Model, Indexer, SparseInnerAttention | 29 | from torchtitan_npu.models.deepseek_v3_2.model import DeepSeekV32Model, Indexer, SparseInnerAttention |
| 30 | -from torchtitan_npu.patches.torchtitan.distributed.varlen_cp import CPVarlenMetadata | ||
| 31 | from torchtitan_npu.patches.torchtitan.models.common.aux_loss import AuxLoss | 30 | from torchtitan_npu.patches.torchtitan.models.common.aux_loss import AuxLoss |
| 32 | 31 | ||
| 33 | # Two documents in one packed row, the second one longer than ``topk``. | 32 | # Two documents in one packed row, the second one longer than ``topk``. |
| @@ -305,27 +304,6 @@ def test_the_indexer_loss_reads_the_selected_rows_of_every_document(): | |||
| 305 | assert float(core.indexer_loss.instance_acc) == pytest.approx(kl / denominator, rel=1e-5) | 304 | assert float(core.indexer_loss.instance_acc) == pytest.approx(kl / denominator, rel=1e-5) |
| 306 | 305 | ||
| 307 | 306 | ||
| 308 | -def test_the_reference_core_rejects_context_parallel_metadata(): | ||
| 309 | - """A CP rank holds a document's middle, which attn-gym's prefix-aligned causal cannot express.""" | ||
| 310 | - inputs = _inputs(seed=0) | ||
| 311 | - cu = torch.tensor([0, 3, 8], dtype=torch.int32) | ||
| 312 | - cp_metadata = CPVarlenMetadata( | ||
| 313 | - cu_seq_q=cu, | ||
| 314 | - cu_seq_k=torch.tensor([0, 3, 5], dtype=torch.int32), | ||
| 315 | - max_q=3, | ||
| 316 | - max_k=3, | ||
| 317 | - k_global_gather_indices=torch.arange(8), | ||
| 318 | - ) | ||
| 319 | - | ||
| 320 | - try: | ||
| 321 | - _core()(attention_masks=cp_metadata, scale=_SCALE, **inputs) | ||
| 322 | - except ValueError as error: | ||
| 323 | - assert "context-parallel" in str(error) | ||
| 324 | - assert "override.deepseek_v3_2.sparse_attn.asc" in str(error) | ||
| 325 | - else: | ||
| 326 | - raise AssertionError("the reference core must refuse context-parallel metadata") | ||
| 327 | - | ||
| 328 | - | ||
| 329 | def test_the_shipped_layers_dispatch_to_a_varlen_mask(): | 307 | def test_the_shipped_layers_dispatch_to_a_varlen_mask(): |
| 330 | """The mask seam reads the inner attention's config, so the model must declare a varlen one. | 308 | """The mask seam reads the inner attention's config, so the model must declare a varlen one. |
| 331 | 309 | ||
| @@ -1,212 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 2 | -# | ||
| 3 | -# This source code is licensed under the BSD-style license found in the | ||
| 4 | -# LICENSE file in the root directory of this source tree. | ||
| 5 | - | ||
| 6 | -"""CPU oracle for DeepSeek-V3.2 context-parallel varlen metadata. | ||
| 7 | - | ||
| 8 | -The DSV3.2 CP2 integration case proves that the NPU training entry can be | ||
| 9 | -triggered. These tests cover the metadata hand-off before that entry: | ||
| 10 | -document boundaries, causal K ranges, and gather indices for each rank. The | ||
| 11 | -expected values below are derived from the document layout and the head/tail | ||
| 12 | -permutation, not from ``CPVarlenMetadata`` itself. The query-index union check | ||
| 13 | -only guards rank partition coverage; production input sharding and the | ||
| 14 | -Attention consumer remain the responsibility of the integration case. | ||
| 15 | - | ||
| 16 | -No NPU or collective is required here. Cross-rank communication and kernel | ||
| 17 | -execution remain the responsibility of ``dsv3_2_dsa_cp2``. | ||
| 18 | -""" | ||
| 19 | - | ||
| 20 | -from bisect import bisect_right | ||
| 21 | -from itertools import pairwise | ||
| 22 | - | ||
| 23 | -import torch | ||
| 24 | -from torch.distributed.tensor.experimental._context_parallel._load_balancer import ( | ||
| 25 | - _HeadTailLoadBalancer, | ||
| 26 | -) | ||
| 27 | -from torchtitan.models.common.attention import VarlenMetadata | ||
| 28 | - | ||
| 29 | -from torchtitan_npu.patches.torchtitan.distributed.varlen_cp import CPVarlenMetadata | ||
| 30 | - | ||
| 31 | - | ||
| 32 | -class _FakeCPMesh: | ||
| 33 | - """Small CPU stand-in for the 1-D DeviceMesh metadata contract.""" | ||
| 34 | - | ||
| 35 | - ndim = 1 | ||
| 36 | - | ||
| 37 | - def __init__(self, rank: int, world_size: int): | ||
| 38 | - self._rank = rank | ||
| 39 | - self._world_size = world_size | ||
| 40 | - | ||
| 41 | - def size(self) -> int: | ||
| 42 | - return self._world_size | ||
| 43 | - | ||
| 44 | - def get_local_rank(self) -> int: | ||
| 45 | - return self._rank | ||
| 46 | - | ||
| 47 | - | ||
| 48 | -def _global_metadata() -> VarlenMetadata: | ||
| 49 | - # Two batches with deliberately different document boundaries. The | ||
| 50 | - # flattened offsets are [0, 3, 8, 13, 16], which exposes both a document | ||
| 51 | - # split inside a rank and a split across CP ranks. | ||
| 52 | - cu = torch.tensor([0, 3, 8, 13, 16], dtype=torch.int32) | ||
| 53 | - return VarlenMetadata(cu_seq_q=cu, cu_seq_k=cu, max_q=5, max_k=5) | ||
| 54 | - | ||
| 55 | - | ||
| 56 | -def _headtail_indices(seq_length: int, cp_world_size: int) -> list[int]: | ||
| 57 | - """Independent reference for the head/tail rank permutation.""" | ||
| 58 | - chunk = seq_length // (2 * cp_world_size) | ||
| 59 | - return [ | ||
| 60 | - pos | ||
| 61 | - for rank in range(cp_world_size) | ||
| 62 | - for chunk_id in (rank, 2 * cp_world_size - 1 - rank) | ||
| 63 | - for pos in range(chunk_id * chunk, (chunk_id + 1) * chunk) | ||
| 64 | - ] | ||
| 65 | - | ||
| 66 | - | ||
| 67 | -def _reference_layout( | ||
| 68 | - cu_seq: list[int], | ||
| 69 | - *, | ||
| 70 | - batch_size: int, | ||
| 71 | - seq_length: int, | ||
| 72 | - cp_world_size: int, | ||
| 73 | - rank: int, | ||
| 74 | - permutation: list[int], | ||
| 75 | -) -> tuple[list[int], list[int], list[int], list[int], list[list[int]]]: | ||
| 76 | - """Derive rank-local metadata with a small, non-tensor reference. | ||
| 77 | - | ||
| 78 | - ``permutation`` maps a position in the head/tail stream to its original | ||
| 79 | - position. The reference deliberately uses Python list operations and | ||
| 80 | - document boundaries instead of reproducing ``CPVarlenMetadata``'s tensor | ||
| 81 | - implementation. | ||
| 82 | - """ | ||
| 83 | - shard_len = seq_length // cp_world_size | ||
| 84 | - rank_q = [ | ||
| 85 | - batch * seq_length + position | ||
| 86 | - for batch in range(batch_size) | ||
| 87 | - for position in permutation[rank * shard_len : (rank + 1) * shard_len] | ||
| 88 | - ] | ||
| 89 | - inverse = [permutation.index(position) for position in range(seq_length)] | ||
| 90 | - | ||
| 91 | - q_lengths: list[int] = [] | ||
| 92 | - k_lengths: list[int] = [] | ||
| 93 | - gather: list[int] = [] | ||
| 94 | - causal_ranges: list[list[int]] = [] | ||
| 95 | - segment_start = 0 | ||
| 96 | - for index in range(1, len(rank_q) + 1): | ||
| 97 | - is_end = index == len(rank_q) | ||
| 98 | - if not is_end: | ||
| 99 | - previous, current = rank_q[index - 1], rank_q[index] | ||
| 100 | - previous_doc = bisect_right(cu_seq, previous) - 1 | ||
| 101 | - current_doc = bisect_right(cu_seq, current) - 1 | ||
| 102 | - is_end = previous_doc != current_doc or current != previous + 1 | ||
| 103 | - if not is_end: | ||
| 104 | - continue | ||
| 105 | - | ||
| 106 | - segment = rank_q[segment_start:index] | ||
| 107 | - document = bisect_right(cu_seq, segment[0]) - 1 | ||
| 108 | - document_start = cu_seq[document] | ||
| 109 | - causal_end = segment[-1] | ||
| 110 | - causal = list(range(document_start, causal_end + 1)) | ||
| 111 | - q_lengths.append(len(segment)) | ||
| 112 | - k_lengths.append(len(causal)) | ||
| 113 | - causal_ranges.append(causal) | ||
| 114 | - for position in causal: | ||
| 115 | - batch, local_position = divmod(position, seq_length) | ||
| 116 | - gather.append(batch * seq_length + inverse[local_position]) | ||
| 117 | - segment_start = index | ||
| 118 | - | ||
| 119 | - def cumulative(lengths: list[int]) -> list[int]: | ||
| 120 | - result = [0] | ||
| 121 | - for length in lengths: | ||
| 122 | - result.append(result[-1] + length) | ||
| 123 | - return result | ||
| 124 | - | ||
| 125 | - return cumulative(q_lengths), cumulative(k_lengths), gather, rank_q, causal_ranges | ||
| 126 | - | ||
| 127 | - | ||
| 128 | -def _assert_tensor(actual: torch.Tensor, expected: list[int]) -> None: | ||
| 129 | - torch.testing.assert_close(actual.cpu(), torch.tensor(expected, dtype=actual.dtype)) | ||
| 130 | - | ||
| 131 | - | ||
| 132 | -def _assert_metadata_dtypes(metadata: CPVarlenMetadata) -> None: | ||
| 133 | - assert metadata.cu_seq_q.dtype == torch.int32 | ||
| 134 | - assert metadata.cu_seq_k.dtype == torch.int32 | ||
| 135 | - assert metadata.k_global_gather_indices.dtype == torch.int64 | ||
| 136 | - | ||
| 137 | - | ||
| 138 | -def test_cp_varlen_metadata_cp1_is_the_global_layout(): | ||
| 139 | - metadata = _global_metadata() | ||
| 140 | - expected_q, expected_k, expected_gather, _, _ = _reference_layout( | ||
| 141 | - metadata.cu_seq_q.tolist(), | ||
| 142 | - batch_size=2, | ||
| 143 | - seq_length=8, | ||
| 144 | - cp_world_size=1, | ||
| 145 | - rank=0, | ||
| 146 | - permutation=list(range(8)), | ||
| 147 | - ) | ||
| 148 | - result = CPVarlenMetadata.from_global( | ||
| 149 | - metadata, | ||
| 150 | - _FakeCPMesh(rank=0, world_size=1), | ||
| 151 | - batch_size=2, | ||
| 152 | - seq_length=8, | ||
| 153 | - ) | ||
| 154 | - | ||
| 155 | - _assert_metadata_dtypes(result) | ||
| 156 | - _assert_tensor(result.cu_seq_q, expected_q) | ||
| 157 | - _assert_tensor(result.cu_seq_k, expected_k) | ||
| 158 | - _assert_tensor(result.k_global_gather_indices, expected_gather) | ||
| 159 | - expected_max_q = max(q - p for p, q in pairwise(expected_q)) | ||
| 160 | - expected_max_k = max(k - p for p, k in pairwise(expected_k)) | ||
| 161 | - assert (result.max_q, result.max_k) == (expected_max_q, expected_max_k) | ||
| 162 | - | ||
| 163 | - | ||
| 164 | -def test_cp_varlen_metadata_cp2_headtail_preserves_cp1_document_semantics(): | ||
| 165 | - metadata = _global_metadata() | ||
| 166 | - batch_size = 2 | ||
| 167 | - sequence_length = 8 | ||
| 168 | - permutation = _headtail_indices(sequence_length, cp_world_size=2) | ||
| 169 | - assert permutation == [0, 1, 6, 7, 2, 3, 4, 5] | ||
| 170 | - | ||
| 171 | - load_balancer = _HeadTailLoadBalancer(sequence_length, 2, "cpu") | ||
| 172 | - torch.testing.assert_close(load_balancer._generate_indices()[0], torch.tensor(permutation, dtype=torch.int32)) | ||
| 173 | - | ||
| 174 | - all_rank_q: list[int] = [] | ||
| 175 | - for rank in range(2): | ||
| 176 | - cu_q, cu_k, gather, rank_q, causal_ranges = _reference_layout( | ||
| 177 | - metadata.cu_seq_q.tolist(), | ||
| 178 | - batch_size=batch_size, | ||
| 179 | - seq_length=sequence_length, | ||
| 180 | - cp_world_size=2, | ||
| 181 | - rank=rank, | ||
| 182 | - permutation=permutation, | ||
| 183 | - ) | ||
| 184 | - all_rank_q.extend(rank_q) | ||
| 185 | - result = CPVarlenMetadata.from_global( | ||
| 186 | - metadata, | ||
| 187 | - _FakeCPMesh(rank=rank, world_size=2), | ||
| 188 | - batch_size=batch_size, | ||
| 189 | - seq_length=sequence_length, | ||
| 190 | - load_balancer=load_balancer, | ||
| 191 | - ) | ||
| 192 | - _assert_metadata_dtypes(result) | ||
| 193 | - _assert_tensor(result.cu_seq_q, cu_q) | ||
| 194 | - _assert_tensor(result.cu_seq_k, cu_k) | ||
| 195 | - _assert_tensor(result.k_global_gather_indices, gather) | ||
| 196 | - assert result.max_q == max(q - p for p, q in pairwise(cu_q)) | ||
| 197 | - assert result.max_k == max(k - p for p, k in pairwise(cu_k)) | ||
| 198 | - | ||
| 199 | - # The production gather indices address the head/tail-reordered K | ||
| 200 | - # stream. Mapping them back through the independent permutation must | ||
| 201 | - # recover each CP segment's ordinary causal prefix from the CP=1 | ||
| 202 | - # layout. This is the actual semantic equivalence being protected. | ||
| 203 | - restored = [ | ||
| 204 | - permutation[index % sequence_length] + (index // sequence_length) * sequence_length for index in gather | ||
| 205 | - ] | ||
| 206 | - token_ids = torch.arange(batch_size * sequence_length) | ||
| 207 | - restored_tokens = token_ids[restored].tolist() | ||
| 208 | - for segment, expected_causal in enumerate(causal_ranges): | ||
| 209 | - k_start, k_end = cu_k[segment], cu_k[segment + 1] | ||
| 210 | - assert restored_tokens[k_start:k_end] == expected_causal | ||
| 211 | - | ||
| 212 | - assert sorted(all_rank_q) == list(range(2 * sequence_length)) | ||
| @@ -9,18 +9,20 @@ The stack used to build one mask object in ``DeepSeekV32Model`` and post-process | |||
| 9 | it through a ``metadata_extension``. Now every attention backend declares what | 9 | it through a ``metadata_extension``. Now every attention backend declares what |
| 10 | it consumes (upstream #4897's ``build_attention_metadata``): the reference core | 10 | it consumes (upstream #4897's ``build_attention_metadata``): the reference core |
| 11 | names the packed layout it reads, the AscendC override wraps that layout with the | 11 | names the packed layout it reads, the AscendC override wraps that layout with the |
| 12 | -host length lists its TND kernels take, and the decoder builds one entry per | 12 | +host length list its TND kernels take, and the decoder builds one entry per |
| 13 | -backend for the whole microbatch. These tests pin that sharing, the CP half the | 13 | +backend for the whole microbatch. These tests pin that sharing and the AscendC |
| 14 | -AscendC entry derives for itself, and the reference core's refusal to be sharded. | 14 | +entry's host length list. |
| 15 | """ | 15 | """ |
| 16 | 16 | ||
| 17 | from types import SimpleNamespace | 17 | from types import SimpleNamespace |
| 18 | 18 | ||
| 19 | import pytest | 19 | import pytest |
| 20 | import torch | 20 | import torch |
| 21 | +from torchtitan.config import ParallelismConfig | ||
| 22 | +from torchtitan.models.common.attention import VarlenMetadata | ||
| 23 | +from torchtitan.models.common.decoder import Decoder | ||
| 21 | 24 | ||
| 22 | import torchtitan_npu # noqa: F401 imported for its patch chain: the seam under test | 25 | import torchtitan_npu # noqa: F401 imported for its patch chain: the seam under test |
| 23 | -from torchtitan.models.common.attention import VarlenMetadata | ||
| 24 | from torchtitan_npu.models.deepseek_v3_2 import ( | 26 | from torchtitan_npu.models.deepseek_v3_2 import ( |
| 25 | ComplexRoPE, | 27 | ComplexRoPE, |
| 26 | DeepSeekV32Model, | 28 | DeepSeekV32Model, |
| @@ -30,14 +32,11 @@ from torchtitan_npu.models.deepseek_v3_2 import ( | |||
| 30 | _build_dsv3_2_layers, | 32 | _build_dsv3_2_layers, |
| 31 | ) | 33 | ) |
| 32 | from torchtitan_npu.models.deepseek_v3_2 import model as v32_model | 34 | from torchtitan_npu.models.deepseek_v3_2 import model as v32_model |
| 33 | -from torchtitan_npu.models.deepseek_v3_2.model import ReferenceVarlenMetadata, SparseInnerAttention | 35 | +from torchtitan_npu.models.deepseek_v3_2.model import SparseInnerAttention |
| 34 | -from torchtitan_npu.override.deepseek_v3_2.sparse_attn import asc | 36 | +from torchtitan_npu.override.deepseek_v3_2.sparse_attn import asc, ascendc |
| 35 | from torchtitan_npu.override.deepseek_v3_2.sparse_attn.ascendc import AscSparseInnerAttention, AscVarlenMetadata | 37 | from torchtitan_npu.override.deepseek_v3_2.sparse_attn.ascendc import AscSparseInnerAttention, AscVarlenMetadata |
| 36 | -from torchtitan_npu.patches.torchtitan.distributed.varlen_cp import CPVarlenMetadata | ||
| 37 | -from torchtitan_npu.patches.torchtitan.models.common.attention_metadata import cp_shard_context_set | ||
| 38 | 38 | ||
| 39 | -# Two documents of four tokens in one packed row: the headtail load balancer | 39 | +# Two documents of four tokens in one packed row. |
| 40 | -# needs a sequence length divisible by ``2 * cp`` for the two-rank case below. | ||
| 41 | _POSITIONS = torch.tensor([0, 1, 2, 3, 0, 1, 2, 3]) | 40 | _POSITIONS = torch.tensor([0, 1, 2, 3, 0, 1, 2, 3]) |
| 42 | _SEQ_LEN = 8 | 41 | _SEQ_LEN = 8 |
| 43 | _CU_SEQ = [0, 4, 8] | 42 | _CU_SEQ = [0, 4, 8] |
| @@ -45,23 +44,6 @@ _NO_CP_DIMS = SimpleNamespace(cp_enabled=False, get_mesh=lambda name: None) | |||
| 45 | _NO_SPMD = SimpleNamespace(spmd_backend="partial_dtensor") | 44 | _NO_SPMD = SimpleNamespace(spmd_backend="partial_dtensor") |
| 46 | 45 | ||
| 47 | 46 | ||
| 48 | -class _FakeCPMesh: | ||
| 49 | - """The 1-D mesh contract ``CPVarlenMetadata.from_global`` reads.""" | ||
| 50 | - | ||
| 51 | - ndim = 1 | ||
| 52 | - device_type = "cpu" | ||
| 53 | - | ||
| 54 | - def __init__(self, rank: int, world_size: int): | ||
| 55 | - self._rank = rank | ||
| 56 | - self._world_size = world_size | ||
| 57 | - | ||
| 58 | - def size(self, dim: int | None = None) -> int: | ||
| 59 | - return self._world_size | ||
| 60 | - | ||
| 61 | - def get_local_rank(self) -> int: | ||
| 62 | - return self._rank | ||
| 63 | - | ||
| 64 | - | ||
| 65 | def _model_config(n_layers: int = 3, *, ascendc: bool = False) -> DeepSeekV32Model.Config: | 47 | def _model_config(n_layers: int = 3, *, ascendc: bool = False) -> DeepSeekV32Model.Config: |
| 66 | layers = _build_dsv3_2_layers( | 48 | layers = _build_dsv3_2_layers( |
| 67 | n_layers=n_layers, | 49 | n_layers=n_layers, |
| @@ -104,7 +86,11 @@ def _model_config(n_layers: int = 3, *, ascendc: bool = False) -> DeepSeekV32Mod | |||
| 104 | 86 | ||
| 105 | @pytest.fixture | 87 | @pytest.fixture |
| 106 | def builds(monkeypatch) -> list: | 88 | def builds(monkeypatch) -> list: |
| 107 | - """Record every packed-layout build, whichever backend asked for one.""" | 89 | + """Record every packed-layout build, whichever backend asked for one. |
| 90 | + | ||
| 91 | + Both backends capture ``create_varlen_metadata_for_document`` in their own | ||
| 92 | + module namespace, so the counter is installed in each of the two. | ||
| 93 | + """ | ||
| 108 | recorded: list = [] | 94 | recorded: list = [] |
| 109 | build = v32_model.create_varlen_metadata_for_document | 95 | build = v32_model.create_varlen_metadata_for_document |
| 110 | 96 | ||
| @@ -113,6 +99,7 @@ def builds(monkeypatch) -> list: | |||
| 113 | return build(positions) | 99 | return build(positions) |
| 114 | 100 | ||
| 115 | monkeypatch.setattr(v32_model, "create_varlen_metadata_for_document", counting_build) | 101 | monkeypatch.setattr(v32_model, "create_varlen_metadata_for_document", counting_build) |
| 102 | + monkeypatch.setattr(ascendc, "create_varlen_metadata_for_document", counting_build) | ||
| 116 | return recorded | 103 | return recorded |
| 117 | 104 | ||
| 118 | 105 | ||
| @@ -125,7 +112,7 @@ def test_the_decoder_builds_one_entry_for_the_whole_stack(builds): | |||
| 125 | assert len(builds) == 1 | 112 | assert len(builds) == 1 |
| 126 | assert set(attention_metadata) == {SparseInnerAttention} | 113 | assert set(attention_metadata) == {SparseInnerAttention} |
| 127 | entry = attention_metadata[SparseInnerAttention] | 114 | entry = attention_metadata[SparseInnerAttention] |
| 128 | - assert isinstance(entry, ReferenceVarlenMetadata) | 115 | + assert isinstance(entry, VarlenMetadata) |
| 129 | assert entry.cu_seq_q.tolist() == _CU_SEQ | 116 | assert entry.cu_seq_q.tolist() == _CU_SEQ |
| 130 | # Every layer dispatches by the key the one entry is stored under. | 117 | # Every layer dispatches by the key the one entry is stored under. |
| 131 | keys = {layer.attention.attention_metadata_key for layer in model.layers.values()} | 118 | keys = {layer.attention.attention_metadata_key for layer in model.layers.values()} |
| @@ -151,8 +138,30 @@ def test_preprocess_inputs_hands_the_map_to_the_forward(): | |||
| 151 | assert "attention_masks" not in extra_kwargs | 138 | assert "attention_masks" not in extra_kwargs |
| 152 | 139 | ||
| 153 | 140 | ||
| 141 | +def test_decoder_update_from_config_refuses_context_parallel(): | ||
| 142 | + """The decoder guard the V3.2 config delegates to refuses CP for these cores. | ||
| 143 | + | ||
| 144 | + This is the guard the retired rank-local hook used to supplement: it runs at | ||
| 145 | + configuration time, before any layer could read a global varlen layout. The | ||
| 146 | + test calls the decoder contract directly so it does not depend on the | ||
| 147 | + deferred pre-fold ``DeepSeekV32Model.Config.update_from_config`` rope step. | ||
| 148 | + """ | ||
| 149 | + config = _model_config(n_layers=1) | ||
| 150 | + | ||
| 151 | + with pytest.raises(NotImplementedError, match="Context Parallel is not supported"): | ||
| 152 | + Decoder.Config.update_from_config( | ||
| 153 | + config, | ||
| 154 | + config=SimpleNamespace( | ||
| 155 | + parallelism=ParallelismConfig( | ||
| 156 | + context_parallel_degree=2, | ||
| 157 | + spmd_backend="spmd_types", | ||
| 158 | + ), | ||
| 159 | + ), | ||
| 160 | + ) | ||
| 161 | + | ||
| 162 | + | ||
| 154 | def test_the_ascendc_backend_owns_the_tnd_metadata(builds): | 163 | def test_the_ascendc_backend_owns_the_tnd_metadata(builds): |
| 155 | - """The fused backend wraps the shared layout with its host length lists.""" | 164 | + """The fused backend wraps the shared layout with its host length list.""" |
| 156 | model = _model_config(n_layers=3, ascendc=True).build() | 165 | model = _model_config(n_layers=3, ascendc=True).build() |
| 157 | 166 | ||
| 158 | attention_metadata = model._get_attention_metadata(_POSITIONS) | 167 | attention_metadata = model._get_attention_metadata(_POSITIONS) |
| @@ -162,54 +171,10 @@ def test_the_ascendc_backend_owns_the_tnd_metadata(builds): | |||
| 162 | entry = attention_metadata[AscSparseInnerAttention] | 171 | entry = attention_metadata[AscSparseInnerAttention] |
| 163 | assert isinstance(entry, AscVarlenMetadata) | 172 | assert isinstance(entry, AscVarlenMetadata) |
| 164 | # The TND kernels take the cumulative end offsets on host, not the device | 173 | # The TND kernels take the cumulative end offsets on host, not the device |
| 165 | - # tensor they were read from. | 174 | + # tensor they were read from. One list serves the q and k kernel arguments |
| 166 | - assert entry.actual_seq_qlen == _CU_SEQ[1:] | 175 | + # because the builder hands both offset tensors the same packed layout. |
| 167 | - assert entry.actual_seq_klen == _CU_SEQ[1:] | 176 | + assert entry.actual_seq_lengths == _CU_SEQ[1:] |
| 168 | assert isinstance(entry.varlen_meta, VarlenMetadata) | 177 | assert isinstance(entry.varlen_meta, VarlenMetadata) |
| 169 | assert entry.varlen_meta.cu_seq_q.tolist() == _CU_SEQ | 178 | assert entry.varlen_meta.cu_seq_q.tolist() == _CU_SEQ |
| 179 | + assert entry.varlen_meta.cu_seq_k.tolist() == _CU_SEQ | ||
| 170 | assert {layer.attention.attention_metadata_key for layer in model.layers.values()} == {AscSparseInnerAttention} | 180 | assert {layer.attention.attention_metadata_key for layer in model.layers.values()} == {AscSparseInnerAttention} |
| 171 | - | ||
| 172 | - | ||
| 173 | -def test_the_ascendc_entry_prepares_this_ranks_copy_for_context_parallel(): | ||
| 174 | - """Under CP the entry re-reads its host lists from the rank-local offsets.""" | ||
| 175 | - global_entry = AscVarlenMetadata.from_varlen(v32_model.build_reference_varlen_metadata(_POSITIONS)) | ||
| 176 | - assert global_entry.actual_seq_qlen == _CU_SEQ[1:] | ||
| 177 | - | ||
| 178 | - locals_per_rank = [_prepare_for_rank(AscVarlenMetadata, global_entry, rank) for rank in range(2)] | ||
| 179 | - | ||
| 180 | - for entry in locals_per_rank: | ||
| 181 | - assert isinstance(entry.varlen_meta, CPVarlenMetadata) | ||
| 182 | - # Each rank holds half the row, and its host lists describe that half: | ||
| 183 | - # the offsets are this rank's own, not the global row's. | ||
| 184 | - assert entry.actual_seq_qlen == entry.varlen_meta.cu_seq_q[1:].cpu().tolist() | ||
| 185 | - assert entry.actual_seq_qlen[-1] == _SEQ_LEN // 2 | ||
| 186 | - assert entry.actual_seq_qlen != global_entry.actual_seq_qlen | ||
| 187 | - assert entry.varlen_meta.k_global_gather_indices.numel() > 0 | ||
| 188 | - | ||
| 189 | - # The two ranks' segments differ: the copy really is rank-local. | ||
| 190 | - assert locals_per_rank[0].varlen_meta.k_global_gather_indices.tolist() != ( | ||
| 191 | - locals_per_rank[1].varlen_meta.k_global_gather_indices.tolist() | ||
| 192 | - ) | ||
| 193 | - | ||
| 194 | - | ||
| 195 | -def test_the_reference_core_refuses_context_parallel_while_preparing(): | ||
| 196 | - """A stack that cannot be sharded says so during preparation, not later.""" | ||
| 197 | - entry = v32_model.build_reference_varlen_metadata(_POSITIONS) | ||
| 198 | - | ||
| 199 | - with pytest.raises(ValueError, match="not context-parallel"): | ||
| 200 | - _prepare_for_rank(ReferenceVarlenMetadata, entry, 0) | ||
| 201 | - | ||
| 202 | - | ||
| 203 | -def _prepare_for_rank(metadata_type, attention_metadata, rank: int): | ||
| 204 | - """Run one metadata type's CP transform the way ``Decoder._cp_shard`` does. | ||
| 205 | - | ||
| 206 | - The transform takes the permutation alone (upstream #4617); what it cannot | ||
| 207 | - recover -- the mesh, the load-balancer type and the *pre-shard* positions -- | ||
| 208 | - comes from the context the patched shard publishes around the call. | ||
| 209 | - """ | ||
| 210 | - with cp_shard_context_set( | ||
| 211 | - cp_mesh=_FakeCPMesh(rank, 2), | ||
| 212 | - load_balancer_type="headtail", | ||
| 213 | - positions=_POSITIONS, | ||
| 214 | - ): | ||
| 215 | - return metadata_type.prepare_cp_metadata(attention_metadata, permutation=None) | ||
| @@ -82,9 +82,9 @@ def test_dsv32_mtp_keeps_community_cp_restriction(): | |||
| 82 | context_parallel_degree=2, | 82 | context_parallel_degree=2, |
| 83 | ) | 83 | ) |
| 84 | 84 | ||
| 85 | - # The community decoder's own refusal fires at config time for the | 85 | + # The pinned decoder refuses CP for the VarlenAttention-derived cores at |
| 86 | - # VarlenAttention-derived cores; the reference core's metadata-seam | 86 | + # configuration time. DeepSeek-V3.2 has no successor rank-local CP path: |
| 87 | - # refusal (``ReferenceVarlenMetadata``) is the later, rank-local guard. | 87 | + # its retired varlen-CP metadata system is not replaced by a second guard. |
| 88 | with pytest.raises(NotImplementedError, match="Context Parallel is not supported"): | 88 | with pytest.raises(NotImplementedError, match="Context Parallel is not supported"): |
| 89 | config.model_spec.model.update_from_config(config=config) | 89 | config.model_spec.model.update_from_config(config=config) |
| 90 | 90 | ||
| @@ -13,8 +13,8 @@ from pathlib import Path | |||
| 13 | import pytest | 13 | import pytest |
| 14 | import torch | 14 | import torch |
| 15 | 15 | ||
| 16 | -# Every test here exercises the not-yet-migrated context-parallel metadata path. | 16 | +# Metadata conversion is CPU-only; the remaining CP tests await the folded migration. |
| 17 | -pytestmark = pytest.mark.skip( | 17 | +_requires_folded_cp = pytest.mark.skip( |
| 18 | reason="Qwen3.5 NPU context parallel is not migrated to the folded token layout yet; " | 18 | reason="Qwen3.5 NPU context parallel is not migrated to the folded token layout yet; " |
| 19 | "re-enable with the Qwen CP folded-token migration" | 19 | "re-enable with the Qwen CP folded-token migration" |
| 20 | ) | 20 | ) |
| @@ -55,7 +55,7 @@ def qwen_cp(monkeypatch): | |||
| 55 | 55 | ||
| 56 | def test_build_sequence_metadata_caches_cpu_lengths(qwen_cp): | 56 | def test_build_sequence_metadata_caches_cpu_lengths(qwen_cp): |
| 57 | varlen = types.SimpleNamespace(cu_seq_q=torch.tensor([0, 3, 8], dtype=torch.int32)) | 57 | varlen = types.SimpleNamespace(cu_seq_q=torch.tensor([0, 3, 8], dtype=torch.int32)) |
| 58 | - metadata = qwen_cp.build_sequence_metadata(varlen, _Mesh(), batch=1, length=8) | 58 | + metadata = qwen_cp.build_sequence_metadata(varlen) |
| 59 | 59 | ||
| 60 | assert metadata.cu_seqlens.dtype == torch.int64 | 60 | assert metadata.cu_seqlens.dtype == torch.int64 |
| 61 | assert metadata.cu_seqlens.device.type == "cpu" | 61 | assert metadata.cu_seqlens.device.type == "cpu" |
| @@ -67,7 +67,7 @@ def test_build_sequence_metadata_caches_cpu_lengths(qwen_cp): | |||
| 67 | def test_prepare_sequence_metadata_replaces_varlen_input(qwen_cp): | 67 | def test_prepare_sequence_metadata_replaces_varlen_input(qwen_cp): |
| 68 | varlen = types.SimpleNamespace(cu_seq_q=torch.tensor([0, 2, 5], dtype=torch.int32)) | 68 | varlen = types.SimpleNamespace(cu_seq_q=torch.tensor([0, 2, 5], dtype=torch.int32)) |
| 69 | args = (torch.empty(1, 5, 4),) | 69 | args = (torch.empty(1, 5, 4),) |
| 70 | - module = types.SimpleNamespace(context_parallel_mesh=_Mesh(size=1, rank=0)) | 70 | + module = types.SimpleNamespace() |
| 71 | 71 | ||
| 72 | returned_args, returned_kwargs = qwen_cp.prepare_sequence_metadata(module, args, {"attention_masks": varlen}) | 72 | returned_args, returned_kwargs = qwen_cp.prepare_sequence_metadata(module, args, {"attention_masks": varlen}) |
| 73 | 73 | ||
| @@ -76,6 +76,7 @@ def test_prepare_sequence_metadata_replaces_varlen_input(qwen_cp): | |||
| 76 | assert torch.equal(returned_kwargs["attention_masks"].actual_seq_qlen, torch.tensor([2, 5])) | 76 | assert torch.equal(returned_kwargs["attention_masks"].actual_seq_qlen, torch.tensor([2, 5])) |
| 77 | 77 | ||
| 78 | 78 | ||
| 79 | +@_requires_folded_cp | ||
| 79 | def test_shard_local_heads_selects_rank_chunk(qwen_cp): | 80 | def test_shard_local_heads_selects_rank_chunk(qwen_cp): |
| 80 | tensor = torch.arange(8).view(4, 2) | 81 | tensor = torch.arange(8).view(4, 2) |
| 81 | shard = qwen_cp.shard_local_heads(tensor, _Mesh(size=2, rank=1)) | 82 | shard = qwen_cp.shard_local_heads(tensor, _Mesh(size=2, rank=1)) |
| @@ -90,6 +91,7 @@ def _plain_cp_model(): | |||
| 90 | return types.SimpleNamespace(vision_encoder=None) | 91 | return types.SimpleNamespace(vision_encoder=None) |
| 91 | 92 | ||
| 92 | 93 | ||
| 94 | +@_requires_folded_cp | ||
| 93 | def test_cp_parallelizer_refuses_unmigrated_folded_path(qwen_cp): | 95 | def test_cp_parallelizer_refuses_unmigrated_folded_path(qwen_cp): |
| 94 | with pytest.raises(NotImplementedError, match="not migrated to the folded token layout"): | 96 | with pytest.raises(NotImplementedError, match="not migrated to the folded token layout"): |
| 95 | qwen_cp.parallelize_qwen3_5_cp( | 97 | qwen_cp.parallelize_qwen3_5_cp( |
| @@ -103,6 +105,7 @@ def test_cp_parallelizer_refuses_unmigrated_folded_path(qwen_cp): | |||
| 103 | ) | 105 | ) |
| 104 | 106 | ||
| 105 | 107 | ||
| 108 | +@_requires_folded_cp | ||
| 106 | def test_npu_dispatcher_refuses_cp_before_touching_the_model(qwen_cp): | 109 | def test_npu_dispatcher_refuses_cp_before_touching_the_model(qwen_cp): |
| 107 | # The refusal must fire before any FSDP wrap/parallelize call: the fake | 110 | # The refusal must fire before any FSDP wrap/parallelize call: the fake |
| 108 | # model exposes neither, so reaching them would raise AttributeError. | 111 | # model exposes neither, so reaching them would raise AttributeError. |
| @@ -33,54 +33,9 @@ from torchtitan.models.deepseek_v3.mtp import MTPDecoder | |||
| 33 | from torchtitan.protocols.module import Module | 33 | from torchtitan.protocols.module import Module |
| 34 | 34 | ||
| 35 | from torchtitan_npu.models.common.document_intervals import document_intervals | 35 | from torchtitan_npu.models.common.document_intervals import document_intervals |
| 36 | -from torchtitan_npu.patches.torchtitan.distributed.varlen_cp import CPVarlenMetadata | ||
| 37 | from torchtitan_npu.patches.torchtitan.models.common.aux_loss import AuxLoss | 36 | from torchtitan_npu.patches.torchtitan.models.common.aux_loss import AuxLoss |
| 38 | from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear | 37 | from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear |
| 39 | 38 | ||
| 40 | -# The two forms of the packed offsets the reference core reads: the row's own documents, and | ||
| 41 | -# the rank-local segments the context-parallel transform derives from them. They are not | ||
| 42 | -# related by inheritance, but they carry the same two offset tensors. | ||
| 43 | -AttentionMetadata = VarlenMetadata | CPVarlenMetadata | ||
| 44 | - | ||
| 45 | -_REFERENCE_CP_UNSUPPORTED = ( | ||
| 46 | - "the DeepSeek-V3.2 reference core is not context-parallel: attn-gym's indexer " | ||
| 47 | - "selects a query's prefix of its own document, while a CP rank holds a " | ||
| 48 | - "document's middle and needs the kernels' end-aligned causal range. Use the " | ||
| 49 | - "AscendC override (override.deepseek_v3_2.sparse_attn.asc) under context " | ||
| 50 | - "parallel." | ||
| 51 | -) | ||
| 52 | - | ||
| 53 | - | ||
| 54 | -class ReferenceVarlenMetadata(VarlenMetadata): | ||
| 55 | - """The reference core's global packed layout, which context parallel cannot shard. | ||
| 56 | - | ||
| 57 | - The refusal lives here, beside the layout it refuses (upstream #4617's hook, hosted | ||
| 58 | - by the metadata rather than by the backend): a stack that cannot be sharded must say | ||
| 59 | - so while the rank-local metadata is being prepared, or the layer would silently | ||
| 60 | - attend to a global layout it does not hold. | ||
| 61 | - """ | ||
| 62 | - | ||
| 63 | - @staticmethod | ||
| 64 | - def prepare_cp_metadata(attention_metadata, *, permutation): | ||
| 65 | - """Refuse context parallel while the rank-local metadata is prepared. | ||
| 66 | - | ||
| 67 | - attn-gym's indexer selects a query's prefix of its own document, while a CP rank | ||
| 68 | - holds a document's middle; the kernels need their end-aligned causal range, which | ||
| 69 | - this core cannot express. | ||
| 70 | - """ | ||
| 71 | - del attention_metadata, permutation | ||
| 72 | - raise ValueError(_REFERENCE_CP_UNSUPPORTED) | ||
| 73 | - | ||
| 74 | - | ||
| 75 | -def build_reference_varlen_metadata(positions: torch.Tensor) -> ReferenceVarlenMetadata: | ||
| 76 | - """The packed document layout both DeepSeek-V3.2 attention cores read. | ||
| 77 | - | ||
| 78 | - Together with :class:`ReferenceVarlenMetadata` this is the whole metadata | ||
| 79 | - contract of the reference core; the AscendC core reads the same documents | ||
| 80 | - and wraps the result, so the two backends' builders share this one call. | ||
| 81 | - """ | ||
| 82 | - return ReferenceVarlenMetadata(*create_varlen_metadata_for_document(positions)) | ||
| 83 | - | ||
| 84 | 39 | ||
| 85 | @functools.cache | 40 | @functools.cache |
| 86 | def _hadamard(dim: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: | 41 | def _hadamard(dim: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: |
| @@ -152,7 +107,7 @@ class Indexer(Module): | |||
| 152 | idx_q_BLNH: torch.Tensor, | 107 | idx_q_BLNH: torch.Tensor, |
| 153 | idx_k_BL1H: torch.Tensor, | 108 | idx_k_BL1H: torch.Tensor, |
| 154 | idx_w_BLN: torch.Tensor, | 109 | idx_w_BLN: torch.Tensor, |
| 155 | - attention_masks: AttentionMetadata, | 110 | + attention_masks: VarlenMetadata, |
| 156 | index_topk: int, | 111 | index_topk: int, |
| 157 | ) -> tuple[torch.Tensor, torch.Tensor]: | 112 | ) -> tuple[torch.Tensor, torch.Tensor]: |
| 158 | """The top-k selection and the student's logits at the slots it picked. | 113 | """The top-k selection and the student's logits at the slots it picked. |
| @@ -263,7 +218,7 @@ class SparseIndexerLoss(AuxLoss): | |||
| 263 | scale: float, | 218 | scale: float, |
| 264 | topk_indices_BLqK: torch.Tensor, | 219 | topk_indices_BLqK: torch.Tensor, |
| 265 | topk_scores_BLqK: torch.Tensor, | 220 | topk_scores_BLqK: torch.Tensor, |
| 266 | - attention_masks: AttentionMetadata, | 221 | + attention_masks: VarlenMetadata, |
| 267 | *, | 222 | *, |
| 268 | carrier: torch.Tensor, | 223 | carrier: torch.Tensor, |
| 269 | ) -> torch.Tensor: | 224 | ) -> torch.Tensor: |
| @@ -355,7 +310,7 @@ class SparseInnerAttention(VarlenAttention): | |||
| 355 | padding_mask: torch.Tensor | None = None, | 310 | padding_mask: torch.Tensor | None = None, |
| 356 | max_num_documents: int | None = None, | 311 | max_num_documents: int | None = None, |
| 357 | max_context_length: int | None = None, | 312 | max_context_length: int | None = None, |
| 358 | - ) -> ReferenceVarlenMetadata: | 313 | + ) -> VarlenMetadata: |
| 359 | """The packed document layout the reference core reads. | 314 | """The packed document layout the reference core reads. |
| 360 | 315 | ||
| 361 | Upstream #4897 makes the attention backend own this construction, so | 316 | Upstream #4897 makes the attention backend own this construction, so |
| @@ -363,7 +318,7 @@ class SparseInnerAttention(VarlenAttention): | |||
| 363 | geometry shares it. | 318 | geometry shares it. |
| 364 | """ | 319 | """ |
| 365 | del padding_mask, max_num_documents, max_context_length | 320 | del padding_mask, max_num_documents, max_context_length |
| 366 | - return build_reference_varlen_metadata(positions) | 321 | + return create_varlen_metadata_for_document(positions) |
| 367 | 322 | ||
| 368 | def __init__(self, config: Config): | 323 | def __init__(self, config: Config): |
| 369 | super().__init__(config) | 324 | super().__init__(config) |
| @@ -380,11 +335,9 @@ class SparseInnerAttention(VarlenAttention): | |||
| 380 | idx_k_BL1H: torch.Tensor, | 335 | idx_k_BL1H: torch.Tensor, |
| 381 | idx_w_BLN: torch.Tensor, | 336 | idx_w_BLN: torch.Tensor, |
| 382 | *, | 337 | *, |
| 383 | - attention_masks: AttentionMetadata, | 338 | + attention_masks: VarlenMetadata, |
| 384 | scale: float, | 339 | scale: float, |
| 385 | ) -> torch.Tensor: | 340 | ) -> torch.Tensor: |
| 386 | - if isinstance(attention_masks, CPVarlenMetadata): | ||
| 387 | - raise ValueError(_REFERENCE_CP_UNSUPPORTED) | ||
| 388 | q_BLNH = torch.cat([q_nope_BLNH, q_rope_BLNH], dim=-1) | 341 | q_BLNH = torch.cat([q_nope_BLNH, q_rope_BLNH], dim=-1) |
| 389 | k_BL1H = torch.cat([k_nope_BL1H, k_rope_BL1H], dim=-1) | 342 | k_BL1H = torch.cat([k_nope_BL1H, k_rope_BL1H], dim=-1) |
| 390 | 343 | ||
| @@ -421,7 +374,7 @@ class SparseInnerAttention(VarlenAttention): | |||
| 421 | q_BLNH: torch.Tensor, | 374 | q_BLNH: torch.Tensor, |
| 422 | k_BL1H: torch.Tensor, | 375 | k_BL1H: torch.Tensor, |
| 423 | topk_indices_BLqK: torch.Tensor, | 376 | topk_indices_BLqK: torch.Tensor, |
| 424 | - attention_masks: AttentionMetadata, | 377 | + attention_masks: VarlenMetadata, |
| 425 | value_head_dim: int, | 378 | value_head_dim: int, |
| 426 | scale: float, | 379 | scale: float, |
| 427 | ) -> torch.Tensor: | 380 | ) -> torch.Tensor: |
| @@ -17,20 +17,13 @@ from dataclasses import dataclass | |||
| 17 | import spmd_types as spmd | 17 | import spmd_types as spmd |
| 18 | import torch | 18 | import torch |
| 19 | import torch_npu | 19 | import torch_npu |
| 20 | -from torch.distributed.tensor.experimental._attention import _HeadTailLoadBalancer | ||
| 21 | from torchtitan.models.common.attention import ( | 20 | from torchtitan.models.common.attention import ( |
| 22 | VarlenAttention, | 21 | VarlenAttention, |
| 23 | VarlenMetadata, | 22 | VarlenMetadata, |
| 23 | + create_varlen_metadata_for_document, | ||
| 24 | ) | 24 | ) |
| 25 | 25 | ||
| 26 | -from torchtitan_npu.models.deepseek_v3_2.model import ( | 26 | +from torchtitan_npu.models.deepseek_v3_2.model import SparseIndexerLoss |
| 27 | - SparseIndexerLoss, | ||
| 28 | - build_reference_varlen_metadata, | ||
| 29 | -) | ||
| 30 | -from torchtitan_npu.patches.torchtitan.distributed.varlen_cp import CPVarlenMetadata | ||
| 31 | -from torchtitan_npu.patches.torchtitan.models.common.attention_metadata import ( | ||
| 32 | - cp_shard_context, | ||
| 33 | -) | ||
| 34 | from torchtitan_npu.patches.torchtitan.models.common.aux_loss import AuxLoss | 27 | from torchtitan_npu.patches.torchtitan.models.common.aux_loss import AuxLoss |
| 35 | 28 | ||
| 36 | 29 | ||
| @@ -237,13 +230,14 @@ class AscSparseInnerAttention(VarlenAttention): | |||
| 237 | ) -> AscVarlenMetadata: | 230 | ) -> AscVarlenMetadata: |
| 238 | """The TND metadata this backend consumes (upstream #4897). | 231 | """The TND metadata this backend consumes (upstream #4897). |
| 239 | 232 | ||
| 240 | - The packed layout comes from the reference core's builder -- the | 233 | + The packed layout comes from the same upstream factory the |
| 241 | - fused path reads the same documents -- and the host length lists the | 234 | + reference core uses -- the fused path reads the same documents -- |
| 242 | - TND kernels take are read here: once per microbatch for every layer | 235 | + and the host length list the TND kernels take is read here: once |
| 243 | - of this geometry, instead of once per layer. | 236 | + per microbatch for every layer of this geometry, instead of once |
| 237 | + per layer. | ||
| 244 | """ | 238 | """ |
| 245 | del padding_mask, max_num_documents, max_context_length | 239 | del padding_mask, max_num_documents, max_context_length |
| 246 | - return AscVarlenMetadata.from_varlen(build_reference_varlen_metadata(positions)) | 240 | + return AscVarlenMetadata.from_varlen(create_varlen_metadata_for_document(positions)) |
| 247 | 241 | ||
| 248 | def __init__(self, config: Config) -> None: | 242 | def __init__(self, config: Config) -> None: |
| 249 | super().__init__(config) | 243 | super().__init__(config) |
| @@ -278,12 +272,6 @@ class AscSparseInnerAttention(VarlenAttention): | |||
| 278 | idx_w_TN = idx_w_BLN.reshape(T_q, N2) | 272 | idx_w_TN = idx_w_BLN.reshape(T_q, N2) |
| 279 | 273 | ||
| 280 | varlen_meta = attention_masks.varlen_meta | 274 | varlen_meta = attention_masks.varlen_meta |
| 281 | - if isinstance(varlen_meta, CPVarlenMetadata): | ||
| 282 | - gather = varlen_meta.k_global_gather_indices | ||
| 283 | - k_nope_T1H = k_nope_T1H.index_select(0, gather) | ||
| 284 | - k_rope_T1H = k_rope_T1H.index_select(0, gather) | ||
| 285 | - idx_k_T1H = idx_k_T1H.index_select(0, gather) | ||
| 286 | - | ||
| 287 | cu_seq_q_1 = varlen_meta.cu_seq_q[1:] | 275 | cu_seq_q_1 = varlen_meta.cu_seq_q[1:] |
| 288 | cu_seq_k_1 = varlen_meta.cu_seq_k[1:] | 276 | cu_seq_k_1 = varlen_meta.cu_seq_k[1:] |
| 289 | 277 | ||
| @@ -330,8 +318,8 @@ class AscSparseInnerAttention(VarlenAttention): | |||
| 330 | scale, | 318 | scale, |
| 331 | q_rope_TNH, | 319 | q_rope_TNH, |
| 332 | k_rope_T1H, | 320 | k_rope_T1H, |
| 333 | - attention_masks.actual_seq_qlen, | 321 | + attention_masks.actual_seq_lengths, |
| 334 | - attention_masks.actual_seq_klen, | 322 | + attention_masks.actual_seq_lengths, |
| 335 | carrier=output_TNH, | 323 | carrier=output_TNH, |
| 336 | ) | 324 | ) |
| 337 | 325 | ||
| @@ -347,57 +335,24 @@ class AscSparseInnerAttention(VarlenAttention): | |||
| 347 | class AscVarlenMetadata: | 335 | class AscVarlenMetadata: |
| 348 | """Varlen metadata with the host offsets the TND kernels require. | 336 | """Varlen metadata with the host offsets the TND kernels require. |
| 349 | 337 | ||
| 350 | - ``actual_seq_qlen``/``actual_seq_klen`` are the CANN ``actual_seq_lengths`` | 338 | + ``actual_seq_lengths`` is the CANN ``actual_seq_lengths`` form of the packed |
| 351 | - form of the packed layout -- the cumulative end offsets, not per-segment | 339 | + layout -- the cumulative end offsets, not per-segment lengths -- read off the |
| 352 | - lengths -- read off the device once per batch and kept next to the tensor | 340 | + device once per batch and kept next to the tensor it came from, so the host |
| 353 | - they came from, so a rank's copy is re-read in one transfer. | 341 | + list is read in one transfer. One list serves both the query and the key |
| 342 | + kernel argument: ``create_varlen_metadata_for_document`` hands the same | ||
| 343 | + packed offsets to ``cu_seq_q`` and ``cu_seq_k``. | ||
| 354 | """ | 344 | """ |
| 355 | 345 | ||
| 356 | - varlen_meta: VarlenMetadata | CPVarlenMetadata | 346 | + varlen_meta: VarlenMetadata |
| 357 | - actual_seq_qlen: list[int] | 347 | + actual_seq_lengths: list[int] |
| 358 | - actual_seq_klen: list[int] | ||
| 359 | - | ||
| 360 | - @staticmethod | ||
| 361 | - def prepare_cp_metadata(attention_metadata, *, permutation): | ||
| 362 | - """This rank's copy of the packed layout (upstream #4617's CP half). | ||
| 363 | - | ||
| 364 | - The global documents are re-cut for the load-balancer permutation, so the host | ||
| 365 | - length lists are re-read from the rank-local offsets: the TND kernels receive | ||
| 366 | - exactly the segments this rank runs. The hook lives here, on the layout it | ||
| 367 | - rebuilds, rather than on the backend that produced it. | ||
| 368 | - | ||
| 369 | - The balancer is rebuilt here rather than received, because 0.3.0's CP entry takes | ||
| 370 | - its *type* and builds the object internally; anything but ``headtail`` means that | ||
| 371 | - entry sharded with no permutation, so this derivation passes no balancer either and | ||
| 372 | - stays in step with the shard. An unusable type never reaches here: the pinned entry | ||
| 373 | - rejects it first (``ptrr`` included, since the map path hands it no masks). | ||
| 374 | - """ | ||
| 375 | - del permutation | ||
| 376 | - context = cp_shard_context() | ||
| 377 | - if context.cp_mesh is None or context.positions is None: | ||
| 378 | - raise ValueError("prepare_cp_metadata needs the CP mesh and the pre-shard positions") | ||
| 379 | - batch_size, seq_len = context.positions.shape | ||
| 380 | - return AscVarlenMetadata.from_varlen( | ||
| 381 | - CPVarlenMetadata.from_global( | ||
| 382 | - attention_metadata.varlen_meta, | ||
| 383 | - context.cp_mesh, | ||
| 384 | - batch_size, | ||
| 385 | - seq_len, | ||
| 386 | - load_balancer=( | ||
| 387 | - _HeadTailLoadBalancer(seq_len, context.cp_mesh.size(0), context.cp_mesh.device_type) | ||
| 388 | - if context.load_balancer_type == "headtail" | ||
| 389 | - else None | ||
| 390 | - ), | ||
| 391 | - ) | ||
| 392 | - ) | ||
| 393 | 348 | ||
| 394 | @classmethod | 349 | @classmethod |
| 395 | - def from_varlen(cls, varlen_meta: VarlenMetadata | CPVarlenMetadata) -> AscVarlenMetadata: | 350 | + def from_varlen(cls, varlen_meta: VarlenMetadata) -> AscVarlenMetadata: |
| 396 | - """Read both host offset lists of a packed layout in one transfer.""" | 351 | + """Read the host offset list of a packed layout in one transfer.""" |
| 397 | - cu_q, cu_k = varlen_meta.cu_seq_q, varlen_meta.cu_seq_k | 352 | + # ``cu_seq_q`` is read alone because the pinned upstream factory assigns |
| 398 | - actual_seq_qlen, actual_seq_klen = torch.stack([cu_q[1:], cu_k[1:]]).cpu().tolist() | 353 | + # the identical ``packed_cu_seqlens`` tensor to ``cu_seq_q`` and ``cu_seq_k``. |
| 354 | + actual_seq_lengths = varlen_meta.cu_seq_q[1:].cpu().tolist() | ||
| 399 | return cls( | 355 | return cls( |
| 400 | varlen_meta=varlen_meta, | 356 | varlen_meta=varlen_meta, |
| 401 | - actual_seq_qlen=actual_seq_qlen, | 357 | + actual_seq_lengths=actual_seq_lengths, |
| 402 | - actual_seq_klen=actual_seq_klen, | ||
| 403 | ) | 358 | ) |
| @@ -8,7 +8,7 @@ from contextlib import contextmanager | |||
| 8 | from dataclasses import dataclass | 8 | from dataclasses import dataclass |
| 9 | 9 | ||
| 10 | import torch | 10 | import torch |
| 11 | -from torch.distributed.tensor import DTensor, Replicate, Shard | 11 | +from torch.distributed.tensor import DTensor, Shard |
| 12 | from torchtitan.config import TORCH_DTYPE_MAP | 12 | from torchtitan.config import TORCH_DTYPE_MAP |
| 13 | from torchtitan.distributed.compile import apply_compile | 13 | from torchtitan.distributed.compile import apply_compile |
| 14 | from torchtitan.distributed.fsdp import ( | 14 | from torchtitan.distributed.fsdp import ( |
| @@ -190,42 +190,29 @@ def exchange_sequence_heads(tensors, mesh, head_dim): | |||
| 190 | return packed.split([part[0].size(head_dim) for part in shards], head_dim) | 190 | return packed.split([part[0].size(head_dim) for part in shards], head_dim) |
| 191 | 191 | ||
| 192 | 192 | ||
| 193 | -def build_sequence_metadata(varlen, mesh, batch, length): | 193 | +def build_sequence_metadata(varlen): |
| 194 | cu = varlen.cu_seq_q | 194 | cu = varlen.cu_seq_q |
| 195 | - if hasattr(varlen, "k_global_gather_indices"): | ||
| 196 | - reset = torch.zeros(batch * length, dtype=torch.bool, device=cu.device) | ||
| 197 | - starts = cu[:-1].to(torch.long) | ||
| 198 | - reset[starts[cu.diff() == varlen.cu_seq_k.diff()]] = True | ||
| 199 | - reset = DTensor.from_local(reset.view(batch, length), mesh, (Shard(1),), run_check=False) | ||
| 200 | - reset = reset.redistribute(placements=(Replicate(),)).to_local() | ||
| 201 | - starts = reset.flatten().nonzero(as_tuple=False).flatten() | ||
| 202 | - starts = starts[starts != 0] | ||
| 203 | - cu = torch.cat((starts.new_zeros(1), starts, starts.new_tensor([reset.numel()]))) | ||
| 204 | cu = cu.to(torch.int64) | 195 | cu = cu.to(torch.int64) |
| 205 | cu_cpu = cu.cpu() | 196 | cu_cpu = cu.cpu() |
| 206 | return QwenCPMetadata(cu, cu_cpu, cu_cpu[1:]) | 197 | return QwenCPMetadata(cu, cu_cpu, cu_cpu[1:]) |
| 207 | 198 | ||
| 208 | 199 | ||
| 209 | -def _to_qwen_cp_metadata(mask, mesh, batch, length): | 200 | +def _to_qwen_cp_metadata(mask): |
| 210 | if mask is None or isinstance(mask, QwenCPMetadata) or not hasattr(mask, "cu_seq_q"): | 201 | if mask is None or isinstance(mask, QwenCPMetadata) or not hasattr(mask, "cu_seq_q"): |
| 211 | return mask | 202 | return mask |
| 212 | - return build_sequence_metadata(mask, mesh, batch, length) | 203 | + return build_sequence_metadata(mask) |
| 213 | 204 | ||
| 214 | 205 | ||
| 215 | def prepare_sequence_metadata(module, args, kwargs): | 206 | def prepare_sequence_metadata(module, args, kwargs): |
| 216 | masks = kwargs.get("attention_masks") | 207 | masks = kwargs.get("attention_masks") |
| 217 | if masks is None: | 208 | if masks is None: |
| 218 | return args, kwargs | 209 | return args, kwargs |
| 219 | - mesh = module.context_parallel_mesh | ||
| 220 | - batch, length = args[0].shape[:2] | ||
| 221 | if isinstance(masks, dict): | 210 | if isinstance(masks, dict): |
| 222 | # Qwen3.5 hybrid attention passes one mask dict per consumer key; | 211 | # Qwen3.5 hybrid attention passes one mask dict per consumer key; |
| 223 | - # convert each varlen entry to rank-local QwenCPMetadata in place. | 212 | + # convert each varlen entry to QwenCPMetadata in place. |
| 224 | - kwargs["attention_masks"] = { | 213 | + kwargs["attention_masks"] = {key: _to_qwen_cp_metadata(value) for key, value in masks.items()} |
| 225 | - key: _to_qwen_cp_metadata(value, mesh, batch, length) for key, value in masks.items() | ||
| 226 | - } | ||
| 227 | elif not isinstance(masks, QwenCPMetadata): | 214 | elif not isinstance(masks, QwenCPMetadata): |
| 228 | - kwargs["attention_masks"] = build_sequence_metadata(masks, mesh, batch, length) | 215 | + kwargs["attention_masks"] = build_sequence_metadata(masks) |
| 229 | return args, kwargs | 216 | return args, kwargs |
| 230 | 217 | ||
| 231 | 218 | ||
| @@ -1,6 +1,5 @@ | |||
| 1 | <!-- | 1 | <!-- |
| 2 | 待合入的上游 PR: | 2 | 待合入的上游 PR: |
| 3 | -- https://github.com/pytorch/torchtitan/pull/3430 | ||
| 4 | - https://github.com/pytorch/torchtitan/pull/3634 | 3 | - https://github.com/pytorch/torchtitan/pull/3634 |
| 5 | - https://github.com/pytorch/torchtitan/pull/3864 | 4 | - https://github.com/pytorch/torchtitan/pull/3864 |
| 6 | - https://github.com/pytorch/torchtitan/pull/4411 | 5 | - https://github.com/pytorch/torchtitan/pull/4411 |
| @@ -28,18 +27,17 @@ | |||
| 28 | ``` | 27 | ``` |
| 29 | 28 | ||
| 30 | - 模块 docstring 需说明补丁内容,并以 "Remove this module after the TorchTitan dependency includes the PR." 结尾。 | 29 | - 模块 docstring 需说明补丁内容,并以 "Remove this module after the TorchTitan dependency includes the PR." 结尾。 |
| 31 | -- 对原模块/类做属性替换的 monkey patch 必须封装在 `def apply() -> None:` 中并在文件末尾调用(`apply()`),补丁逻辑内使用完整模块路径(`import torchtitan.models.common.moe` 后以 `torchtitan.models.common.moe.X = ...` 赋值),不使用短导入别名。纯定义被模型目录引用的 backport 类(如 `BatchedLinear`、`BaseMaskHandler`、`SingleComplexRoPE`、`AuxLoss`、`VarlenCPMetadata`)不需要 `apply()`。 | 30 | +- 对原模块/类做属性替换的 monkey patch 必须封装在 `def apply() -> None:` 中并在文件末尾调用(`apply()`),补丁逻辑内使用完整模块路径(`import torchtitan.models.common.moe` 后以 `torchtitan.models.common.moe.X = ...` 赋值),不使用短导入别名。纯定义被模型目录引用的 backport 类(如 `BatchedLinear`、`BaseMaskHandler`、`SingleComplexRoPE`、`AuxLoss`)不需要 `apply()`。 |
| 32 | 31 | ||
| 33 | 校验(除 `__init__.py` 等包胶水文件外,每个补丁文件都应命中): | 32 | 校验(除 `__init__.py` 等包胶水文件外,每个补丁文件都应命中): |
| 34 | 33 | ||
| 35 | ```bash | 34 | ```bash |
| 36 | -grep -L "Pending upstream PR: https://github.com/pytorch/torchtitan/pull/" \ | 35 | +grep -L -E "Pending upstream PR: https://github.com/pytorch/(torchtitan|pytorch)/pull/" \ |
| 37 | torchtitan_npu/patches/torchtitan -r --include="*.py" | 36 | torchtitan_npu/patches/torchtitan -r --include="*.py" |
| 38 | ``` | 37 | ``` |
| 39 | 38 | ||
| 40 | | PR | 说明 | | 39 | | PR | 说明 | |
| 41 | | --- | --- | | 40 | | --- | --- | |
| 42 | -| [#3430](https://github.com/pytorch/torchtitan/pull/3430) | 为变长注意力补充 CP 和 Full DTensor 支持 | | ||
| 43 | | [#3634](https://github.com/pytorch/torchtitan/pull/3634) | 补充 DeepSeek-V4 所需的公共组件及训练接入 | | 41 | | [#3634](https://github.com/pytorch/torchtitan/pull/3634) | 补充 DeepSeek-V4 所需的公共组件及训练接入 | |
| 44 | | [#3864](https://github.com/pytorch/torchtitan/pull/3864) | 为 torchtitan 补充 AuxLoss 辅助损失框架 | | 42 | | [#3864](https://github.com/pytorch/torchtitan/pull/3864) | 为 torchtitan 补充 AuxLoss 辅助损失框架 | |
| 45 | | [#4474](https://github.com/pytorch/torchtitan/pull/4474) | 补齐部分初始化的 optimizer state,支持完整 checkpoint 恢复 | | 43 | | [#4474](https://github.com/pytorch/torchtitan/pull/4474) | 补齐部分初始化的 optimizer state,支持完整 checkpoint 恢复 | |
| @@ -60,6 +58,9 @@ grep -L "Pending upstream PR: https://github.com/pytorch/torchtitan/pull/" \ | |||
| 60 | | [#4763](https://github.com/pytorch/torchtitan/pull/4763) | 向 GraphTrainer graph pass 提供运行时上下文,用于 auto-overlap 调度时整图 profiling | | 58 | | [#4763](https://github.com/pytorch/torchtitan/pull/4763) | 向 GraphTrainer graph pass 提供运行时上下文,用于 auto-overlap 调度时整图 profiling | |
| 61 | | [#201621](https://github.com/pytorch/pytorch/pull/201621) | 为本地 FileSystemReader 增加可选 mmap 加载,对应 `distributed/checkpoint/filesystem` | | 59 | | [#201621](https://github.com/pytorch/pytorch/pull/201621) | 为本地 FileSystemReader 增加可选 mmap 加载,对应 `distributed/checkpoint/filesystem` | |
| 62 | 60 | ||
| 61 | +`distributed/context_parallel.py` 的 doc-chunk load balancer 是仓库自有布局(`Upstream-PR: none`): | ||
| 62 | +待上游 `cp_shard` 提供布局注册点,或 doc-chunk 布局并入上游后删除。 | ||
| 63 | + | ||
| 63 | 上述 6 个 TorchTitan PR(#4534、#4575、#4578、#4598、#4663、#4664)已在上游合入,但 `v0.3.0` 尚未包含这些修复。 | 64 | 上述 6 个 TorchTitan PR(#4534、#4575、#4578、#4598、#4663、#4664)已在上游合入,但 `v0.3.0` 尚未包含这些修复。 |
| 64 | 65 | ||
| 65 | 四个 EP overlap 补丁的作用、启用方式与排查手段见 | 66 | 四个 EP overlap 补丁的作用、启用方式与排查手段见 |
| @@ -3,7 +3,9 @@ | |||
| 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 | -# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/3430 | 6 | +# Upstream-PR: none - the doc-chunk load balancer below is repository-specific. |
| 7 | +# The varlen-CP backport this module used to carry (upstream PR #3430) was | ||
| 8 | +# retired with DeepSeek-V3.2's context-parallel capability. | ||
| 7 | 9 | ||
| 8 | """The CP shard, plus the doc-chunk layout as one of its load balancers. | 10 | """The CP shard, plus the doc-chunk layout as one of its load balancers. |
| 9 | 11 | ||
| @@ -26,39 +28,22 @@ from typing import cast | |||
| 26 | 28 | ||
| 27 | import torch | 29 | import torch |
| 28 | from torch.distributed.device_mesh import DeviceMesh | 30 | from torch.distributed.device_mesh import DeviceMesh |
| 29 | -from torch.distributed.tensor.experimental._attention import ( | 31 | +from torch.distributed.tensor.experimental._attention import _context_parallel_shard |
| 30 | - _context_parallel_shard, | ||
| 31 | - _HeadTailLoadBalancer, | ||
| 32 | -) | ||
| 33 | from torch.distributed.tensor.experimental._context_parallel._load_balancer import ( | 32 | from torch.distributed.tensor.experimental._context_parallel._load_balancer import ( |
| 34 | _LoadBalancer, | 33 | _LoadBalancer, |
| 35 | ) | 34 | ) |
| 36 | from torchtitan.distributed.context_parallel.api import cp_shard as original_cp_shard | 35 | from torchtitan.distributed.context_parallel.api import cp_shard as original_cp_shard |
| 37 | -from torchtitan.models.common.attention import AttentionMasksType, VarlenMetadata | 36 | +from torchtitan.models.common.attention import AttentionMasksType |
| 38 | 37 | ||
| 39 | from torchtitan_npu.models.common.restore import ( | 38 | from torchtitan_npu.models.common.restore import ( |
| 40 | DOC_CHUNK_LAYOUT, | 39 | DOC_CHUNK_LAYOUT, |
| 41 | doc_chunk_permutation, | 40 | doc_chunk_permutation, |
| 42 | document_starts, | 41 | document_starts, |
| 43 | ) | 42 | ) |
| 44 | -from torchtitan_npu.patches.torchtitan.distributed.varlen_cp import ( | ||
| 45 | - CPVarlenMetadata, | ||
| 46 | -) | ||
| 47 | 43 | ||
| 48 | logger = logging.getLogger(__name__) | 44 | logger = logging.getLogger(__name__) |
| 49 | 45 | ||
| 50 | 46 | ||
| 51 | -def _varlen_from_masks(masks): | ||
| 52 | - """Return the shared VarlenMetadata behind a bare mask or an all-varlen dict.""" | ||
| 53 | - if isinstance(masks, VarlenMetadata): | ||
| 54 | - return masks | ||
| 55 | - if isinstance(masks, dict): | ||
| 56 | - values = [value for value in masks.values() if value is not None] | ||
| 57 | - if values and all(isinstance(value, VarlenMetadata) for value in values): | ||
| 58 | - return values[0] | ||
| 59 | - return None | ||
| 60 | - | ||
| 61 | - | ||
| 62 | class DocChunkLoadBalancer(_LoadBalancer): | 47 | class DocChunkLoadBalancer(_LoadBalancer): |
| 63 | """The doc-chunk layout, stated as a load balancer (``DOC_CHUNK_LAYOUT``). | 48 | """The doc-chunk layout, stated as a load balancer (``DOC_CHUNK_LAYOUT``). |
| 64 | 49 | ||
| @@ -113,7 +98,7 @@ def patched_cp_shard( | |||
| 113 | ptrr_mask_key: str | None = None, | 98 | ptrr_mask_key: str | None = None, |
| 114 | *, | 99 | *, |
| 115 | positions: torch.Tensor | None = None, | 100 | positions: torch.Tensor | None = None, |
| 116 | -) -> tuple[tuple[torch.Tensor, ...], AttentionMasksType | CPVarlenMetadata | None]: | 101 | +) -> tuple[tuple[torch.Tensor, ...], AttentionMasksType | None]: |
| 117 | """Shard inputs for CP, with this repository's layouts beside the framework's. | 102 | """Shard inputs for CP, with this repository's layouts beside the framework's. |
| 118 | 103 | ||
| 119 | ``positions`` is the row's own positions, and it is what a boundary-driven layout is built | 104 | ``positions`` is the row's own positions, and it is what a boundary-driven layout is built |
| @@ -124,8 +109,8 @@ def patched_cp_shard( | |||
| 124 | The rank-local metadata of these layouts is the model's own transform -- it reads the row's | 109 | The rank-local metadata of these layouts is the model's own transform -- it reads the row's |
| 125 | boundaries, not the sharded rows -- so nothing is returned in place of the masks. | 110 | boundaries, not the sharded rows -- so nothing is returned in place of the masks. |
| 126 | 111 | ||
| 127 | - Without a repository layout the pinned behaviour is unchanged: shard the inputs and, for a | 112 | + Without a repository layout the pinned behaviour is unchanged: the framework shards the |
| 128 | - varlen stack, build the rank-local varlen metadata after sharding. | 113 | + inputs and the masks. |
| 129 | """ | 114 | """ |
| 130 | seq_dims = (input_seq_dims,) * len(inputs) if isinstance(input_seq_dims, int) else input_seq_dims | 115 | seq_dims = (input_seq_dims,) * len(inputs) if isinstance(input_seq_dims, int) else input_seq_dims |
| 131 | if len(seq_dims) != len(inputs): | 116 | if len(seq_dims) != len(inputs): |
| @@ -161,50 +146,15 @@ def patched_cp_shard( | |||
| 161 | # layout is handed tensors only, so the tuple is one of tensors. | 146 | # layout is handed tensors only, so the tuple is one of tensors. |
| 162 | return cast("tuple[torch.Tensor, ...]", tuple(sharded)), attention_masks | 147 | return cast("tuple[torch.Tensor, ...]", tuple(sharded)), attention_masks |
| 163 | 148 | ||
| 164 | - varlen_metadata = _varlen_from_masks(attention_masks) | 149 | + return original_cp_shard( |
| 165 | - is_varlen = varlen_metadata is not None | ||
| 166 | - batch_size = inputs[0].size(0) | ||
| 167 | - seq_len = inputs[0].size(seq_dims[0]) | ||
| 168 | - | ||
| 169 | - inputs, output_masks = original_cp_shard( | ||
| 170 | cp_mesh, | 150 | cp_mesh, |
| 171 | inputs, | 151 | inputs, |
| 172 | - None if is_varlen else attention_masks, | 152 | + attention_masks, |
| 173 | load_balancer_type, | 153 | load_balancer_type, |
| 174 | input_seq_dims=seq_dims, | 154 | input_seq_dims=seq_dims, |
| 175 | ptrr_mask_key=ptrr_mask_key, | 155 | ptrr_mask_key=ptrr_mask_key, |
| 176 | ) | 156 | ) |
| 177 | 157 | ||
| 178 | - if varlen_metadata is not None: | ||
| 179 | - assert load_balancer_type in ( | ||
| 180 | - None, | ||
| 181 | - "headtail", | ||
| 182 | - ), f"varlen only support headtail as load balancer, got ({load_balancer_type})" | ||
| 183 | - | ||
| 184 | - cp_metadata = CPVarlenMetadata.from_global( | ||
| 185 | - varlen_metadata, | ||
| 186 | - cp_mesh, | ||
| 187 | - batch_size, | ||
| 188 | - seq_len, | ||
| 189 | - load_balancer=( | ||
| 190 | - _HeadTailLoadBalancer(seq_len, cp_mesh.size(0), cp_mesh.device_type) | ||
| 191 | - if load_balancer_type == "headtail" | ||
| 192 | - else None | ||
| 193 | - ), | ||
| 194 | - ) | ||
| 195 | - if isinstance(attention_masks, dict): | ||
| 196 | - # Hybrid attention stacks carry one shared varlen metadata under | ||
| 197 | - # multiple mask keys; keep the dict shape so each block can still | ||
| 198 | - # select its mask by key after CP sharding. | ||
| 199 | - output_masks = { | ||
| 200 | - key: cp_metadata if isinstance(value, VarlenMetadata) else value | ||
| 201 | - for key, value in attention_masks.items() | ||
| 202 | - } | ||
| 203 | - else: | ||
| 204 | - output_masks = cp_metadata | ||
| 205 | - | ||
| 206 | - return inputs, output_masks # pyrefly: ignore [bad-return] | ||
| 207 | - | ||
| 208 | 158 | ||
| 209 | def apply() -> None: | 159 | def apply() -> None: |
| 210 | try: | 160 | try: |
| @@ -1,172 +0,0 @@ | |||
| 1 | -# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/3430 | ||
| 2 | - | ||
| 3 | -# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 4 | -# All rights reserved. | ||
| 5 | -# | ||
| 6 | -# This source code is licensed under the BSD-style license found in the | ||
| 7 | -# LICENSE file in the root directory of this source tree. | ||
| 8 | - | ||
| 9 | -"""Context-parallel metadata for variable-length attention. | ||
| 10 | - | ||
| 11 | -This mirrors ``torchtitan/distributed/varlen_cp.py`` from upstream PR #3430. | ||
| 12 | -""" | ||
| 13 | - | ||
| 14 | -from dataclasses import dataclass | ||
| 15 | - | ||
| 16 | -import torch | ||
| 17 | -from torch.distributed.device_mesh import DeviceMesh | ||
| 18 | -from torch.distributed.tensor.experimental._context_parallel._load_balancer import ( | ||
| 19 | - _LoadBalancer, | ||
| 20 | -) | ||
| 21 | -from torchtitan.models.common.attention import VarlenMetadata | ||
| 22 | - | ||
| 23 | - | ||
| 24 | -@dataclass(frozen=True, eq=False) | ||
| 25 | -class CPVarlenMetadata: | ||
| 26 | - """Rank-local varlen metadata with K/V compaction indices. | ||
| 27 | - | ||
| 28 | - ``k_global_gather_indices`` selects visible regions after the CP all-gather | ||
| 29 | - and reverses the load-balancer permutation when present. | ||
| 30 | - """ | ||
| 31 | - | ||
| 32 | - cu_seq_q: torch.Tensor | ||
| 33 | - cu_seq_k: torch.Tensor | ||
| 34 | - max_q: int | ||
| 35 | - max_k: int | ||
| 36 | - k_global_gather_indices: torch.Tensor | ||
| 37 | - | ||
| 38 | - @classmethod | ||
| 39 | - def from_global( | ||
| 40 | - cls, | ||
| 41 | - global_metadata: VarlenMetadata, | ||
| 42 | - device_mesh: DeviceMesh, | ||
| 43 | - batch_size: int, | ||
| 44 | - seq_length: int, | ||
| 45 | - load_balancer: _LoadBalancer | None = None, | ||
| 46 | - ) -> "CPVarlenMetadata": | ||
| 47 | - """Build rank-local metadata from global self-attention boundaries. | ||
| 48 | - | ||
| 49 | - Q is sharded and K/V are assumed to be all-gathered. Each contiguous | ||
| 50 | - Q run becomes a causal segment. Construction uses one host transfer. | ||
| 51 | - """ | ||
| 52 | - if isinstance(global_metadata, CPVarlenMetadata): | ||
| 53 | - raise ValueError( | ||
| 54 | - "from_global received a CPVarlenMetadata; pass the unsharded global VarlenMetadata instead." | ||
| 55 | - ) | ||
| 56 | - # Identity avoids a device-to-host equality check on every forward. | ||
| 57 | - if global_metadata.cu_seq_q is not global_metadata.cu_seq_k: | ||
| 58 | - raise ValueError( | ||
| 59 | - "CP varlen sharding currently supports only self-attention; " | ||
| 60 | - "cu_seq_q and cu_seq_k must be the same tensor object." | ||
| 61 | - ) | ||
| 62 | - cu_seq_q_global = global_metadata.cu_seq_q | ||
| 63 | - | ||
| 64 | - if device_mesh.ndim != 1: | ||
| 65 | - raise ValueError(f"CPVarlenMetadata.from_global expects a 1-D CP mesh, got ndim={device_mesh.ndim}.") | ||
| 66 | - cp_world_size = device_mesh.size() | ||
| 67 | - cp_rank = device_mesh.get_local_rank() | ||
| 68 | - required_divisor = 2 * cp_world_size if load_balancer is not None else cp_world_size | ||
| 69 | - if seq_length % required_divisor != 0: | ||
| 70 | - reason = ( | ||
| 71 | - "2 * cp world size (load balancers chunk each shard into 2 halves)" | ||
| 72 | - if load_balancer is not None | ||
| 73 | - else "cp world size" | ||
| 74 | - ) | ||
| 75 | - raise ValueError( | ||
| 76 | - f"seq_length {seq_length} must be divisible by {required_divisor} " | ||
| 77 | - f"({reason}); got cp world size {cp_world_size}." | ||
| 78 | - ) | ||
| 79 | - shard_len = seq_length // cp_world_size | ||
| 80 | - device = cu_seq_q_global.device | ||
| 81 | - dtype = cu_seq_q_global.dtype | ||
| 82 | - | ||
| 83 | - # Map each batch slot to its pre-balancing token index. | ||
| 84 | - tok_indices_per_batch: torch.Tensor | ||
| 85 | - restore_per_batch: torch.Tensor | None = None | ||
| 86 | - if load_balancer is None: | ||
| 87 | - tok_indices_per_batch = ( | ||
| 88 | - torch.arange(seq_length, device=device, dtype=dtype).unsqueeze(0).expand(batch_size, -1) | ||
| 89 | - ) | ||
| 90 | - else: | ||
| 91 | - rearrange_indices = load_balancer._generate_indices(restore=False) | ||
| 92 | - if rearrange_indices is None: | ||
| 93 | - raise ValueError( | ||
| 94 | - "load_balancer._generate_indices() returned None; a load balancer must return a tensor." | ||
| 95 | - ) | ||
| 96 | - if rearrange_indices.ndim != 2 or rearrange_indices.shape[0] not in ( | ||
| 97 | - 1, | ||
| 98 | - batch_size, | ||
| 99 | - ): | ||
| 100 | - raise ValueError( | ||
| 101 | - "load balancer indices must have shape (1, seq_length) " | ||
| 102 | - "or (batch_size, seq_length); got " | ||
| 103 | - f"{tuple(rearrange_indices.shape)}." | ||
| 104 | - ) | ||
| 105 | - rearrange_indices = rearrange_indices.to(dtype) | ||
| 106 | - if rearrange_indices.shape[0] == 1: | ||
| 107 | - tok_indices_per_batch = rearrange_indices.expand(batch_size, -1) | ||
| 108 | - restore_per_batch = torch.argsort(rearrange_indices, dim=-1).expand(batch_size, -1) | ||
| 109 | - else: | ||
| 110 | - tok_indices_per_batch = rearrange_indices | ||
| 111 | - restore_per_batch = torch.argsort(rearrange_indices, dim=-1) | ||
| 112 | - | ||
| 113 | - # Map rank-local Q slots to sequence positions. | ||
| 114 | - rank_q_indices = tok_indices_per_batch[:, cp_rank * shard_len : (cp_rank + 1) * shard_len] | ||
| 115 | - | ||
| 116 | - # Convert sequence positions to the row-major packed layout. | ||
| 117 | - batch_offsets = torch.arange(batch_size, device=device, dtype=dtype).unsqueeze(1) * seq_length | ||
| 118 | - packed_local_to_global = (batch_offsets + rank_q_indices).reshape(-1) | ||
| 119 | - total_local = batch_size * shard_len | ||
| 120 | - | ||
| 121 | - doc_id = ( | ||
| 122 | - torch.searchsorted( | ||
| 123 | - cu_seq_q_global, | ||
| 124 | - packed_local_to_global, | ||
| 125 | - right=True, | ||
| 126 | - out_int32=(dtype == torch.int32), | ||
| 127 | - ) | ||
| 128 | - - 1 | ||
| 129 | - ) | ||
| 130 | - | ||
| 131 | - # Split on document changes or non-contiguous packed positions. | ||
| 132 | - diff_doc = doc_id[1:] != doc_id[:-1] | ||
| 133 | - diff_global = packed_local_to_global[1:] != packed_local_to_global[:-1] + 1 | ||
| 134 | - is_break = diff_doc | diff_global | ||
| 135 | - seg_starts_inner = (is_break.nonzero(as_tuple=False).squeeze(-1) + 1).to(dtype) | ||
| 136 | - seg_starts = torch.cat([torch.zeros(1, dtype=dtype, device=device), seg_starts_inner]) | ||
| 137 | - seg_ends = torch.cat([seg_starts[1:], torch.tensor([total_local], dtype=dtype, device=device)]) | ||
| 138 | - | ||
| 139 | - seqlen_q = seg_ends - seg_starts | ||
| 140 | - # seqlen_k = (last global pos in segment) - (doc global start) + 1. | ||
| 141 | - last_local_idx = seg_ends - 1 | ||
| 142 | - last_global = packed_local_to_global[last_local_idx] | ||
| 143 | - seg_doc_id = doc_id[seg_starts] | ||
| 144 | - doc_global_start = cu_seq_q_global[seg_doc_id] | ||
| 145 | - seqlen_k = last_global - doc_global_start + 1 | ||
| 146 | - | ||
| 147 | - cu_seq_q = torch.cat([torch.zeros(1, dtype=dtype, device=device), seqlen_q.cumsum(0).to(dtype)]) | ||
| 148 | - cu_seq_k = torch.cat([torch.zeros(1, dtype=dtype, device=device), seqlen_k.cumsum(0).to(dtype)]) | ||
| 149 | - | ||
| 150 | - # Read all host scalars in one device-to-host transfer. | ||
| 151 | - max_q, max_k, total_k = torch.stack([seqlen_q.max(), seqlen_k.max(), seqlen_k.sum()]).cpu().tolist() | ||
| 152 | - | ||
| 153 | - # Gather each segment's K range from its document start. | ||
| 154 | - bases = torch.repeat_interleave(doc_global_start, seqlen_k) | ||
| 155 | - seg_starts_repeated = torch.repeat_interleave(cu_seq_k[:-1], seqlen_k) | ||
| 156 | - within_seg = torch.arange(total_k, device=device, dtype=dtype) - seg_starts_repeated | ||
| 157 | - k_global_gather_indices = bases + within_seg | ||
| 158 | - | ||
| 159 | - # Compose with the inverse load-balancer permutation. | ||
| 160 | - if restore_per_batch is not None: | ||
| 161 | - batch_id = k_global_gather_indices // seq_length | ||
| 162 | - pos_in_batch = k_global_gather_indices % seq_length | ||
| 163 | - restored_pos = restore_per_batch[batch_id, pos_in_batch] | ||
| 164 | - k_global_gather_indices = batch_id * seq_length + restored_pos | ||
| 165 | - | ||
| 166 | - return cls( | ||
| 167 | - cu_seq_q=cu_seq_q, | ||
| 168 | - cu_seq_k=cu_seq_k, | ||
| 169 | - max_q=max_q, | ||
| 170 | - max_k=max_k, | ||
| 171 | - k_global_gather_indices=k_global_gather_indices.to(torch.long), | ||
| 172 | - ) | ||
一般(S2): 【文档同步】需要补充或更新文档。
本 PR 的文档同步要求:
requirements.txt的torchvision==0.29.0、pyproject.toml的0.29.0+cpu以及 qwen3.5 依赖测试里的期望值都与新 pin 一致,用户可见文档不需要动。但.agents/skills/check-pr-docs/references/repo-impact-map.md仍把两个 CI 脚本描述成“改装 nightly 的 torchvision 覆盖 requirements 中的正式版”,本次已改成稳定的 CPU wheel,这句话不再成立;属于低风险的内部参考同步,建议顺手改掉。.agents/skills/check-pr-docs/references/repo-impact-map.md:116:把“.ci/unit_test.sh与.ci/common.sh都改装 nightly 的torchvision覆盖 requirements 中的正式版”改为“.ci/unit_test.sh与.ci/common.sh都改装 PyTorch CPU index 的torchvision==0.29.0+cpu,覆盖镜像内按 requirements 安装的同版本 wheel”,后半句 CANN 入口差异保留。问题编号:R1150-002
审查版本:
d0a787b15d9c1204badd2c0854a83134c1fa1337