Merged
Migration march onto torchtitan 0.4.0 #1127
hanboyouAdd on Oct 29
Migration march onto torchtitan 0.4.0 #1127
Merged
Total: 232 files changed+5662-4859
| @@ -1,9 +1,7 @@ | |||
| 1 | { | 1 | { |
| 2 | "patch_metadata": { | 2 | "patch_metadata": { |
| 3 | "missing": [ | 3 | "missing": [ |
| 4 | - "torchtitan_npu/patches/torchtitan/distributed/flex_shard/_optimizer_reshard_schedule.py", | ||
| 5 | "torchtitan_npu/patches/torchtitan/distributed/flex_shard/dist_muon.py", | 4 | "torchtitan_npu/patches/torchtitan/distributed/flex_shard/dist_muon.py", |
| 6 | - "torchtitan_npu/patches/torchtitan/distributed/flex_shard/optimizer_reshard.py", | ||
| 7 | "torchtitan_npu/patches/torchtitan/distributed/flex_shard/replica_dedup.py", | 5 | "torchtitan_npu/patches/torchtitan/distributed/flex_shard/replica_dedup.py", |
| 8 | "torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py", | 6 | "torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py", |
| 9 | "torchtitan_npu/patches/torchtitan/hf_datasets/text_datasets.py", | 7 | "torchtitan_npu/patches/torchtitan/hf_datasets/text_datasets.py", |
| @@ -32,6 +30,7 @@ | |||
| 32 | "activation_order": { | 30 | "activation_order": { |
| 33 | "torchtitan_npu/extensions/__init__.py": [ | 31 | "torchtitan_npu/extensions/__init__.py": [ |
| 34 | ".torchtitan.ep_process_group", | 32 | ".torchtitan.ep_process_group", |
| 33 | + ".torchtitan.models.common", | ||
| 35 | ".torchtitan.trainer", | 34 | ".torchtitan.trainer", |
| 36 | ".torchtitan.components.metrics", | 35 | ".torchtitan.components.metrics", |
| 37 | ".torchtitan.experiments.graph_trainer", | 36 | ".torchtitan.experiments.graph_trainer", |
| @@ -44,9 +43,7 @@ | |||
| 44 | ".trainer", | 43 | ".trainer", |
| 45 | ".components.metrics", | 44 | ".components.metrics", |
| 46 | ".components.optimizer", | 45 | ".components.optimizer", |
| 47 | - ".components.validate", | ||
| 48 | ".distributed.context_parallel", | 46 | ".distributed.context_parallel", |
| 49 | - ".distributed.full_dtensor", | ||
| 50 | ".distributed.flex_shard.dist_muon", | 47 | ".distributed.flex_shard.dist_muon", |
| 51 | ".experiments.graph_trainer.chunked_loss", | 48 | ".experiments.graph_trainer.chunked_loss", |
| 52 | ".experiments.graph_trainer.ep_chunk_concretization", | 49 | ".experiments.graph_trainer.ep_chunk_concretization", |
| @@ -38,8 +38,8 @@ cd "${PROJECT_ROOT}" | |||
| 38 | 38 | ||
| 39 | PYTHON_BIN="${PYTHON_BIN:-python3.12}" | 39 | PYTHON_BIN="${PYTHON_BIN:-python3.12}" |
| 40 | TORCHTITAN_REPO="${TORCHTITAN_REPO:-https://gitcode.com/GitHub_Trending/to/torchtitan.git}" | 40 | TORCHTITAN_REPO="${TORCHTITAN_REPO:-https://gitcode.com/GitHub_Trending/to/torchtitan.git}" |
| 41 | -TORCHTITAN_VERSION="$(grep -E '^torchtitan==' requirements.txt | head -1 | cut -d= -f3 | tr -d '[:space:][:cntrl:]')" | 41 | +source "${PROJECT_ROOT}/.ci/setup_torchtitan.sh" |
| 42 | -TORCHTITAN_COMMIT="${TORCHTITAN_COMMIT:-v${TORCHTITAN_VERSION}}" | 42 | +TORCHTITAN_COMMIT="$(_torchtitan_revision)" |
| 43 | TORCHTITAN_DIR="${TORCHTITAN_DIR:-${PROJECT_ROOT}/third_party/torchtitan}" | 43 | TORCHTITAN_DIR="${TORCHTITAN_DIR:-${PROJECT_ROOT}/third_party/torchtitan}" |
| 44 | OUTPUT_DIR="${OUTPUT_DIR:-${PROJECT_ROOT}/test_reports/smoke}" | 44 | OUTPUT_DIR="${OUTPUT_DIR:-${PROJECT_ROOT}/test_reports/smoke}" |
| 45 | NGPU="${NGPU:-4}" | 45 | NGPU="${NGPU:-4}" |
| @@ -61,12 +61,7 @@ chmod +x "${PYTHON_SHIMS}/torchrun" | |||
| 61 | export PATH="${PYTHON_SHIMS}:${PATH}" | 61 | export PATH="${PYTHON_SHIMS}:${PATH}" |
| 62 | 62 | ||
| 63 | # Clone and install torchtitan. | 63 | # Clone and install torchtitan. |
| 64 | -if [[ ! -d "${TORCHTITAN_DIR}/.git" ]]; then | 64 | +_setup_torchtitan "${TORCHTITAN_DIR}" |
| 65 | - mkdir -p "$(dirname "${TORCHTITAN_DIR}")" | ||
| 66 | - git clone --filter=blob:none --no-checkout "${TORCHTITAN_REPO}" "${TORCHTITAN_DIR}" | ||
| 67 | -fi | ||
| 68 | -git -C "${TORCHTITAN_DIR}" fetch --depth 1 origin "${TORCHTITAN_COMMIT}" | ||
| 69 | -git -C "${TORCHTITAN_DIR}" checkout --detach --quiet "${TORCHTITAN_COMMIT}" | ||
| 70 | 65 | ||
| 71 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${TORCHTITAN_DIR}" | 66 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${TORCHTITAN_DIR}" |
| 72 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${PROJECT_ROOT}" | 67 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${PROJECT_ROOT}" |
| @@ -74,7 +69,11 @@ git -C "${TORCHTITAN_DIR}" checkout --detach --quiet "${TORCHTITAN_COMMIT}" | |||
| 74 | # The image predates wheels added to requirements.txt; install only the missing | 69 | # The image predates wheels added to requirements.txt; install only the missing |
| 75 | # wheels, never the whole file, whose torch/torch_npu pins differ from the image | 70 | # wheels, never the whole file, whose torch/torch_npu pins differ from the image |
| 76 | # build. | 71 | # build. |
| 77 | -"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir attn-gym==0.0.16 | 72 | +"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir attn-gym==0.0.16 spmd_types==0.2.5 \ |
| 73 | + 'torch_checkpointing>=0.1.0' 'torch_remat>=0.2.0' | ||
| 74 | +# Grain needs its data-pipeline dependencies (for example etils and array-record). | ||
| 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 | ||
| 78 | # The CI image supplies torch 2.15.0.dev; the matching torchvision nightly | 77 | # The CI image supplies torch 2.15.0.dev; the matching torchvision nightly |
| 79 | # 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). |
| 80 | "${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/nightly/cpu "torchvision==0.30.0.dev20260918" |
| @@ -3,30 +3,62 @@ | |||
| 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 | -# Shared torchtitan setup for CI scripts. | 6 | +# Shared torchtitan revision resolution and checkout for CI scripts. |
| 7 | -# Usage: source .ci/setup_torchtitan.sh | 7 | +# Usage: source .ci/setup_torchtitan.sh; _setup_torchtitan <target_dir> |
| 8 | 8 | ||
| 9 | -TORCHTITAN_BRANCH="main" | 9 | +TORCHTITAN_REPOSITORY="${TORCHTITAN_REPOSITORY:-https://gitcode.com/GitHub_Trending/to/torchtitan.git}" |
| 10 | -TORCHTITAN_REPOSITORY="https://gitcode.com/GitHub_Trending/to/torchtitan.git" | 10 | + |
| 11 | +_torchtitan_revision() { | ||
| 12 | + if [[ -n "${TORCHTITAN_COMMIT:-}" ]]; then | ||
| 13 | + printf '%s\n' "${TORCHTITAN_COMMIT}" | ||
| 14 | + return | ||
| 15 | + fi | ||
| 16 | + local requirements_file="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/requirements.txt}" | ||
| 17 | + local line requirement revision="" count=0 | ||
| 18 | + while IFS= read -r line || [[ -n "$line" ]]; do | ||
| 19 | + requirement="${line//[[:space:]]/}" | ||
| 20 | + if [[ "$requirement" =~ ^torchtitan==([0-9][0-9A-Za-z.+-]*)$ ]]; then | ||
| 21 | + revision="v${BASH_REMATCH[1]}" | ||
| 22 | + count=$((count + 1)) | ||
| 23 | + elif [[ "$requirement" =~ ^torchtitan@git\+.+@([[:xdigit:]]{40})$ ]]; then | ||
| 24 | + revision="${BASH_REMATCH[1]}" | ||
| 25 | + count=$((count + 1)) | ||
| 26 | + fi | ||
| 27 | + done < "$requirements_file" | ||
| 28 | + if [[ "$count" != 1 ]]; then | ||
| 29 | + echo "Expected exactly one TorchTitan release or full Git SHA requirement in ${requirements_file}." >&2 | ||
| 30 | + return 1 | ||
| 31 | + fi | ||
| 32 | + printf '%s\n' "$revision" | ||
| 33 | +} | ||
| 11 | 34 | ||
| 12 | _setup_torchtitan() { | 35 | _setup_torchtitan() { |
| 13 | local target_dir="${1:-/tmp/torchtitan}" | 36 | local target_dir="${1:-/tmp/torchtitan}" |
| 14 | - local script_dir | 37 | + local revision repository |
| 15 | - script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | 38 | + revision="$(_torchtitan_revision)" || return |
| 16 | - local requirements_file="${script_dir}/../requirements.txt" | 39 | + repository="${TORCHTITAN_REPO:-${TORCHTITAN_REPOSITORY}}" |
| 17 | - local requirement_pattern='^[[:space:]]*torchtitan==[0-9][0-9A-Za-z.+-]*[[:space:]]*$' | ||
| 18 | - local torchtitan_requirement | ||
| 19 | - torchtitan_requirement="$(grep -E "${requirement_pattern}" "${requirements_file}")" | ||
| 20 | - local torchtitan_version="${torchtitan_requirement##*==}" | ||
| 21 | - torchtitan_version="${torchtitan_version//[[:space:]]/}" | ||
| 22 | - local torchtitan_commit="v${torchtitan_version}" | ||
| 23 | 40 | ||
| 24 | - echo "Preparing torchtitan at ${torchtitan_commit}..." | 41 | + echo "Preparing torchtitan at ${revision}..." |
| 42 | + if [[ ! -e "$target_dir" ]]; then | ||
| 43 | + mkdir -p "$(dirname "$target_dir")" | ||
| 44 | + git clone --filter=blob:none --no-checkout "$repository" "$target_dir" || return | ||
| 45 | + elif ! git -C "$target_dir" rev-parse --git-dir >/dev/null 2>&1 \ | ||
| 46 | + || [[ "$(git -C "$target_dir" rev-parse --show-toplevel)" != "$(cd "$target_dir" && pwd -P)" ]]; then | ||
| 47 | + echo "TorchTitan target exists and is not a Git checkout: ${target_dir}" >&2 | ||
| 48 | + return 1 | ||
| 49 | + elif [[ -n "$(git -C "$target_dir" status --porcelain)" ]]; then | ||
| 50 | + echo "Refusing to change a dirty TorchTitan checkout: ${target_dir}" >&2 | ||
| 51 | + return 1 | ||
| 52 | + fi | ||
| 25 | 53 | ||
| 26 | - echo "Cloning torchtitan source..." | 54 | + # Mirrors may reject fetch-by-SHA while retaining the object in branch history. |
| 27 | - mkdir -p "$(dirname "$target_dir")" | 55 | + if ! git -C "$target_dir" cat-file -e "${revision}^{commit}" 2>/dev/null; then |
| 28 | - git clone --branch "$TORCHTITAN_BRANCH" \ | 56 | + git -C "$target_dir" fetch --filter=blob:none origin \ |
| 29 | - "$TORCHTITAN_REPOSITORY" "$target_dir" | 57 | + '+refs/heads/*:refs/remotes/origin/*' 'refs/tags/*:refs/tags/*' || return |
| 30 | - | 58 | + if ! git -C "$target_dir" cat-file -e "${revision}^{commit}" 2>/dev/null; then |
| 31 | - git -C "$target_dir" checkout "$torchtitan_commit" | 59 | + git -C "$target_dir" fetch --depth 1 origin "$revision" || return |
| 60 | + fi | ||
| 61 | + fi | ||
| 62 | + git -C "$target_dir" checkout --detach --quiet "$revision" || return | ||
| 63 | + git -C "$target_dir" rev-parse HEAD | ||
| 32 | } | 64 | } |
| @@ -33,8 +33,8 @@ trap _cleanup_python_shims EXIT | |||
| 33 | SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | 33 | SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" |
| 34 | PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" | 34 | PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" |
| 35 | TORCHTITAN_REPO="${TORCHTITAN_REPO:-https://gitcode.com/GitHub_Trending/to/torchtitan.git}" | 35 | TORCHTITAN_REPO="${TORCHTITAN_REPO:-https://gitcode.com/GitHub_Trending/to/torchtitan.git}" |
| 36 | -TORCHTITAN_VERSION="$(grep -E '^torchtitan==' "${PROJECT_ROOT}/requirements.txt" | head -1 | cut -d= -f3 | tr -d '[:space:][:cntrl:]')" | 36 | +source "${SCRIPT_DIR}/setup_torchtitan.sh" |
| 37 | -TORCHTITAN_COMMIT="${TORCHTITAN_COMMIT:-v${TORCHTITAN_VERSION}}" | 37 | +TORCHTITAN_COMMIT="$(_torchtitan_revision)" |
| 38 | TORCHTITAN_DIR="${TORCHTITAN_DIR:-${PROJECT_ROOT}/third_party/torchtitan}" | 38 | TORCHTITAN_DIR="${TORCHTITAN_DIR:-${PROJECT_ROOT}/third_party/torchtitan}" |
| 39 | 39 | ||
| 40 | source /home/jenkins/Ascend/cann-9.2.0/set_env.sh | 40 | source /home/jenkins/Ascend/cann-9.2.0/set_env.sh |
| @@ -45,12 +45,8 @@ cd "${PROJECT_ROOT}" | |||
| 45 | export PYTHONPATH="${PROJECT_ROOT}${PYTHONPATH:+:${PYTHONPATH}}" | 45 | export PYTHONPATH="${PROJECT_ROOT}${PYTHONPATH:+:${PYTHONPATH}}" |
| 46 | pip install -r requirements-dev.txt | 46 | pip install -r requirements-dev.txt |
| 47 | 47 | ||
| 48 | -if [[ ! -d "${TORCHTITAN_DIR}/.git" ]]; then | 48 | +_setup_torchtitan "${TORCHTITAN_DIR}" |
| 49 | - mkdir -p "$(dirname "${TORCHTITAN_DIR}")" | 49 | +export TORCHTITAN_DIR |
| 50 | - git clone --filter=blob:none --no-checkout "${TORCHTITAN_REPO}" "${TORCHTITAN_DIR}" | ||
| 51 | -fi | ||
| 52 | -git -C "${TORCHTITAN_DIR}" fetch --depth 1 origin "${TORCHTITAN_COMMIT}" | ||
| 53 | -git -C "${TORCHTITAN_DIR}" checkout --detach --quiet "${TORCHTITAN_COMMIT}" | ||
| 54 | pip install --no-deps -e "${TORCHTITAN_DIR}" | 50 | pip install --no-deps -e "${TORCHTITAN_DIR}" |
| 55 | pip install \ | 51 | pip install \ |
| 56 | --find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torchft/index.html \ | 52 | --find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torchft/index.html \ |
| @@ -62,7 +58,10 @@ pip install --no-deps -e . | |||
| 62 | # the image pins a *different* torch/torch_npu build than requirements.txt does, so | 58 | # the image pins a *different* torch/torch_npu build than requirements.txt does, so |
| 63 | # re-running the whole file would upgrade the CANN stack mid-job (it broke the | 59 | # re-running the whole file would upgrade the CANN stack mid-job (it broke the |
| 64 | # fused-op smoke tests once). New pure-Python runtime wheels go here by name. | 60 | # fused-op smoke tests once). New pure-Python runtime wheels go here by name. |
| 65 | -pip install --no-deps attn-gym==0.0.16 | 61 | +pip install --no-deps attn-gym==0.0.16 spmd_types==0.2.5 \ |
| 62 | + 'torch_checkpointing>=0.1.0' 'torch_remat>=0.2.0' | ||
| 63 | +# Resolve Grain's own data-pipeline dependencies without changing the torch stack. | ||
| 64 | +pip install grain==0.2.18 | ||
| 66 | 65 | ||
| 67 | pip install --no-deps torchvision==0.30.0.dev20260918 \ | 66 | pip install --no-deps torchvision==0.30.0.dev20260918 \ |
| 68 | --extra-index-url https://download.pytorch.org/whl/nightly/cpu | 67 | --extra-index-url https://download.pytorch.org/whl/nightly/cpu |
| @@ -124,3 +124,6 @@ log/ | |||
| 124 | 124 | ||
| 125 | # Generated training-log visualizations (created lazily by the skill). | 125 | # Generated training-log visualizations (created lazily by the skill). |
| 126 | /outputs/ | 126 | /outputs/ |
| 127 | + | ||
| 128 | +# torch.compile debug dumps written by the rope-compile unit tests. | ||
| 129 | +/torch_compile_debug/ | ||
| @@ -204,7 +204,7 @@ token 计数,并重置 FSDP 临时状态;编译本身不负责撤销额外 | |||
| 204 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/cache.py` | 管理路由模式、microbatch slot 和专家 ID 存储。 | | 204 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/cache.py` | 管理路由模式、microbatch slot 和专家 ID 存储。 | |
| 205 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/data.py` | 管理可恢复 iterator、完整 step 读取及仅前向工作副本。 | | 205 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/data.py` | 管理可恢复 iterator、完整 step 读取及仅前向工作副本。 | |
| 206 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/detector.py` | 维护 loss 趋势统计,判定 spike 并回溯 onset。 | | 206 | | `torchtitan_npu/extensions/experiment/anticipatory_routing/detector.py` | 维护 loss 趋势统计,判定 spike 并回溯 onset。 | |
| 207 | -| `torchtitan_npu/extensions/experiment/anticipatory_routing/router.py` | 通过 HashRouter 配置 override 接入录制与重放,查找 router 并创建、绑定共享缓存。 | | 207 | +| `torchtitan_npu/extensions/experiment/anticipatory_routing/router.py` | 查找 router 并绑定共享缓存,在实例选择专家后接入录制与重放。 | |
| 208 | 208 | ||
| 209 | ## 验证范围 | 209 | ## 验证范围 |
| 210 | 210 | ||
| @@ -252,7 +252,7 @@ profiler 仍按实际执行的外层迭代推进,结构化日志的 step 标 | |||
| 252 | 252 | ||
| 253 | 真实入口集成用例 `dsv4_anticipatory_recovery` 注册到 models/deepseek_v4 suite, | 253 | 真实入口集成用例 `dsv4_anticipatory_recovery` 注册到 models/deepseek_v4 suite, |
| 254 | 使用单卡真实 DeepSeek-V4 recipe、CLI 配置和原生 checkpointer,训练目标仅在测试入口中 | 254 | 使用单卡真实 DeepSeek-V4 recipe、CLI 配置和原生 checkpointer,训练目标仅在测试入口中 |
| 255 | -一次性放大以触发真实检测器,验证 override 生效及 WARMUP → ACTIVE → DRAIN → NORMAL。 | 255 | +一次性放大以触发真实检测器,验证缓存接线及 WARMUP → ACTIVE → DRAIN → NORMAL。 |
| 256 | 生产配置不增加手动触发参数。执行命令: | 256 | 生产配置不增加手动触发参数。执行命令: |
| 257 | 257 | ||
| 258 | ```bash | 258 | ```bash |
| @@ -107,21 +107,39 @@ entry 的 `prepare_cp_metadata` 用 rank-local chunk 重建这三个 frame 以 | |||
| 107 | ## 2. 启用方式 | 107 | ## 2. 启用方式 |
| 108 | 108 | ||
| 109 | ```bash | 109 | ```bash |
| 110 | -# DeepSeek-V4 | 110 | +# DeepSeek-V4.1,两个 rank;先设置 HF_ASSETS_PATH 指向 tokenizer。 |
| 111 | -NGPU=2 \ | 111 | +MODULE=torchtitan_npu.models.deepseek_v4_1 CONFIG=deepseek_v4_1_stripped NGPU=2 \ |
| 112 | - bash examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh \ | 112 | + bash scripts/run_train.sh \ |
| 113 | - --parallelism.context-parallel-degree 2 \ | 113 | + --hf-assets-path "$HF_ASSETS_PATH" \ |
| 114 | + --training.max-context-length 512 \ | ||
| 115 | + --training.num-tokens-per-microbatch-per-dp-rank 512 \ | ||
| 116 | + --training.num-tokens-per-train-step 512 \ | ||
| 117 | + --training.steps 2 --training.disable-cuda-graphs --compile.no-enable \ | ||
| 118 | + --dataloader.per-doc-alignment 4 \ | ||
| 114 | --parallelism.spmd-backend spmd_types \ | 119 | --parallelism.spmd-backend spmd_types \ |
| 115 | - --dataloader.per_doc_alignment 256 \ | 120 | + --parallelism.context-parallel-degree 2 \ |
| 116 | - --training.steps 2 | 121 | + --parallelism.context-parallel-load-balancer doc_chunk \ |
| 122 | + --parallelism.data-parallel-shard-degree 1 \ | ||
| 123 | + --parallelism.data-parallel-replicate-degree 1 \ | ||
| 124 | + --parallelism.expert-parallel-degree 1 \ | ||
| 125 | + --parallelism.tensor-parallel-degree 1 \ | ||
| 126 | + --parallelism.pipeline-parallel-degree 1 \ | ||
| 127 | + --optimizer.name AdamW --checkpoint.no-enable \ | ||
| 128 | + --override.imports torchtitan_npu.override.common.rope.workaround \ | ||
| 129 | + torchtitan_npu.override.common.optimizer.virtual \ | ||
| 130 | + torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc \ | ||
| 131 | + torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc | ||
| 117 | ``` | 132 | ``` |
| 118 | 133 | ||
| 134 | +DeepSeek-V4 的 Grain 配置将文档对齐值放在 dataset 的 `AlignedTextProcessor.Config.per_doc_alignment`; | ||
| 135 | +启用 CP 时,需在 recipe 中将该值设为 `128 × CP` 的倍数。 | ||
| 136 | + | ||
| 119 | V4.1 的 CP 配方是 `examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_1m_a5.sh`:脚本默认 | 137 | V4.1 的 CP 配方是 `examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_1m_a5.sh`:脚本默认 |
| 120 | `CP=128`、`EP=128`、`--dataloader.per_doc_alignment 256`,启动时按 `EP` 校验拓扑(`WORLD_SIZE` | 138 | `CP=128`、`EP=128`、`--dataloader.per_doc_alignment 256`,启动时按 `EP` 校验拓扑(`WORLD_SIZE` |
| 121 | 与 `384` 都要能被 `EP` 整除);`CP` / `EP` 可用同名环境变量覆盖。 | 139 | 与 `384` 都要能被 `EP` 整除);`CP` / `EP` 可用同名环境变量覆盖。 |
| 122 | 140 | ||
| 123 | - `--parallelism.context-parallel-degree > 1` 启用 CP;必须配合 | 141 | - `--parallelism.context-parallel-degree > 1` 启用 CP;必须配合 |
| 124 | - `--parallelism.spmd-backend spmd_types`(声明式 `S(1) -> R` all-gather 的前提)。切分与 metadata | 142 | + `--parallelism.spmd-backend spmd_types`(声明式 `S(0) -> R` all-gather 的前提)。切分与 metadata |
| 125 | 重建之后,`preprocess_inputs` 统一施加输入 SPMD 标注,这一步只在 `spmd_types` 后端执行。 | 143 | 重建之后,`preprocess_inputs` 统一施加输入 SPMD 标注,这一步只在 `spmd_types` 后端执行。 |
| 126 | - 布局必须是 doc-chunk:`--parallelism.context-parallel-load-balancer doc_chunk`(上游默认 `headtail` | 144 | - 布局必须是 doc-chunk:`--parallelism.context-parallel-load-balancer doc_chunk`(上游默认 `headtail` |
| 127 | 会被融合 entry 的 `prepare_cp_metadata` 拒绝)。输入在切之前按该置换重排,零通信;示例脚本已按 | 145 | 会被融合 entry 的 `prepare_cp_metadata` 拒绝)。输入在切之前按该置换重排,零通信;示例脚本已按 |
| @@ -133,19 +151,18 @@ V4.1 的 CP 配方是 `examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_1m_a5.sh` | |||
| 133 | 的:CP 把每篇文档切成 `cp` 个等长 chunk,除了 `doc % (cp × ratio) == 0`,**每个 chunk 自身**也 | 151 | 的:CP 把每篇文档切成 `cp` 个等长 chunk,除了 `doc % (cp × ratio) == 0`,**每个 chunk 自身**也 |
| 134 | 必须是 ratio 的整数倍,否则该 rank 的压缩前缀会停在组中间,而部分压缩块不在已验证的内核契约内 | 152 | 必须是 ratio 的整数倍,否则该 rank 的压缩前缀会停在组中间,而部分压缩块不在已验证的内核契约内 |
| 135 | ——因此不放松。例如 cp=2、ratio=128、doc=128 会得到 64-token chunk(不是 128 的倍数)并被明确 | 153 | ——因此不放松。例如 cp=2、ratio=128、doc=128 会得到 64-token chunk(不是 128 的倍数)并被明确 |
| 136 | - 拒绝。`--dataloader.per_doc_alignment` 必须是对应 lcm × cp 的倍数:`Trainer` 启动时由 | 154 | + 拒绝。数据加载器配置的文档对齐值必须是对应 lcm × cp 的倍数:模型配置更新时由 |
| 137 | - `require_per_doc_alignment` 检查,每个 geometry 的 entry 再由 | 155 | + `require_dataloader_alignment` 检查,每个 geometry 的 entry 再由 |
| 138 | `require_document_alignment(cu_seqlens, cp_size=cp, ratio=r)` 检查(V4 在 `doc_chunk_entry`,V4.1 | 156 | `require_document_alignment(cu_seqlens, cp_size=cp, ratio=r)` 检查(V4 在 `doc_chunk_entry`,V4.1 |
| 139 | - 在 `shard_asc_v41_metadata`),示例脚本已按该值传入 `--dataloader.per_doc_alignment`。 | 157 | + 在 `shard_asc_v41_metadata`),V4.1 使用 `--dataloader.per-doc-alignment`;V4 Grain 使用 dataset processor 的配置。 |
| 140 | - 需要完整 NPU 环境(`torch_npu`、CANN、HCCL、匹配的 `cann_ops_transformer`)。只有 AscendC 融合 | 158 | - 需要完整 NPU 环境(`torch_npu`、CANN、HCCL、匹配的 `cann_ops_transformer`)。只有 AscendC 融合 |
| 141 | 路径支持 CP;模型目录的参考 metadata hook 显式拒绝 CP,V4.1 的 `update_from_config` 还会要求 | 159 | 路径支持 CP;模型目录的参考 metadata hook 显式拒绝 CP,V4.1 的 `update_from_config` 还会要求 |
| 142 | 同时请求 `override.deepseek_v4_1.sparse_attn.asc` 与 | 160 | 同时请求 `override.deepseek_v4_1.sparse_attn.asc` 与 |
| 143 | `override.deepseek_v4_1.lightning_indexer.asc`。 | 161 | `override.deepseek_v4_1.lightning_indexer.asc`。 |
| 144 | - 量化后端(V4 的 `QuantV4Metadata`、V4.1 的 `_V41QuantAttentionMetadata`)目前不重建 rank-local | 162 | - 量化后端(V4 的 `QuantV4Metadata`、V4.1 的 `_V41QuantAttentionMetadata`)目前不重建 rank-local |
| 145 | metadata,`prepare_cp_metadata` 直接拒绝:量化路径只能跑 `context-parallel-degree 1`。 | 163 | metadata,`prepare_cp_metadata` 直接拒绝:量化路径只能跑 `context-parallel-degree 1`。 |
| 146 | -- DeepSeek-V4 的融合注意力在 CP=1 时支持 `local_batch_size > 1`(输入布局按批展平,attention 输出保留 | 164 | +- 模型输入使用 folded-token 布局:token 与位置为 `[T]`,隐藏状态为 `[T, D]`。 |
| 147 | - `[B, S]`)。CP>1 暂不支持 `local_batch_size > 1`,`CarryExchange` 在交换或边界计算前显式报错;DSA 路径 | 165 | + 不同文档通过 positions 重置及 metadata 边界区分;DSA 路径的 TP 限制以模型配置为准。 |
| 148 | - TP 固定为 1。 | ||
| 149 | 166 | ||
| 150 | ## 3. 两栈差异总览 | 167 | ## 3. 两栈差异总览 |
| 151 | 168 | ||
| @@ -153,9 +170,9 @@ V4.1 的 CP 配方是 `examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_1m_a5.sh` | |||
| 153 | | --- | --- | --- | | 170 | | --- | --- | --- | |
| 154 | | 输入布局 | 同一份:`cp_shard` 的 doc-chunk 置换,tokens / labels / positions / MTP 深度一次到位 | 同左 | | 171 | | 输入布局 | 同一份:`cp_shard` 的 doc-chunk 置换,tokens / labels / positions / MTP 深度一次到位 | 同左 | |
| 155 | | 压缩器与 CP | ratio-4 重叠块需要前驱 rank 的 carry:`CarryExchange`(与压缩器同级的模块)做交换/prepend,调用点压缩后再裁剪 | 压缩器 CP-agnostic:文档按 `cp × ratio` 对齐后,本 rank 的 slab 起点就是组边界,本地池化即可;无 carry | | 172 | | 压缩器与 CP | ratio-4 重叠块需要前驱 rank 的 carry:`CarryExchange`(与压缩器同级的模块)做交换/prepend,调用点压缩后再裁剪 | 压缩器 CP-agnostic:文档按 `cp × ratio` 对齐后,本 rank 的 slab 起点就是组边界,本地池化即可;无 carry | |
| 156 | -| 压缩流取得方式 | 本地流(含 carry)池化后,内核边界 `S(1) -> R` gather 成整行 | 本地 slab 池化后同样在核心边界 `S(1) -> R` gather | | 173 | +| 压缩流取得方式 | 本地流(含 carry)池化后,内核边界 `S(0) -> R` gather 成整行 | 本地 slab 池化后同样在核心边界 `S(0) -> R` gather | |
| 157 | -| 内核锚定 | arch35 读 `seqused_q` / `seqused_ori_kv` / `seqused_cmp_kv`,窗口与压缩因果上限直接锚在 reach 上;arch22 的内核不读 key 侧 `seqused`、把 mask 右对齐到 frame 末尾,因此非末尾 rank 的两路 key 流要压成 rank-local 前缀 | 同 arch35(V4.1 只跑在 arch35 上) | | 174 | +| 内核锚定 | arch35 读 `seqused_q` / `seqused_ori_kv` / `seqused_cmp_kv`,窗口与压缩因果上限直接锚在 reach 上;arch22 的内核不读 key 侧 `seqused`、把 mask 右对齐到 frame 末尾,因此非末尾 rank 的两路 key 流要压成 rank-local 前缀 | arch22 同样对 key 前缀做整理;arch35 读取 `seqused` | |
| 158 | -| rank-local key 压缩(仅 arch22) | `A3KeyWorkaround`(`override/a3_workaround.py`):`swa_k_gather` / `cmp_k_gather` 两个可微 `index_select`,由 `build_aicpu_metadata` 在 `if not _IS_A5:` 里加在 `AscV4Metadata` 上 | 无 | | 175 | +| rank-local key 压缩(仅 arch22) | `A3KeyWorkaround`(`override/a3_workaround.py`):`swa_k_gather` / `cmp_k_gather` 两个可微 `index_select`,由 `build_aicpu_metadata` 在 `if not _IS_A5:` 里加在 `AscV4Metadata` 上 | 同样使用 `A3KeyWorkaround` | |
| 159 | | frame 归属 | 模型 metadata(`DeepSeekV4Metadata`,含 `cp: CPDeepSeekMetadata(restore)`) | 融合 entry(`AscV41Metadata`) | | 176 | | frame 归属 | 模型 metadata(`DeepSeekV4Metadata`,含 `cp: CPDeepSeekMetadata(restore)`) | 融合 entry(`AscV41Metadata`) | |
| 160 | | indexer teacher 归一化 | `_LightningIndexerTND.backward` 除以整行 token 数 `swa_k.cu_seqlens[-1]` | `num_global_queries`(本 step 全部 query 数,按 DP 求和) | | 177 | | indexer teacher 归一化 | `_LightningIndexerTND.backward` 除以整行 token 数 `swa_k.cu_seqlens[-1]` | `num_global_queries`(本 step 全部 query 数,按 DP 求和) | |
| 161 | | 参考 metadata | `DeepSeekV4Metadata.prepare_cp_metadata` 拒绝 | `DeepSeekV41Metadata.prepare_cp_metadata` 拒绝 | | 178 | | 参考 metadata | `DeepSeekV4Metadata.prepare_cp_metadata` 拒绝 | `DeepSeekV41Metadata.prepare_cp_metadata` 拒绝 | |
| @@ -167,7 +184,7 @@ V4.1 的 CP 配方是 `examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_1m_a5.sh` | |||
| 167 | 184 | ||
| 168 | ```text | 185 | ```text |
| 169 | Decoder.preprocess_inputs(每个 microbatch 一次) | 186 | Decoder.preprocess_inputs(每个 microbatch 一次) |
| 170 | - 整行 [1, N] --cp_shard(doc_chunk 置换)--> 本地 chunk 行 [1, C] | 187 | + 整行 [N] --cp_shard(doc_chunk 置换)--> 本地 chunk 行 [C] |
| 171 | tokens / labels / positions 随同一次切分到位(零通信) | 188 | tokens / labels / positions 随同一次切分到位(零通信) |
| 172 | 随后按 spmd_backend == spmd_types 施加 annotate_input_spmd_types | 189 | 随后按 spmd_backend == spmd_types 施加 annotate_input_spmd_types |
| 173 | DeepSeekV4Model.preprocess_inputs 只额外准备 MTP 深度,并让它们走同一次 cp_shard | 190 | DeepSeekV4Model.preprocess_inputs 只额外准备 MTP 深度,并让它们走同一次 cp_shard |
| @@ -175,14 +192,14 @@ DeepSeekV4Model.preprocess_inputs 只额外准备 MTP 深度,并让它们走 | |||
| 175 | Attention.forward(每层) | 192 | Attention.forward(每层) |
| 176 | x(doc-chunk 行) | 193 | x(doc-chunk 行) |
| 177 | ├─ wq_a / q_norm / wq_b / q_head_norm / rope(positions) [查询不移动] | 194 | ├─ wq_a / q_norm / wq_b / q_head_norm / rope(positions) [查询不移动] |
| 178 | - ├─ swa:wkv / kv_norm / rope(positions)(chunk 行) [CP=S(1)] | 195 | + ├─ swa:wkv / kv_norm / rope(positions)(chunk 行) [CP=S(0)] |
| 179 | │ └─ key_stream(RestorePlan.apply)-> 本 rank slab,供核心边界 gather | 196 | │ └─ key_stream(RestorePlan.apply)-> 本 rank slab,供核心边界 gather |
| 180 | - ├─ compressor(x)(见 4.3:内部 restore + ratio-4 carry) [CP=S(1)] | 197 | + ├─ compressor(x)(见 4.3:内部 restore + ratio-4 carry) [CP=S(0)] |
| 181 | └─ indexer:idx_q / idx_w 在 chunk 行上投影;idx_k 由它自己的压缩器产出 | 198 | └─ indexer:idx_q / idx_w 在 chunk 行上投影;idx_k 由它自己的压缩器产出 |
| 182 | wo_a / wo_b 输出留在 doc-chunk 行(不 unpermute) | 199 | wo_a / wo_b 输出留在 doc-chunk 行(不 unpermute) |
| 183 | 200 | ||
| 184 | inner_attention / lightning_indexer 的 ShardingConfig | 201 | inner_attention / lightning_indexer 的 ShardingConfig |
| 185 | - swa_k, cmp_k(核心)与 idx_k(selector): cp S(1) -> R(内核边界 all-gather 整行) | 202 | + swa_k, cmp_k(核心)与 idx_k(selector): cp S(0) -> R(内核边界 all-gather 整行) |
| 186 | q, idx_q, idx_w: 保持本 rank 的 chunk(attention 直接调用这两个模块) | 203 | q, idx_q, idx_w: 保持本 rank 的 chunk(attention 直接调用这两个模块) |
| 187 | ``` | 204 | ``` |
| 188 | 205 | ||
| @@ -220,7 +237,7 @@ plan 搬过的。 | |||
| 220 | - `a3_key_gather(cu_seqlens, seqused)`:在 device 上算出把整行压到该帧的 `index_select` 下标 | 237 | - `a3_key_gather(cu_seqlens, seqused)`:在 device 上算出把整行压到该帧的 `index_select` 下标 |
| 221 | (`repeat_interleave` + 比较 + `nonzero`;`nonzero` 的行数是 device 值,每个 microbatch 每条流 | 238 | (`repeat_interleave` + 比较 + `nonzero`;`nonzero` 的行数是 device 值,每个 microbatch 每条流 |
| 222 | 一次同步,代价见 §7 的性能注); | 239 | 一次同步,代价见 §7 的性能注); |
| 223 | -- 两个 gather 都可微:反向经 scatter 回整行,再由 `S(1) -> R` 的 reduce-scatter 回到本 rank 的 | 240 | +- 两个 gather 都可微:反向经 scatter 回整行,再由 `S(0) -> R` 的 reduce-scatter 回到本 rank 的 |
| 224 | chunk;`cp=1` 与最后一个 rank 的 reach 就是整篇文档,此时两个 gather 都是 `None`。 | 241 | chunk;`cp=1` 与最后一个 rank 的 reach 就是整篇文档,此时两个 gather 都是 `None`。 |
| 225 | 242 | ||
| 226 | entry 的 `swa_k` / `cmp_k` 就是内核帧,forward / backward / selector 各取一个 frame 与一个 gather, | 243 | entry 的 `swa_k` / `cmp_k` 就是内核帧,forward / backward / selector 各取一个 frame 与一个 gather, |
| @@ -282,10 +299,9 @@ rank 0 只发送、不接收;最后一个 rank 只接收、不发送;其余 | |||
| 282 | 直接返回同一份流,压缩器拿到的是整行边界。参考实现与融合实现共用同一接口 | 299 | 直接返回同一份流,压缩器拿到的是整行边界。参考实现与融合实现共用同一接口 |
| 283 | `compressor(x, positions, *, cu_seqlens=None)`(`cu_seqlens` 是 keyword-only:带 sharding | 300 | `compressor(x, positions, *, cu_seqlens=None)`(`cu_seqlens` 是 keyword-only:带 sharding |
| 284 | config 的模块走框架的位置参数契约,位置参数个数必须与签名一致)。 | 301 | config 的模块走框架的位置参数契约,位置参数个数必须与签名一致)。 |
| 285 | -输入 `x` 为 `[B, L, D]`,每行 token 数必须是 `ratio` 的整数倍,positions 为 `[B, L]`。 | 302 | +输入 `x` 为 folded-token 形状 `[T, D]`,positions 为 `[T]`,每篇文档的 token 数必须按 |
| 286 | -CP=1 时可将整批展平成 `[1, B * L, D]` 打包流执行压缩,再还原为 `[B, L // ratio, D]`; | 303 | +压缩比对齐。内部压缩实现使用单行容器,输出再恢复为 `[T / ratio, D]`;文档边界防止 ratio-4 |
| 287 | -每行 positions 从 0 开始,上游 `create_varlen_metadata_for_document` 将这些行首记为文档边界, | 304 | +的重叠跨文档。 |
| 288 | -避免 ratio-4 的重叠跨行。CP>1 的 carry/prepend/trim 仍要求 B=1。 | ||
| 289 | 305 | ||
| 290 | ### 4.4 参考路径 | 306 | ### 4.4 参考路径 |
| 291 | 307 | ||
| @@ -302,16 +318,16 @@ CP=1/CP=2 之间做。 | |||
| 302 | Attention.forward | 318 | Attention.forward |
| 303 | x (本 rank 的 chunk 行,输入布局已放好,查询不移动) | 319 | x (本 rank 的 chunk 行,输入布局已放好,查询不移动) |
| 304 | ├─ q 投影 / q_norm / rope(positions) | 320 | ├─ q 投影 / q_norm / rope(positions) |
| 305 | - ├─ swa_k 投影 + rope(positions)(chunk 行) [CP=S(1)] | 321 | + ├─ swa_k 投影 + rope(positions)(chunk 行) [CP=S(0)] |
| 306 | │ └─ key_stream(RestorePlan.apply)-> 本 rank slab,供核心边界 gather | 322 | │ └─ key_stream(RestorePlan.apply)-> 本 rank slab,供核心边界 gather |
| 307 | - ├─ compressor(x, position_k):内部 restore,source 层池化,无 carry [CP=S(1)] | 323 | + ├─ compressor(x, position_k):内部 restore,source 层池化,无 carry [CP=S(0)] |
| 308 | └─ indexer:idx_q / weights 在 chunk 行上投影,idx_k 由压缩器的 slab latent 投影 | 324 | └─ indexer:idx_q / weights 在 chunk 行上投影,idx_k 由压缩器的 slab latent 投影 |
| 309 | 输出留在 chunk 行:rope(positions, inverse) -> wo_a -> wo_b | 325 | 输出留在 chunk 行:rope(positions, inverse) -> wo_a -> wo_b |
| 310 | 326 | ||
| 311 | Sparse core / selector(sharding 声明) | 327 | Sparse core / selector(sharding 声明) |
| 312 | - swa_k, cmp_k, idx_k: cp S(1) -> R(整行) | 328 | + swa_k, cmp_k, idx_k: cp S(0) -> R(整行) |
| 313 | q, idx_q, weights: 保持本 rank 的 chunk | 329 | q, idx_q, weights: 保持本 rank 的 chunk |
| 314 | - topk_indices, sink: replicated | 330 | + topk_indices: 按 token 维切分;sink: 不按 CP 切分 |
| 315 | ``` | 331 | ``` |
| 316 | 332 | ||
| 317 | V4.1 的参考 metadata(`DeepSeekV41Metadata`)只带整行边界与 `position_k`(degree=1 时等于输入的 | 333 | V4.1 的参考 metadata(`DeepSeekV41Metadata`)只带整行边界与 `position_k`(degree=1 时等于输入的 |
| @@ -328,7 +344,7 @@ seqused = diff(cu_seq_q) | |||
| 328 | alignment = cp_size * max(ratio, 1) # 每篇文档必须对齐 | 344 | alignment = cp_size * max(ratio, 1) # 每篇文档必须对齐 |
| 329 | chunk = seqused // cp_size # Q_d | 345 | chunk = seqused // cp_size # Q_d |
| 330 | reach = (cp_rank + 1) * chunk # K_d | 346 | reach = (cp_rank + 1) * chunk # K_d |
| 331 | -exchange = cp_plan(cu_seq_q, cp_size, cp_rank, seq_len) | 347 | +exchange = chunk_plan(cu_seq_q, cp_size, cp_rank, slab_len) |
| 332 | q = Frame(cu_seq_q // cp_size, chunk) | 348 | q = Frame(cu_seq_q // cp_size, chunk) |
| 333 | swa_k = Frame(cu_seq_q, reach) | 349 | swa_k = Frame(cu_seq_q, reach) |
| 334 | cmp_k = Frame(cu_seq_k, reach // ratio, residual=reach % ratio) # ratio > 0 | 350 | cmp_k = Frame(cu_seq_k, reach // ratio, residual=reach % ratio) # ratio > 0 |
| @@ -339,7 +355,7 @@ position_k = slab_positions(cu_seq_q, cp_size, cp_rank, seq_len) | |||
| 339 | `restore.slab_positions`(纯 device 算术,与本 rank slab 真实所在的行同一组数;degree=1 时它就是 | 355 | `restore.slab_positions`(纯 device 算术,与本 rank slab 真实所在的行同一组数;degree=1 时它就是 |
| 340 | 输入的 `positions`)。 | 356 | 输入的 `positions`)。 |
| 341 | 357 | ||
| 342 | -并检查 `sum(chunk) == batch_size * seq_len`(边界描述的必须是调用方切出来的那条行)。frame 变 | 358 | +并检查 `sum(chunk) == slab_len`(边界描述的必须是调用方切出来的那条行)。frame 变 |
| 343 | 则记录必须重算:entry 用 `build_aicpu_metadata(local, geometry=...)`(读 entry 自己的 | 359 | 则记录必须重算:entry 用 `build_aicpu_metadata(local, geometry=...)`(读 entry 自己的 |
| 344 | `q` / `swa_k` / `cmp_k`)重建 `sparse_attn` 与 `lightning_indexer` 两组 `*_metadata`; | 360 | `q` / `swa_k` / `cmp_k`)重建 `sparse_attn` 与 `lightning_indexer` 两组 `*_metadata`; |
| 345 | `reach` 这类"本 rank 的数"由 python int 的 `cp_rank` 参与张量运算(rank 是 host 值,见 §1.2)。 | 361 | `reach` 这类"本 rank 的数"由 python int 的 `cp_rank` 参与张量运算(rank 是 host 值,见 §1.2)。 |
| @@ -352,16 +368,16 @@ V4.1 的 `compress_ratio` 可以是 0(window-only,没有任何压缩 frame | |||
| 352 | 368 | ||
| 353 | V4.1 的 `Compressor`(`torchtitan_npu/models/deepseek_v4_1/compressor.py`)没有 CP 分支:source | 369 | V4.1 的 `Compressor`(`torchtitan_npu/models/deepseek_v4_1/compressor.py`)没有 CP 分支:source |
| 354 | layer 在本地 slab 上做 `ratio` 折叠(ratio==1 是普通投影),因为文档已按 `cp × ratio` 对齐, | 370 | layer 在本地 slab 上做 `ratio` 折叠(ratio==1 是普通投影),因为文档已按 `cp × ratio` 对齐, |
| 355 | -本 rank 的 slab 起点就是组边界,`C/ratio` 是整数块。压缩输出(`[B, C/ratio, D]`)在 sparse core | 371 | +本 rank 的 slab 起点就是组边界,`C/ratio` 是整数块。压缩输出(`[C/ratio, D]`)在 sparse core |
| 356 | -的边界被声明式 `cp: S(1) -> R` gather 成整行;`cmp_k.seqused = reach // ratio` 让内核只读本 rank | 372 | +的边界被声明式 `cp: S(0) -> R` gather 成整行;`cmp_k.seqused = reach // ratio` 让内核只读本 rank |
| 357 | 之前的块。ratio-4 那种跨 slab 的 carry 在 V4.1 不存在,因此没有 `CarryExchange`。 | 373 | 之前的块。ratio-4 那种跨 slab 的 carry 在 V4.1 不存在,因此没有 `CarryExchange`。 |
| 358 | 374 | ||
| 359 | `torchtitan_npu/models/deepseek_v4_1/sharding.py` 声明 CP 的输入/输出放置: | 375 | `torchtitan_npu/models/deepseek_v4_1/sharding.py` 声明 CP 的输入/输出放置: |
| 360 | 376 | ||
| 361 | -- sparse core:`q` 保持 `S(2)`(本 rank chunk),`swa_k` / `cmp_k` 在消费侧为整行 | 377 | +- sparse core:`q` 的 CP token 维保持 `S(0)`,TP head 维为 `S(1)`(本 rank chunk),`swa_k` / `cmp_k` 在消费侧为整行 |
| 362 | - (`in_src_shardings` 是 replicated、`in_dst_shardings` 是行放置,即 `S(1) -> R`), | 378 | + (CP 输入为 `S(0)`,消费侧为 `R`), |
| 363 | - `topk_indices` 与 `attn_sink` replicated; | 379 | + `topk_indices` 按 token 维切分,`attn_sink` 不按 CP 切分; |
| 364 | -- selector:`idx_q` / `weights` replicated,`idx_k` 做同样的 `S(1) -> R`(选择器用整行 index keys | 380 | +- selector:`idx_q` / `weights` replicated,`idx_k` 做同样的 `S(0) -> R`(选择器用整行 index keys |
| 365 | 给本 rank 的 chunk 打分)。 | 381 | 给本 rank 的 chunk 打分)。 |
| 366 | 382 | ||
| 367 | ### 5.4 indexer teacher 的归一化 | 383 | ### 5.4 indexer teacher 的归一化 |
| @@ -379,11 +395,11 @@ microbatch 的 query token 数(在 CP 切分之前统计,DP 维再求和) | |||
| 379 | 395 | ||
| 380 | Engram 不在这一列。它的 token history 要的是每行**在本文档内**的前驱,doc-chunk 下这些前驱不是 | 396 | Engram 不在这一列。它的 token history 要的是每行**在本文档内**的前驱,doc-chunk 下这些前驱不是 |
| 381 | 全局行的一段连续区间(`[lo - H, lo)` 是别的文档的尾巴),一个窗口也说不出每行各自的前驱。所以 | 397 | 全局行的一段连续区间(`[lo - H, lo)` 是别的文档的尾巴),一个窗口也说不出每行各自的前驱。所以 |
| 382 | -`DeepSeekV41Model.preprocess_inputs` 在切分之前把整行的前驱算成 `[B, C, H]`(第 `d - 1` 项是这一行 | 398 | +`DeepSeekV41Model.preprocess_inputs` 在切分之前把整行的前驱算成 `[C, H]`(第 `d - 1` 项是这一行 |
| 383 | 往前第 `d` 个 token),`doc_chunk_permutation` 与 shard 用的是同一个置换,因此不需要任何跨 rank | 399 | 往前第 `d` 个 token),`doc_chunk_permutation` 与 shard 用的是同一个置换,因此不需要任何跨 rank |
| 384 | 通信;文档起点那几行没有前驱,仍然由 entry 的 `positions`(`positions >= distance`)掩掉。engram 的 | 400 | 通信;文档起点那几行没有前驱,仍然由 entry 的 `positions`(`positions >= distance`)掩掉。engram 的 |
| 385 | -`_shift_tokens` 因此有两种 history 契约:`[B, H]`(连续切分给的一个窗口)与 `[B, L, H]`(按行)。 | 401 | +`_shift_tokens` 因此有两种 history 契约:`[H]`(连续切分给的一个窗口)与 `[T, H]`(按 token)。 |
| 386 | -按行那一支直接取 `token_history[:, :, distance - 1]` 这一片,**不**先分配一个填满 pad 的缓冲再整片写回: | 402 | +按行那一支直接取 `token_history[:, distance - 1]` 这一片,**不**先分配一个填满 pad 的缓冲再整片写回: |
| 387 | 整片写回读起来像一次拷贝,但在分片的派发下写进了错的那一片(A5 单卡 cp=2 实测里 rank 0 有 970/1024 | 403 | 整片写回读起来像一次拷贝,但在分片的派发下写进了错的那一片(A5 单卡 cp=2 实测里 rank 0 有 970/1024 |
| 388 | 行拿到了 rank 1 的 token,step 1 的 `loss` 从 11.94468 变到 11.94288,而两个 degree 各自仍是可复现的)。 | 404 | 行拿到了 rank 1 的 token,step 1 的 `loss` 从 11.94468 变到 11.94288,而两个 degree 各自仍是可复现的)。 |
| 389 | `deepseek_v4_1_stripped` 现在挂 Engram(`_stripped` 结尾走 `_attach_engram`,只挂一层 | 405 | `deepseek_v4_1_stripped` 现在挂 Engram(`_stripped` 结尾走 `_attach_engram`,只挂一层 |
| @@ -403,15 +419,15 @@ Engram 不在这一列。它的 token history 要的是每行**在本文档内** | |||
| 403 | | `torchtitan_npu/models/deepseek_v4/attention.py` | 查询与 key 都在 doc-chunk 行上投影;swa 键在核心前用 `key_stream` 恢复、压缩器内部恢复+carry、selector + 内层核心直调(无 wrapper)、输出不 unpermute;参考内核读 `q` / `cmp_k` frame 与预计算的 HCA 选择 | | 419 | | `torchtitan_npu/models/deepseek_v4/attention.py` | 查询与 key 都在 doc-chunk 行上投影;swa 键在核心前用 `key_stream` 恢复、压缩器内部恢复+carry、selector + 内层核心直调(无 wrapper)、输出不 unpermute;参考内核读 `q` / `cmp_k` frame 与预计算的 HCA 选择 | |
| 404 | | `torchtitan_npu/models/common/carry_exchange.py` | `CarryExchange` / `CarryStream`:ratio-4 carry 的 ring(只换 tokens;位置由 `slab_positions` 算出)、增强 `cu_seqlens` 与 `trim`;cp=1 为 no-op | | 420 | | `torchtitan_npu/models/common/carry_exchange.py` | `CarryExchange` / `CarryStream`:ratio-4 carry 的 ring(只换 tokens;位置由 `slab_positions` 算出)、增强 `cu_seqlens` 与 `trim`;cp=1 为 no-op | |
| 405 | | `torchtitan_npu/models/deepseek_v4/compressor.py` | 压缩器(CP/非 CP 同一实例):`forward` 用 `attention_metadata.key_stream` 恢复窗口、ratio-4 时内部 carry 并裁掉自己那块;`Indexer` 复用它,`idx_q` 在 chunk 行、`idx_k` 是行内的池化块 | | 421 | | `torchtitan_npu/models/deepseek_v4/compressor.py` | 压缩器(CP/非 CP 同一实例):`forward` 用 `attention_metadata.key_stream` 恢复窗口、ratio-4 时内部 carry 并裁掉自己那块;`Indexer` 复用它,`idx_q` 在 chunk 行、`idx_k` 是行内的池化块 | |
| 406 | -| `torchtitan_npu/models/deepseek_v4/sharding.py` | `swa_k` / `cmp_k` / `idx_k` 的 `cp: S(1) -> R` 声明 | | 422 | +| `torchtitan_npu/models/deepseek_v4/sharding.py` | `swa_k` / `cmp_k` / `idx_k` 的 `cp: S(0) -> R` 声明 | |
| 407 | | `torchtitan_npu/override/deepseek_v4/metadata.py` | `AicpuMetadata` / `AscV4Metadata`(`aicpu_metadata` + `a3_workaround`)/ `prepare_cp_metadata`(`doc_chunk_entry` + `build_aicpu_metadata`) | | 423 | | `torchtitan_npu/override/deepseek_v4/metadata.py` | `AicpuMetadata` / `AscV4Metadata`(`aicpu_metadata` + `a3_workaround`)/ `prepare_cp_metadata`(`doc_chunk_entry` + `build_aicpu_metadata`) | |
| 408 | | `torchtitan_npu/override/deepseek_v4/sparse_attn/ascendc.py` | `build_aicpu_metadata`(按 entry 的 frame 重建记录,arch22 上建 key 压缩)、SMLA/SMLAG 的 frame 参数 | | 424 | | `torchtitan_npu/override/deepseek_v4/sparse_attn/ascendc.py` | `build_aicpu_metadata`(按 entry 的 frame 重建记录,arch22 上建 key 压缩)、SMLA/SMLAG 的 frame 参数 | |
| 409 | | `torchtitan_npu/override/deepseek_v4/lightning_indexer/ascendc.py` | LI 前向 / SLIKG 反向(选择器自己的 frame、arch22 的压缩池、teacher 边,分母为 `swa_k.cu_seqlens[-1]`) | | 425 | | `torchtitan_npu/override/deepseek_v4/lightning_indexer/ascendc.py` | LI 前向 / SLIKG 反向(选择器自己的 frame、arch22 的压缩池、teacher 边,分母为 `swa_k.cu_seqlens[-1]`) | |
| 410 | | `torchtitan_npu/override/deepseek_v4/lightning_indexer/pypto.py` | PyPTO 版 selector:独立实现同一契约(输入准备、排序、teacher 边),只替换 LI/SLIKG kernel 对 | | 426 | | `torchtitan_npu/override/deepseek_v4/lightning_indexer/pypto.py` | PyPTO 版 selector:独立实现同一契约(输入准备、排序、teacher 边),只替换 LI/SLIKG kernel 对 | |
| 411 | | `torchtitan_npu/override/deepseek_v4/compressor/ascendc.py` | CANN 融合压缩器(无 carry、无 CP 分支;`_state_inputs` 按 stream 形状内部构造零 tiling 表) | | 427 | | `torchtitan_npu/override/deepseek_v4/compressor/ascendc.py` | CANN 融合压缩器(无 carry、无 CP 分支;`_state_inputs` 按 stream 形状内部构造零 tiling 表) | |
| 412 | -| `torchtitan_npu/models/deepseek_v4_1/attention.py` | V4.1 查询交换、本地 KV/压缩、输出 `unpermute` | | 428 | +| `torchtitan_npu/models/deepseek_v4_1/attention.py` | V4.1 查询保持 doc-chunk 布局,key 消费方按需恢复 slab | |
| 413 | | `torchtitan_npu/models/deepseek_v4_1/compressor.py` | V4.1 本地池化压缩器(CP-agnostic,无 carry) | | 429 | | `torchtitan_npu/models/deepseek_v4_1/compressor.py` | V4.1 本地池化压缩器(CP-agnostic,无 carry) | |
| 414 | -| `torchtitan_npu/models/deepseek_v4_1/sharding.py` | V4.1 sparse core / selector 的 `S(1) -> R` 声明 | | 430 | +| `torchtitan_npu/models/deepseek_v4_1/sharding.py` | V4.1 sparse core / selector 的 `S(0) -> R` 声明 | |
| 415 | | `torchtitan_npu/models/deepseek_v4_1/model.py` | `DeepSeekV41Metadata` 与 `build_v41_frames`(整行边界与三帧);`prepare_cp_metadata` 拒绝 CP;`preprocess_inputs` 按行构造 Engram 的 token history;teacher 成对启用检查 | | 431 | | `torchtitan_npu/models/deepseek_v4_1/model.py` | `DeepSeekV41Metadata` 与 `build_v41_frames`(整行边界与三帧);`prepare_cp_metadata` 拒绝 CP;`preprocess_inputs` 按行构造 Engram 的 token history;teacher 成对启用检查 | |
| 416 | | `torchtitan_npu/override/deepseek_v4_1/sparse_attn/ascendc.py` | `AscV41Metadata` / `shard_asc_v41_metadata` / `build_fused_metadata` | | 432 | | `torchtitan_npu/override/deepseek_v4_1/sparse_attn/ascendc.py` | `AscV41Metadata` / `shard_asc_v41_metadata` / `build_fused_metadata` | |
| 417 | | `torchtitan_npu/override/deepseek_v4_1/lightning_indexer/ascendc.py` | V4.1 BF16 selector(整行 index keys × 本 rank chunk) | | 433 | | `torchtitan_npu/override/deepseek_v4_1/lightning_indexer/ascendc.py` | V4.1 BF16 selector(整行 index keys × 本 rank chunk) | |
| @@ -419,6 +435,9 @@ Engram 不在这一列。它的 token history 要的是每行**在本文档内** | |||
| 419 | 435 | ||
| 420 | ## 7. 验证 | 436 | ## 7. 验证 |
| 421 | 437 | ||
| 438 | +以下跨 CP degree 的数值记录来自原有实现的历史验证,不能直接作为当前 folded-token | ||
| 439 | +迁移版本的数值结论。迁移版本需要重新按相同 checkpoint、输入和确定性条件验证。 | ||
| 440 | + | ||
| 422 | ### 7.1 层次与判据 | 441 | ### 7.1 层次与判据 |
| 423 | 442 | ||
| 424 | CP 的验收分三层,越往下越严格: | 443 | CP 的验收分三层,越往下越严格: |
| @@ -459,7 +478,7 @@ CP 的验收分三层,越往下越严格: | |||
| 459 | 不是单 rank 那次抽样的并集(`Replicate` 是)。做法是由一侧导出完整张量、按 shard 规则切分后写回。 | 478 | 不是单 rank 那次抽样的并集(`Replicate` 是)。做法是由一侧导出完整张量、按 shard 规则切分后写回。 |
| 460 | - **`NGPU` 必须等于 `CP`**:CP=1 的对照必须 `NGPU=1`,否则 `cp=1` 会落到 `dp_shard=2`,两侧看的 | 479 | - **`NGPU` 必须等于 `CP`**:CP=1 的对照必须 `NGPU=1`,否则 `cp=1` 会落到 `dp_shard=2`,两侧看的 |
| 461 | 不是同一条样本、也不是同一份权重。 | 480 | 不是同一条样本、也不是同一份权重。 |
| 462 | -- **`--dataloader.per_doc_alignment` 两侧相同**:示例脚本按 `lcm × CP` 写,跨 degree 对比时要显式 | 481 | +- **文档对齐值两侧相同**:按 `lcm × CP` 配置,跨 degree 对比时要显式 |
| 463 | 写同一个值(否则文档边界不同,比的是两份数据)。 | 482 | 写同一个值(否则文档边界不同,比的是两份数据)。 |
| 464 | - **A5 上需要 `torch_npu.npu.set_deterministic_level(3)`,两侧同时打开**:不加时同一 degree 重复跑 | 483 | - **A5 上需要 `torch_npu.npu.set_deterministic_level(3)`,两侧同时打开**:不加时同一 degree 重复跑 |
| 465 | 是逐位可复现的,但不同 degree 会落到不同的 kernel 实现上(形状相关的实现选择),logits 差异可达 | 484 | 是逐位可复现的,但不同 degree 会落到不同的 kernel 实现上(形状相关的实现选择),logits 差异可达 |
| @@ -484,8 +503,7 @@ CP 的验收分三层,越往下越严格: | |||
| 484 | 503 | ||
| 485 | 挂 Engram 的 `deepseek_v4_1_debugmodel_text` 过不了融合内核(`SparseFlashMla` 要求 q head dim 为 | 504 | 挂 Engram 的 `deepseek_v4_1_debugmodel_text` 过不了融合内核(`SparseFlashMla` 要求 q head dim 为 |
| 486 | 512、RoPE 表 512),所以这一路用 `deepseek_v4_1_stripped`:released 几何 + debug 的 Engram 表(只挂 | 505 | 512、RoPE 表 512),所以这一路用 `deepseek_v4_1_stripped`:released 几何 + debug 的 Engram 表(只挂 |
| 487 | -一层,`layer_ids=(1,)`)。它同时是两个 degree 的精度基线,`examples/deepseek_v4_1/debug/ | 506 | +一层,`layer_ids=(1,)`)。它同时是两个 degree 的精度基线,可按第 2 节使用 `NGPU=2`、`CP=2` 和融合算子。 |
| 488 | -deepseek_v4_1_stripped_2p_cp2_a5.sh` 就是这条配方(NGPU=2、CP=2、融合算子、完全重计算)。 | ||
| 489 | 507 | ||
| 490 | 拼好之后的判据与其它用例相同,两条都实测过(A5 单卡,level 3,同一份镜像权重): | 508 | 拼好之后的判据与其它用例相同,两条都实测过(A5 单卡,level 3,同一份镜像权重): |
| 491 | 509 | ||
| @@ -94,13 +94,31 @@ cu_seqlens = [0, 3, 5] # 一行里打包了 2 条序列 | |||
| 94 | 94 | ||
| 95 | 文档在进入行拼接前按 `lcm(compress_ratios)`(V4 为 `128`)对齐:dataloader 在 EOS 之后补 pad token | 95 | 文档在进入行拼接前按 `lcm(compress_ratios)`(V4 为 `128`)对齐:dataloader 在 EOS 之后补 pad token |
| 96 | (label 为 `-100`,位置继续累加),因此每篇文档都是所有压缩比的整数倍,尾部余数恒为 0,压缩块不会跨文档。 | 96 | (label 为 `-100`,位置继续累加),因此每篇文档都是所有压缩比的整数倍,尾部余数恒为 0,压缩块不会跨文档。 |
| 97 | -对齐由 `dataloader.per_doc_alignment` 驱动:非 CP 时 registry 从 `compress_ratios` 推出 `lcm`(V4 为 `128`);CP 时该值提升为 `lcm × cp_size`(V4 为 `128 × cp`,由 recipe/example 传入 `--dataloader.per_doc_alignment`),与压缩器、内核看到的块网格同源。布局构建器把这条契约当作前提:`build_v4_metadata` 对非空且按 | 97 | +对齐由 processor 的 `per_doc_alignment` 驱动:非 CP 时 registry 从 `compress_ratios` 推出 `lcm`(V4 为 `128`);CP 时该值提升为 `lcm × cp_size`(V4 为 `128 × cp`,由 recipe/example 通过 `DSV4_PER_DOC_ALIGNMENT` 指定),与压缩器、内核看到的块网格同源。布局构建器把这条契约当作前提:`build_v4_metadata` 对非空且按 |
| 98 | `lcm(compress_ratios)` 对齐的流,直接把这一行按 ratio 除出压缩网格(`cmp_k.cu_seqlens`),没有逐文档扫描、 | 98 | `lcm(compress_ratios)` 对齐的流,直接把这一行按 ratio 除出压缩网格(`cmp_k.cu_seqlens`),没有逐文档扫描、 |
| 99 | 也没有「尾部不足一块」的分支;破约的流(含空文档或长度不是对齐倍数)在构建处直接报错。压缩器本身同样是扁平的 | 99 | 也没有「尾部不足一块」的分支;破约的流(含空文档或长度不是对齐倍数)在构建处直接报错。压缩器本身同样是扁平的 |
| 100 | `unflatten(1, (-1, ratio))` 折叠,只有在 ratio-4 重叠时才用 `cu_seqlens` 的段起点做掩码。CP 时文档按 `128 × cp` 对齐(每个 entry 再检查 `cp × max(ratio, 1)`):查询按文档内部分 cp 片,切分后每段仍要是压缩块的整数倍。`doc_chunk_entry` 对未按该值对齐的流直接报错。CP=128 面向长文本(1M 序列),把短文档拼成长文本再切分不是目标场景,填充开销在该场景下可接受。 | 100 | `unflatten(1, (-1, ratio))` 折叠,只有在 ratio-4 重叠时才用 `cu_seqlens` 的段起点做掩码。CP 时文档按 `128 × cp` 对齐(每个 entry 再检查 `cp × max(ratio, 1)`):查询按文档内部分 cp 片,切分后每段仍要是压缩块的整数倍。`doc_chunk_entry` 对未按该值对齐的流直接报错。CP=128 面向长文本(1M 序列),把短文档拼成长文本再切分不是目标场景,填充开销在该场景下可接受。 |
| 101 | 101 | ||
| 102 | -同一对齐值也约束后续两条路径:`seq_len` 必须是 `per_doc_alignment` 的倍数(loader 在构建时校验), | 102 | +`max_context_length` 和每批 token 数必须是对齐值的倍数,processor 在构建时校验。 |
| 103 | -SFT 的 chat 数据集按同一个值补 pad(`chat_dataloader.sft` 把对齐值透传到 `DeepSeekV4ChatDataLoader`)。 | 103 | +CPT 与 SFT 直接使用上游 `GrainDataLoader`,无需 loader override。 |
| 104 | +`SingleDatasetConfig` 连接 Hugging Face 数据源、processor 与过滤:CPT 使用 `AlignedTextProcessor`, | ||
| 105 | +SFT 使用 `DeepSeekV4ChatProcessor`,两个 processor 共用 `align_text_sequence` 补齐文档。 | ||
| 106 | +聊天处理器保留官方 chat encoder 的 tool、developer、reminder 和 assistant-only 标签语义, | ||
| 107 | +先做 next-token shift,再补无监督 pad。过长或无监督 token 的对话被过滤。 | ||
| 108 | +CPT 使用 `ConcatThenSplitPackingConfig`,SFT 使用 `FirstFitPackingConfig`。 | ||
| 109 | + | ||
| 110 | +SFT 入口选择 `deepseek_v4_flash_sft` recipe;JSON/JSONL 路径通过 `DSV4_SFT_DATASET` 传入。 | ||
| 111 | +现有 launcher 将 `DATASET_PATH` 转为该变量: | ||
| 112 | + | ||
| 113 | +```bash | ||
| 114 | +DATASET_PATH=/path/to/train.jsonl \ | ||
| 115 | +bash examples/deepseek_v4/deepseek_v4_flash_sft_4k_a3.sh | ||
| 116 | +``` | ||
| 117 | + | ||
| 118 | +自定义 recipe 可按 registry 中的嵌套配置组合随机访问或流式 Hugging Face source、chat encoder 和 | ||
| 119 | +`num_packing_bins`(默认 `1`),并配置上游 loader 的 seed、shuffle/repeat、read options 和 prefetch。 | ||
| 120 | +数据采用 Grain 的排序、分片和打包状态,不能直接恢复旧 | ||
| 121 | +TorchData loader 的 checkpoint;迁移后需使用新的训练 checkpoint 目录,模型权重可单独初始化。 | ||
| 104 | 122 | ||
| 105 | 补出的 pad 只影响它自己的位置:压缩槽位只在所属块的**最后一个** token 上可见,而被 pad 补完的尾块最后一个位置必然是 pad, | 123 | 补出的 pad 只影响它自己的位置:压缩槽位只在所属块的**最后一个** token 上可见,而被 pad 补完的尾块最后一个位置必然是 pad, |
| 106 | 因此真实 token 因果上看不到任何含 pad 的压缩键(ratio-4 的选择器同样只会从因果可达的整块里挑),pad 的 label 又是 | 124 | 因此真实 token 因果上看不到任何含 pad 的压缩键(ratio-4 的选择器同样只会从因果可达的整块里挑),pad 的 label 又是 |
| @@ -152,6 +170,19 @@ CP 的 `cmp_k.residual = reach % ratio`;文档按 `cp × ratio` 对齐后 `rea | |||
| 152 | | `layout_q` / `layout_kv` | 固定为 `TND` | | 170 | | `layout_q` / `layout_kv` | 固定为 `TND` | |
| 153 | | 四个 `*_metadata` 张量 | metadata 的 `asc`(融合 backend 的 config 在 metadata 边界预计算;CP 下按 rank-local frame 重建) | | 171 | | 四个 `*_metadata` 张量 | metadata 的 `asc`(融合 backend 的 config 在 metadata 边界预计算;CP 下按 rank-local frame 重建) | |
| 154 | 172 | ||
| 173 | +## Grain SFT 集成验证 | ||
| 174 | + | ||
| 175 | +`tests/integration_tests/deepseek_v4.py` 注册了 `dsv4_grain_sft`:单 NPU、debugmodel、参考算子、eager,检查两步训练完成。提供包含官方 `encoding_dsv4.py` 的 tokenizer 目录和至少一条编码后不超过 512 token、含 assistant 监督标签的 JSON/JSONL 样本: | ||
| 176 | + | ||
| 177 | +```bash | ||
| 178 | +DSV4_SFT_ASSETS=/path/to/DeepSeekV4_tokenizer \ | ||
| 179 | +DSV4_SFT_DATASET=/path/to/short_chat.jsonl \ | ||
| 180 | +python -m tests.integration_tests.run_tests /tmp/dsv4-grain-sft-results \ | ||
| 181 | + --test_suite deepseek_v4 --test_name dsv4_grain_sft --ngpu 1 --no-parallel | ||
| 182 | +``` | ||
| 183 | + | ||
| 184 | +输出目录必须为空。未提供两个环境变量时该 case 被禁用;不能把跳过视为验证通过。外部语料没有固定 golden loss,此 case 只检查完成性,不证明旧 loader 的数值等价或吞吐提升。CPU 单测使用固定编码结果验证 labels、padding、positions 和 Grain 状态恢复,不替代官方编码器与真实 NPU 训练验证。 | ||
| 185 | + | ||
| 155 | ## 当前边界 | 186 | ## 当前边界 |
| 156 | 187 | ||
| 157 | | 项目 | 当前状态 | | 188 | | 项目 | 当前状态 | |
| @@ -21,8 +21,7 @@ MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" | |||
| 21 | CONFIG="${CONFIG:-deepseek_v4_flash_43layers_16experts}" | 21 | CONFIG="${CONFIG:-deepseek_v4_flash_43layers_16experts}" |
| 22 | 22 | ||
| 23 | # Dataloader & Checkpoint | 23 | # Dataloader & Checkpoint |
| 24 | -DATASET="${DATASET:-c4_test}" | 24 | +# Dataset selection and source paths belong to the selected MODULE/CONFIG recipe. |
| 25 | -DATASET_PATH="${DATASET_PATH:-tests/assets/c4_test}" # your data path | ||
| 26 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path | 25 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path |
| 27 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path | 26 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path |
| 28 | 27 | ||
| @@ -37,8 +36,8 @@ SPMD_BACKEND="spmd_types" | |||
| 37 | 36 | ||
| 38 | # Training | 37 | # Training |
| 39 | SEQ_LEN=4096 | 38 | SEQ_LEN=4096 |
| 40 | -MBS=1 | 39 | +NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096 |
| 41 | -GBS=64 | 40 | +NUM_TOKENS_PER_TRAIN_STEP=262144 |
| 42 | STEPS=100 | 41 | STEPS=100 |
| 43 | 42 | ||
| 44 | # Debug | 43 | # Debug |
| @@ -53,13 +52,6 @@ HF_ASSETS_ARGS=" | |||
| 53 | --hf-assets-path ${HF_ASSETS_PATH} | 52 | --hf-assets-path ${HF_ASSETS_PATH} |
| 54 | " | 53 | " |
| 55 | 54 | ||
| 56 | -# Dataloader | ||
| 57 | -DATALOADER_ARGS=" | ||
| 58 | - --dataloader.dataset ${DATASET} | ||
| 59 | - --dataloader.per_doc_alignment $((128 * CP)) | ||
| 60 | - --dataloader.dataset-path ${DATASET_PATH} | ||
| 61 | -" | ||
| 62 | - | ||
| 63 | # Parallelism | 55 | # Parallelism |
| 64 | PARALLELISM_ARGS=" | 56 | PARALLELISM_ARGS=" |
| 65 | --parallelism.spmd-backend ${SPMD_BACKEND} | 57 | --parallelism.spmd-backend ${SPMD_BACKEND} |
| @@ -81,9 +73,9 @@ COMPILE_ARGS=" | |||
| 81 | 73 | ||
| 82 | # Training | 74 | # Training |
| 83 | TRAINING_ARGS=" | 75 | TRAINING_ARGS=" |
| 84 | - --training.local-batch-size ${MBS} | 76 | + --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK} |
| 85 | - --training.global-batch-size ${GBS} | 77 | + --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP} |
| 86 | - --training.seq-len ${SEQ_LEN} | 78 | + --training.max-context-length ${SEQ_LEN} |
| 87 | --training.steps ${STEPS} | 79 | --training.steps ${STEPS} |
| 88 | --training.disable-cuda-graphs | 80 | --training.disable-cuda-graphs |
| 89 | " | 81 | " |
| @@ -154,6 +146,7 @@ fi | |||
| 154 | # Wrapper defaults extend override.imports after the base targets. | 146 | # Wrapper defaults extend override.imports after the base targets. |
| 155 | CLI_OVERRIDES="${CLI_OVERRIDES:-${DEFAULT_CLI_OVERRIDES}}" | 147 | CLI_OVERRIDES="${CLI_OVERRIDES:-${DEFAULT_CLI_OVERRIDES}}" |
| 156 | 148 | ||
| 149 | +DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-$((128 * CP))}" \ | ||
| 157 | MODULE="${MODULE}" \ | 150 | MODULE="${MODULE}" \ |
| 158 | CONFIG="${CONFIG}" \ | 151 | CONFIG="${CONFIG}" \ |
| 159 | NGPU="${NGPU}" \ | 152 | NGPU="${NGPU}" \ |
| @@ -161,7 +154,6 @@ LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | |||
| 161 | bash scripts/run_train.sh \ | 154 | bash scripts/run_train.sh \ |
| 162 | $COMPILE_ARGS \ | 155 | $COMPILE_ARGS \ |
| 163 | $HF_ASSETS_ARGS \ | 156 | $HF_ASSETS_ARGS \ |
| 164 | - $DATALOADER_ARGS \ | ||
| 165 | $PARALLELISM_ARGS \ | 157 | $PARALLELISM_ARGS \ |
| 166 | $TRAINING_ARGS \ | 158 | $TRAINING_ARGS \ |
| 167 | $DEBUG_ARGS \ | 159 | $DEBUG_ARGS \ |
| @@ -57,7 +57,7 @@ export OPTIMIZER_OVERRIDES="" | |||
| 57 | # Tyro treats activation-checkpoint:selective as a subcommand, so it must be | 57 | # Tyro treats activation-checkpoint:selective as a subcommand, so it must be |
| 58 | # the final token after all regular options and override targets. | 58 | # the final token after all regular options and override targets. |
| 59 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \ | 59 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \ |
| 60 | - --training.local-batch-size 2 \ | 60 | + --training.num-tokens-per-microbatch-per-dp-rank 8192 \ |
| 61 | "${QUANTIZATION_ARGS[@]}" \ | 61 | "${QUANTIZATION_ARGS[@]}" \ |
| 62 | --debug.moe-force-load-balance \ | 62 | --debug.moe-force-load-balance \ |
| 63 | "$@" \ | 63 | "$@" \ |
| @@ -18,7 +18,6 @@ bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5.sh \ | |||
| 18 | --parallelism.data-parallel-shard-degree "${NGPU}" \ | 18 | --parallelism.data-parallel-shard-degree "${NGPU}" \ |
| 19 | --parallelism.data-parallel-replicate-degree 1 \ | 19 | --parallelism.data-parallel-replicate-degree 1 \ |
| 20 | --parallelism.expert-parallel-degree "${NGPU}" \ | 20 | --parallelism.expert-parallel-degree "${NGPU}" \ |
| 21 | - --training.local-batch-size 2 \ | ||
| 22 | --compile.mode aot_fx_trace \ | 21 | --compile.mode aot_fx_trace \ |
| 23 | --compile.enable-passes \ | 22 | --compile.enable-passes \ |
| 24 | --compile.backend aot_eager \ | 23 | --compile.backend aot_eager \ |
| @@ -16,9 +16,6 @@ export TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER=1 | |||
| 16 | export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=0 | 16 | export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=0 |
| 17 | export TORCH_NPU_USE_COMPATIBLE_IMPL=1 | 17 | export TORCH_NPU_USE_COMPATIBLE_IMPL=1 |
| 18 | 18 | ||
| 19 | -SEQ_LEN="${SEQ_LEN:-4096}" | ||
| 20 | -MBS="${MBS:-2}" | ||
| 21 | -GBS="${GBS:-64}" | ||
| 22 | STEPS="${STEPS:-20}" | 19 | STEPS="${STEPS:-20}" |
| 23 | 20 | ||
| 24 | EP_OVERLAP_ARGS=( | 21 | EP_OVERLAP_ARGS=( |
| @@ -33,9 +30,6 @@ exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a5.sh" \ | |||
| 33 | --debug.moe-force-load-balance \ | 30 | --debug.moe-force-load-balance \ |
| 34 | --parallelism.spmd-backend partial_dtensor \ | 31 | --parallelism.spmd-backend partial_dtensor \ |
| 35 | --compile.memory-policy dsv4-mhc-moe-save \ | 32 | --compile.memory-policy dsv4-mhc-moe-save \ |
| 36 | - --training.local-batch-size "${MBS}" \ | ||
| 37 | - --training.global-batch-size "${GBS}" \ | ||
| 38 | - --training.seq-len "${SEQ_LEN}" \ | ||
| 39 | --training.steps "${STEPS}" \ | 33 | --training.steps "${STEPS}" \ |
| 40 | "${EP_OVERLAP_ARGS[@]}" \ | 34 | "${EP_OVERLAP_ARGS[@]}" \ |
| 41 | "$@" | 35 | "$@" |
| @@ -10,13 +10,11 @@ | |||
| 10 | set -euo pipefail | 10 | set -euo pipefail |
| 11 | 11 | ||
| 12 | SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | 12 | SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" |
| 13 | -SFT_OVERRIDE="${SFT_OVERRIDE:-torchtitan_npu.override.deepseek_v4.chat_dataloader.sft}" | ||
| 14 | DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}" | 13 | DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}" |
| 15 | 14 | ||
| 15 | +CONFIG="${CONFIG:-deepseek_v4_flash_43layers_16experts_sft}" \ | ||
| 16 | +DSV4_SFT_DATASET="${DATASET_PATH}" \ | ||
| 16 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \ | 17 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \ |
| 17 | - "${SFT_OVERRIDE}" \ | ||
| 18 | - --dataloader.dataset json \ | ||
| 19 | - --dataloader.dataset-path "${DATASET_PATH}" \ | ||
| 20 | --checkpoint.enable \ | 18 | --checkpoint.enable \ |
| 21 | --checkpoint.no-load-only \ | 19 | --checkpoint.no-load-only \ |
| 22 | "$@" | 20 | "$@" |
| @@ -7,7 +7,7 @@ | |||
| 7 | # Run this script on a single node. | 7 | # Run this script on a single node. |
| 8 | # Append CLI arguments to override the defaults below: | 8 | # Append CLI arguments to override the defaults below: |
| 9 | # ./examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh --training.steps 5 | 9 | # ./examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh --training.steps 5 |
| 10 | -# USE_GOLDEN=1 selects the reference combination (the model's default attention). | 10 | +# USE_GOLDEN=1 selects reference attention, the RoPE workaround and AdamW. |
| 11 | # For deterministic execution, append | 11 | # For deterministic execution, append |
| 12 | # --debug.seed 42 --debug.deterministic to the command line. | 12 | # --debug.seed 42 --debug.deterministic to the command line. |
| 13 | 13 | ||
| @@ -21,8 +21,7 @@ MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" | |||
| 21 | CONFIG="${CONFIG:-deepseek_v4_debugmodel}" | 21 | CONFIG="${CONFIG:-deepseek_v4_debugmodel}" |
| 22 | 22 | ||
| 23 | # Dataloader & Checkpoint | 23 | # Dataloader & Checkpoint |
| 24 | -DATASET="${DATASET:-c4_test}" | 24 | +# Dataset selection and source paths belong to the selected MODULE/CONFIG recipe. |
| 25 | -DATASET_PATH="${DATASET_PATH:-tests/assets/c4_test}" # your data path | ||
| 26 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path | 25 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path |
| 27 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path | 26 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path |
| 28 | 27 | ||
| @@ -37,8 +36,8 @@ SPMD_BACKEND="spmd_types" | |||
| 37 | 36 | ||
| 38 | # Training | 37 | # Training |
| 39 | SEQ_LEN=2048 | 38 | SEQ_LEN=2048 |
| 40 | -MBS=1 | 39 | +NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=2048 |
| 41 | -GBS=-1 | 40 | +NUM_TOKENS_PER_TRAIN_STEP=-1 |
| 42 | STEPS=100 | 41 | STEPS=100 |
| 43 | 42 | ||
| 44 | # Debug | 43 | # Debug |
| @@ -52,13 +51,6 @@ HF_ASSETS_ARGS=" | |||
| 52 | --hf-assets-path ${HF_ASSETS_PATH} | 51 | --hf-assets-path ${HF_ASSETS_PATH} |
| 53 | " | 52 | " |
| 54 | 53 | ||
| 55 | -# Dataloader | ||
| 56 | -DATALOADER_ARGS=" | ||
| 57 | - --dataloader.dataset ${DATASET} | ||
| 58 | - --dataloader.per_doc_alignment $((128 * CP)) | ||
| 59 | - --dataloader.dataset-path ${DATASET_PATH} | ||
| 60 | -" | ||
| 61 | - | ||
| 62 | # Parallelism | 54 | # Parallelism |
| 63 | PARALLELISM_ARGS=" | 55 | PARALLELISM_ARGS=" |
| 64 | --parallelism.spmd-backend ${SPMD_BACKEND} | 56 | --parallelism.spmd-backend ${SPMD_BACKEND} |
| @@ -73,9 +65,9 @@ PARALLELISM_ARGS=" | |||
| 73 | 65 | ||
| 74 | # Training | 66 | # Training |
| 75 | TRAINING_ARGS=" | 67 | TRAINING_ARGS=" |
| 76 | - --training.local-batch-size ${MBS} | 68 | + --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK} |
| 77 | - --training.global-batch-size ${GBS} | 69 | + --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP} |
| 78 | - --training.seq-len ${SEQ_LEN} | 70 | + --training.max-context-length ${SEQ_LEN} |
| 79 | --training.steps ${STEPS} | 71 | --training.steps ${STEPS} |
| 80 | --training.disable-cuda-graphs | 72 | --training.disable-cuda-graphs |
| 81 | " | 73 | " |
| @@ -124,6 +116,8 @@ OPTIMIZER_OVERRIDES=" | |||
| 124 | " | 116 | " |
| 125 | 117 | ||
| 126 | if [[ "${USE_GOLDEN}" == "1" ]]; then | 118 | if [[ "${USE_GOLDEN}" == "1" ]]; then |
| 119 | + OPTIMIZER_ARGS="--optimizer.name AdamW --optimizer.lr 1.0e-5" | ||
| 120 | + OPTIMIZER_OVERRIDES="" | ||
| 127 | NPU_OPS_OVERRIDES=( | 121 | NPU_OPS_OVERRIDES=( |
| 128 | torchtitan_npu.override.common.rope.workaround | 122 | torchtitan_npu.override.common.rope.workaround |
| 129 | ) | 123 | ) |
| @@ -150,7 +144,6 @@ NGPU="${NGPU}" \ | |||
| 150 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | 144 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ |
| 151 | bash scripts/run_train.sh \ | 145 | bash scripts/run_train.sh \ |
| 152 | $HF_ASSETS_ARGS \ | 146 | $HF_ASSETS_ARGS \ |
| 153 | - $DATALOADER_ARGS \ | ||
| 154 | $PARALLELISM_ARGS \ | 147 | $PARALLELISM_ARGS \ |
| 155 | $TRAINING_ARGS \ | 148 | $TRAINING_ARGS \ |
| 156 | $DEBUG_ARGS \ | 149 | $DEBUG_ARGS \ |
| @@ -34,8 +34,6 @@ MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" | |||
| 34 | CONFIG="${CONFIG:-deepseek_v4_pro_61layers_32experts}" | 34 | CONFIG="${CONFIG:-deepseek_v4_pro_61layers_32experts}" |
| 35 | 35 | ||
| 36 | # Dataloader & Checkpoint | 36 | # Dataloader & Checkpoint |
| 37 | -DATASET="${DATASET:-c4_test}" | ||
| 38 | -DATASET_PATH="${DATASET_PATH:-tests/assets/c4_test}" # your data path | ||
| 39 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path | 37 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path |
| 40 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path | 38 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path |
| 41 | CKPT_INIT_LOAD_PATH="${CKPT_INIT_LOAD_PATH:-/path/to/init_load_ckpt}" # your model initial load ckpt path | 39 | CKPT_INIT_LOAD_PATH="${CKPT_INIT_LOAD_PATH:-/path/to/init_load_ckpt}" # your model initial load ckpt path |
| @@ -50,9 +48,9 @@ DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP))) | |||
| 50 | SPMD_BACKEND="spmd_types" | 48 | SPMD_BACKEND="spmd_types" |
| 51 | 49 | ||
| 52 | # Training | 50 | # Training |
| 53 | -SEQ_LEN="${SEQ_LEN:-4096}" | 51 | +SEQ_LEN=4096 |
| 54 | -MBS=1 | 52 | +NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096 |
| 55 | -GBS="${GBS:-256}" | 53 | +NUM_TOKENS_PER_TRAIN_STEP=1048576 |
| 56 | STEPS="${STEPS:-100}" | 54 | STEPS="${STEPS:-100}" |
| 57 | 55 | ||
| 58 | # Debug | 56 | # Debug |
| @@ -74,13 +72,6 @@ HF_ASSETS_ARGS=" | |||
| 74 | --hf-assets-path ${HF_ASSETS_PATH} | 72 | --hf-assets-path ${HF_ASSETS_PATH} |
| 75 | " | 73 | " |
| 76 | 74 | ||
| 77 | -# Dataloader | ||
| 78 | -DATALOADER_ARGS=" | ||
| 79 | - --dataloader.dataset ${DATASET} | ||
| 80 | - --dataloader.per_doc_alignment $((128 * CP)) | ||
| 81 | - --dataloader.dataset-path ${DATASET_PATH} | ||
| 82 | -" | ||
| 83 | - | ||
| 84 | # Parallelism | 75 | # Parallelism |
| 85 | PARALLELISM_ARGS=" | 76 | PARALLELISM_ARGS=" |
| 86 | --parallelism.spmd-backend ${SPMD_BACKEND} | 77 | --parallelism.spmd-backend ${SPMD_BACKEND} |
| @@ -95,9 +86,9 @@ PARALLELISM_ARGS=" | |||
| 95 | 86 | ||
| 96 | # Training | 87 | # Training |
| 97 | TRAINING_ARGS=" | 88 | TRAINING_ARGS=" |
| 98 | - --training.local-batch-size ${MBS} | 89 | + --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK} |
| 99 | - --training.global-batch-size ${GBS} | 90 | + --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP} |
| 100 | - --training.seq-len ${SEQ_LEN} | 91 | + --training.max-context-length ${SEQ_LEN} |
| 101 | --training.steps ${STEPS} | 92 | --training.steps ${STEPS} |
| 102 | --training.disable-cuda-graphs | 93 | --training.disable-cuda-graphs |
| 103 | " | 94 | " |
| @@ -173,6 +164,7 @@ else | |||
| 173 | ) | 164 | ) |
| 174 | fi | 165 | fi |
| 175 | 166 | ||
| 167 | +DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-$((128 * CP))}" \ | ||
| 176 | MODULE="${MODULE}" \ | 168 | MODULE="${MODULE}" \ |
| 177 | CONFIG="${CONFIG}" \ | 169 | CONFIG="${CONFIG}" \ |
| 178 | NODE_IPS="${NODE_IPS}" \ | 170 | NODE_IPS="${NODE_IPS}" \ |
| @@ -180,7 +172,6 @@ NGPU="${NGPU}" \ | |||
| 180 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | 172 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ |
| 181 | bash scripts/run_train_multinodes.sh \ | 173 | bash scripts/run_train_multinodes.sh \ |
| 182 | $HF_ASSETS_ARGS \ | 174 | $HF_ASSETS_ARGS \ |
| 183 | - $DATALOADER_ARGS \ | ||
| 184 | $PARALLELISM_ARGS \ | 175 | $PARALLELISM_ARGS \ |
| 185 | $TRAINING_ARGS \ | 176 | $TRAINING_ARGS \ |
| 186 | $DEBUG_ARGS \ | 177 | $DEBUG_ARGS \ |
| @@ -24,8 +24,6 @@ MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" | |||
| 24 | CONFIG="${CONFIG:-deepseek_v4_pro_61layers_12experts}" | 24 | CONFIG="${CONFIG:-deepseek_v4_pro_61layers_12experts}" |
| 25 | 25 | ||
| 26 | # Dataloader & Checkpoint | 26 | # Dataloader & Checkpoint |
| 27 | -DATASET="${DATASET:-c4_test}" | ||
| 28 | -DATASET_PATH="${DATASET_PATH:-tests/assets/c4_test}" # your data path | ||
| 29 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path | 27 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path |
| 30 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path | 28 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path |
| 31 | CKPT_INIT_LOAD_PATH="${CKPT_INIT_LOAD_PATH:-/path/to/init_load_ckpt}" # your model initial load ckpt path | 29 | CKPT_INIT_LOAD_PATH="${CKPT_INIT_LOAD_PATH:-/path/to/init_load_ckpt}" # your model initial load ckpt path |
| @@ -40,9 +38,9 @@ DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP))) | |||
| 40 | SPMD_BACKEND="spmd_types" | 38 | SPMD_BACKEND="spmd_types" |
| 41 | 39 | ||
| 42 | # Training | 40 | # Training |
| 43 | -SEQ_LEN="${SEQ_LEN:-4096}" | 41 | +SEQ_LEN=4096 |
| 44 | -MBS=1 | 42 | +NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096 |
| 45 | -GBS="${GBS:-64}" | 43 | +NUM_TOKENS_PER_TRAIN_STEP=262144 |
| 46 | STEPS="${STEPS:-100}" | 44 | STEPS="${STEPS:-100}" |
| 47 | 45 | ||
| 48 | # Debug | 46 | # Debug |
| @@ -57,13 +55,6 @@ HF_ASSETS_ARGS=" | |||
| 57 | --hf-assets-path ${HF_ASSETS_PATH} | 55 | --hf-assets-path ${HF_ASSETS_PATH} |
| 58 | " | 56 | " |
| 59 | 57 | ||
| 60 | -# Dataloader | ||
| 61 | -DATALOADER_ARGS=" | ||
| 62 | - --dataloader.dataset ${DATASET} | ||
| 63 | - --dataloader.per_doc_alignment $((128 * CP)) | ||
| 64 | - --dataloader.dataset-path ${DATASET_PATH} | ||
| 65 | -" | ||
| 66 | - | ||
| 67 | # Parallelism | 58 | # Parallelism |
| 68 | PARALLELISM_ARGS=" | 59 | PARALLELISM_ARGS=" |
| 69 | --parallelism.spmd-backend ${SPMD_BACKEND} | 60 | --parallelism.spmd-backend ${SPMD_BACKEND} |
| @@ -78,9 +69,9 @@ PARALLELISM_ARGS=" | |||
| 78 | 69 | ||
| 79 | # Training | 70 | # Training |
| 80 | TRAINING_ARGS=" | 71 | TRAINING_ARGS=" |
| 81 | - --training.local-batch-size ${MBS} | 72 | + --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK} |
| 82 | - --training.global-batch-size ${GBS} | 73 | + --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP} |
| 83 | - --training.seq-len ${SEQ_LEN} | 74 | + --training.max-context-length ${SEQ_LEN} |
| 84 | --training.steps ${STEPS} | 75 | --training.steps ${STEPS} |
| 85 | --training.disable-cuda-graphs | 76 | --training.disable-cuda-graphs |
| 86 | --training.enable-cpu-offload | 77 | --training.enable-cpu-offload |
| @@ -157,13 +148,13 @@ else | |||
| 157 | ) | 148 | ) |
| 158 | fi | 149 | fi |
| 159 | 150 | ||
| 151 | +DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-$((128 * CP))}" \ | ||
| 160 | MODULE="${MODULE}" \ | 152 | MODULE="${MODULE}" \ |
| 161 | CONFIG="${CONFIG}" \ | 153 | CONFIG="${CONFIG}" \ |
| 162 | NGPU="${NGPU}" \ | 154 | NGPU="${NGPU}" \ |
| 163 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | 155 | LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ |
| 164 | bash scripts/run_train.sh \ | 156 | bash scripts/run_train.sh \ |
| 165 | $HF_ASSETS_ARGS \ | 157 | $HF_ASSETS_ARGS \ |
| 166 | - $DATALOADER_ARGS \ | ||
| 167 | $PARALLELISM_ARGS \ | 158 | $PARALLELISM_ARGS \ |
| 168 | $TRAINING_ARGS \ | 159 | $TRAINING_ARGS \ |
| 169 | $DEBUG_ARGS \ | 160 | $DEBUG_ARGS \ |
| @@ -14,17 +14,13 @@ set -euo pipefail | |||
| 14 | 14 | ||
| 15 | SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | 15 | SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" |
| 16 | 16 | ||
| 17 | -# Prefetch/pin 1M GA8 batches so queue drain and async H2D can overlap compute. | 17 | +DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-16384}" \ |
| 18 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \ | 18 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \ |
| 19 | + --training.max-context-length 1048576 \ | ||
| 20 | + --training.num-tokens-per-microbatch-per-dp-rank 1048576 \ | ||
| 21 | + --training.num-tokens-per-train-step 8388608 \ | ||
| 19 | --parallelism.context-parallel-degree 128 \ | 22 | --parallelism.context-parallel-degree 128 \ |
| 20 | - --dataloader.per_doc_alignment 16384 \ | ||
| 21 | --parallelism.context-parallel-load-balancer doc_chunk \ | 23 | --parallelism.context-parallel-load-balancer doc_chunk \ |
| 22 | --parallelism.data-parallel-shard-degree 1 \ | 24 | --parallelism.data-parallel-shard-degree 1 \ |
| 23 | --parallelism.data-parallel-replicate-degree 1 \ | 25 | --parallelism.data-parallel-replicate-degree 1 \ |
| 24 | - --training.seq-len 1048576 \ | ||
| 25 | - --training.local-batch-size 1 \ | ||
| 26 | - --training.global-batch-size 8 \ | ||
| 27 | - --dataloader.num-workers 1 \ | ||
| 28 | - --dataloader.prefetch-factor 8 \ | ||
| 29 | - --dataloader.pin-memory \ | ||
| 30 | "$@" | 26 | "$@" |
| @@ -26,8 +26,6 @@ MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}" | |||
| 26 | CONFIG="${CONFIG:-deepseek_v4_flash}" | 26 | CONFIG="${CONFIG:-deepseek_v4_flash}" |
| 27 | 27 | ||
| 28 | # Dataloader & Checkpoint | 28 | # Dataloader & Checkpoint |
| 29 | -DATASET="${DATASET:-c4_test}" | ||
| 30 | -DATASET_PATH="${DATASET_PATH:-tests/assets/c4_test}" # your data path | ||
| 31 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path | 29 | HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path |
| 32 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path | 30 | CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path |
| 33 | CKPT_INIT_LOAD_PATH="${CKPT_INIT_LOAD_PATH:-/path/to/init_load_ckpt}" # your model initial load ckpt path | 31 | CKPT_INIT_LOAD_PATH="${CKPT_INIT_LOAD_PATH:-/path/to/init_load_ckpt}" # your model initial load ckpt path |
| @@ -43,8 +41,8 @@ SPMD_BACKEND="spmd_types" | |||
| 43 | 41 | ||
| 44 | # Training | 42 | # Training |
| 45 | SEQ_LEN=4096 | 43 | SEQ_LEN=4096 |
| 46 | -MBS=1 | 44 | +NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096 |
| 47 | -GBS=1024 | 45 | +NUM_TOKENS_PER_TRAIN_STEP=4194304 |
| 48 | STEPS=100 | 46 | STEPS=100 |
| 49 | 47 | ||
| 50 | # Debug | 48 | # Debug |
| @@ -59,12 +57,7 @@ HF_ASSETS_ARGS=" | |||
| 59 | --hf-assets-path ${HF_ASSETS_PATH} | 57 | --hf-assets-path ${HF_ASSETS_PATH} |
| 60 | " | 58 | " |
| 61 | 59 | ||
| 62 | -# Dataloader | 60 | +# The Grain dataset is configured by the recipe or an explicit override. |
| 63 | -DATALOADER_ARGS=" | ||
| 64 | - --dataloader.dataset ${DATASET} | ||
| 65 | - --dataloader.per_doc_alignment $((128 * CP)) | ||
| 66 | - --dataloader.dataset-path ${DATASET_PATH} | ||
| 67 | -" | ||
| 68 | 61 | ||
| 69 | # Parallelism | 62 | # Parallelism |
| 70 | PARALLELISM_ARGS=" | 63 | PARALLELISM_ARGS=" |
| @@ -87,9 +80,9 @@ COMPILE_ARGS=" | |||
| 87 | 80 | ||
| 88 | # Training | 81 | # Training |
| 89 | TRAINING_ARGS=" | 82 | TRAINING_ARGS=" |
| 90 | - --training.local-batch-size ${MBS} | 83 | + --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK} |
| 91 | - --training.global-batch-size ${GBS} | 84 | + --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP} |
| 92 | - --training.seq-len ${SEQ_LEN} | 85 | + --training.max-context-length ${SEQ_LEN} |
| 93 | --training.steps ${STEPS} | 86 | --training.steps ${STEPS} |
| 94 | --training.disable-cuda-graphs | 87 | --training.disable-cuda-graphs |
| 95 | " | 88 | " |
| @@ -163,6 +156,7 @@ fi | |||
| 163 | # Wrapper defaults extend override.imports after the base targets. | 156 | # Wrapper defaults extend override.imports after the base targets. |
| 164 | CLI_OVERRIDES="${CLI_OVERRIDES:-${DEFAULT_CLI_OVERRIDES}}" | 157 | CLI_OVERRIDES="${CLI_OVERRIDES:-${DEFAULT_CLI_OVERRIDES}}" |
| 165 | 158 | ||
| 159 | +DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-$((128 * CP))}" \ | ||
| 166 | MODULE="${MODULE}" \ | 160 | MODULE="${MODULE}" \ |
| 167 | CONFIG="${CONFIG}" \ | 161 | CONFIG="${CONFIG}" \ |
| 168 | NODE_IPS="${NODE_IPS}" \ | 162 | NODE_IPS="${NODE_IPS}" \ |
| @@ -171,7 +165,6 @@ LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \ | |||
| 171 | bash scripts/run_train_multinodes.sh \ | 165 | bash scripts/run_train_multinodes.sh \ |
| 172 | $COMPILE_ARGS \ | 166 | $COMPILE_ARGS \ |
| 173 | $HF_ASSETS_ARGS \ | 167 | $HF_ASSETS_ARGS \ |
| 174 | - $DATALOADER_ARGS \ | ||
| 175 | $PARALLELISM_ARGS \ | 168 | $PARALLELISM_ARGS \ |
| 176 | $TRAINING_ARGS \ | 169 | $TRAINING_ARGS \ |
| 177 | $DEBUG_ARGS \ | 170 | $DEBUG_ARGS \ |
| @@ -64,7 +64,7 @@ QUANTIZATION_ARGS=( | |||
| 64 | export OPTIMIZER_OVERRIDES="" | 64 | export OPTIMIZER_OVERRIDES="" |
| 65 | 65 | ||
| 66 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh" \ | 66 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh" \ |
| 67 | - --training.local-batch-size 2 \ | 67 | + --training.num-tokens-per-microbatch-per-dp-rank 8192 \ |
| 68 | "${QUANTIZATION_ARGS[@]}" \ | 68 | "${QUANTIZATION_ARGS[@]}" \ |
| 69 | "$@" \ | 69 | "$@" \ |
| 70 | activation-checkpoint:selective | 70 | activation-checkpoint:selective |
| @@ -16,9 +16,6 @@ export TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER=1 | |||
| 16 | export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=0 | 16 | export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=0 |
| 17 | export TORCH_NPU_USE_COMPATIBLE_IMPL=1 | 17 | export TORCH_NPU_USE_COMPATIBLE_IMPL=1 |
| 18 | 18 | ||
| 19 | -SEQ_LEN="${SEQ_LEN:-4096}" | ||
| 20 | -MBS="${MBS:-2}" | ||
| 21 | -GBS="${GBS:-512}" | ||
| 22 | STEPS="${STEPS:-20}" | 19 | STEPS="${STEPS:-20}" |
| 23 | 20 | ||
| 24 | EP_OVERLAP_ARGS=( | 21 | EP_OVERLAP_ARGS=( |
| @@ -30,10 +27,8 @@ EP_OVERLAP_ARGS=( | |||
| 30 | ) | 27 | ) |
| 31 | 28 | ||
| 32 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \ | 29 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \ |
| 30 | + --training.num-tokens-per-train-step 2097152 \ | ||
| 33 | --parallelism.spmd-backend partial_dtensor \ | 31 | --parallelism.spmd-backend partial_dtensor \ |
| 34 | - --training.local-batch-size "${MBS}" \ | ||
| 35 | - --training.global-batch-size "${GBS}" \ | ||
| 36 | - --training.seq-len "${SEQ_LEN}" \ | ||
| 37 | --training.steps "${STEPS}" \ | 32 | --training.steps "${STEPS}" \ |
| 38 | --debug.moe-force-load-balance \ | 33 | --debug.moe-force-load-balance \ |
| 39 | "${EP_OVERLAP_ARGS[@]}" \ | 34 | "${EP_OVERLAP_ARGS[@]}" \ |
| @@ -11,13 +11,11 @@ set -euo pipefail | |||
| 11 | 11 | ||
| 12 | SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | 12 | SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" |
| 13 | CPT_SCRIPT="${CPT_SCRIPT:-${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh}" | 13 | CPT_SCRIPT="${CPT_SCRIPT:-${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh}" |
| 14 | -SFT_OVERRIDE="${SFT_OVERRIDE:-torchtitan_npu.override.deepseek_v4.chat_dataloader.sft}" | ||
| 15 | DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}" | 14 | DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}" |
| 16 | 15 | ||
| 16 | +CONFIG="${CONFIG:-deepseek_v4_flash_sft}" \ | ||
| 17 | +DSV4_SFT_DATASET="${DATASET_PATH}" \ | ||
| 17 | exec bash "${CPT_SCRIPT}" \ | 18 | exec bash "${CPT_SCRIPT}" \ |
| 18 | - "${SFT_OVERRIDE}" \ | ||
| 19 | - --dataloader.dataset json \ | ||
| 20 | - --dataloader.dataset-path "${DATASET_PATH}" \ | ||
| 21 | --checkpoint.enable \ | 19 | --checkpoint.enable \ |
| 22 | --checkpoint.no-load-only \ | 20 | --checkpoint.no-load-only \ |
| 23 | "$@" | 21 | "$@" |
| @@ -35,6 +35,12 @@ export CKPT_INIT_LOAD_PATH=/path/to/init_hf_ckpt | |||
| 35 | ``` | 35 | ``` |
| 36 | 36 | ||
| 37 | A5 默认每节点使用 8 张 NPU,A3 默认每节点使用 16 张 NPU;需要改变时设置 `NGPU`。 | 37 | A5 默认每节点使用 8 张 NPU,A3 默认每节点使用 16 张 NPU;需要改变时设置 `NGPU`。 |
| 38 | +训练参数在基础脚本中直接设置;派生入口通过 CLI 覆盖不同的默认值。命令末尾的 | ||
| 39 | +`--training.max-context-length`、`--training.num-tokens-per-microbatch-per-dp-rank` 和 | ||
| 40 | +`--training.num-tokens-per-train-step` 可覆盖相应参数。单独修改上下文长度不会重算 microbatch, | ||
| 41 | +单独修改 microbatch 也不会重算每步预算;需要调整时应同时指定相关参数。 | ||
| 42 | +每步预算须能被「每 rank microbatch token 数 × 有效 DP 度 × PP microbatch 数」整除。 | ||
| 43 | +例如 8 卡 Flash debug 的 A3 默认梯度累积 8 次,A5 默认梯度累积 4 次。 | ||
| 38 | 44 | ||
| 39 | ## 裁剪 Debug 模型 | 45 | ## 裁剪 Debug 模型 |
| 40 | 46 | ||
| @@ -42,13 +48,32 @@ Debug/performance 验证优先使用等价裁剪模型,避免为了快速验 | |||
| 42 | 48 | ||
| 43 | ### 1P mini 模型 | 49 | ### 1P mini 模型 |
| 44 | 50 | ||
| 51 | +固定 TorchTitan 基线使用展平的 token 布局:输入与标签为 `[T]`,隐藏状态为 | ||
| 52 | +`[T, D]`。此入口默认每步处理 2048 个 token,最大上下文长度为 2048。 | ||
| 53 | +数据集及源文件由 `MODULE` / `CONFIG` 选择的 recipe 配置,入口不再读取 | ||
| 54 | +`DATASET` / `DATASET_PATH`。自定义数据源通过独立 recipe 指定。 | ||
| 55 | + | ||
| 56 | +`USE_GOLDEN=1` 选择模型默认的参考 attention、实数缓存 RoPE 和 AdamW。 | ||
| 57 | +在当前 Ascend A3 环境中,此组合已完成单卡、确定性 eager 前向、反向及 | ||
| 58 | +optimizer step;参考 indexer 的离散选择不提供 indexer 训练目标。 | ||
| 59 | +默认融合组合使用 Muon。融合算子组合另以 AdamW 完成两步功能验证;当前 | ||
| 60 | +CANN 的 `SparseFlashMlaGrad` 拒绝确定性模式,因此该功能验证未启用 | ||
| 61 | +`--debug.deterministic`,不能作为数值对齐证据。Muon、多卡及编译仍需独立验证。 | ||
| 62 | + | ||
| 45 | ```sh | 63 | ```sh |
| 46 | bash examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh | 64 | bash examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh |
| 47 | 65 | ||
| 48 | -USE_GOLDEN=1 \ | 66 | +USE_GOLDEN=1 HF_ASSETS_PATH="$PWD/tests/assets/deepseek_v3" \ |
| 49 | -bash examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh | 67 | +bash examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh \ |
| 68 | + --training.steps 2 --debug.seed 42 --debug.deterministic | ||
| 50 | ``` | 69 | ``` |
| 51 | 70 | ||
| 71 | +token 预算使用 `--training.num-tokens-per-microbatch-per-dp-rank` 和 | ||
| 72 | +`--training.num-tokens-per-train-step`;两者均统计 token slot。模型上下文 | ||
| 73 | +在 registry 构造时选定,recipe 同步设置 `training.max_context_length`。 | ||
| 74 | +单独覆盖训练上下文不会重新配置 RoPE;修改上下文长度需使用匹配的 recipe。 | ||
| 75 | +其他入口的迁移与验证状态独立于本单卡 mini 记录。 | ||
| 76 | + | ||
| 52 | ### 8P Flash 16-expert Debug | 77 | ### 8P Flash 16-expert Debug |
| 53 | 78 | ||
| 54 | ```sh | 79 | ```sh |
| @@ -86,8 +111,9 @@ bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \ | |||
| 86 | --compile.backend inductor \ | 111 | --compile.backend inductor \ |
| 87 | --parallelism.data-parallel-shard-degree 1 \ | 112 | --parallelism.data-parallel-shard-degree 1 \ |
| 88 | --parallelism.data-parallel-replicate-degree 1 \ | 113 | --parallelism.data-parallel-replicate-degree 1 \ |
| 89 | - --training.seq-len 131072 \ | 114 | + --training.max-context-length 131072 \ |
| 90 | - --training.global-batch-size 8 \ | 115 | + --training.num-tokens-per-microbatch-per-dp-rank 131072 \ |
| 116 | + --training.num-tokens-per-train-step 1048576 \ | ||
| 91 | --debug.moe-force-load-balance \ | 117 | --debug.moe-force-load-balance \ |
| 92 | --training.steps 20 | 118 | --training.steps 20 |
| 93 | ``` | 119 | ``` |
| @@ -156,8 +182,9 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \ | |||
| 156 | --compile.backend inductor \ | 182 | --compile.backend inductor \ |
| 157 | --parallelism.data-parallel-shard-degree 16 \ | 183 | --parallelism.data-parallel-shard-degree 16 \ |
| 158 | --parallelism.data-parallel-replicate-degree 1 \ | 184 | --parallelism.data-parallel-replicate-degree 1 \ |
| 159 | - --training.seq-len 65536 \ | 185 | + --training.max-context-length 65536 \ |
| 160 | - --training.global-batch-size 128 \ | 186 | + --training.num-tokens-per-microbatch-per-dp-rank 131072 \ |
| 187 | + --training.num-tokens-per-train-step 8388608 \ | ||
| 161 | --debug.moe-force-load-balance \ | 188 | --debug.moe-force-load-balance \ |
| 162 | --training.steps 20 | 189 | --training.steps 20 |
| 163 | ``` | 190 | ``` |
| @@ -182,8 +209,9 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_1024k_a5.sh \ | |||
| 182 | CP=128 \ | 209 | CP=128 \ |
| 183 | --parallelism.data-parallel-shard-degree 1 \ | 210 | --parallelism.data-parallel-shard-degree 1 \ |
| 184 | --parallelism.data-parallel-replicate-degree 1 \ | 211 | --parallelism.data-parallel-replicate-degree 1 \ |
| 185 | ---training.seq-len 1048576 \ | 212 | +--training.max-context-length 1048576 \ |
| 186 | ---training.global-batch-size 8 | 213 | +--training.num-tokens-per-microbatch-per-dp-rank 1048576 \ |
| 214 | +--training.num-tokens-per-train-step 8388608 | ||
| 187 | ``` | 215 | ``` |
| 188 | 216 | ||
| 189 | ## A5 量化与 BF16 | 217 | ## A5 量化与 BF16 |
| @@ -38,8 +38,8 @@ SPMD_BACKEND="spmd_types" | |||
| 38 | # Training | 38 | # Training |
| 39 | # Retain the validated eager / Muon / FullAC resource crop. | 39 | # Retain the validated eager / Muon / FullAC resource crop. |
| 40 | SEQ_LEN=4096 | 40 | SEQ_LEN=4096 |
| 41 | -MBS=1 | 41 | +NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096 |
| 42 | -GBS=8 | 42 | +NUM_TOKENS_PER_TRAIN_STEP=32768 |
| 43 | STEPS=40 | 43 | STEPS=40 |
| 44 | 44 | ||
| 45 | # Debug | 45 | # Debug |
| @@ -87,9 +87,9 @@ COMPILE_ARGS=" | |||
| 87 | 87 | ||
| 88 | # Training | 88 | # Training |
| 89 | TRAINING_ARGS=" | 89 | TRAINING_ARGS=" |
| 90 | - --training.local-batch-size ${MBS} | 90 | + --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK} |
| 91 | - --training.global-batch-size ${GBS} | 91 | + --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP} |
| 92 | - --training.seq-len ${SEQ_LEN} | 92 | + --training.max-context-length ${SEQ_LEN} |
| 93 | --training.steps ${STEPS} | 93 | --training.steps ${STEPS} |
| 94 | --training.disable-cuda-graphs | 94 | --training.disable-cuda-graphs |
| 95 | --metrics.log-freq 1 | 95 | --metrics.log-freq 1 |
Rexamples/deepseek_v4_1/debug/deepseek_v4_1_stripped_1p_a5.sh→examples/deepseek_v4_1/debug/deepseek_v4_1_mini_1p_cpt_a5.sh+12-14
| @@ -18,11 +18,10 @@ | |||
| 18 | # the first ratio-1 layer -- so this shape does not invent a combination the model lacks. | 18 | # the first ratio-1 layer -- so this shape does not invent a combination the model lacks. |
| 19 | # | 19 | # |
| 20 | # Run from the repository root: | 20 | # Run from the repository root: |
| 21 | -# NGPU=1 bash examples/deepseek_v4_1/debug/deepseek_v4_1_stripped_1p_a5.sh --training.steps 5 | 21 | +# NGPU=1 bash examples/deepseek_v4_1/debug/deepseek_v4_1_mini_1p_cpt_a5.sh --training.steps 5 |
| 22 | # | 22 | # |
| 23 | -# Append CLI arguments to override the defaults below. `QUANTIZATION_ARGS` swaps the whole | 23 | +# Append CLI arguments to override the defaults below. `QUANTIZATION_ARGS` enables |
| 24 | -# quantized stack in -- QLI/QSLI for the selector and the quantized sparse attention for the | 24 | +# the all_block_fp8 training recipe. |
| 25 | -# teacher provider -- and needs `custom_ops`; without those flags the recipe runs both BF16 ports. | ||
| 26 | 25 | ||
| 27 | set -euo pipefail | 26 | set -euo pipefail |
| 28 | 27 | ||
| @@ -39,13 +38,10 @@ export TORCHTITAN_ENGRAM_TABLE_ROWS="${TORCHTITAN_ENGRAM_TABLE_ROWS:-100000}" | |||
| 39 | # | 38 | # |
| 40 | LIGHTNING_INDEXER_OVERRIDE="torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc" | 39 | LIGHTNING_INDEXER_OVERRIDE="torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc" |
| 41 | 40 | ||
| 42 | -# The quantized selector launches the quantized sparse attention's schedules, so the two switches | 41 | +# Enable block FP8 quantized training. |
| 43 | -# go together: without the sparse-attention quantization the entry carries the unquantized kernel's | ||
| 44 | -# metadata, which is a different schedule. Needs `custom_ops` (kv_compress_epilog_v2). | ||
| 45 | QUANTIZATION_ARGS=( | 42 | QUANTIZATION_ARGS=( |
| 46 | --extension.quantization.enable-quantized-training | 43 | --extension.quantization.enable-quantized-training |
| 47 | - --extension.quantization.li-quantization mxfp4 | 44 | + --extension.quantization.recipe all_block_fp8 |
| 48 | - --extension.quantization.enable-sparse-attention-quantization | ||
| 49 | ) | 45 | ) |
| 50 | 46 | ||
| 51 | CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rms_norm.asc \ | 47 | CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rms_norm.asc \ |
| @@ -54,13 +50,15 @@ CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rms_norm.asc \ | |||
| 54 | ${LIGHTNING_INDEXER_OVERRIDE} \ | 50 | ${LIGHTNING_INDEXER_OVERRIDE} \ |
| 55 | torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc}" | 51 | torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc}" |
| 56 | 52 | ||
| 53 | +SEQ_LEN=2048 | ||
| 54 | +NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=2048 | ||
| 55 | +NUM_TOKENS_PER_TRAIN_STEP=2048 | ||
| 56 | + | ||
| 57 | exec bash scripts/run_train.sh \ | 57 | exec bash scripts/run_train.sh \ |
| 58 | --hf-assets-path "${HF_ASSETS_PATH:-tests/assets/deepseek_v3}" \ | 58 | --hf-assets-path "${HF_ASSETS_PATH:-tests/assets/deepseek_v3}" \ |
| 59 | - --dataloader.dataset "${DATASET:-c4_test}" \ | 59 | + --training.num-tokens-per-microbatch-per-dp-rank "${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK}" \ |
| 60 | - --dataloader.dataset-path "${DATASET_PATH:-tests/assets/c4_test}" \ | 60 | + --training.num-tokens-per-train-step "${NUM_TOKENS_PER_TRAIN_STEP}" \ |
| 61 | - --training.local-batch-size "${MBS:-1}" \ | 61 | + --training.max-context-length "${SEQ_LEN}" \ |
| 62 | - --training.global-batch-size "${GBS:-1}" \ | ||
| 63 | - --training.seq-len "${SEQ_LEN:-2048}" \ | ||
| 64 | --training.steps "${STEPS:-5}" \ | 62 | --training.steps "${STEPS:-5}" \ |
| 65 | --parallelism.data-parallel-shard-degree 1 \ | 63 | --parallelism.data-parallel-shard-degree 1 \ |
| 66 | --parallelism.data-parallel-replicate-degree 1 \ | 64 | --parallelism.data-parallel-replicate-degree 1 \ |
| @@ -45,9 +45,9 @@ SPMD_BACKEND="spmd_types" | |||
| 45 | 45 | ||
| 46 | # Training | 46 | # Training |
| 47 | # Full Flash uses eager execution and the recipe-owned FullAC policy. | 47 | # Full Flash uses eager execution and the recipe-owned FullAC policy. |
| 48 | -SEQ_LEN="${SEQ_LEN:-1048576}" | 48 | +SEQ_LEN=1048576 |
| 49 | -MBS="${MBS:-1}" | 49 | +NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=1048576 |
| 50 | -GBS="${GBS:-1}" | 50 | +NUM_TOKENS_PER_TRAIN_STEP=1048576 |
| 51 | STEPS="${STEPS:-10}" | 51 | STEPS="${STEPS:-10}" |
| 52 | 52 | ||
| 53 | # Debug | 53 | # Debug |
| @@ -96,9 +96,9 @@ COMPILE_ARGS=" | |||
| 96 | 96 | ||
| 97 | # Training | 97 | # Training |
| 98 | TRAINING_ARGS=" | 98 | TRAINING_ARGS=" |
| 99 | - --training.local-batch-size ${MBS} | 99 | + --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK} |
| 100 | - --training.global-batch-size ${GBS} | 100 | + --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP} |
| 101 | - --training.seq-len ${SEQ_LEN} | 101 | + --training.max-context-length ${SEQ_LEN} |
| 102 | --training.steps ${STEPS} | 102 | --training.steps ${STEPS} |
| 103 | --training.disable-cuda-graphs | 103 | --training.disable-cuda-graphs |
| 104 | --metrics.log-freq 1 | 104 | --metrics.log-freq 1 |
| @@ -47,8 +47,8 @@ SPMD_BACKEND="spmd_types" | |||
| 47 | # Training | 47 | # Training |
| 48 | # Full Flash uses eager execution and the recipe-owned FullAC policy. | 48 | # Full Flash uses eager execution and the recipe-owned FullAC policy. |
| 49 | SEQ_LEN=4096 | 49 | SEQ_LEN=4096 |
| 50 | -MBS="${MBS:-1}" | 50 | +NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096 |
| 51 | -GBS="${GBS:-1024}" | 51 | +NUM_TOKENS_PER_TRAIN_STEP=4194304 |
| 52 | STEPS="${STEPS:-100}" | 52 | STEPS="${STEPS:-100}" |
| 53 | 53 | ||
| 54 | # Debug | 54 | # Debug |
| @@ -96,9 +96,9 @@ COMPILE_ARGS=" | |||
| 96 | 96 | ||
| 97 | # Training | 97 | # Training |
| 98 | TRAINING_ARGS=" | 98 | TRAINING_ARGS=" |
| 99 | - --training.local-batch-size ${MBS} | 99 | + --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK} |
| 100 | - --training.global-batch-size ${GBS} | 100 | + --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP} |
| 101 | - --training.seq-len ${SEQ_LEN} | 101 | + --training.max-context-length ${SEQ_LEN} |
| 102 | --training.steps ${STEPS} | 102 | --training.steps ${STEPS} |
| 103 | --training.disable-cuda-graphs | 103 | --training.disable-cuda-graphs |
| 104 | --metrics.log-freq 1 | 104 | --metrics.log-freq 1 |
| @@ -49,7 +49,6 @@ NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx. | |||
| 49 | xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}" | 49 | xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}" |
| 50 | NGPU="${NGPU:-8}" | 50 | NGPU="${NGPU:-8}" |
| 51 | export NODE_IPS NGPU | 51 | export NODE_IPS NGPU |
| 52 | -export MBS="${MBS:-1}" | ||
| 53 | 52 | ||
| 54 | # A5 defaults to block-FP8 quantized training. | 53 | # A5 defaults to block-FP8 quantized training. |
| 55 | QUANTIZATION_ARGS=( | 54 | QUANTIZATION_ARGS=( |
| @@ -1,8 +1,12 @@ | |||
| 1 | ### V4.1 独立训练基线与融合栈 | 1 | ### V4.1 独立训练基线与融合栈 |
| 2 | 2 | ||
| 3 | +本分支正在迁移至上游 `dc3985ad4912f67f71d5a125f2fdf40144ec8354`。当前已验证配置构造、HF map 纯文本输入链路(CP=TP=PP=1、partial_dtensor)和 folded 主干/mHC 的局部前反向;真实 attention、MoE、Engram、分布式训练和图文链路尚待后续验收。下文融合与并行配方记录已有设计,不代表迁移后已全部可运行。 | ||
| 4 | + | ||
| 5 | +训练参数在基础脚本中直接设置;派生入口通过 CLI 覆盖不同的默认值。命令末尾的 `--training.max-context-length`、`--training.num-tokens-per-microbatch-per-dp-rank` 和 `--training.num-tokens-per-train-step` 可覆盖相应参数。单独修改上下文长度不会重算 microbatch,单独修改 microbatch 也不会重算每步预算;需要调整时应同时指定相关参数。预算包括 padding,每步预算须能被「每 rank microbatch token 数 × 有效 DP 度 × PP microbatch 数」整除;CP/EP 不重复计入 DP 度。 | ||
| 6 | + | ||
| 3 | V4.1 的模型、图像路由、压缩 attention、metadata 和并行化均由 `torchtitan_npu/models/deepseek_v4_1` 持有,不依赖 V4 模型或其专属 override。模型默认算子是 Attention Gym 的 eager `gather_attn`(`CompressedSparseInnerAttention2`)与公共 MoE 工厂;模型目录不含 indexer 训练目标,eager 路径也没有:它只在 A5 的两个融合 override 同开时由两者的反向传递,见下文。 | 7 | V4.1 的模型、图像路由、压缩 attention、metadata 和并行化均由 `torchtitan_npu/models/deepseek_v4_1` 持有,不依赖 V4 模型或其专属 override。模型默认算子是 Attention Gym 的 eager `gather_attn`(`CompressedSparseInnerAttention2`)与公共 MoE 工厂;模型目录不含 indexer 训练目标,eager 路径也没有:它只在 A5 的两个融合 override 同开时由两者的反向传递,见下文。 |
| 4 | 8 | ||
| 5 | -当前支持 **FSDP + EP、TP1 / CP1 / PP1、eager 执行与 torch.compile**,保留 FullAC 与图文输入。A3 脚本组织公共实验参数与融合列表,A5 调用 A3 并追加 CPU 亲和性、partial 文本 RoPE、两项 SwiGLUGroup、sparse attention 与 mHC Sinkhorn;两种入口均通过 `USE_GOLDEN=1` 选择 reference。A3 默认融合包含 RMSNorm、文本(`asc_complex`)与视觉 RoPE、MoE token dispatcher 和 mHC post;A5 将文本 RoPE 换为 `asc_partial` 并追加 routed/shared SwiGLUGroup、sparse 与 Sinkhorn。routed experts 的 grouped GEMM 是 reference 与融合共用的公共路径,不再作为独立融合开关。已接入量化入口及 Host Engram;不支持 MTP、DSpark、GraphTrainer;不支持的 TP、CP、PP 和 compile 配置在入口拒绝。 | 9 | +既有配方覆盖 **FSDP + EP、TP1 / CP1 / PP1、eager 执行与 torch.compile**,包含 FullAC 与图文输入;迁移验收范围见开头说明。A3 脚本组织公共实验参数与融合列表,A5 调用 A3 并追加 CPU 亲和性、partial 文本 RoPE、两项 SwiGLUGroup、sparse attention 与 mHC Sinkhorn;两种入口均通过 `USE_GOLDEN=1` 选择 reference。A3 默认融合包含 RMSNorm、文本(`asc_complex`)与视觉 RoPE、MoE token dispatcher 和 mHC post;A5 将文本 RoPE 换为 `asc_partial` 并追加 routed/shared SwiGLUGroup、sparse 与 Sinkhorn。routed experts 的 grouped GEMM 是 reference 与融合共用的公共路径,不再作为独立融合开关。已接入量化入口及 Host Engram;不支持 MTP、DSpark、GraphTrainer;不支持的 TP、CP、PP 和 compile 配置在入口拒绝。 |
| 6 | 10 | ||
| 7 | **torch.compile 已支持**(每个 TransformerBlock 整图编译,跨层状态为显式前向参数),通过脚本 `"$@"` 透传超参开启: | 11 | **torch.compile 已支持**(每个 TransformerBlock 整图编译,跨层状态为显式前向参数),通过脚本 `"$@"` 透传超参开启: |
| 8 | 12 | ||
| @@ -40,9 +44,9 @@ bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \ | |||
| 40 | --training.steps 3 --lr-scheduler.total-steps 3 --lr-scheduler.warmup-steps 2 | 44 | --training.steps 3 --lr-scheduler.total-steps 3 --lr-scheduler.warmup-steps 2 |
| 41 | ``` | 45 | ``` |
| 42 | 46 | ||
| 43 | -单机 8 卡默认使用 40 层模型,A3 为 16 个路由专家,A5 为 24 个路由专家;均使用 seq4096(4k)、local/global batch 1/8、FSDP8/EP8、Muon(NS steps=10)、eager、FullAC,训练与调度均为 40 步。Python 配方保留模型结构、数据协议和优化器参数布局;实验参数由脚本组织,末尾 CLI 参数覆盖脚本默认值。`CONFIG` 可选择 `deepseek_v4_1_debugmodel_multimodal` 调试宽度,硬件选择仍由脚本负责。 | 47 | +单机 8 卡默认使用 40 层模型,A3 为 16 个路由专家,A5 为 24 个路由专家;上下文上限均为 4096,每 rank microbatch 为 4096 tokens,每步全局为 32768 tokens,使用 FSDP8/EP8、Muon(NS steps=10)、eager 和 FullAC,训练与调度均为 40 步。Python 配方保留模型结构、数据协议和优化器参数布局;实验参数由脚本组织,末尾 CLI 参数覆盖脚本默认值。`CONFIG` 可选择 `deepseek_v4_1_debugmodel_multimodal` 调试宽度,硬件选择仍由脚本负责。 |
| 44 | 48 | ||
| 45 | -关闭 Engram 使用 `--no-engram-enabled`;优化器由脚本显式选择,末尾 `--optimizer.name AdamW` 仍可覆盖。A3 单机使用 `--training.seq-len 2048`,脚本保留 4k 默认配置。A5 多机保留与单机一致的 swap override;可通过 `OPTIMIZER_OVERRIDES` 显式覆盖。 | 49 | +关闭 Engram 使用 `--no-engram-enabled`;优化器由脚本显式选择,末尾 `--optimizer.name AdamW` 仍可覆盖。A3 单机可通过末尾 CLI 参数调整上下文、microbatch 和每步 token 预算;默认每步预算为 32768 tokens。A5 多机保留与单机一致的 swap override;可通过 `OPTIMIZER_OVERRIDES` 显式覆盖。 |
| 46 | 50 | ||
| 47 | A5 的 `CPU_AFFINITY_CONF` 应按主机拓扑覆盖。通过 `CLI_OVERRIDES` 扩展融合列表:A3 基础列表之外,文本 RoPE 经该通道按硬件选择(A3 默认 `asc_complex`,A5 换为 `asc_partial`),A5 默认追加 SwiGLUGroup、sparse attention、融合 LI 选分与 Sinkhorn,不重复传入 `--override.imports`。显式传 `--override.imports` 会替换整个集合,需自行包含所需的 RoPE 与 swap optimizer。最终选择随 Trainer Config 打印。 | 51 | A5 的 `CPU_AFFINITY_CONF` 应按主机拓扑覆盖。通过 `CLI_OVERRIDES` 扩展融合列表:A3 基础列表之外,文本 RoPE 经该通道按硬件选择(A3 默认 `asc_complex`,A5 换为 `asc_partial`),A5 默认追加 SwiGLUGroup、sparse attention、融合 LI 选分与 Sinkhorn,不重复传入 `--override.imports`。显式传 `--override.imports` 会替换整个集合,需自行包含所需的 RoPE 与 swap optimizer。最终选择随 Trainer Config 打印。 |
| 48 | 52 | ||
| @@ -65,9 +69,9 @@ DATASET_PATH=/path/to/cc12m_tar_dir \ | |||
| 65 | bash examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_4k_a5.sh | 69 | bash examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_4k_a5.sh |
| 66 | ``` | 70 | ``` |
| 67 | 71 | ||
| 68 | -A5 默认每机 8 卡、EP128/FSDP128、TP1/CP1/PP1、MBS1/GBS1024、100 步、Muon、eager/FullAC、强制负载均衡,默认开启 SMLA/LI 及 block-FP8 训练。A3 对应 `deepseek_v4_1_flash_cpt_4k_a3.sh`,默认每机 16 卡、其余并行度相同,使用 A3 融合列表且不默认量化。 | 72 | +A5 默认每机 8 卡、EP128/FSDP128、TP1/CP1/PP1、每 rank microbatch 4096 tokens、每步全局 4194304 tokens、100 步、Muon、eager/FullAC、强制负载均衡,默认开启 SMLA/LI 及 block-FP8 训练。A3 对应 `deepseek_v4_1_flash_cpt_4k_a3.sh`,默认每机 16 卡、其余并行度相同,使用 A3 融合列表且不默认量化。 |
| 69 | 73 | ||
| 70 | -`NGPU`、`EP`、`DP_SHARD`、`GBS`、`STEPS` 可通过环境变量设置;`NODE_IPS` 必填。总卡数须能被 EP 和 DP_SHARD 整除,EP 须兼容 384 专家;MBS 必须为 1。CLI 参数放在最后,可覆盖训练配置;修改拓扑请优先使用上述环境变量,保证派生的 DP_REPLICATE 一致。Host Engram 需要正确的 tokenizer 压缩映射与足够主机内存。 | 74 | +`NGPU`、`EP`、`DP_SHARD`、`STEPS` 可通过环境变量设置;`NODE_IPS` 必填。总卡数须能被 EP 和 DP_SHARD 整除,EP 须兼容 384 专家。CLI 参数放在最后,可覆盖训练配置;修改拓扑请优先使用上述环境变量,保证派生的 DP_REPLICATE 一致。Host Engram 需要正确的 tokenizer 压缩映射与足够主机内存。 |
| 71 | 75 | ||
| 72 | 初始权重不会因设置 `HF_ASSETS_PATH` 自动加载:需要时设置 `CKPT_INIT_LOAD_PATH` 指向 HF checkpoint;保存 checkpoint 另加 `--checkpoint.no-load-only`。默认不启用参数/梯度 CPU offload,保留 `swap_optimizer` 对 Engram 的适配。`USE_GOLDEN=1` 切换 reference override;A5 若还要关闭量化,追加 `--extension.quantization.no-enable-quantized-training`。 | 76 | 初始权重不会因设置 `HF_ASSETS_PATH` 自动加载:需要时设置 `CKPT_INIT_LOAD_PATH` 指向 HF checkpoint;保存 checkpoint 另加 `--checkpoint.no-load-only`。默认不启用参数/梯度 CPU offload,保留 `swap_optimizer` 对 Engram 的适配。`USE_GOLDEN=1` 切换 reference override;A5 若还要关闭量化,追加 `--extension.quantization.no-enable-quantized-training`。 |
| 73 | 77 | ||
| @@ -83,6 +87,18 @@ Engram HF 表以全局逻辑行保存,不包含本地 padding,支持 EP 分 | |||
| 83 | 87 | ||
| 84 | 当前补齐的是 Engram 表及 gate 的 HF 映射和 MXFP8 读取;V4.1 主线尚不能直接读取官方整包的所有非 Engram 量化权重(例如 Attention),因此开启 quantized 选项不意味着官方整包可以直接开始训练。HF 导出遵循 `export_dtype`,不导出优化器状态,也不生成官方 MXFP8 发布格式。 | 88 | 当前补齐的是 Engram 表及 gate 的 HF 映射和 MXFP8 读取;V4.1 主线尚不能直接读取官方整包的所有非 Engram 量化权重(例如 Attention),因此开启 quantized 选项不意味着官方整包可以直接开始训练。HF 导出遵循 `export_dtype`,不导出优化器状态,也不生成官方 MXFP8 发布格式。 |
| 85 | 89 | ||
| 90 | +### 纯文本 Grain 数据入口 | ||
| 91 | + | ||
| 92 | +纯文本和纯文本 LoRA recipe 使用上游 `GrainDataLoader`、`SingleDatasetConfig` 和 | ||
| 93 | +`ConcatThenSplitPackingConfig`。`AlignedTextProcessor` 在 next-token shift 后按模型压缩比补齐文档, | ||
| 94 | +默认对齐值为 `2`;CP recipe 可通过 `DSV41_PER_DOC_ALIGNMENT` 指定更大的对齐值。 | ||
| 95 | +默认数据源为 `tests/assets/c4_test/data.json`,自定义源在 Python recipe 中配置。 | ||
| 96 | + | ||
| 97 | +纯文本 recipe 使用通用 `scripts/run_train.sh` 启动,不传入图文入口的 | ||
| 98 | +`--dataloader.dataset` / `--dataloader.dataset-path`。排序、DP 分片、长文档位置边界和状态恢复均遵循 | ||
| 99 | +当前固定 TorchTitan 的 Grain 管线;旧 loader 的排序和续行规则不再保留,旧数据加载状态不能直接续用, | ||
| 100 | +模型权重可单独初始化。图像数据入口保持独立。 | ||
| 101 | + | ||
| 86 | ### 真实 CC12M 数据入口(图像条件 caption 预测) | 102 | ### 真实 CC12M 数据入口(图像条件 caption 预测) |
| 87 | 103 | ||
| 88 | 数据入口与 GitHub TorchTitan 的 Qwen/Kimi 多模态训练一致,使用 CC12M WebDataset tar(同名 `.jpg` / `.txt` 样本对)。默认 `dataset=cc12m-test`,读取仓内 `tests/assets/cc12m_test/`,无需传入 dataloader 参数;其他本地 tar 目录通过 `--dataloader.dataset-path <cc12m_tar_dir>` 指定。不提供 manifest、离线准备或 digest 专用脚本。 | 104 | 数据入口与 GitHub TorchTitan 的 Qwen/Kimi 多模态训练一致,使用 CC12M WebDataset tar(同名 `.jpg` / `.txt` 样本对)。默认 `dataset=cc12m-test`,读取仓内 `tests/assets/cc12m_test/`,无需传入 dataloader 参数;其他本地 tar 目录通过 `--dataloader.dataset-path <cc12m_tar_dir>` 指定。不提供 manifest、离线准备或 digest 专用脚本。 |
| @@ -94,7 +110,7 @@ Engram HF 表以全局逻辑行保存,不包含本地 padding,支持 EP 分 | |||
| 94 | 110 | ||
| 95 | `cc12m-train-0000.tar` 原样复用 [GitHub TorchTitan v0.3.0 测试资产](https://github.com/pytorch/torchtitan/blob/v0.3.0/tests/assets/cc12m_test/cc12m-train-0000.tar),包含 32 条图文样本,仅用于测试。完整在线数据源通过 `--dataloader.dataset cc12m` 选择;指定本地目录后,读取的是该目录的数据,而非仓内测试资产。 | 111 | `cc12m-train-0000.tar` 原样复用 [GitHub TorchTitan v0.3.0 测试资产](https://github.com/pytorch/torchtitan/blob/v0.3.0/tests/assets/cc12m_test/cc12m-train-0000.tar),包含 32 条图文样本,仅用于测试。完整在线数据源通过 `--dataloader.dataset cc12m` 选择;指定本地目录后,读取的是该目录的数据,而非仓内测试资产。 |
| 96 | 112 | ||
| 97 | -直接复用上游 `HuggingFaceMultiModalDataset` 的 DP 分片、`MMSamplePacker` 和状态恢复,以及 `ParallelAwareDataloader`。针对 TorchTitan 0.3.0 的 HF 恢复起点跨 epoch 重放问题,按上游文本 loader 的方式补齐 `set_epoch`;packing 缓冲满时调用上游 `flush()`。DSV4.1 只适配协议层:`BOS + 完整图片协议 + caption + EOS`;只有 caption 与 EOS 参与监督,图片特征索引按 pack 中的图片顺序连续编号,每篇文档的位置从零开始。每篇文档按 dataloader 的 `per_doc_alignment`(recipe 由模型压缩比取 LCM 得到,当前为 2)在 EOS 后补至整数个池化组:pad 的 label 为 `-100`,位置继续累加,因此它留在本文档内、既不被监督也不改变下一篇文档的起点。注意 pad 会顶掉奇数长度文档 EOS 的目标(label 在文档内右移,EOS 的下一个位置变成了 pad,而 pad 的 label 是 `-100`),即每篇奇数长度文档少一个监督目标;对齐不覆盖行切分,长于 `seq_len` 的文档仍按行切开,续行另起一套池化组。 | 113 | +图文 CPT loader 使用上游 Grain 的数据源、packing 和恢复机制,保留 `BOS + 完整图片协议 + caption + EOS`、caption/EOS 监督和逐文档压缩对齐。当前 collator 仍返回 `[1,T]`,图文到 folded decoder 的协议迁移尚未完成。文本 loader 使用 `AlignedTextDataLoader`:逐文档 shift labels、补齐压缩组,再交给 Grain concat-then-split;positions 在切行后归零,再按上下文上限切分。HF map 数据先按 DP 分片,首轮保持原顺序,后续 epoch 按 `seed + epoch` 重排;Grain 负责打包缓冲与恢复。有限数据集结束时,丢弃不足一个 token batch 的尾部;文档内部的对齐 padding 保留在输入中,但 labels 为 `IGNORE_INDEX`,不计入有效 token 数。纯文本已验证从 loader 到公共 Decoder 的 metadata map;streaming 的旧新顺序一致性、CP>1 和 `spmd_types` 输入链路尚未验收。旧 loader 状态格式不与 Grain 状态互通,跨版本对照应从同一 model-only checkpoint 和数据起点开始。 |
| 98 | 114 | ||
| 99 | 与上游一致,`--dataloader.packing-buffer-size 0` 默认关闭 packing;设置正值(例如 `128`)启用。一个 rank 的 local batch 仍为 1,但一个 packed 序列可以包含多篇图文样本。装箱和合并仍调用上游实现;缓冲量还包括待输出的 packed 队列及 loader 预取,不是进程内存的硬上限。 | 115 | 与上游一致,`--dataloader.packing-buffer-size 0` 默认关闭 packing;设置正值(例如 `128`)启用。一个 rank 的 local batch 仍为 1,但一个 packed 序列可以包含多篇图文样本。装箱和合并仍调用上游实现;缓冲量还包括待输出的 packed 队列及 loader 预取,不是进程内存的硬上限。 |
| 100 | 116 | ||
| @@ -120,7 +136,7 @@ SFT 复用同目录的 CPT launcher,只替换 dataloader;不另设 checkpoin | |||
| 120 | 136 | ||
| 121 | 图片相对路径默认以数据文件所在目录为根;也可以通过 override 的 `image_root` 指定统一根目录。普通 HTTP(S) URL 不在训练 worker 中下载,需先落盘;data URI 可以直接使用。无图片的纯文本样本沿用同一官方 chat encoding。 | 137 | 图片相对路径默认以数据文件所在目录为根;也可以通过 override 的 `image_root` 指定统一根目录。普通 HTTP(S) URL 不在训练 worker 中下载,需先落盘;data URI 可以直接使用。无图片的纯文本样本沿用同一官方 chat encoding。 |
| 122 | 138 | ||
| 123 | -默认 `chat` 模式对每个 assistant 回复计算监督,system/user/image/padding label 均为 `-100`,assistant 回复及 EOS 参与 loss。超过 `training.seq_len` 的样本被跳过。与 CPT 一样,每个数据并行 rank 处理一条序列(`training.local_batch_size=1`);这不限制节点数,global batch 由有效 DP 度和梯度累积扩展。`dataloader.num_workers` 等 worker 配置与 tensor batch 独立并正常透传,DP shard 和恢复状态沿用公共 V4.1 数据生命周期。 | 139 | +默认 `chat` 模式对每个 assistant 回复计算监督,system/user/image/padding label 均为 `-100`,assistant 回复及 EOS 参与 loss。SFT loader 仍使用旧上游接口,尚未完成本分支的 Grain 和 folded-token 迁移;本节描述原有监督规则,不作为当前可运行入口。迁移后的长度上限使用 `training.max_context_length`,token 预算由 `training.num_tokens_per_microbatch_per_dp_rank` 和 `training.num_tokens_per_train_step` 指定。 |
| 124 | 140 | ||
| 125 | ```sh | 141 | ```sh |
| 126 | DATASET_PATH=/path/to/vqa.jsonl \ | 142 | DATASET_PATH=/path/to/vqa.jsonl \ |
| @@ -199,4 +215,6 @@ CPU 单测覆盖模型与融合配置选择、RoPE 输出/梯度等核心行为 | |||
| 199 | 215 | ||
| 200 | ## LoRA | 216 | ## LoRA |
| 201 | 217 | ||
| 202 | -通过 [LoRA 脚本](deepseek_v4_1_flash_lora_4k_a3.sh) 复用 CPT 入口。默认配置为多模态 `deepseek_v4_1_flash_lora`,设置 `CONFIG=deepseek_v4_1_flash_text_lora` 可选择纯文本模型。AdamW/Muon、Engram 冻结、native DCP 恢复和 PEFT 导出/合并方式见 [V4.1 LoRA 指南](../../docs/feature_guides/deepseek_v4_1_lora.md)。 | 218 | +通过 [LoRA 脚本](deepseek_v4_1_flash_lora_4k_a3.sh) 复用多模态 CPT 入口,默认配置为 `deepseek_v4_1_flash_lora`。 |
| 219 | +纯文本选择 `deepseek_v4_1_flash_text_lora` recipe,并通过通用 `scripts/run_train.sh` 启动。 | ||
| 220 | +AdamW/Muon、Engram 冻结、native DCP 恢复和 PEFT 导出/合并方式见 [V4.1 LoRA 指南](../../docs/feature_guides/deepseek_v4_1_lora.md)。 | ||
| @@ -8,6 +8,12 @@ | |||
| 8 | - `qwen3_5_debugmodel_moe_8p_cpt_512.sh`:Qwen3.5 MoE debugmodel 8 卡入口, | 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 后端)。 | 9 | 默认 `qwen35_debugmodel_moe` 配置,EP=8/DP_SHARD=8(spmd_types 后端)。 |
| 10 | 10 | ||
| 11 | +纯文本 SFT 的 `qwen35_27b_4k_sft` 和 `qwen35_27b_long_text_sft` recipe 使用 | ||
| 12 | +`GrainDataLoader`、Hugging Face JSON/JSONL source、上游 `ChatProcessor` 和 first-fit packing。 | ||
| 13 | +`DATA_FILES` 指定文件,长文本 recipe 支持逗号分隔的多个文件;样本由各自的消息转换函数映射为 | ||
| 14 | +单轮 `[user, assistant]`,原始 `messages` 也须满足上游单轮约束。训练长度与 microbatch 均使用 token 预算字段。 | ||
| 15 | +多模态 debug 入口的数据管线与此独立。 | ||
| 16 | + | ||
| 11 | ## Qwen3.5 multimodal dependencies | 17 | ## Qwen3.5 multimodal dependencies |
| 12 | 18 | ||
| 13 | The Qwen3.5 adapter reuses TorchTitan's upstream image and video preprocessing. | 19 | The Qwen3.5 adapter reuses TorchTitan's upstream image and video preprocessing. |
| @@ -37,7 +37,8 @@ ARGS=( | |||
| 37 | --checkpoint.initial-load-in-hf | 37 | --checkpoint.initial-load-in-hf |
| 38 | --checkpoint.initial-load-model-only | 38 | --checkpoint.initial-load-model-only |
| 39 | --dump-folder "${DUMP_FOLDER:-./outputs/qwen3_6_4k_sft}" | 39 | --dump-folder "${DUMP_FOLDER:-./outputs/qwen3_6_4k_sft}" |
| 40 | - --training.seq-len "${SEQ_LEN}" | 40 | + --training.max-context-length "${SEQ_LEN}" |
| 41 | + --training.num-tokens-per-microbatch-per-dp-rank "${SEQ_LEN}" | ||
| 41 | "$@" | 42 | "$@" |
| 42 | ) | 43 | ) |
| 43 | 44 | ||
| @@ -19,9 +19,9 @@ from torchao_npu.quantized_modules.deepseek_v4 import lightning_indexer | |||
| 19 | @pytest.mark.parametrize("batch", [1, 2]) | 19 | @pytest.mark.parametrize("batch", [1, 2]) |
| 20 | def test_module_swap_routes_teacher_to_indexer_inputs(monkeypatch, batch): | 20 | def test_module_swap_routes_teacher_to_indexer_inputs(monkeypatch, batch): |
| 21 | tokens, heads, dim, topk = 8, 2, 4, 4 | 21 | tokens, heads, dim, topk = 8, 2, 4, 4 |
| 22 | - query = torch.zeros(batch, tokens, heads, dim, dtype=torch.bfloat16, requires_grad=True) | 22 | + query = torch.zeros(batch * tokens, heads, dim, dtype=torch.bfloat16, requires_grad=True) |
| 23 | - key = torch.zeros(batch, 2, dim, dtype=torch.bfloat16, requires_grad=True) | 23 | + key = torch.zeros(batch * 2, dim, dtype=torch.bfloat16, requires_grad=True) |
| 24 | - weights = torch.zeros(batch, tokens, heads, dtype=torch.bfloat16, requires_grad=True) | 24 | + weights = torch.zeros(batch * tokens, heads, dtype=torch.bfloat16, requires_grad=True) |
| 25 | forward_record = torch.tensor([7], dtype=torch.int32) | 25 | forward_record = torch.tensor([7], dtype=torch.int32) |
| 26 | backward_record = torch.tensor([9], dtype=torch.int32) | 26 | backward_record = torch.tensor([9], dtype=torch.int32) |
| 27 | cu_q = torch.arange(batch + 1, dtype=torch.int32) * tokens | 27 | cu_q = torch.arange(batch + 1, dtype=torch.int32) * tokens |
| @@ -36,9 +36,9 @@ def test_module_swap_routes_teacher_to_indexer_inputs(monkeypatch, batch): | |||
| 36 | # The host adapter establishes packed TND operands before the autograd node. | 36 | # The host adapter establishes packed TND operands before the autograd node. |
| 37 | assert md is metadata | 37 | assert md is metadata |
| 38 | return lightning_indexer.QuantizedLightningIndexerInputs( | 38 | return lightning_indexer.QuantizedLightningIndexerInputs( |
| 39 | - query=q.flatten(0, 1), | 39 | + query=q, |
| 40 | - key=k.flatten(0, 1).unsqueeze(1).contiguous(), | 40 | + key=k.unsqueeze(1).contiguous(), |
| 41 | - weights=w.flatten(0, 1).float(), | 41 | + weights=w.float(), |
| 42 | topk=topk, | 42 | topk=topk, |
| 43 | metadata=md.forward, | 43 | metadata=md.forward, |
| 44 | cu_seqlens_q=cu_q, | 44 | cu_seqlens_q=cu_q, |
| @@ -73,11 +73,11 @@ def test_module_swap_routes_teacher_to_indexer_inputs(monkeypatch, batch): | |||
| 73 | indices, scores = selector(query, key, weights, attention_metadata=metadata) | 73 | indices, scores = selector(query, key, weights, attention_metadata=metadata) |
| 74 | 74 | ||
| 75 | assert selector.forward.__func__ is lightning_indexer.quantized_lightning_indexer_forward | 75 | assert selector.forward.__func__ is lightning_indexer.quantized_lightning_indexer_forward |
| 76 | - assert indices.shape == (batch, tokens, topk) and indices.dtype == torch.int32 | 76 | + assert indices.shape == (batch * tokens, topk) and indices.dtype == torch.int32 |
| 77 | assert not indices.requires_grad | 77 | assert not indices.requires_grad |
| 78 | assert scores.shape == indices.shape and scores.dtype == torch.float32 | 78 | assert scores.shape == indices.shape and scores.dtype == torch.float32 |
| 79 | assert scores.grad_fn is not None | 79 | assert scores.grad_fn is not None |
| 80 | - torch.testing.assert_close(indices[0, 0], torch.tensor([1, 0, -1, -1], dtype=torch.int32)) | 80 | + torch.testing.assert_close(indices[0], torch.tensor([1, 0, -1, -1], dtype=torch.int32)) |
| 81 | assert seen["forward"]["metadata"] is forward_record | 81 | assert seen["forward"]["metadata"] is forward_record |
| 82 | assert seen["forward"]["quant_mode"] == 5 | 82 | assert seen["forward"]["quant_mode"] == 5 |
| 83 | assert seen["forward"]["topk"] == topk | 83 | assert seen["forward"]["topk"] == topk |
| @@ -87,7 +87,7 @@ def test_module_swap_routes_teacher_to_indexer_inputs(monkeypatch, batch): | |||
| 87 | assert operands.shape == expected_shape | 87 | assert operands.shape == expected_shape |
| 88 | 88 | ||
| 89 | # The real attention emits teacher mass with padding zeroed and softmax_scale applied. | 89 | # The real attention emits teacher mass with padding zeroed and softmax_scale applied. |
| 90 | - teacher = torch.tensor([8.0, 4.0, 0.0, 0.0]).expand(batch, tokens, topk) | 90 | + teacher = torch.tensor([8.0, 4.0, 0.0, 0.0]).expand(batch * tokens, topk) |
| 91 | scores.data.fill_(float("nan")) | 91 | scores.data.fill_(float("nan")) |
| 92 | scores.backward(teacher) | 92 | scores.backward(teacher) |
| 93 | 93 | ||
| @@ -112,16 +112,16 @@ def test_module_swap_routes_teacher_to_indexer_inputs(monkeypatch, batch): | |||
| 112 | 112 | ||
| 113 | 113 | ||
| 114 | def test_module_swap_rejects_missing_teacher_gradient(monkeypatch): | 114 | def test_module_swap_rejects_missing_teacher_gradient(monkeypatch): |
| 115 | - query = torch.ones(1, 2, 1, 4, dtype=torch.bfloat16, requires_grad=True) | 115 | + query = torch.ones(2, 1, 4, dtype=torch.bfloat16, requires_grad=True) |
| 116 | - key = torch.ones(1, 1, 4, dtype=torch.bfloat16, requires_grad=True) | 116 | + key = torch.ones(1, 4, dtype=torch.bfloat16, requires_grad=True) |
| 117 | - weights = torch.ones(1, 2, 1, dtype=torch.bfloat16, requires_grad=True) | 117 | + weights = torch.ones(2, 1, dtype=torch.bfloat16, requires_grad=True) |
| 118 | record = torch.tensor([7], dtype=torch.int32) | 118 | record = torch.tensor([7], dtype=torch.int32) |
| 119 | 119 | ||
| 120 | def input_adapter(module, q, k, w, metadata): | 120 | def input_adapter(module, q, k, w, metadata): |
| 121 | return lightning_indexer.QuantizedLightningIndexerInputs( | 121 | return lightning_indexer.QuantizedLightningIndexerInputs( |
| 122 | - query=q.flatten(0, 1), | 122 | + query=q, |
| 123 | - key=k.flatten(0, 1).unsqueeze(1), | 123 | + key=k.unsqueeze(1), |
| 124 | - weights=w.flatten(0, 1).float(), | 124 | + weights=w.float(), |
| 125 | topk=1, | 125 | topk=1, |
| 126 | metadata=metadata, | 126 | metadata=metadata, |
| 127 | cu_seqlens_q=torch.tensor([0, 2], dtype=torch.int32), | 127 | cu_seqlens_q=torch.tensor([0, 2], dtype=torch.int32), |
| @@ -106,5 +106,4 @@ def quantized_lightning_indexer_forward(self, idx_q, idx_k, idx_w, *, attention_ | |||
| 106 | raise RuntimeError("Quantized LI requires a host input adapter") | 106 | raise RuntimeError("Quantized LI requires a host input adapter") |
| 107 | inputs = config.input_adapter(self, idx_q, idx_k, idx_w, attention_metadata) | 107 | inputs = config.input_adapter(self, idx_q, idx_k, idx_w, attention_metadata) |
| 108 | indices, scores = _QuantLightningIndexerTND.apply(inputs.query, inputs.key, inputs.weights, inputs, config) | 108 | indices, scores = _QuantLightningIndexerTND.apply(inputs.query, inputs.key, inputs.weights, inputs, config) |
| 109 | - batch, seqlen = idx_q.shape[:2] | 109 | + return indices.squeeze(1), scores.squeeze(1) |
| 110 | - return indices.reshape(batch, seqlen, -1), scores.reshape(batch, seqlen, -1) | ||
| @@ -7,7 +7,12 @@ name = "torchtitan-npu" | |||
| 7 | version = "0.1.0" | 7 | version = "0.1.0" |
| 8 | description = "Huawei Ascend NPU overrides for torchtitan" | 8 | description = "Huawei Ascend NPU overrides for torchtitan" |
| 9 | requires-python = ">=3.12" | 9 | requires-python = ">=3.12" |
| 10 | -dependencies = ["torchtitan", "torch-npu", "attn-gym==0.0.16", "torchvision"] | 10 | +dependencies = [ |
| 11 | + "torchtitan @ git+https://gitcode.com/GitHub_Trending/to/torchtitan.git@dc3985ad4912f67f71d5a125f2fdf40144ec8354", | ||
| 12 | + "torch-npu", | ||
| 13 | + "attn-gym==0.0.16", | ||
| 14 | + "torchvision", | ||
| 15 | +] | ||
| 11 | 16 | ||
| 12 | [project.optional-dependencies] | 17 | [project.optional-dependencies] |
| 13 | multimodal = [ | 18 | multimodal = [ |
| @@ -34,7 +39,19 @@ markers = [ | |||
| 34 | ] | 39 | ] |
| 35 | 40 | ||
| 36 | [tool.pyrefly] | 41 | [tool.pyrefly] |
| 37 | -project-excludes = ["**/tests/**", "CI", "torchtitan_npu/ops/pypto", "torchtitan_npu/ops/triton", "scripts"] | 42 | +project-excludes = [ |
| 43 | + "**/tests/**", "CI", "scripts", | ||
| 44 | + # torch.compile debug dumps written by the rope-compile unit tests. | ||
| 45 | + "torch_compile_debug", | ||
| 46 | + # Kernel DSL tensor annotations are not Python type annotations. | ||
| 47 | + "torchtitan_npu/ops/pypto", "torchtitan_npu/ops/pypto_pro", | ||
| 48 | + "torchtitan_npu/ops/triton", "torchtitan_npu/ops/tilelang", | ||
| 49 | + # Re-enable with the DeepSeek-V3.2 folded-token model migration. | ||
| 50 | + "torchtitan_npu/models/deepseek_v3_2/sharding.py", | ||
| 51 | + # TorchFT still targets the trainer before the folded-token migration. | ||
| 52 | + "torchtitan_npu/patches/torchtitan/experiments/torchft", | ||
| 53 | + "torchtitan_npu/extensions/torchtitan/experiments/torchft", | ||
| 54 | +] | ||
| 38 | ignore-missing-imports = [ | 55 | ignore-missing-imports = [ |
| 39 | "attn_gym", | 56 | "attn_gym", |
| 40 | "attn_gym.*", | 57 | "attn_gym.*", |
| @@ -7,7 +7,7 @@ torch==2.14.0 | |||
| 7 | torchvision==0.29.0 | 7 | torchvision==0.29.0 |
| 8 | --find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torch-npu/index.html | 8 | --find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torch-npu/index.html |
| 9 | torch_npu==2.14.0.dev20260918 | 9 | torch_npu==2.14.0.dev20260918 |
| 10 | -torchtitan==0.3.0 | 10 | +torchtitan @ git+https://gitcode.com/GitHub_Trending/to/torchtitan.git@dc3985ad4912f67f71d5a125f2fdf40144ec8354 |
| 11 | attn-gym==0.0.16 | 11 | attn-gym==0.0.16 |
| 12 | pybind11==3.0.4 | 12 | pybind11==3.0.4 |
| 13 | numpy | 13 | numpy |
| @@ -162,6 +162,8 @@ python scripts/numerical_alignment/loss_compare.py HEAD HEAD \ | |||
| 162 | 两种模式都不改变两次训练本身的卡数。跨并行布局加载是否支持取决于模型的 checkpoint 实现;当前不支持恢复完整训练状态的续训比较。 | 162 | 两种模式都不改变两次训练本身的卡数。跨并行布局加载是否支持取决于模型的 checkpoint 实现;当前不支持恢复完整训练状态的续训比较。 |
| 163 | 若两侧无法共用 seed checkpoint,可用 `--no-seed-checkpoint` 改为固定种子初始化。 | 163 | 若两侧无法共用 seed checkpoint,可用 `--no-seed-checkpoint` 改为固定种子初始化。 |
| 164 | 164 | ||
| 165 | +两侧默认使用 token 预算接口。迁移比较可分别选择序列长度参数:`--baseline-training-api legacy` 使用 `--training.seq-len`,`--test-training-api tokens` 使用 `--training.max-context-length`;长度仍由 `--seq-len` 统一指定。旧侧 local/global batch 与新侧 microbatch/train-step token 预算通过各自 options 显式传入,工具不推断数据并行度或梯度累积。`--baseline-upstream` / `--test-upstream` 可分别指定 TorchTitan 源码目录,并加入对应进程的 `PYTHONPATH`;解释器及依赖仍由各侧环境提供。 | ||
| 166 | + | ||
| 165 | #### 输出与清理 | 167 | #### 输出与清理 |
| 166 | 168 | ||
| 167 | 默认在 `outputs/compare_results/` 下创建独立结果目录,可用 `--output-dir` 指定空目录或尚不存在的目录。 | 169 | 默认在 `outputs/compare_results/` 下创建独立结果目录,可用 `--output-dir` 指定空目录或尚不存在的目录。 |
| @@ -97,7 +97,8 @@ def configure_reduced_moe( | |||
| 97 | moe.router.num_experts = num_experts | 97 | moe.router.num_experts = num_experts |
| 98 | moe.router.gate.out_features = num_experts | 98 | moe.router.gate.out_features = num_experts |
| 99 | moe.router.top_k = top_k | 99 | moe.router.top_k = top_k |
| 100 | - moe.router.hash = layer_id < n_hash_layers | 100 | + moe.router.layer_id = layer_id |
| 101 | + moe.router.n_hash_layers = n_hash_layers | ||
| 101 | moe.routed_experts.inner_experts.num_experts = num_experts | 102 | moe.routed_experts.inner_experts.num_experts = num_experts |
| 102 | moe.routed_experts.token_dispatcher.num_experts = num_experts | 103 | moe.routed_experts.token_dispatcher.num_experts = num_experts |
| 103 | moe.routed_experts.token_dispatcher.top_k = top_k | 104 | moe.routed_experts.token_dispatcher.top_k = top_k |
| @@ -101,15 +101,18 @@ def _register(core, trace, *, transformers: bool) -> trace_hooks.TraceHookRegist | |||
| 101 | inner_attention = _require_attr(attention, "inner_attention") | 101 | inner_attention = _require_attr(attention, "inner_attention") |
| 102 | 102 | ||
| 103 | def attention_core_pre_hook(_module, args, *, prefix=prefix): | 103 | def attention_core_pre_hook(_module, args, *, prefix=prefix): |
| 104 | - trace_hooks.record_trace(trace, f"{prefix}.attention.q", args[0]) | 104 | + trace_hooks.record_trace(trace, f"{prefix}.attention.q", args[0].unsqueeze(0)) |
| 105 | - batch = args[0].shape[0] | 105 | + kv = args[1] |
| 106 | - kv = args[1].reshape(batch, -1, args[1].shape[-1]) | ||
| 107 | if len(args) > 2 and args[2] is not None and args[2].numel() > 0: | 106 | if len(args) > 2 and args[2] is not None and args[2].numel() > 0: |
| 108 | - kv = torch.cat([kv, args[2].reshape(batch, -1, args[2].shape[-1])], dim=1) | 107 | + kv = torch.cat([kv, args[2]], dim=0) |
| 109 | - trace_hooks.record_trace(trace, f"{prefix}.attention.kv", kv) | 108 | + trace_hooks.record_trace(trace, f"{prefix}.attention.kv", kv.unsqueeze(0)) |
| 110 | 109 | ||
| 111 | registry.callback(inner_attention, attention_core_pre_hook, pre=True) | 110 | registry.callback(inner_attention, attention_core_pre_hook, pre=True) |
| 112 | - registry.forward(inner_attention, f"{prefix}.attention.core") | 111 | + registry.forward( |
| 112 | + inner_attention, | ||
| 113 | + f"{prefix}.attention.core", | ||
| 114 | + lambda output: (output[0] if isinstance(output, tuple) else output).unsqueeze(0), | ||
| 115 | + ) | ||
| 113 | registry.forward(moe, f"{prefix}.moe") | 116 | registry.forward(moe, f"{prefix}.moe") |
| 114 | registry.callback(_require_attr(moe, "gate" if transformers else "router"), router_hook) | 117 | registry.callback(_require_attr(moe, "gate" if transformers else "router"), router_hook) |
| 115 | # Record the routed output after token combine, rather than the expanded | 118 | # Record the routed output after token combine, rather than the expanded |
| @@ -48,8 +48,9 @@ def build_model_config( | |||
| 48 | from torchtitan.config import apply_overrides | 48 | from torchtitan.config import apply_overrides |
| 49 | 49 | ||
| 50 | cfg = dsv4_config.build_torchtitan_config(model_flavor) | 50 | cfg = dsv4_config.build_torchtitan_config(model_flavor) |
| 51 | - cfg.training.global_batch_size = global_batch_size | 51 | + cfg.training.num_tokens_per_microbatch_per_dp_rank = global_batch_size * seq_len |
| 52 | - cfg.training.seq_len = seq_len | 52 | + cfg.training.num_tokens_per_train_step = global_batch_size * seq_len |
| 53 | + cfg.training.max_context_length = seq_len | ||
| 53 | model_config = cfg.model_spec.model | 54 | model_config = cfg.model_spec.model |
| 54 | dsv4_config.truncate_model_config(model_config, n_layers) | 55 | dsv4_config.truncate_model_config(model_config, n_layers) |
| 55 | if (num_experts is None) != (top_k is None): | 56 | if (num_experts is None) != (top_k is None): |
| @@ -113,15 +114,7 @@ def forward_logits( | |||
| 113 | ) -> torch.Tensor: | 114 | ) -> torch.Tensor: |
| 114 | """Run the DSV4 TorchTitan forward protocol and return logits.""" | 115 | """Run the DSV4 TorchTitan forward protocol and return logits.""" |
| 115 | 116 | ||
| 116 | - positions = ( | 117 | + positions = torch.arange(tokens.shape[1], dtype=torch.int64, device=tokens.device).repeat(tokens.shape[0]) |
| 117 | - torch.arange( | ||
| 118 | - tokens.shape[1], | ||
| 119 | - dtype=torch.int64, | ||
| 120 | - device=tokens.device, | ||
| 121 | - ) | ||
| 122 | - .unsqueeze(0) | ||
| 123 | - .expand(tokens.shape[0], -1) | ||
| 124 | - ) | ||
| 125 | # The model owns the metadata seam (upstream #4897/#4116): it builds one entry per | 118 | # The model owns the metadata seam (upstream #4897/#4116): it builds one entry per |
| 126 | # attention geometry and hands the map to the forward, so an offline forward owes it the | 119 | # attention geometry and hands the map to the forward, so an offline forward owes it the |
| 127 | # same preprocessing the trainer does. | 120 | # same preprocessing the trainer does. |
| @@ -131,12 +124,13 @@ def forward_logits( | |||
| 131 | context_parallel_load_balancer=DOC_CHUNK_LAYOUT, | 124 | context_parallel_load_balancer=DOC_CHUNK_LAYOUT, |
| 132 | context_parallel_ptrr_mask_key=None, | 125 | context_parallel_ptrr_mask_key=None, |
| 133 | ) | 126 | ) |
| 134 | - tokens, _, extra_kwargs = model.preprocess_inputs( | 127 | + flat_tokens = tokens.flatten() |
| 135 | - {"input": tokens, "positions": positions}, | 128 | + inputs, _, extra_kwargs = model.preprocess_inputs( |
| 136 | - None, | 129 | + {"input": flat_tokens, "labels": flat_tokens, "positions": positions}, |
| 137 | parallel_dims=parallel_dims, | 130 | parallel_dims=parallel_dims, |
| 138 | - device=tokens.device, | ||
| 139 | parallelism=parallelism, | 131 | parallelism=parallelism, |
| 132 | + max_num_documents=tokens.shape[0], | ||
| 133 | + max_context_length=tokens.shape[1], | ||
| 140 | ) | 134 | ) |
| 141 | - logits = model(tokens, **extra_kwargs) | 135 | + logits = model(inputs, **extra_kwargs).reshape(*tokens.shape, -1) |
| 142 | return logits[:, -1, :] if last_token_only else logits | 136 | return logits[:, -1, :] if last_token_only else logits |
| @@ -19,11 +19,13 @@ r"""比较两个训练脚本或 Git 版本的 loss 和 grad norm。 | |||
| 19 | TensorBoard 读取每个 step 的 loss 和 grad_norm → 按 bitwise 或 close 模式判定 | 19 | TensorBoard 读取每个 step 的 loss 和 grad_norm → 按 bitwise 或 close 模式判定 |
| 20 | → 将结果写入 comparison.json。 | 20 | → 将结果写入 comparison.json。 |
| 21 | 21 | ||
| 22 | -默认在创建 seed checkpoint 和两次训练时设置 `--training.seq-len=4096`、 | 22 | +默认在创建 seed checkpoint 和两次训练时设置 `--training.max-context-length=4096`、 |
| 23 | `--debug.seed=42`,并启用 `--debug.deterministic`。其他序列长度通过 `--seq-len` 统一指定, | 23 | `--debug.seed=42`,并启用 `--debug.deterministic`。其他序列长度通过 `--seq-len` 统一指定, |
| 24 | 步数通过 `--steps` 指定,`--no-deterministic` 可关闭确定性算法。这些由脚本控制的选项及固定的 | 24 | 步数通过 `--steps` 指定,`--no-deterministic` 可关闭确定性算法。这些由脚本控制的选项及固定的 |
| 25 | 随机种子、TensorBoard 配置不能放入 `--baseline-options` / `--test-options`。 | 25 | 随机种子、TensorBoard 配置不能放入 `--baseline-options` / `--test-options`。 |
| 26 | `--no-seed-checkpoint` 可跳过共享 checkpoint。 | 26 | `--no-seed-checkpoint` 可跳过共享 checkpoint。 |
| 27 | +旧版本可使用 `--baseline-training-api legacy`,将 baseline 的长度参数改为 `--training.seq-len`。 | ||
| 28 | +`--baseline-upstream` / `--test-upstream` 分别指定独立的 TorchTitan 源码目录。 | ||
| 27 | 29 | ||
| 28 | Engram 等按并行布局保存原生 checkpoint 的模型,应使用 `--seed-mode distributed`。 | 30 | Engram 等按并行布局保存原生 checkpoint 的模型,应使用 `--seed-mode distributed`。 |
| 29 | 该模式按 baseline 的 NPU 数、入口配置及额外选项构建模型,在训练前保存 step-0, | 31 | 该模式按 baseline 的 NPU 数、入口配置及额外选项构建模型,在训练前保存 step-0, |
| @@ -132,6 +134,7 @@ import os | |||
| 132 | import shlex | 134 | import shlex |
| 133 | import shutil | 135 | import shutil |
| 134 | import signal | 136 | import signal |
| 137 | +import struct | ||
| 135 | import subprocess | 138 | import subprocess |
| 136 | import sys | 139 | import sys |
| 137 | import tempfile | 140 | import tempfile |
| @@ -320,9 +323,9 @@ def resolve_runner(repo_root: Path, runner: Path) -> Path: | |||
| 320 | return path | 323 | return path |
| 321 | 324 | ||
| 322 | 325 | ||
| 323 | -def _fixed_training_options(*, deterministic: bool, seq_len: int) -> list[str]: | 326 | +def _fixed_training_options(*, deterministic: bool, seq_len: int, training_api: str = "tokens") -> list[str]: |
| 324 | return [ | 327 | return [ |
| 325 | - f"--training.seq-len={seq_len}", | 328 | + f"--training.{'max-context-length' if training_api == 'tokens' else 'seq-len'}={seq_len}", |
| 326 | *(option for option in FIXED_TRAINING_OPTIONS if deterministic or option != "--debug.deterministic"), | 329 | *(option for option in FIXED_TRAINING_OPTIONS if deterministic or option != "--debug.deterministic"), |
| 327 | ] | 330 | ] |
| 328 | 331 | ||
| @@ -333,6 +336,7 @@ def build_seed_command( | |||
| 333 | *, | 336 | *, |
| 334 | deterministic: bool = True, | 337 | deterministic: bool = True, |
| 335 | seq_len: int = DEFAULT_SEQ_LEN, | 338 | seq_len: int = DEFAULT_SEQ_LEN, |
| 339 | + training_api: str = "tokens", | ||
| 336 | distributed: bool = False, | 340 | distributed: bool = False, |
| 337 | options: str = "", | 341 | options: str = "", |
| 338 | ) -> list[str]: | 342 | ) -> list[str]: |
| @@ -361,7 +365,7 @@ def build_seed_command( | |||
| 361 | "--checkpoint.no-load-only", | 365 | "--checkpoint.no-load-only", |
| 362 | f"--checkpoint.folder={dump_folder / 'checkpoint'}", | 366 | f"--checkpoint.folder={dump_folder / 'checkpoint'}", |
| 363 | "--checkpoint.last-save-model-only", | 367 | "--checkpoint.last-save-model-only", |
| 364 | - *_fixed_training_options(deterministic=deterministic, seq_len=seq_len), | 368 | + *_fixed_training_options(deterministic=deterministic, seq_len=seq_len, training_api=training_api), |
| 365 | ] | 369 | ] |
| 366 | 370 | ||
| 367 | 371 | ||
| @@ -374,12 +378,13 @@ def build_training_command( | |||
| 374 | seed_checkpoint: Path | None, | 378 | seed_checkpoint: Path | None, |
| 375 | deterministic: bool = True, | 379 | deterministic: bool = True, |
| 376 | seq_len: int = DEFAULT_SEQ_LEN, | 380 | seq_len: int = DEFAULT_SEQ_LEN, |
| 381 | + training_api: str = "tokens", | ||
| 377 | ) -> list[str]: | 382 | ) -> list[str]: |
| 378 | command = [ | 383 | command = [ |
| 379 | str(runner), | 384 | str(runner), |
| 380 | f"--dump_folder={dump_folder}", | 385 | f"--dump_folder={dump_folder}", |
| 381 | *shlex.split(options), | 386 | *shlex.split(options), |
| 382 | - *_fixed_training_options(deterministic=deterministic, seq_len=seq_len), | 387 | + *_fixed_training_options(deterministic=deterministic, seq_len=seq_len, training_api=training_api), |
| 383 | f"--training.steps={steps}", | 388 | f"--training.steps={steps}", |
| 384 | f"--metrics.save_tb_folder={TENSORBOARD_FOLDER}", | 389 | f"--metrics.save_tb_folder={TENSORBOARD_FOLDER}", |
| 385 | ] | 390 | ] |
| @@ -470,13 +475,17 @@ def run_with_realtime_output( | |||
| 470 | raise subprocess.CalledProcessError(return_code, command) | 475 | raise subprocess.CalledProcessError(return_code, command) |
| 471 | 476 | ||
| 472 | 477 | ||
| 473 | -def training_env(ngpus: int | None, extra_env: Mapping[str, str] | None = None) -> dict[str, str]: | 478 | +def training_env( |
| 479 | + ngpus: int | None, extra_env: Mapping[str, str] | None = None, *, upstream: Path | None = None | ||
| 480 | +) -> dict[str, str]: | ||
| 474 | env = os.environ.copy() | 481 | env = os.environ.copy() |
| 475 | env["PYTHONUNBUFFERED"] = "1" | 482 | env["PYTHONUNBUFFERED"] = "1" |
| 476 | if extra_env: | 483 | if extra_env: |
| 477 | env.update(extra_env) | 484 | env.update(extra_env) |
| 478 | if ngpus is not None: | 485 | if ngpus is not None: |
| 479 | env["NGPU"] = str(ngpus) | 486 | env["NGPU"] = str(ngpus) |
| 487 | + if upstream is not None: | ||
| 488 | + env["PYTHONPATH"] = os.pathsep.join(filter(None, (str(upstream.resolve()), env.get("PYTHONPATH", "")))) | ||
| 480 | return env | 489 | return env |
| 481 | 490 | ||
| 482 | 491 | ||
| @@ -558,7 +567,11 @@ def compare_metric( | |||
| 558 | rel_diff = abs_diff / denominator | 567 | rel_diff = abs_diff / denominator |
| 559 | errors.append((step, baseline_value, test_value, abs_diff, rel_diff)) | 568 | errors.append((step, baseline_value, test_value, abs_diff, rel_diff)) |
| 560 | 569 | ||
| 561 | - if mode == "bitwise" and first_mismatch is None and not (finite and test_value == baseline_value): | 570 | + if ( |
| 571 | + mode == "bitwise" | ||
| 572 | + and first_mismatch is None | ||
| 573 | + and not (finite and struct.pack("!d", test_value) == struct.pack("!d", baseline_value)) | ||
| 574 | + ): | ||
| 562 | first_mismatch = { | 575 | first_mismatch = { |
| 563 | "step": step, | 576 | "step": step, |
| 564 | "baseline": baseline_value, | 577 | "baseline": baseline_value, |
| @@ -605,7 +618,12 @@ def compare_metric( | |||
| 605 | max_re=max_re, | 618 | max_re=max_re, |
| 606 | mean_re=mean_re, | 619 | mean_re=mean_re, |
| 607 | passed=not ( | 620 | passed=not ( |
| 608 | - baseline_missing_steps or baseline_extra_steps or test_missing_steps or test_extra_steps or failed_metrics | 621 | + baseline_missing_steps |
| 622 | + or baseline_extra_steps | ||
| 623 | + or test_missing_steps | ||
| 624 | + or test_extra_steps | ||
| 625 | + or failed_metrics | ||
| 626 | + or (mode == "bitwise" and first_mismatch is not None) | ||
| 609 | ), | 627 | ), |
| 610 | failed_metrics=failed_metrics, | 628 | failed_metrics=failed_metrics, |
| 611 | missing_steps=missing_steps, | 629 | missing_steps=missing_steps, |
| @@ -686,6 +704,7 @@ def write_report( | |||
| 686 | thresholds: MetricThresholds, | 704 | thresholds: MetricThresholds, |
| 687 | comparisons: Sequence[MetricComparison], | 705 | comparisons: Sequence[MetricComparison], |
| 688 | seed_mode: str = "unsharded", | 706 | seed_mode: str = "unsharded", |
| 707 | + runtime_options: Mapping[str, Any] | None = None, | ||
| 689 | ) -> None: | 708 | ) -> None: |
| 690 | report: dict[str, Any] = { | 709 | report: dict[str, Any] = { |
| 691 | "baseline": { | 710 | "baseline": { |
| @@ -707,6 +726,7 @@ def write_report( | |||
| 707 | "thresholds": asdict(thresholds), | 726 | "thresholds": asdict(thresholds), |
| 708 | "passed": all(result.passed for result in comparisons), | 727 | "passed": all(result.passed for result in comparisons), |
| 709 | "metrics": [asdict(result) for result in comparisons], | 728 | "metrics": [asdict(result) for result in comparisons], |
| 729 | + "runtime_options": dict(runtime_options or {}), | ||
| 710 | } | 730 | } |
| 711 | with (output_dir / "comparison.json").open("w") as output: | 731 | with (output_dir / "comparison.json").open("w") as output: |
| 712 | json.dump(report, output, indent=2) | 732 | json.dump(report, output, indent=2) |
| @@ -806,6 +826,15 @@ def parse_args() -> argparse.Namespace: | |||
| 806 | "keep baseline/test training outputs and the comparison report " | 826 | "keep baseline/test training outputs and the comparison report " |
| 807 | "(default: enabled; --no-cleanup-after-test keeps all artifacts)", | 827 | "(default: enabled; --no-cleanup-after-test keeps all artifacts)", |
| 808 | ) | 828 | ) |
| 829 | + for side in ("baseline", "test"): | ||
| 830 | + parser.add_argument( | ||
| 831 | + f"--{side}-training-api", | ||
| 832 | + choices=("legacy", "tokens"), | ||
| 833 | + default="tokens", | ||
| 834 | + help="sequence-length CLI: legacy seq-len or folded max-context-length; " | ||
| 835 | + "pass batch/token budgets in side options", | ||
| 836 | + ) | ||
| 837 | + parser.add_argument(f"--{side}-upstream", type=Path, help="independent TorchTitan source root for this side") | ||
| 809 | parser.add_argument("--baseline-options", default="") | 838 | parser.add_argument("--baseline-options", default="") |
| 810 | parser.add_argument("--test-options", default="") | 839 | parser.add_argument("--test-options", default="") |
| 811 | parser.add_argument( | 840 | parser.add_argument( |
| @@ -852,9 +881,10 @@ def parse_args() -> argparse.Namespace: | |||
| 852 | option.partition("=")[0].replace("_", "-") | 881 | option.partition("=")[0].replace("_", "-") |
| 853 | for option in _fixed_training_options(deterministic=True, seq_len=args.seq_len) | 882 | for option in _fixed_training_options(deterministic=True, seq_len=args.seq_len) |
| 854 | } | 883 | } |
| 855 | - managed_keys.update(("--training.steps", "--metrics.save-tb-folder")) | 884 | + managed_keys.update(("--training.steps", "--metrics.save-tb-folder", "--training.seq-len")) |
| 856 | option_hints = { | 885 | option_hints = { |
| 857 | "--training.seq-len": "use --seq-len for seed and both runs", | 886 | "--training.seq-len": "use --seq-len for seed and both runs", |
| 887 | + "--training.max-context-length": "use --seq-len for seed and both runs", | ||
| 858 | "--training.steps": "use --steps for both runs", | 888 | "--training.steps": "use --steps for both runs", |
| 859 | "--debug.deterministic": "use --no-deterministic to disable deterministic algorithms for both runs", | 889 | "--debug.deterministic": "use --no-deterministic to disable deterministic algorithms for both runs", |
| 860 | "--debug.seed": "the seed is fixed at 42 for seed creation and both runs", | 890 | "--debug.seed": "the seed is fixed at 42 for seed creation and both runs", |
| @@ -904,8 +934,8 @@ def main() -> None: | |||
| 904 | log_info(f"Test: {test_ref} ({test_commit})") | 934 | log_info(f"Test: {test_ref} ({test_commit})") |
| 905 | base_n = args.baseline_ngpus if args.baseline_ngpus is not None else args.ngpus | 935 | base_n = args.baseline_ngpus if args.baseline_ngpus is not None else args.ngpus |
| 906 | test_n = args.test_ngpus if args.test_ngpus is not None else args.ngpus | 936 | test_n = args.test_ngpus if args.test_ngpus is not None else args.ngpus |
| 907 | - baseline_env = training_env(base_n, _merged_env(args.baseline_env)) | 937 | + baseline_env = training_env(base_n, _merged_env(args.baseline_env), upstream=args.baseline_upstream) |
| 908 | - test_env = training_env(test_n, _merged_env(args.test_env)) | 938 | + test_env = training_env(test_n, _merged_env(args.test_env), upstream=args.test_upstream) |
| 909 | baseline_npu_processes = describe_npu_processes(base_n, baseline_env) | 939 | baseline_npu_processes = describe_npu_processes(base_n, baseline_env) |
| 910 | test_npu_processes = describe_npu_processes(test_n, test_env) | 940 | test_npu_processes = describe_npu_processes(test_n, test_env) |
| 911 | log_info(f"Mode: {args.mode}; steps: {args.steps}") | 941 | log_info(f"Mode: {args.mode}; steps: {args.steps}") |
| @@ -965,7 +995,9 @@ def main() -> None: | |||
| 965 | log_step("Creating shared seed checkpoint") | 995 | log_step("Creating shared seed checkpoint") |
| 966 | seed_dump = output_dir / "seed" | 996 | seed_dump = output_dir / "seed" |
| 967 | distributed_seed = args.seed_mode == "distributed" | 997 | distributed_seed = args.seed_mode == "distributed" |
| 968 | - seed_env = training_env(base_n if distributed_seed else 1, _merged_env(args.baseline_env)) | 998 | + seed_env = training_env( |
| 999 | + base_n if distributed_seed else 1, _merged_env(args.baseline_env), upstream=args.baseline_upstream | ||
| 1000 | + ) | ||
| 969 | if distributed_seed: | 1001 | if distributed_seed: |
| 970 | # Use this CLI's helper even when the baseline ref predates it. | 1002 | # Use this CLI's helper even when the baseline ref predates it. |
| 971 | # Expose only the helper, not sibling modules such as utils. | 1003 | # Expose only the helper, not sibling modules such as utils. |
| @@ -982,6 +1014,7 @@ def main() -> None: | |||
| 982 | seed_dump, | 1014 | seed_dump, |
| 983 | deterministic=not args.no_deterministic, | 1015 | deterministic=not args.no_deterministic, |
| 984 | seq_len=args.seq_len, | 1016 | seq_len=args.seq_len, |
| 1017 | + training_api=args.baseline_training_api, | ||
| 985 | distributed=distributed_seed, | 1018 | distributed=distributed_seed, |
| 986 | options=args.baseline_options, | 1019 | options=args.baseline_options, |
| 987 | ), | 1020 | ), |
| @@ -1005,6 +1038,7 @@ def main() -> None: | |||
| 1005 | baseline_dump, | 1038 | baseline_dump, |
| 1006 | steps=args.steps, | 1039 | steps=args.steps, |
| 1007 | options=args.baseline_options, | 1040 | options=args.baseline_options, |
| 1041 | + training_api=args.baseline_training_api, | ||
| 1008 | seed_checkpoint=seed_checkpoint, | 1042 | seed_checkpoint=seed_checkpoint, |
| 1009 | deterministic=not args.no_deterministic, | 1043 | deterministic=not args.no_deterministic, |
| 1010 | seq_len=args.seq_len, | 1044 | seq_len=args.seq_len, |
| @@ -1030,6 +1064,7 @@ def main() -> None: | |||
| 1030 | test_dump, | 1064 | test_dump, |
| 1031 | steps=args.steps, | 1065 | steps=args.steps, |
| 1032 | options=args.test_options, | 1066 | options=args.test_options, |
| 1067 | + training_api=args.test_training_api, | ||
| 1033 | seed_checkpoint=seed_checkpoint, | 1068 | seed_checkpoint=seed_checkpoint, |
| 1034 | deterministic=not args.no_deterministic, | 1069 | deterministic=not args.no_deterministic, |
| 1035 | seq_len=args.seq_len, | 1070 | seq_len=args.seq_len, |
| @@ -1073,6 +1108,14 @@ def main() -> None: | |||
| 1073 | thresholds=(thresholds if args.mode == "close" else BITWISE_THRESHOLDS), | 1108 | thresholds=(thresholds if args.mode == "close" else BITWISE_THRESHOLDS), |
| 1074 | comparisons=comparisons, | 1109 | comparisons=comparisons, |
| 1075 | seed_mode="none" if args.no_seed_checkpoint else args.seed_mode, | 1110 | seed_mode="none" if args.no_seed_checkpoint else args.seed_mode, |
| 1111 | + runtime_options={ | ||
| 1112 | + side: { | ||
| 1113 | + "training_api": getattr(args, f"{side}_training_api"), | ||
| 1114 | + "upstream": str(getattr(args, f"{side}_upstream")) if getattr(args, f"{side}_upstream") else None, | ||
| 1115 | + "options": getattr(args, f"{side}_options"), | ||
| 1116 | + } | ||
| 1117 | + for side in ("baseline", "test") | ||
| 1118 | + }, | ||
| 1076 | ) | 1119 | ) |
| 1077 | log_success(f"Report written: {output_dir / 'comparison.json'}") | 1120 | log_success(f"Report written: {output_dir / 'comparison.json'}") |
| 1078 | if not all(result.passed for result in comparisons): | 1121 | if not all(result.passed for result in comparisons): |
| @@ -53,6 +53,17 @@ python -m tests.integration_tests.run_tests \ | |||
| 53 | * **`deepseek_v4_1_fused`**:DeepSeek-V4.1 多模态打包/融合与 Muon 冒烟,需 vision fixture,单独运行; | 53 | * **`deepseek_v4_1_fused`**:DeepSeek-V4.1 多模态打包/融合与 Muon 冒烟,需 vision fixture,单独运行; |
| 54 | * **`deepseek_v4_1_engram_hf`**:DeepSeek-V4.1 Engram MXFP8 专项校验与 DCP/HF 权重回环测试。 | 54 | * **`deepseek_v4_1_engram_hf`**:DeepSeek-V4.1 Engram MXFP8 专项校验与 DCP/HF 权重回环测试。 |
| 55 | 55 | ||
| 56 | +本轮 Router / MoE 重构的 NPU golden 验收范围为 `TP=1 / CP=1 / PP=1`、两卡 `FSDP2 / EP2`。保留的 Gloo TP2 CPU 测试只验证通用布局与计数合同,不表示 NPU TP2 支持。当前 NPU runtime 对非 gather 维度分片的 DTensor 存在 gather backward 全局形状未局部化及输入形状缓存键遗漏问题;其修复与 NPU TP2 复现测试已拆出,本轮不包含该修复。 | ||
| 57 | + | ||
| 58 | +`deepseek_v4_1_reference_multimodal` 运行两卡 CPT / SFT 参考实现,使用 FullAC、Host Engram 和 virtual AdamW,并检查三步训练及 TensorBoard 步数;它也纳入默认 `models` suite。CPT 使用仓内 `cc12m_test`。只有同时设置 `DSV41_SFT_TOKENIZER_PATH` 和 `DSV41_SFT_FIXTURE_PATH` 才注册 SFT:前者指向配套的官方 `encoding.py` 与 tokenizer 目录,后者指向 JSON、JSONL 或 Parquet 数据。SFT 固定每 rank token 预算与 context 均为 512,`packing_buffer_size=0`;缺少任一变量时 SFT 不注册。运行包含 SFT 的 suite 示例: | ||
| 59 | + | ||
| 60 | +```bash | ||
| 61 | +DSV41_SFT_TOKENIZER_PATH=/path/to/tokenizer-view \ | ||
| 62 | +DSV41_SFT_FIXTURE_PATH=/path/to/sft_rows.jsonl \ | ||
| 63 | +python -m tests.integration_tests.run_tests ./test_reports/v41-reference-mm \ | ||
| 64 | + --test_suite deepseek_v4_1_reference_multimodal --ngpu 2 --no-parallel | ||
| 65 | +``` | ||
| 66 | + | ||
| 56 | #### 核心用例清单矩阵 | 67 | #### 核心用例清单矩阵 |
| 57 | 68 | ||
| 58 | | Case 名称 | 对应模型 | 并行配置 | 卡数 (ngpu) | Check Loss | 核心校验点与说明 | | 69 | | Case 名称 | 对应模型 | 并行配置 | 卡数 (ngpu) | Check Loss | 核心校验点与说明 | |
| @@ -9,12 +9,15 @@ from functools import wraps | |||
| 9 | 9 | ||
| 10 | 10 | ||
| 11 | def main(): | 11 | def main(): |
| 12 | - import torchtitan_npu # noqa: F401 | 12 | + import torchtitan_npu # noqa: F401, I001 |
| 13 | + | ||
| 14 | + # Initialize the NPU backend before importing upstream trainer modules. | ||
| 15 | + from torchtitan.models.common.moe import TokenChoiceTopKRouter | ||
| 13 | from torchtitan.train import main as train_main | 16 | from torchtitan.train import main as train_main |
| 14 | - from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx | 17 | + |
| 15 | - from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager | ||
| 16 | - from torchtitan_npu.extensions.experiment.anticipatory_routing.router import AnticipatoryHashRouter | ||
| 17 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import Phase | 18 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import Phase |
| 19 | + from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager | ||
| 20 | + from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx | ||
| 18 | 21 | ||
| 19 | original_init, original_step, original_train = TrainerEx.__init__, TrainerEx.train_step, TrainerEx.train | 22 | original_init, original_step, original_train = TrainerEx.__init__, TrainerEx.train_step, TrainerEx.train |
| 20 | 23 | ||
| @@ -24,7 +27,12 @@ def main(): | |||
| 24 | assert isinstance(config, TrainerEx.Config) | 27 | assert isinstance(config, TrainerEx.Config) |
| 25 | assert isinstance(self.checkpointer, CheckpointManager) | 28 | assert isinstance(self.checkpointer, CheckpointManager) |
| 26 | assert self.anticipatory_schedule is not None | 29 | assert self.anticipatory_schedule is not None |
| 27 | - routers = [m for part in self.model_parts for m in part.modules() if isinstance(m, AnticipatoryHashRouter)] | 30 | + routers = [ |
| 31 | + m | ||
| 32 | + for part in self.model_parts | ||
| 33 | + for m in part.modules() | ||
| 34 | + if isinstance(m, TokenChoiceTopKRouter) and hasattr(m, "_anticipatory_cache") | ||
| 35 | + ] | ||
| 28 | assert routers, "CLI router override did not construct dynamic anticipatory routers" | 36 | assert routers, "CLI router override did not construct dynamic anticipatory routers" |
| 29 | assert all(m._anticipatory_cache is self.anticipatory_schedule.cache for m in routers) | 37 | assert all(m._anticipatory_cache is self.anticipatory_schedule.cache for m in routers) |
| 30 | self._test_injected = False | 38 | self._test_injected = False |
| @@ -3,6 +3,7 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 3 | # This source code is licensed under the BSD-style license found in the |
| 4 | # LICENSE file in the root directory of this source tree. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | +import os | ||
| 6 | from dataclasses import replace | 7 | from dataclasses import replace |
| 7 | 8 | ||
| 8 | from tests.integration_tests import OverrideDefinitions | 9 | from tests.integration_tests import OverrideDefinitions |
| @@ -28,6 +29,14 @@ GOLDEN_OVERRIDES = ( | |||
| 28 | "torchtitan_npu.override.common.rope.workaround", | 29 | "torchtitan_npu.override.common.rope.workaround", |
| 29 | ) | 30 | ) |
| 30 | 31 | ||
| 32 | +# The V4 Grain recipe already points at tests/assets/c4_test/data.json. | ||
| 33 | +V4_TRAIN_ARGS = ( | ||
| 34 | + "--metrics.enable_tensorboard", | ||
| 35 | + "--metrics.log_freq=1", | ||
| 36 | + "--metrics.save_tb_folder=tb", | ||
| 37 | + "--training.disable-cuda-graphs", | ||
| 38 | +) | ||
| 39 | + | ||
| 31 | 40 | ||
| 32 | def _build_case( | 41 | def _build_case( |
| 33 | *, | 42 | *, |
| @@ -51,6 +60,7 @@ def _build_case( | |||
| 51 | recipe = GOLDEN_OVERRIDES if use_golden else NPU_OVERRIDES | 60 | recipe = GOLDEN_OVERRIDES if use_golden else NPU_OVERRIDES |
| 52 | return OverrideDefinitions( | 61 | return OverrideDefinitions( |
| 53 | override_args=[recipe + extra_override_imports + extra_args], | 62 | override_args=[recipe + extra_override_imports + extra_args], |
| 63 | + train_args=V4_TRAIN_ARGS, | ||
| 54 | test_descr=test_descr, | 64 | test_descr=test_descr, |
| 55 | test_name=test_name, | 65 | test_name=test_name, |
| 56 | ngpu=ngpu, | 66 | ngpu=ngpu, |
| @@ -69,7 +79,7 @@ def build_deepseek_v4_checkpoint_resume_test_list() -> list[OverrideDefinitions] | |||
| 69 | "--checkpoint.no-last-save-model-only", | 79 | "--checkpoint.no-last-save-model-only", |
| 70 | "--checkpoint.keep-latest-k=0", | 80 | "--checkpoint.keep-latest-k=0", |
| 71 | "--hf-assets-path=tests/assets/deepseek_v3", | 81 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 72 | - "--training.global-batch-size=2", | 82 | + "--training.num-tokens-per-train-step=4096", |
| 73 | "--training.steps=4", | 83 | "--training.steps=4", |
| 74 | "--parallelism.data-parallel-shard-degree=2", | 84 | "--parallelism.data-parallel-shard-degree=2", |
| 75 | "--parallelism.expert-parallel-degree=2", | 85 | "--parallelism.expert-parallel-degree=2", |
| @@ -80,6 +90,7 @@ def build_deepseek_v4_checkpoint_resume_test_list() -> list[OverrideDefinitions] | |||
| 80 | "torchtitan_npu.override.common.optimizer.swap_optimizer", | 90 | "torchtitan_npu.override.common.optimizer.swap_optimizer", |
| 81 | ) | 91 | ) |
| 82 | checkpoint_case = OverrideDefinitions( | 92 | checkpoint_case = OverrideDefinitions( |
| 93 | + train_args=V4_TRAIN_ARGS, | ||
| 83 | override_args=[ | 94 | override_args=[ |
| 84 | adamw_swap_overrides + adamw_swap_args, | 95 | adamw_swap_overrides + adamw_swap_args, |
| 85 | adamw_swap_overrides + adamw_swap_args + ("--checkpoint.load-step=2",), | 96 | adamw_swap_overrides + adamw_swap_args + ("--checkpoint.load-step=2",), |
| @@ -106,6 +117,7 @@ def build_deepseek_v4_checkpoint_resume_test_list() -> list[OverrideDefinitions] | |||
| 106 | def build_deepseek_v4_quantized_test_list() -> list[OverrideDefinitions]: | 117 | def build_deepseek_v4_quantized_test_list() -> list[OverrideDefinitions]: |
| 107 | return [ | 118 | return [ |
| 108 | OverrideDefinitions( | 119 | OverrideDefinitions( |
| 120 | + train_args=V4_TRAIN_ARGS, | ||
| 109 | test_name="dsv4_mxfp4_communication_fsdp2", | 121 | test_name="dsv4_mxfp4_communication_fsdp2", |
| 110 | test_descr="MXFP4 QAT communication, two forward/backward/optimizer steps on A5", | 122 | test_descr="MXFP4 QAT communication, two forward/backward/optimizer steps on A5", |
| 111 | env_vars={"MODULE": "torchtitan_npu.models.deepseek_v4", "CONFIG": "deepseek_v4_debugmodel"}, | 123 | env_vars={"MODULE": "torchtitan_npu.models.deepseek_v4", "CONFIG": "deepseek_v4_debugmodel"}, |
| @@ -113,8 +125,9 @@ def build_deepseek_v4_quantized_test_list() -> list[OverrideDefinitions]: | |||
| 113 | ( | 125 | ( |
| 114 | *GOLDEN_OVERRIDES, | 126 | *GOLDEN_OVERRIDES, |
| 115 | "--training.steps=2", | 127 | "--training.steps=2", |
| 116 | - "--training.global-batch-size=2", | 128 | + "--training.num-tokens-per-microbatch-per-dp-rank=256", |
| 117 | - "--training.seq-len=256", | 129 | + "--training.num-tokens-per-train-step=512", |
| 130 | + "--training.max-context-length=256", | ||
| 118 | "--parallelism.data-parallel-shard-degree=2", | 131 | "--parallelism.data-parallel-shard-degree=2", |
| 119 | "--parallelism.expert-parallel-degree=1", | 132 | "--parallelism.expert-parallel-degree=1", |
| 120 | "--parallelism.fsdp-reshard-after-forward=always", | 133 | "--parallelism.fsdp-reshard-after-forward=always", |
| @@ -140,7 +153,7 @@ def build_deepseek_v4_quantized_test_list() -> list[OverrideDefinitions]: | |||
| 140 | ( | 153 | ( |
| 141 | *GOLDEN_OVERRIDES, | 154 | *GOLDEN_OVERRIDES, |
| 142 | "--training.steps=2", | 155 | "--training.steps=2", |
| 143 | - "--training.global-batch-size=2", | 156 | + "--training.num-tokens-per-train-step=4096", |
| 144 | "--optimizer.name=AdamW", | 157 | "--optimizer.name=AdamW", |
| 145 | "--parallelism.data-parallel-shard-degree=2", | 158 | "--parallelism.data-parallel-shard-degree=2", |
| 146 | "--parallelism.expert-parallel-degree=2", | 159 | "--parallelism.expert-parallel-degree=2", |
| @@ -153,9 +166,46 @@ def build_deepseek_v4_quantized_test_list() -> list[OverrideDefinitions]: | |||
| 153 | ] | 166 | ] |
| 154 | 167 | ||
| 155 | 168 | ||
| 169 | +def _build_grain_sft_case() -> OverrideDefinitions: | ||
| 170 | + """Opt in with official V4 assets and a short, supervised JSONL corpus.""" | ||
| 171 | + assets = os.environ.get("DSV4_SFT_ASSETS", "") | ||
| 172 | + dataset = os.environ.get("DSV4_SFT_DATASET", "") | ||
| 173 | + return OverrideDefinitions( | ||
| 174 | + test_name="dsv4_grain_sft", | ||
| 175 | + test_descr="DeepSeek-V4 native Grain SFT: two eager training steps", | ||
| 176 | + disabled=not (assets and dataset), | ||
| 177 | + ngpu=1, | ||
| 178 | + timeout=600, | ||
| 179 | + env_vars={ | ||
| 180 | + "MODULE": "torchtitan_npu.models.deepseek_v4", | ||
| 181 | + "CONFIG": "deepseek_v4_debugmodel_sft", | ||
| 182 | + "DSV4_SFT_DATASET": dataset, | ||
| 183 | + }, | ||
| 184 | + train_args=("--metrics.enable_tensorboard", "--metrics.log_freq=1", "--training.disable-cuda-graphs"), | ||
| 185 | + override_args=[ | ||
| 186 | + ( | ||
| 187 | + *GOLDEN_OVERRIDES, | ||
| 188 | + f"--hf-assets-path={assets}", | ||
| 189 | + "--training.steps=2", | ||
| 190 | + "--training.max-context-length=512", | ||
| 191 | + "--training.num-tokens-per-microbatch-per-dp-rank=512", | ||
| 192 | + "--training.num-tokens-per-train-step=512", | ||
| 193 | + "--parallelism.data-parallel-shard-degree=1", | ||
| 194 | + "--parallelism.expert-parallel-degree=1", | ||
| 195 | + ) | ||
| 196 | + ], | ||
| 197 | + expected_steps=((1, 2),), | ||
| 198 | + use_golden=True, | ||
| 199 | + # External assets/corpus have no fixed golden loss. This checks completion only. | ||
| 200 | + check_loss=False, | ||
| 201 | + ) | ||
| 202 | + | ||
| 203 | + | ||
| 156 | def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | 204 | def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: |
| 157 | return [ | 205 | return [ |
| 206 | + _build_grain_sft_case(), | ||
| 158 | OverrideDefinitions( | 207 | OverrideDefinitions( |
| 208 | + train_args=V4_TRAIN_ARGS, | ||
| 159 | test_name="dsv4_anticipatory_recovery", | 209 | test_name="dsv4_anticipatory_recovery", |
| 160 | test_descr="DeepSeek-V4 CLI loss spike, native checkpoint rollback and route replay", | 210 | test_descr="DeepSeek-V4 CLI loss spike, native checkpoint rollback and route replay", |
| 161 | env_vars={ | 211 | env_vars={ |
| @@ -167,8 +217,9 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 167 | ( | 217 | ( |
| 168 | *GOLDEN_OVERRIDES, | 218 | *GOLDEN_OVERRIDES, |
| 169 | "--training.steps=10", | 219 | "--training.steps=10", |
| 170 | - "--training.seq-len=256", | 220 | + "--training.num-tokens-per-microbatch-per-dp-rank=256", |
| 171 | - "--training.global-batch-size=1", | 221 | + "--training.num-tokens-per-train-step=256", |
| 222 | + "--training.max-context-length=256", | ||
| 172 | "--parallelism.data-parallel-shard-degree=1", | 223 | "--parallelism.data-parallel-shard-degree=1", |
| 173 | "--parallelism.expert-parallel-degree=1", | 224 | "--parallelism.expert-parallel-degree=1", |
| 174 | "--hf-assets-path=tests/assets/deepseek_v3", | 225 | "--hf-assets-path=tests/assets/deepseek_v3", |
| @@ -191,6 +242,7 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 191 | check_loss=False, | 242 | check_loss=False, |
| 192 | ), | 243 | ), |
| 193 | OverrideDefinitions( | 244 | OverrideDefinitions( |
| 245 | + train_args=V4_TRAIN_ARGS, | ||
| 194 | test_name="dsv4_lora_ep2_fsdp2", | 246 | test_name="dsv4_lora_ep2_fsdp2", |
| 195 | test_descr="DeepSeek-V4 LoRA A/B training, frozen base and PEFT export EP2/FSDP2", | 247 | test_descr="DeepSeek-V4 LoRA A/B training, frozen base and PEFT export EP2/FSDP2", |
| 196 | env_vars={"MODULE": "tests.integration_tests.lora_config", "CONFIG": "deepseek_v4_lora_training"}, | 248 | env_vars={"MODULE": "tests.integration_tests.lora_config", "CONFIG": "deepseek_v4_lora_training"}, |
| @@ -198,7 +250,7 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 198 | ( | 250 | ( |
| 199 | *GOLDEN_OVERRIDES, | 251 | *GOLDEN_OVERRIDES, |
| 200 | "--training.steps=2", | 252 | "--training.steps=2", |
| 201 | - "--training.global-batch-size=2", | 253 | + "--training.num-tokens-per-train-step=4096", |
| 202 | "--optimizer.name=Muon", | 254 | "--optimizer.name=Muon", |
| 203 | "--parallelism.data-parallel-shard-degree=2", | 255 | "--parallelism.data-parallel-shard-degree=2", |
| 204 | "--parallelism.expert-parallel-degree=2", | 256 | "--parallelism.expert-parallel-degree=2", |
| @@ -221,7 +273,7 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 221 | "--training.steps=30", | 273 | "--training.steps=30", |
| 222 | "--lr-scheduler.total-steps=100", | 274 | "--lr-scheduler.total-steps=100", |
| 223 | "--hf-assets-path=tests/assets/deepseek_v3", | 275 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 224 | - "--training.global-batch-size=2", | 276 | + "--training.num-tokens-per-train-step=4096", |
| 225 | ), | 277 | ), |
| 226 | use_golden=True, | 278 | use_golden=True, |
| 227 | check_loss=True, | 279 | check_loss=True, |
| @@ -235,7 +287,7 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 235 | "--lr-scheduler.total-steps=100", | 287 | "--lr-scheduler.total-steps=100", |
| 236 | "--parallelism.expert-parallel-degree=2", | 288 | "--parallelism.expert-parallel-degree=2", |
| 237 | "--hf-assets-path=tests/assets/deepseek_v3", | 289 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 238 | - "--training.global-batch-size=2", | 290 | + "--training.num-tokens-per-train-step=4096", |
| 239 | ), | 291 | ), |
| 240 | use_golden=True, | 292 | use_golden=True, |
| 241 | check_loss=True, | 293 | check_loss=True, |
| @@ -249,7 +301,7 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 249 | "--compile.enable", | 301 | "--compile.enable", |
| 250 | "--compile.backend=aot_eager", | 302 | "--compile.backend=aot_eager", |
| 251 | "--hf-assets-path=tests/assets/deepseek_v3", | 303 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 252 | - "--training.global-batch-size=2", | 304 | + "--training.num-tokens-per-train-step=4096", |
| 253 | ), | 305 | ), |
| 254 | use_golden=False, | 306 | use_golden=False, |
| 255 | check_loss=False, | 307 | check_loss=False, |
| @@ -264,7 +316,7 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 264 | "--compile.enable", | 316 | "--compile.enable", |
| 265 | "--compile.backend=aot_eager", | 317 | "--compile.backend=aot_eager", |
| 266 | "--hf-assets-path=tests/assets/deepseek_v3", | 318 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 267 | - "--training.global-batch-size=2", | 319 | + "--training.num-tokens-per-train-step=4096", |
| 268 | ), | 320 | ), |
| 269 | use_golden=False, | 321 | use_golden=False, |
| 270 | check_loss=False, | 322 | check_loss=False, |
| @@ -281,7 +333,7 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 281 | "--parallelism.spmd-backend=spmd_types", | 333 | "--parallelism.spmd-backend=spmd_types", |
| 282 | "--dataloader.per_doc_alignment=256", | 334 | "--dataloader.per_doc_alignment=256", |
| 283 | "--hf-assets-path=tests/assets/deepseek_v3", | 335 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 284 | - "--training.global-batch-size=2", | 336 | + "--training.num-tokens-per-train-step=4096", |
| 285 | "--optimizer.name=Muon", | 337 | "--optimizer.name=Muon", |
| 286 | ), | 338 | ), |
| 287 | use_golden=False, | 339 | use_golden=False, |
| @@ -307,7 +359,7 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 307 | "--parallelism.spmd-backend=spmd_types", | 359 | "--parallelism.spmd-backend=spmd_types", |
| 308 | "--dataloader.per_doc_alignment=256", | 360 | "--dataloader.per_doc_alignment=256", |
| 309 | "--hf-assets-path=tests/assets/deepseek_v3", | 361 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 310 | - "--training.global-batch-size=2", | 362 | + "--training.num-tokens-per-train-step=4096", |
| 311 | "--optimizer.name=Muon", | 363 | "--optimizer.name=Muon", |
| 312 | ), | 364 | ), |
| 313 | use_golden=False, | 365 | use_golden=False, |
| @@ -17,6 +17,7 @@ smoke stays outside the default pool: it needs the vision fixture data and is | |||
| 17 | selected explicitly. | 17 | selected explicitly. |
| 18 | """ | 18 | """ |
| 19 | 19 | ||
| 20 | +import os | ||
| 20 | from dataclasses import replace | 21 | from dataclasses import replace |
| 21 | 22 | ||
| 22 | from tests.integration_tests import OverrideDefinitions | 23 | from tests.integration_tests import OverrideDefinitions |
| @@ -26,7 +27,8 @@ def build_deepseek_v4_1_test_list() -> list[OverrideDefinitions]: | |||
| 26 | args = ( | 27 | args = ( |
| 27 | "--override.imports", "torchtitan_npu.override.common.rope.workaround", | 28 | "--override.imports", "torchtitan_npu.override.common.rope.workaround", |
| 28 | "--hf-assets-path=tests/assets/deepseek_v3", "--training.steps=2", | 29 | "--hf-assets-path=tests/assets/deepseek_v3", "--training.steps=2", |
| 29 | - "--training.seq-len=128", "--training.global-batch-size=2", | 30 | + "--training.num-tokens-per-microbatch-per-dp-rank=128", |
| 31 | + "--training.num-tokens-per-train-step=256", "--training.max-context-length=128", | ||
| 30 | "--parallelism.data-parallel-shard-degree=2", "--parallelism.expert-parallel-degree=2", | 32 | "--parallelism.data-parallel-shard-degree=2", "--parallelism.expert-parallel-degree=2", |
| 31 | "--checkpoint.enable", "--checkpoint.no-last-save-model-only", | 33 | "--checkpoint.enable", "--checkpoint.no-last-save-model-only", |
| 32 | "--checkpoint.keep-latest-k=0", "--debug.seed=42", "--debug.deterministic", | 34 | "--checkpoint.keep-latest-k=0", "--debug.seed=42", "--debug.deterministic", |
| @@ -47,7 +49,69 @@ def build_deepseek_v4_1_test_list() -> list[OverrideDefinitions]: | |||
| 47 | "CONFIG": "deepseek_v4_1_lora_multimodal_training", | 49 | "CONFIG": "deepseek_v4_1_lora_multimodal_training", |
| 48 | }, | 50 | }, |
| 49 | ) | 51 | ) |
| 50 | - return [text, multimodal] | 52 | + no_engram = OverrideDefinitions( |
| 53 | + test_name="dsv41_text_no_engram_adamw_1p", | ||
| 54 | + test_descr="V4.1 text reference attention/indexer with eager AdamW on one NPU", | ||
| 55 | + env_vars=GOLDEN_ENV, | ||
| 56 | + override_args=[ | ||
| 57 | + ( | ||
| 58 | + "--override.imports", | ||
| 59 | + "torchtitan_npu.override.common.rope.workaround", | ||
| 60 | + "--hf-assets-path=tests/assets/deepseek_v3", | ||
| 61 | + "--training.steps=3", | ||
| 62 | + "--training.num-tokens-per-microbatch-per-dp-rank=128", | ||
| 63 | + "--training.num-tokens-per-train-step=128", | ||
| 64 | + "--training.max-context-length=128", | ||
| 65 | + "--parallelism.data-parallel-shard-degree=1", | ||
| 66 | + "--parallelism.expert-parallel-degree=1", | ||
| 67 | + "--parallelism.data-parallel-replicate-degree=1", | ||
| 68 | + "--parallelism.tensor-parallel-degree=1", | ||
| 69 | + "--parallelism.context-parallel-degree=1", | ||
| 70 | + "--parallelism.pipeline-parallel-degree=1", | ||
| 71 | + "--parallelism.context-parallel-load-balancer=None", | ||
| 72 | + "--parallelism.spmd-backend=partial_dtensor", | ||
| 73 | + "--debug.no-moe-force-load-balance", | ||
| 74 | + "--debug.seed=42", | ||
| 75 | + "--debug.deterministic", | ||
| 76 | + "--optimizer.name=AdamW", | ||
| 77 | + "--compile.no-enable", | ||
| 78 | + "--no-engram-enabled", | ||
| 79 | + "--checkpoint.no-enable", | ||
| 80 | + "activation-checkpoint:none", | ||
| 81 | + ) | ||
| 82 | + ], | ||
| 83 | + expected_steps=((1, 2, 3),), | ||
| 84 | + ngpu=1, | ||
| 85 | + use_golden=True, | ||
| 86 | + check_loss=False, | ||
| 87 | + timeout=1800, | ||
| 88 | + ) | ||
| 89 | + engram_args = tuple(arg for arg in no_engram.override_args[0] if arg != "--no-engram-enabled") | ||
| 90 | + # The override consumes values until the next option, so place virtual with RoPE. | ||
| 91 | + engram_args = (engram_args[0], engram_args[1], "torchtitan_npu.override.common.optimizer.virtual", *engram_args[2:]) | ||
| 92 | + engram_1p = replace( | ||
| 93 | + no_engram, test_name="dsv41_text_engram_adamw_1p", | ||
| 94 | + test_descr="V4.1 Host Engram and virtual AdamW on one NPU", | ||
| 95 | + override_args=[engram_args], | ||
| 96 | + ) | ||
| 97 | + engram_2p_args = tuple({ | ||
| 98 | + "--training.num-tokens-per-train-step=128": "--training.num-tokens-per-train-step=256", | ||
| 99 | + "--parallelism.data-parallel-shard-degree=1": "--parallelism.data-parallel-shard-degree=2", | ||
| 100 | + "--parallelism.expert-parallel-degree=1": "--parallelism.expert-parallel-degree=2", | ||
| 101 | + "activation-checkpoint:none": "activation-checkpoint:full", | ||
| 102 | + }.get(arg, arg) for arg in engram_args) | ||
| 103 | + engram_2p = replace( | ||
| 104 | + engram_1p, test_name="dsv41_text_engram_adamw_ep2_fsdp2", | ||
| 105 | + test_descr="V4.1 Host Engram, virtual AdamW, EP2/FSDP2 and FullAC", | ||
| 106 | + override_args=[engram_2p_args], ngpu=2, | ||
| 107 | + ) | ||
| 108 | + engram_2p_noac = replace( | ||
| 109 | + engram_2p, test_name="dsv41_text_engram_adamw_ep2_fsdp2_noac", | ||
| 110 | + test_descr="V4.1 Host Engram, virtual AdamW and EP2/FSDP2 without AC", | ||
| 111 | + override_args=[tuple("activation-checkpoint:none" if arg == "activation-checkpoint:full" else arg | ||
| 112 | + for arg in engram_2p_args)], | ||
| 113 | + ) | ||
| 114 | + return [text, multimodal, no_engram, engram_1p, engram_2p_noac, engram_2p] | ||
| 51 | 115 | ||
| 52 | 116 | ||
| 53 | def build_deepseek_v4_1_checkpoint_test_list( | 117 | def build_deepseek_v4_1_checkpoint_test_list( |
| @@ -123,9 +187,11 @@ def build_deepseek_v4_1_golden_test_list() -> list[OverrideDefinitions]: | |||
| 123 | GOLDEN_OVERRIDES | 187 | GOLDEN_OVERRIDES |
| 124 | + ( | 188 | + ( |
| 125 | "--training.steps=30", | 189 | "--training.steps=30", |
| 126 | - "--training.local-batch-size=1", | 190 | + "--training.num-tokens-per-microbatch-per-dp-rank=512", |
| 127 | - "--training.global-batch-size=2", | 191 | + "--training.num-tokens-per-train-step=1024", |
| 128 | - "--training.seq-len=512", | 192 | + "--training.max-context-length=512", |
| 193 | + "--training.disable-cuda-graphs", | ||
| 194 | + "--compile.no-enable", | ||
| 129 | "--parallelism.spmd-backend=partial_dtensor", | 195 | "--parallelism.spmd-backend=partial_dtensor", |
| 130 | "--parallelism.data-parallel-shard-degree=2", | 196 | "--parallelism.data-parallel-shard-degree=2", |
| 131 | "--parallelism.data-parallel-replicate-degree=1", | 197 | "--parallelism.data-parallel-replicate-degree=1", |
| @@ -166,7 +232,7 @@ def build_deepseek_v4_1_fused_test_list() -> list[OverrideDefinitions]: | |||
| 166 | 232 | ||
| 167 | Restored from the case that was removed with the V4.1 refactor, with the two | 233 | Restored from the case that was removed with the V4.1 refactor, with the two |
| 168 | arguments the current config registry needs (``deepseek_v4_1_debugmodel_multimodal`` | 234 | arguments the current config registry needs (``deepseek_v4_1_debugmodel_multimodal`` |
| 169 | - and ``--training.seq-len=512``, the debug model's RoPE limit). It stays opt-in | 235 | + and ``--training.max-context-length=512``, the debug model's RoPE limit). It stays opt-in |
| 170 | because it needs the vision fixture data and because the multimodal forward | 236 | because it needs the vision fixture data and because the multimodal forward |
| 171 | currently dies in ``aclnnIndex`` (DT_COMPLEX64 input) on the 2026-09-20 PTA | 237 | currently dies in ``aclnnIndex`` (DT_COMPLEX64 input) on the 2026-09-20 PTA |
| 172 | build, which is independent of this case list. | 238 | build, which is independent of this case list. |
| @@ -176,11 +242,12 @@ def build_deepseek_v4_1_fused_test_list() -> list[OverrideDefinitions]: | |||
| 176 | "--dataloader.dataset-path=tests/assets/cc12m_test", | 242 | "--dataloader.dataset-path=tests/assets/cc12m_test", |
| 177 | "--hf-assets-path=tests/assets/deepseek_v3", | 243 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 178 | "--training.steps=2", | 244 | "--training.steps=2", |
| 179 | - "--training.seq-len=512", | 245 | + "--training.max-context-length=512", |
| 180 | "--dataloader.packing-buffer-size=4", | 246 | "--dataloader.packing-buffer-size=4", |
| 181 | "--debug.seed=42", | 247 | "--debug.seed=42", |
| 182 | "--debug.deterministic", | 248 | "--debug.deterministic", |
| 183 | - f"--training.global-batch-size={ngpu}", | 249 | + "--training.num-tokens-per-microbatch-per-dp-rank=512", |
| 250 | + f"--training.num-tokens-per-train-step={512 * ngpu}", | ||
| 184 | f"--parallelism.data-parallel-shard-degree={ngpu}", | 251 | f"--parallelism.data-parallel-shard-degree={ngpu}", |
| 185 | "--parallelism.data-parallel-replicate-degree=1", | 252 | "--parallelism.data-parallel-replicate-degree=1", |
| 186 | f"--parallelism.expert-parallel-degree={ngpu}", | 253 | f"--parallelism.expert-parallel-degree={ngpu}", |
| @@ -207,3 +274,44 @@ def build_deepseek_v4_1_fused_test_list() -> list[OverrideDefinitions]: | |||
| 207 | timeout=3600, | 274 | timeout=3600, |
| 208 | ) | 275 | ) |
| 209 | ] | 276 | ] |
| 277 | + | ||
| 278 | + | ||
| 279 | +def build_deepseek_v4_1_reference_multimodal_test_list() -> list[OverrideDefinitions]: | ||
| 280 | + args = ( | ||
| 281 | + "--override.imports", "torchtitan_npu.override.common.rope.workaround", | ||
| 282 | + "torchtitan_npu.override.common.optimizer.virtual", | ||
| 283 | + "--dataloader.dataset=cc12m-test", "--dataloader.dataset-path=tests/assets/cc12m_test", | ||
| 284 | + "--dataloader.packing-buffer-size=4", "--hf-assets-path=tests/assets/deepseek_v3", | ||
| 285 | + "--training.steps=3", "--training.max-context-length=512", | ||
| 286 | + "--training.num-tokens-per-microbatch-per-dp-rank=512", | ||
| 287 | + "--training.num-tokens-per-train-step=1024", | ||
| 288 | + "--parallelism.data-parallel-shard-degree=2", "--parallelism.expert-parallel-degree=2", | ||
| 289 | + "--parallelism.data-parallel-replicate-degree=1", "--parallelism.tensor-parallel-degree=1", | ||
| 290 | + "--parallelism.context-parallel-degree=1", "--parallelism.pipeline-parallel-degree=1", | ||
| 291 | + "--parallelism.context-parallel-load-balancer=None", "--parallelism.spmd-backend=partial_dtensor", | ||
| 292 | + "--debug.no-moe-force-load-balance", "--debug.seed=42", "--debug.deterministic", | ||
| 293 | + "--optimizer.name=AdamW", "--compile.no-enable", "--checkpoint.no-enable", | ||
| 294 | + ) | ||
| 295 | + cpt = OverrideDefinitions( | ||
| 296 | + test_name="dsv41_multimodal_cpt_reference_ep2_fsdp2", | ||
| 297 | + test_descr="V4.1 CPT reference attention with Host Engram, FullAC and virtual AdamW", | ||
| 298 | + env_vars={"MODULE": "torchtitan_npu.models.deepseek_v4_1", "CONFIG": "deepseek_v4_1_debugmodel_multimodal"}, | ||
| 299 | + override_args=[args], expected_steps=((1, 2, 3),), ngpu=2, | ||
| 300 | + use_golden=True, check_loss=False, timeout=1800, | ||
| 301 | + ) | ||
| 302 | + # The structured SFT encoder requires a matched official tokenizer/encoding pair. | ||
| 303 | + tokenizer = os.environ.get("DSV41_SFT_TOKENIZER_PATH") | ||
| 304 | + fixture = os.environ.get("DSV41_SFT_FIXTURE_PATH") | ||
| 305 | + if not tokenizer or not fixture: | ||
| 306 | + return [cpt] | ||
| 307 | + sft_args = tuple({ | ||
| 308 | + "--dataloader.packing-buffer-size=4": "--dataloader.packing-buffer-size=0", | ||
| 309 | + "--dataloader.dataset-path=tests/assets/cc12m_test": f"--dataloader.dataset-path={fixture}", | ||
| 310 | + "--hf-assets-path=tests/assets/deepseek_v3": f"--hf-assets-path={tokenizer}", | ||
| 311 | + }.get(arg, arg) for arg in args) | ||
| 312 | + sft_args = (*sft_args[:3], "torchtitan_npu.override.deepseek_v4_1.vision_language_dataloader.sft", *sft_args[3:]) | ||
| 313 | + return [cpt, replace( | ||
| 314 | + cpt, test_name="dsv41_multimodal_sft_reference_ep2_fsdp2", | ||
| 315 | + test_descr="V4.1 official-encoding SFT with Host Engram, FullAC and virtual AdamW", | ||
| 316 | + override_args=[sft_args], | ||
| 317 | + )] | ||
| @@ -11,7 +11,7 @@ from pathlib import Path | |||
| 11 | import torch.distributed.checkpoint as dcp | 11 | import torch.distributed.checkpoint as dcp |
| 12 | 12 | ||
| 13 | from tests.integration_tests import OverrideDefinitions | 13 | from tests.integration_tests import OverrideDefinitions |
| 14 | -from tests.integration_tests.deepseek_v4 import GOLDEN_OVERRIDES | 14 | +from tests.integration_tests.deepseek_v4 import GOLDEN_OVERRIDES, V4_TRAIN_ARGS |
| 15 | 15 | ||
| 16 | _EMA_CHECKPOINT_PREFIX = "ema_optimizer." | 16 | _EMA_CHECKPOINT_PREFIX = "ema_optimizer." |
| 17 | 17 | ||
| @@ -27,7 +27,7 @@ def build_ema_test_list() -> list[OverrideDefinitions]: | |||
| 27 | "--training.steps=2", | 27 | "--training.steps=2", |
| 28 | "--parallelism.expert-parallel-degree=2", | 28 | "--parallelism.expert-parallel-degree=2", |
| 29 | "--hf-assets-path=tests/assets/deepseek_v3", | 29 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 30 | - "--training.global-batch-size=2", | 30 | + "--training.num-tokens-per-train-step=4096", |
| 31 | "--ema-weights.enable", | 31 | "--ema-weights.enable", |
| 32 | "--ema-weights.decay=0.5", | 32 | "--ema-weights.decay=0.5", |
| 33 | "--ema-weights.offload-to-cpu", | 33 | "--ema-weights.offload-to-cpu", |
| @@ -39,6 +39,7 @@ def build_ema_test_list() -> list[OverrideDefinitions]: | |||
| 39 | test_descr="DeepSeek-V4 EMA EP2/FSDP2 CPU-offload checkpoint smoke", | 39 | test_descr="DeepSeek-V4 EMA EP2/FSDP2 CPU-offload checkpoint smoke", |
| 40 | test_name="dsv4_ema_ep2_fsdp2", | 40 | test_name="dsv4_ema_ep2_fsdp2", |
| 41 | ngpu=2, | 41 | ngpu=2, |
| 42 | + train_args=V4_TRAIN_ARGS, | ||
| 42 | use_golden=True, | 43 | use_golden=True, |
| 43 | check_loss=False, | 44 | check_loss=False, |
| 44 | verify_ema_checkpoint=True, | 45 | verify_ema_checkpoint=True, |
| @@ -13,6 +13,7 @@ from __future__ import annotations | |||
| 13 | 13 | ||
| 14 | import math | 14 | import math |
| 15 | import os | 15 | import os |
| 16 | +import struct | ||
| 16 | import unittest | 17 | import unittest |
| 17 | from typing import TYPE_CHECKING | 18 | from typing import TYPE_CHECKING |
| 18 | 19 | ||
| @@ -73,7 +74,7 @@ def compare_checkpoint_metrics(job_dump_folder: str | Path, expected_steps: Sequ | |||
| 73 | raise ValueError(f"{tag} phase {idx}: expected steps {list(expected_steps[idx])}, got {sorted(values)}") | 74 | raise ValueError(f"{tag} phase {idx}: expected steps {list(expected_steps[idx])}, got {sorted(values)}") |
| 74 | baseline, resumed = phases | 75 | baseline, resumed = phases |
| 75 | for step, value in resumed.items(): | 76 | for step, value in resumed.items(): |
| 76 | - if step not in baseline or baseline[step] != value: | 77 | + if step not in baseline or struct.pack("!f", baseline[step]) != struct.pack("!f", value): |
| 77 | raise AssertionError( | 78 | raise AssertionError( |
| 78 | f"{tag} mismatch at step {step}: uninterrupted={baseline.get(step)!r}, resumed={value!r}" | 79 | f"{tag} mismatch at step {step}: uninterrupted={baseline.get(step)!r}, resumed={value!r}" |
| 79 | ) | 80 | ) |
| @@ -36,6 +36,7 @@ from tests.integration_tests.deepseek_v4_1 import ( | |||
| 36 | build_deepseek_v4_1_fused_test_list, | 36 | build_deepseek_v4_1_fused_test_list, |
| 37 | build_deepseek_v4_1_golden_test_list, | 37 | build_deepseek_v4_1_golden_test_list, |
| 38 | build_deepseek_v4_1_quantized_test_list, | 38 | build_deepseek_v4_1_quantized_test_list, |
| 39 | + build_deepseek_v4_1_reference_multimodal_test_list, | ||
| 39 | build_deepseek_v4_1_test_list, | 40 | build_deepseek_v4_1_test_list, |
| 40 | ) | 41 | ) |
| 41 | from tests.integration_tests.ema import assert_ema_checkpoint_written, build_ema_test_list | 42 | from tests.integration_tests.ema import assert_ema_checkpoint_written, build_ema_test_list |
| @@ -65,6 +66,7 @@ def build_models_test_list() -> list[OverrideDefinitions]: | |||
| 65 | build_deepseek_v4_test_list() | 66 | build_deepseek_v4_test_list() |
| 66 | + build_deepseek_v4_1_test_list() | 67 | + build_deepseek_v4_1_test_list() |
| 67 | + build_deepseek_v4_1_golden_test_list() | 68 | + build_deepseek_v4_1_golden_test_list() |
| 69 | + + build_deepseek_v4_1_reference_multimodal_test_list() | ||
| 68 | + build_deepseek_v3_2_test_list() | 70 | + build_deepseek_v3_2_test_list() |
| 69 | + build_qwen3_5_test_list() | 71 | + build_qwen3_5_test_list() |
| 70 | ) | 72 | ) |
| @@ -93,6 +95,7 @@ _TEST_SUITES_FUNCTION = { | |||
| 93 | "deepseek_v4_1_fused": build_deepseek_v4_1_fused_test_list, | 95 | "deepseek_v4_1_fused": build_deepseek_v4_1_fused_test_list, |
| 94 | "deepseek_v4_1_golden": build_deepseek_v4_1_golden_test_list, | 96 | "deepseek_v4_1_golden": build_deepseek_v4_1_golden_test_list, |
| 95 | "deepseek_v4_1_quantized": build_deepseek_v4_1_quantized_test_list, | 97 | "deepseek_v4_1_quantized": build_deepseek_v4_1_quantized_test_list, |
| 98 | + "deepseek_v4_1_reference_multimodal": build_deepseek_v4_1_reference_multimodal_test_list, | ||
| 96 | "deepseek_v4_checkpoint": build_deepseek_v4_checkpoint_resume_test_list, | 99 | "deepseek_v4_checkpoint": build_deepseek_v4_checkpoint_resume_test_list, |
| 97 | "deepseek_v4_quantized": build_deepseek_v4_quantized_test_list, | 100 | "deepseek_v4_quantized": build_deepseek_v4_quantized_test_list, |
| 98 | "ema": build_ema_test_list, | 101 | "ema": build_ema_test_list, |
| @@ -396,7 +399,6 @@ DEFAULT_TRAIN_ARGS = ( | |||
| 396 | "--metrics.enable_tensorboard", | 399 | "--metrics.enable_tensorboard", |
| 397 | "--metrics.log_freq=1", | 400 | "--metrics.log_freq=1", |
| 398 | "--metrics.save_tb_folder=tb", | 401 | "--metrics.save_tb_folder=tb", |
| 399 | - "--dataloader.dataset-path=tests/assets/c4_test", | ||
| 400 | "--training.disable-cuda-graphs", | 402 | "--training.disable-cuda-graphs", |
| 401 | ) | 403 | ) |
| 402 | DETERMINISTIC_ARGS = ( | 404 | DETERMINISTIC_ARGS = ( |
| @@ -507,12 +509,12 @@ def run_single_test( | |||
| 507 | cmd += list(train_args) | 509 | cmd += list(train_args) |
| 508 | if test_flavor.check_loss or test_flavor.check_resume: | 510 | if test_flavor.check_loss or test_flavor.check_resume: |
| 509 | cmd += list(DETERMINISTIC_ARGS) | 511 | cmd += list(DETERMINISTIC_ARGS) |
| 510 | - if override_arg: | 512 | + # Keep root options before tyro subcommands in the case overrides. |
| 511 | - cmd += list(override_arg) | 513 | + # A subcommand such as activation-checkpoint:none ends root parsing. |
| 512 | - # Multi-phase cases (checkpoint resume) write each phase to its own | ||
| 513 | - # TensorBoard folder; the phase suffix overrides the default "tb". | ||
| 514 | if test_flavor.expected_steps is not None: | 514 | if test_flavor.expected_steps is not None: |
| 515 | cmd.append(f"--metrics.save_tb_folder=tb_phase_{idx}") | 515 | cmd.append(f"--metrics.save_tb_folder=tb_phase_{idx}") |
| 516 | + if override_arg: | ||
| 517 | + cmd += list(override_arg) | ||
| 516 | # Human-readable rendering for the log header and error messages: | 518 | # Human-readable rendering for the log header and error messages: |
| 517 | # the runner-controlled env settings followed by the argv command. | 519 | # the runner-controlled env settings followed by the argv command. |
| 518 | shown_cmd = ( | 520 | shown_cmd = ( |
| @@ -630,6 +632,13 @@ def _filter_tests( | |||
| 630 | continue | 632 | continue |
| 631 | if test_flavor.disabled or test_flavor.test_name in exclude_set: | 633 | if test_flavor.disabled or test_flavor.test_name in exclude_set: |
| 632 | continue | 634 | continue |
| 635 | + # This branch validates the folded-token AdamW training paths first. | ||
| 636 | + # Keep the unmigrated cases defined, with an explicit reason when a | ||
| 637 | + # default suite or a manual selector encounters one. | ||
| 638 | + migration_pending = _migration_pending_reason(test_flavor) | ||
| 639 | + if migration_pending is not None: | ||
| 640 | + log_print(f"Skipping {test_flavor.test_name}: {migration_pending}") | ||
| 641 | + continue | ||
| 633 | if args.ngpu < test_flavor.ngpu: | 642 | if args.ngpu < test_flavor.ngpu: |
| 634 | skipped_ngpu.append(test_flavor) | 643 | skipped_ngpu.append(test_flavor) |
| 635 | continue | 644 | continue |
| @@ -637,6 +646,19 @@ def _filter_tests( | |||
| 637 | return runnable, skipped_ngpu | 646 | return runnable, skipped_ngpu |
| 638 | 647 | ||
| 639 | 648 | ||
| 649 | +def _migration_pending_reason(case: OverrideDefinitions) -> str | None: | ||
| 650 | + if any(modality in case.test_name for modality in ("vision", "multimodal")): | ||
| 651 | + return "vision migration is outside the current text migration" | ||
| 652 | + if case.test_name.startswith("dsv3_2_"): | ||
| 653 | + return "DeepSeek-V3.2 model boundary still requires the folded-token migration" | ||
| 654 | + arguments = {arg for phase in case.override_args for arg in phase} | ||
| 655 | + if "--optimizer.name=Muon" in arguments: | ||
| 656 | + return "Muon migration is pending" | ||
| 657 | + if case.check_resume or case.verify_ema_checkpoint or "--checkpoint.enable" in arguments: | ||
| 658 | + return "checkpoint/EMA migration is pending" | ||
| 659 | + return None | ||
| 660 | + | ||
| 661 | + | ||
| 640 | def run_tests( | 662 | def run_tests( |
| 641 | args, | 663 | args, |
| 642 | test_list: list[OverrideDefinitions], | 664 | test_list: list[OverrideDefinitions], |
| @@ -9,7 +9,7 @@ from pathlib import Path | |||
| 9 | import torch | 9 | import torch |
| 10 | import torch.distributed as dist | 10 | import torch.distributed as dist |
| 11 | import torch.distributed.checkpoint as dcp | 11 | import torch.distributed.checkpoint as dcp |
| 12 | -from torchtitan.components.checkpoint_utils import canonical_fqn | 12 | +from torchtitan.components.checkpointer.utils import canonical_fqn |
| 13 | from torchtitan.config import derive | 13 | from torchtitan.config import derive |
| 14 | from torchtitan.tools.logging import logger | 14 | from torchtitan.tools.logging import logger |
| 15 | 15 | ||
| @@ -89,12 +89,12 @@ def _worker(folder): | |||
| 89 | rank = dist.get_rank() | 89 | rank = dist.get_rank() |
| 90 | local_rank = int(os.environ["LOCAL_RANK"]) | 90 | local_rank = int(os.environ["LOCAL_RANK"]) |
| 91 | 91 | ||
| 92 | - from torchtitan.components.checkpoint import DATALOADER, LR_SCHEDULER, MODEL, OPTIMIZER, TRAIN_STATE | 92 | + from torchtitan.components.checkpointer import DATALOADER, LR_SCHEDULER, MODEL, OPTIMIZER, TRAIN_STATE |
| 93 | + from torchtitan.models.common.moe import TokenChoiceTopKRouter | ||
| 93 | 94 | ||
| 94 | from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode | 95 | from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode |
| 95 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig | 96 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig |
| 96 | from torchtitan_npu.extensions.experiment.anticipatory_routing.detector import LossSpikeDetector | 97 | from torchtitan_npu.extensions.experiment.anticipatory_routing.detector import LossSpikeDetector |
| 97 | - from torchtitan_npu.extensions.experiment.anticipatory_routing.router import AnticipatoryHashRouter | ||
| 98 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase | 98 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase |
| 99 | from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx | 99 | from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 100 | 100 | ||
| @@ -112,7 +112,7 @@ def _worker(folder): | |||
| 112 | if rank == 0 and index in (10, 11) and index not in self.injected: | 112 | if rank == 0 and index in (10, 11) and index not in self.injected: |
| 113 | target = 1 | 113 | target = 1 |
| 114 | self.injected.add(index) | 114 | self.injected.add(index) |
| 115 | - yield {"input": inputs}, torch.tensor([[target]]) | 115 | + yield {"input": inputs, "num_valid_tokens": 1}, torch.tensor([[target]]) |
| 116 | 116 | ||
| 117 | def state_dict(self): | 117 | def state_dict(self): |
| 118 | return {"position": self.position} | 118 | return {"position": self.position} |
| @@ -126,11 +126,9 @@ def _worker(folder): | |||
| 126 | super().__init__() | 126 | super().__init__() |
| 127 | self.routers = torch.nn.ModuleList() | 127 | self.routers = torch.nn.ModuleList() |
| 128 | for _ in range(2): | 128 | for _ in range(2): |
| 129 | - router = AnticipatoryHashRouter.__new__(AnticipatoryHashRouter) | 129 | + router = TokenChoiceTopKRouter.__new__(TokenChoiceTopKRouter) |
| 130 | torch.nn.Module.__init__(router) | 130 | torch.nn.Module.__init__(router) |
| 131 | router.gate = torch.nn.Identity() | 131 | router.gate = torch.nn.Identity() |
| 132 | - router.hash = False | ||
| 133 | - router.sorted_topk = False | ||
| 134 | router.score_func = "sigmoid" | 132 | router.score_func = "sigmoid" |
| 135 | router.num_experts, router.top_k = 2, 1 | 133 | router.num_experts, router.top_k = 2, 1 |
| 136 | router.num_expert_groups = None | 134 | router.num_expert_groups = None |
| @@ -143,6 +141,9 @@ def _worker(folder): | |||
| 143 | self.replayed = [] | 141 | self.replayed = [] |
| 144 | self.trained = [] | 142 | self.trained = [] |
| 145 | 143 | ||
| 144 | + def preprocess_inputs(self, batch, **kwargs): | ||
| 145 | + return batch["input"], batch["labels"], {} | ||
| 146 | + | ||
| 146 | def forward(self, x): | 147 | def forward(self, x): |
| 147 | self.counter.add_(1) | 148 | self.counter.add_(1) |
| 148 | index = int(x[0, 0, 0].item()) - 1 | 149 | index = int(x[0, 0, 0].item()) - 1 |
| @@ -179,7 +180,7 @@ def _worker(folder): | |||
| 179 | trainer.model_parts = [model] | 180 | trainer.model_parts = [model] |
| 180 | trainer.dataloader = Loader() | 181 | trainer.dataloader = Loader() |
| 181 | trainer.gradient_accumulation_steps = 2 | 182 | trainer.gradient_accumulation_steps = 2 |
| 182 | - trainer.num_pipeline_parallel_microbatches = 1 | 183 | + trainer.num_pp_microbatches = 1 |
| 183 | trainer.config = SimpleNamespace( | 184 | trainer.config = SimpleNamespace( |
| 184 | anticipatory=AnticipatoryRoutingConfig( | 185 | anticipatory=AnticipatoryRoutingConfig( |
| 185 | enable=True, | 186 | enable=True, |
| @@ -189,6 +190,7 @@ def _worker(folder): | |||
| 189 | ), | 190 | ), |
| 190 | training=SimpleNamespace(steps=10, disable_cuda_graphs=True, max_norm=100.0), | 191 | training=SimpleNamespace(steps=10, disable_cuda_graphs=True, max_norm=100.0), |
| 191 | checkpoint=SimpleNamespace(interval=2, keep_latest_k=0), | 192 | checkpoint=SimpleNamespace(interval=2, keep_latest_k=0), |
| 193 | + parallelism=SimpleNamespace(), | ||
| 192 | ) | 194 | ) |
| 193 | trainer.parallel_dims = SimpleNamespace( | 195 | trainer.parallel_dims = SimpleNamespace( |
| 194 | pp_enabled=False, | 196 | pp_enabled=False, |
| @@ -203,6 +205,7 @@ def _worker(folder): | |||
| 203 | should_log=lambda step: False, | 205 | should_log=lambda step: False, |
| 204 | ) | 206 | ) |
| 205 | trainer.train_context = nullcontext | 207 | trainer.train_context = nullcontext |
| 208 | + trainer.sdc_replayer = None | ||
| 206 | trainer._sdc = SimpleNamespace(finalize_sdc_step=lambda: None) | 209 | trainer._sdc = SimpleNamespace(finalize_sdc_step=lambda: None) |
| 207 | trainer.optimizers = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9) | 210 | trainer.optimizers = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9) |
| 208 | trainer.lr_schedulers = Scheduler(trainer.optimizers, step_size=1, gamma=0.99) | 211 | trainer.lr_schedulers = Scheduler(trainer.optimizers, step_size=1, gamma=0.99) |
| @@ -1,4 +1,7 @@ | |||
| 1 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | 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. | ||
| 2 | 5 | ||
| 3 | from __future__ import annotations | 6 | from __future__ import annotations |
| 4 | 7 | ||
| @@ -32,6 +35,7 @@ def test_merged_gdn_forward_backward(): | |||
| 32 | assert beta_logits.grad is not None and torch.isfinite(beta_logits.grad).all() | 35 | assert beta_logits.grad is not None and torch.isfinite(beta_logits.grad).all() |
| 33 | 36 | ||
| 34 | 37 | ||
| 38 | +@pytest.mark.skip(reason="vision migration is outside the current text migration") | ||
| 35 | def test_qwen3_5_learned_position_embedding_has_npu_backward(): | 39 | def test_qwen3_5_learned_position_embedding_has_npu_backward(): |
| 36 | __import__("torchtitan_npu.models.qwen3_5") | 40 | __import__("torchtitan_npu.models.qwen3_5") |
| 37 | 41 | ||
| @@ -48,7 +52,6 @@ def test_qwen3_5_learned_position_embedding_has_npu_backward(): | |||
| 48 | output = _compute_learned_pos_embeds( | 52 | output = _compute_learned_pos_embeds( |
| 49 | pos_embed, | 53 | pos_embed, |
| 50 | [[1, 4, 4]], | 54 | [[1, 4, 4]], |
| 51 | - max_num_patch=16, | ||
| 52 | num_grid_per_side=16, | 55 | num_grid_per_side=16, |
| 53 | spatial_merge_size=2, | 56 | spatial_merge_size=2, |
| 54 | dim=8, | 57 | dim=8, |
| @@ -56,7 +59,7 @@ def test_qwen3_5_learned_position_embedding_has_npu_backward(): | |||
| 56 | output.float().sum().backward() | 59 | output.float().sum().backward() |
| 57 | torch.npu.synchronize() | 60 | torch.npu.synchronize() |
| 58 | 61 | ||
| 59 | - assert output.shape == (1, 16, 8) | 62 | + assert output.shape == (16, 8) |
| 60 | assert pos_embed.grad is not None | 63 | assert pos_embed.grad is not None |
| 61 | assert torch.isfinite(pos_embed.grad).all() | 64 | assert torch.isfinite(pos_embed.grad).all() |
| 62 | assert bool(pos_embed.grad.abs().sum() > 0) | 65 | assert bool(pos_embed.grad.abs().sum() > 0) |
| @@ -50,8 +50,8 @@ def test_config_manager_adapts_standard_component_configs_without_changing_value | |||
| 50 | hf_assets_path=str(tmp_path), | 50 | hf_assets_path=str(tmp_path), |
| 51 | dump_folder="custom-output", | 51 | dump_folder="custom-output", |
| 52 | training=UpstreamTrainingConfig( | 52 | training=UpstreamTrainingConfig( |
| 53 | - local_batch_size=3, | 53 | + num_tokens_per_microbatch_per_dp_rank=3 * 4096, |
| 54 | - seq_len=4096, | 54 | + num_tokens_per_train_step=6 * 4096, |
| 55 | steps=17, | 55 | steps=17, |
| 56 | ), | 56 | ), |
| 57 | ) | 57 | ) |
| @@ -1,3 +1,8 @@ | |||
| 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 | + | ||
| 1 | """Shared pytest fixtures for the CPU unit-test suite. | 6 | """Shared pytest fixtures for the CPU unit-test suite. |
| 2 | 7 | ||
| 3 | The plugin's model-dir and override host logic import against the real | 8 | The plugin's model-dir and override host logic import against the real |
| @@ -21,6 +26,124 @@ _REPO = Path(__file__).resolve().parents[2] | |||
| 21 | sys.path.insert(0, str(_REPO)) | 26 | sys.path.insert(0, str(_REPO)) |
| 22 | sys.path.insert(0, os.environ.get("TORCHTITAN_DIR", os.path.expanduser("~/workspace/torchtitan"))) | 27 | sys.path.insert(0, os.environ.get("TORCHTITAN_DIR", os.path.expanduser("~/workspace/torchtitan"))) |
| 23 | 28 | ||
| 29 | +# These features still use the pre-fold-batch trainer/optimizer interfaces. | ||
| 30 | +# Keep their tests out of collection until the feature itself is migrated; | ||
| 31 | +# skip marks cannot prevent imports of removed upstream symbols. | ||
| 32 | +collect_ignore = [ | ||
| 33 | + "ema", | ||
| 34 | + "extensions/experiment/cv_parallel", | ||
| 35 | + "extensions/torchtitan/experiments/graph_trainer", | ||
| 36 | + "extensions/torchtitan/experiments/torchft", | ||
| 37 | + "patches/torchft", | ||
| 38 | + "patches/torchtitan/experiments/graph_trainer", | ||
| 39 | + "test_dsv4_muon.py", | ||
| 40 | + "models/deepseek_v4_1/test_muon_profile.py", | ||
| 41 | + # Qwen runtime migration is deferred. Upstream eagerly imports CUDA-only | ||
| 42 | + # CuTeDSL code, which is not installed in the NPU test image. | ||
| 43 | + "models/qwen3_5/test_qwen3_5_npu_adapter.py", | ||
| 44 | + "override/qwen3_5/test_gated_delta.py", | ||
| 45 | + # Vision is outside the current text migration. Avoid importing its suites. | ||
| 46 | + "models/deepseek_v4_1/test_training_contract.py", | ||
| 47 | + "models/deepseek_v4_1/test_vision_attention.py", | ||
| 48 | + "models/deepseek_v4_1/test_vision_dataloader.py", | ||
| 49 | + "models/deepseek_v4_1/test_vision_language_sft.py", | ||
| 50 | + "models/deepseek_v4_1/test_vision_layout.py", | ||
| 51 | +] | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +# Mixed modules retain their text cases; entries may name a whole vision class. | ||
| 55 | +_DEFERRED_VISION_TESTS = { | ||
| 56 | + "models/qwen3_5/test_qwen3_5_torchvision_dependency.py": { | ||
| 57 | + "test_multimodal_dependency_and_package_discovery_are_explicit", | ||
| 58 | + "test_torchvision_native_image_ops_and_v2_transforms_are_available", | ||
| 59 | + "test_qwen3_5_adapter_uses_real_torchvision_without_compat_modules", | ||
| 60 | + }, | ||
| 61 | + "models/deepseek_v4_1/test_baseline_contract.py": { | ||
| 62 | + "test_v41_moe_rides_the_common_stack_with_an_opt_in_vision_bias", | ||
| 63 | + "test_vision_bias_follows_the_factory_switch", | ||
| 64 | + }, | ||
| 65 | + "models/deepseek_v4_1/test_engram.py": { | ||
| 66 | + "test_image_tokens_reset_hash_history_and_receive_no_residual_gradient", | ||
| 67 | + }, | ||
| 68 | + "models/deepseek_v4_1/test_grain_metadata.py": { | ||
| 69 | + "test_multimodal_preprocess_annotates_vision_inputs", | ||
| 70 | + }, | ||
| 71 | + "models/deepseek_v4_1/test_model_split.py": { | ||
| 72 | + "test_only_the_multimodal_half_carries_vision_parameters", | ||
| 73 | + "test_multimodal_rejects_context_parallel", | ||
| 74 | + "test_parallelize_asks_the_multimodal_stack_for_both_hooks", | ||
| 75 | + "test_multimodal_ac_hook_wraps_every_vision_block", | ||
| 76 | + }, | ||
| 77 | + "models/deepseek_v4_1/test_rms_norm.py": { | ||
| 78 | + "test_override_reaches_vision_and_preserves_parameter_names", | ||
| 79 | + }, | ||
| 80 | + "models/deepseek_v4_1/test_state_dict_adapter.py": { | ||
| 81 | + "TestVisionAdapterOwnership", | ||
| 82 | + "TestComposedAdapterPartition", | ||
| 83 | + "TestAdapterPartitionIsTotal", | ||
| 84 | + }, | ||
| 85 | + "models/deepseek_v4_1/test_v41_lora.py": { | ||
| 86 | + "test_multimodal_lora_updates_adapters_with_frozen_vision_and_engram", | ||
| 87 | + }, | ||
| 88 | + "patches/torchtitan/models/common/test_hash_moe_counts.py": { | ||
| 89 | + "test_moe_forwards_image_mask_to_router", | ||
| 90 | + }, | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | + | ||
| 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 | ||
| 96 | +# entry's positions unpack and the decoder config's context-length knob. Match | ||
| 97 | +# the integration runner's dsv3_2 deferral until the folded-token migration lands. | ||
| 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": { | ||
| 103 | + "test_dsv32_mtp_keeps_community_cp_restriction", | ||
| 104 | + }, | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def pytest_collection_modifyitems(items): | ||
| 109 | + for item in items: | ||
| 110 | + if not item.path.is_relative_to(_REPO / "tests/unit_tests"): | ||
| 111 | + continue | ||
| 112 | + relative_path = item.path.relative_to(_REPO / "tests/unit_tests").as_posix() | ||
| 113 | + vision_names = _DEFERRED_VISION_TESTS.get(relative_path, ()) | ||
| 114 | + is_vision = any(getattr(node, "originalname", node.name) in vision_names for node in item.listchain()) | ||
| 115 | + if relative_path.startswith("models/deepseek_v4_1/"): | ||
| 116 | + params = getattr(getattr(item, "callspec", None), "params", {}) | ||
| 117 | + is_vision |= ( | ||
| 118 | + params.get("vision") is True | ||
| 119 | + or params.get("multimodal") is True | ||
| 120 | + or params.get("modality") == "multimodal" | ||
| 121 | + or ( | ||
| 122 | + relative_path == "models/deepseek_v4_1/test_v41_lora.py" | ||
| 123 | + and params.get("flavor") == "deepseek_v4_1_debugmodel" | ||
| 124 | + ) | ||
| 125 | + or getattr(params.get("factory"), "__name__", "").endswith("_multimodal") | ||
| 126 | + or params.get("image_mask") is not None | ||
| 127 | + ) | ||
| 128 | + if relative_path == "models/deepseek_v4_1/test_router.py": | ||
| 129 | + settings = params.get("settings", {}) | ||
| 130 | + # Hash routing discards the vision flag and uses token IDs. | ||
| 131 | + is_vision |= settings.get("vision_enabled", False) and not settings.get("hash", False) | ||
| 132 | + if is_vision: | ||
| 133 | + item.add_marker(pytest.mark.skip(reason="vision migration is outside the current text migration")) | ||
| 134 | + if getattr(item, "originalname", item.name) in _DEFERRED_DSV32_FOLD_TESTS.get(relative_path, ()): | ||
| 135 | + item.add_marker( | ||
| 136 | + pytest.mark.skip(reason="DeepSeek-V3.2 model boundary still requires the folded-token migration") | ||
| 137 | + ) | ||
| 138 | + # Checkpoint resume and Muon are deliberately deferred on this branch. | ||
| 139 | + if "muon" in item.name.lower() or item.name.startswith( | ||
| 140 | + ( | ||
| 141 | + "test_lora_training_freezes_engram_and_native_dcp_resumes", | ||
| 142 | + "test_v41_adapter_only_resume_restores_engram_and_next_step", | ||
| 143 | + ) | ||
| 144 | + ): | ||
| 145 | + item.add_marker(pytest.mark.skip(reason="checkpoint/Muon migration is pending")) | ||
| 146 | + | ||
| 24 | 147 | ||
| 25 | # --------------------------------------------------------------------------- | 148 | # --------------------------------------------------------------------------- |
| 26 | # The NPU-bound seam: a fake ``cann_ops_transformer`` call recorder. | 149 | # The NPU-bound seam: a fake ``cann_ops_transformer`` call recorder. |
| @@ -103,7 +103,7 @@ def _load_checkpoint_conversion_module() -> types.ModuleType: | |||
| 103 | 103 | ||
| 104 | @pytest.fixture | 104 | @pytest.fixture |
| 105 | def isolated_ema_environment(): | 105 | def isolated_ema_environment(): |
| 106 | - import torchtitan.components.checkpoint as upstream_checkpoint | 106 | + import torchtitan.components.checkpointer as upstream_checkpoint |
| 107 | import torchtitan.components.checkpointer as upstream_checkpointer | 107 | import torchtitan.components.checkpointer as upstream_checkpointer |
| 108 | import torchtitan.trainer as upstream_trainer | 108 | import torchtitan.trainer as upstream_trainer |
| 109 | 109 | ||
| @@ -508,7 +508,7 @@ def test_ema_schema_is_inherited_by_npu_trainer_ex_config() -> None: | |||
| 508 | from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx | 508 | from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 509 | from torchtitan_npu.patches.torchtitan import trainer as trainer_module | 509 | from torchtitan_npu.patches.torchtitan import trainer as trainer_module |
| 510 | from torchtitan_npu.patches.torchtitan.components.checkpoint import EMACheckpointManager | 510 | from torchtitan_npu.patches.torchtitan.components.checkpoint import EMACheckpointManager |
| 511 | - import torchtitan.components.checkpoint as upstream_checkpoint | 511 | + import torchtitan.components.checkpointer as upstream_checkpoint |
| 512 | import torchtitan.trainer as upstream_trainer | 512 | import torchtitan.trainer as upstream_trainer |
| 513 | from torchtitan.experiments.graph_trainer.trainer import GraphTrainer | 513 | from torchtitan.experiments.graph_trainer.trainer import GraphTrainer |
| 514 | 514 | ||
| @@ -621,13 +621,11 @@ def test_v4_quantized_indexer_adapter_preserves_backward_record_and_frames(conve | |||
| 621 | AscSparseAttentionMetadata, | 621 | AscSparseAttentionMetadata, |
| 622 | ) | 622 | ) |
| 623 | 623 | ||
| 624 | - positions = torch.arange(8).unsqueeze(0) | 624 | + positions = torch.arange(8) |
| 625 | row = build_v4_metadata(positions, ratio=4, build_slots=False) | 625 | row = build_v4_metadata(positions, ratio=4, build_slots=False) |
| 626 | forward_record = torch.tensor([7], dtype=torch.int32) | 626 | forward_record = torch.tensor([7], dtype=torch.int32) |
| 627 | backward_record = torch.tensor([9], dtype=torch.int32) | 627 | backward_record = torch.tensor([9], dtype=torch.int32) |
| 628 | metadata = QuantV4Metadata( | 628 | metadata = QuantV4Metadata( |
| 629 | - cu_seq_q=row.cu_seq_q, | ||
| 630 | - cu_seq_k=row.cu_seq_k, | ||
| 631 | ratio=row.ratio, | 629 | ratio=row.ratio, |
| 632 | position_k=row.position_k, | 630 | position_k=row.position_k, |
| 633 | q=row.q, | 631 | q=row.q, |
| @@ -641,9 +639,9 @@ def test_v4_quantized_indexer_adapter_preserves_backward_record_and_frames(conve | |||
| 641 | lightning_indexer=AscLightningIndexerMetadata(fwd=forward_record, bwd=backward_record), | 639 | lightning_indexer=AscLightningIndexerMetadata(fwd=forward_record, bwd=backward_record), |
| 642 | ), | 640 | ), |
| 643 | ) | 641 | ) |
| 644 | - query = torch.zeros(1, 8, 2, 4, dtype=torch.bfloat16) | 642 | + query = torch.zeros(8, 2, 4, dtype=torch.bfloat16) |
| 645 | - key = torch.zeros(1, 2, 4, dtype=torch.bfloat16) | 643 | + key = torch.zeros(2, 4, dtype=torch.bfloat16) |
| 646 | - weights = torch.zeros(1, 8, 2, dtype=torch.bfloat16) | 644 | + weights = torch.zeros(8, 2, dtype=torch.bfloat16) |
| 647 | 645 | ||
| 648 | inputs = converter_module._prepare_quant_lightning_indexer_inputs( | 646 | inputs = converter_module._prepare_quant_lightning_indexer_inputs( |
| 649 | SimpleNamespace(index_topk=4), query, key, weights, metadata | 647 | SimpleNamespace(index_topk=4), query, key, weights, metadata |
| @@ -655,6 +653,6 @@ def test_v4_quantized_indexer_adapter_preserves_backward_record_and_frames(conve | |||
| 655 | assert inputs.metadata is forward_record and inputs.backward_metadata is backward_record | 653 | assert inputs.metadata is forward_record and inputs.backward_metadata is backward_record |
| 656 | assert inputs.seqused_q is metadata.q.seqused | 654 | assert inputs.seqused_q is metadata.q.seqused |
| 657 | assert inputs.seqused_k is metadata.cmp_k.seqused | 655 | assert inputs.seqused_k is metadata.cmp_k.seqused |
| 658 | - assert inputs.cu_seqlens_q is row.cu_seq_q | 656 | + assert inputs.cu_seqlens_q is row.q.cu_seqlens |
| 659 | assert inputs.cu_seqlens_k is row.cmp_k.cu_seqlens | 657 | assert inputs.cu_seqlens_k is row.cmp_k.cu_seqlens |
| 660 | assert inputs.cmp_residual_k is row.cmp_k.residual | 658 | assert inputs.cmp_residual_k is row.cmp_k.residual |
| @@ -81,7 +81,7 @@ class _AsyncCheckpointManager: | |||
| 81 | return self.checkpoint_path | 81 | return self.checkpoint_path |
| 82 | 82 | ||
| 83 | 83 | ||
| 84 | -checkpoint_stub = types.ModuleType("torchtitan.components.checkpoint") | 84 | +checkpoint_stub = types.ModuleType("torchtitan.components.checkpointer") |
| 85 | checkpoint_stub.AsyncMode = _AsyncMode | 85 | checkpoint_stub.AsyncMode = _AsyncMode |
| 86 | tools_stub = types.ModuleType("torchtitan.tools") | 86 | tools_stub = types.ModuleType("torchtitan.tools") |
| 87 | tools_stub.filesystem = _FilesystemAdapter | 87 | tools_stub.filesystem = _FilesystemAdapter |
| @@ -93,7 +93,7 @@ product_validation = importlib.util.module_from_spec(module_spec) | |||
| 93 | with patch.dict( | 93 | with patch.dict( |
| 94 | sys.modules, | 94 | sys.modules, |
| 95 | { | 95 | { |
| 96 | - "torchtitan.components.checkpoint": checkpoint_stub, | 96 | + "torchtitan.components.checkpointer": checkpoint_stub, |
| 97 | "torchtitan.tools": tools_stub, | 97 | "torchtitan.tools": tools_stub, |
| 98 | }, | 98 | }, |
| 99 | ): | 99 | ): |
| @@ -12,14 +12,13 @@ from types import SimpleNamespace | |||
| 12 | import pytest | 12 | import pytest |
| 13 | import torch | 13 | import torch |
| 14 | from torch import nn | 14 | from torch import nn |
| 15 | +from torchtitan.models.common.moe import TokenChoiceTopKRouter | ||
| 15 | 16 | ||
| 16 | -from torchtitan_npu.extensions.torchtitan.trainer import Trainer, TrainerEx | ||
| 17 | from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode | 17 | from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode |
| 18 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig | 18 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig |
| 19 | - | ||
| 20 | from torchtitan_npu.extensions.experiment.anticipatory_routing.router import build_routing_cache | 19 | from torchtitan_npu.extensions.experiment.anticipatory_routing.router import build_routing_cache |
| 21 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase | 20 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase |
| 22 | -from torchtitan_npu.extensions.experiment.anticipatory_routing.router import AnticipatoryHashRouter | 21 | +from torchtitan_npu.extensions.torchtitan.trainer import Trainer, TrainerEx |
| 23 | 22 | ||
| 24 | 23 | ||
| 25 | class Scheduler(torch.optim.lr_scheduler.StepLR): | 24 | class Scheduler(torch.optim.lr_scheduler.StepLR): |
| @@ -37,7 +36,7 @@ class Loader: | |||
| 37 | for i in range(self.position, self.size): | 36 | for i in range(self.position, self.size): |
| 38 | self.position = i + 1 | 37 | self.position = i + 1 |
| 39 | self.reads.append(i) | 38 | self.reads.append(i) |
| 40 | - yield [{"input": torch.tensor([[[i + 1.0, 0.0]]])}, torch.tensor([[i]])] | 39 | + yield [{"input": torch.tensor([[[i + 1.0, 0.0]]]), "num_valid_tokens": 1}, torch.tensor([[i]])] |
| 41 | 40 | ||
| 42 | def state_dict(self): | 41 | def state_dict(self): |
| 43 | return {"position": self.position} | 42 | return {"position": self.position} |
| @@ -49,11 +48,9 @@ class Loader: | |||
| 49 | class Model(nn.Module): | 48 | class Model(nn.Module): |
| 50 | def __init__(self): | 49 | def __init__(self): |
| 51 | super().__init__() | 50 | super().__init__() |
| 52 | - router = AnticipatoryHashRouter.__new__(AnticipatoryHashRouter) | 51 | + router = TokenChoiceTopKRouter.__new__(TokenChoiceTopKRouter) |
| 53 | nn.Module.__init__(router) | 52 | nn.Module.__init__(router) |
| 54 | router.gate = nn.Identity() | 53 | router.gate = nn.Identity() |
| 55 | - router.hash = False | ||
| 56 | - router.sorted_topk = False | ||
| 57 | router.score_func = "sigmoid" | 54 | router.score_func = "sigmoid" |
| 58 | router.num_experts, router.top_k = 2, 1 | 55 | router.num_experts, router.top_k = 2, 1 |
| 59 | router.num_expert_groups = None | 56 | router.num_expert_groups = None |
| @@ -64,12 +61,39 @@ class Model(nn.Module): | |||
| 64 | self.register_buffer("counter", torch.tensor(0.0)) | 61 | self.register_buffer("counter", torch.tensor(0.0)) |
| 65 | 62 | ||
| 66 | 63 | ||
| 64 | + def preprocess_inputs(self, batch, **kwargs): | ||
| 65 | + return batch["input"], batch["labels"], {} | ||
| 66 | + | ||
| 67 | def forward(self, x): | 67 | def forward(self, x): |
| 68 | self.counter.add_(1) | 68 | self.counter.add_(1) |
| 69 | self.router(x) | 69 | self.router(x) |
| 70 | return x * self.weight | 70 | return x * self.weight |
| 71 | 71 | ||
| 72 | 72 | ||
| 73 | +def test_forward_only_preserves_batch_and_forwards_model_metadata(): | ||
| 74 | + from torchtitan_npu.extensions.experiment.anticipatory_routing.engine import AnticipatoryTrainingEngine | ||
| 75 | + | ||
| 76 | + class ForwardModel(nn.Module): | ||
| 77 | + def preprocess_inputs(self, batch, **kwargs): | ||
| 78 | + return batch.pop("input"), batch.pop("labels"), batch | ||
| 79 | + | ||
| 80 | + def forward(self, inputs, *, positions): | ||
| 81 | + self.seen = (inputs, positions) | ||
| 82 | + | ||
| 83 | + model = ForwardModel() | ||
| 84 | + engine = object.__new__(AnticipatoryTrainingEngine) | ||
| 85 | + engine.trainer = SimpleNamespace( | ||
| 86 | + model_parts=[model], device=torch.device("cpu"), ntokens_seen=0, | ||
| 87 | + train_context=nullcontext, parallel_dims=SimpleNamespace(), config=SimpleNamespace(parallelism=None), | ||
| 88 | + ) | ||
| 89 | + inputs, positions, labels = torch.tensor([1]), torch.tensor([2]), torch.tensor([3]) | ||
| 90 | + batch = ({"input": inputs, "positions": positions, "num_valid_tokens": 1}, labels) | ||
| 91 | + engine.forward_only_microbatch(batch) | ||
| 92 | + torch.testing.assert_close(model.seen, (inputs, positions)) | ||
| 93 | + assert batch[0]["num_valid_tokens"] == 1 | ||
| 94 | + assert set(batch[0]) == {"input", "positions", "num_valid_tokens"} | ||
| 95 | + | ||
| 96 | + | ||
| 73 | def make_trainer(monkeypatch, *, delay=2, active=3, size=40, steps=10, device="cpu", compile_backend=None): | 97 | def make_trainer(monkeypatch, *, delay=2, active=3, size=40, steps=10, device="cpu", compile_backend=None): |
| 74 | trainer = object.__new__(TrainerEx) | 98 | trainer = object.__new__(TrainerEx) |
| 75 | trainer.device = torch.device(device) | 99 | trainer.device = torch.device(device) |
| @@ -80,9 +104,9 @@ def make_trainer(monkeypatch, *, delay=2, active=3, size=40, steps=10, device="c | |||
| 80 | enable=True, delay_steps=delay, active_steps=active | 104 | enable=True, delay_steps=delay, active_steps=active |
| 81 | ) | 105 | ) |
| 82 | trainer.config = SimpleNamespace( | 106 | trainer.config = SimpleNamespace( |
| 83 | - anticipatory=config, training=SimpleNamespace(steps=steps, disable_cuda_graphs=True, max_norm=100.0), checkpoint=SimpleNamespace(interval=2, keep_latest_k=0) | 107 | + anticipatory=config, training=SimpleNamespace(steps=steps, disable_cuda_graphs=True, max_norm=100.0), checkpoint=SimpleNamespace(interval=2, keep_latest_k=0), parallelism=SimpleNamespace() |
| 84 | ) | 108 | ) |
| 85 | - trainer.gradient_accumulation_steps, trainer.num_pipeline_parallel_microbatches = 2, 1 | 109 | + trainer.gradient_accumulation_steps, trainer.num_pp_microbatches = 2, 1 |
| 86 | trainer.parallel_dims = SimpleNamespace( | 110 | trainer.parallel_dims = SimpleNamespace( |
| 87 | pp_enabled=False, dp_enabled=False, ep_enabled=False, dp_cp_enabled=False, get_optional_mesh=lambda name: None | 111 | pp_enabled=False, dp_enabled=False, ep_enabled=False, dp_cp_enabled=False, get_optional_mesh=lambda name: None |
| 88 | ) | 112 | ) |
| @@ -90,6 +114,7 @@ def make_trainer(monkeypatch, *, delay=2, active=3, size=40, steps=10, device="c | |||
| 90 | ntokens_since_last_log=0, data_loading_times=[], should_log=lambda step: False | 114 | ntokens_since_last_log=0, data_loading_times=[], should_log=lambda step: False |
| 91 | ) | 115 | ) |
| 92 | trainer.train_context = nullcontext | 116 | trainer.train_context = nullcontext |
| 117 | + trainer.sdc_replayer = None | ||
| 93 | trainer._sdc = SimpleNamespace(finalize_sdc_step=lambda: None) | 118 | trainer._sdc = SimpleNamespace(finalize_sdc_step=lambda: None) |
| 94 | # Avoid torch_npu's automatic optimizer backend probe in CPU-only CI. | 119 | # Avoid torch_npu's automatic optimizer backend probe in CPU-only CI. |
| 95 | trainer.optimizers = torch.optim.SGD( | 120 | trainer.optimizers = torch.optim.SGD( |
| @@ -439,7 +464,8 @@ def test_recording_failure_resets_routing_before_next_forward(monkeypatch, stage | |||
| 439 | 464 | ||
| 440 | 465 | ||
| 441 | def test_rollback_target_skips_checkpoint_without_optimizer(monkeypatch, tmp_path): | 466 | def test_rollback_target_skips_checkpoint_without_optimizer(monkeypatch, tmp_path): |
| 442 | - from torchtitan.components.checkpoint import MODEL, OPTIMIZER | 467 | + from torchtitan.components.checkpointer import MODEL, OPTIMIZER |
| 468 | + | ||
| 443 | from torchtitan_npu.extensions.experiment.anticipatory_routing import engine as engine_module | 469 | from torchtitan_npu.extensions.experiment.anticipatory_routing import engine as engine_module |
| 444 | 470 | ||
| 445 | trainer, _ = make_trainer(monkeypatch) | 471 | trainer, _ = make_trainer(monkeypatch) |
| @@ -516,7 +542,7 @@ def test_routing_operation_controls_capture_and_replay(monkeypatch, backend, cap | |||
| 516 | cache.reset() | 542 | cache.reset() |
| 517 | torch.testing.assert_close(actual, expected, rtol=0, atol=0) | 543 | torch.testing.assert_close(actual, expected, rtol=0, atol=0) |
| 518 | torch.testing.assert_close(slot[router._anticipatory_key], expected.to(torch.int16), rtol=0, atol=0) | 544 | torch.testing.assert_close(slot[router._anticipatory_key], expected.to(torch.int16), rtol=0, atol=0) |
| 519 | - buffer = router._anticipatory_replay_buffer | 545 | + buffer = cache.replay_buffers[router._anticipatory_key] |
| 520 | recording = buffer.capture_indices.clone() | 546 | recording = buffer.capture_indices.clone() |
| 521 | 547 | ||
| 522 | try: | 548 | try: |
| @@ -551,8 +577,8 @@ def test_compiled_routes_share_graphs_across_layers_modes_and_microbatches( | |||
| 551 | monkeypatch, full_ac, compile_every, *, device="cpu", backend_name="aot_eager" | 577 | monkeypatch, full_ac, compile_every, *, device="cpu", backend_name="aot_eager" |
| 552 | ): | 578 | ): |
| 553 | """Forty distinct router keys must not require forty compiled variants.""" | 579 | """Forty distinct router keys must not require forty compiled variants.""" |
| 554 | - from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper | ||
| 555 | from torch._dynamo.backends.registry import lookup_backend | 580 | from torch._dynamo.backends.registry import lookup_backend |
| 581 | + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper | ||
| 556 | from torch.utils.checkpoint import DefaultDeviceType | 582 | from torch.utils.checkpoint import DefaultDeviceType |
| 557 | 583 | ||
| 558 | from torchtitan_npu.extensions.experiment.anticipatory_routing.engine import AnticipatoryTrainingEngine | 584 | from torchtitan_npu.extensions.experiment.anticipatory_routing.engine import AnticipatoryTrainingEngine |
| @@ -588,6 +614,9 @@ def test_compiled_routes_share_graphs_across_layers_modes_and_microbatches( | |||
| 588 | checkpoint_wrapper(Block()) if full_ac else Block() for _ in range(40) | 614 | checkpoint_wrapper(Block()) if full_ac else Block() for _ in range(40) |
| 589 | ]) | 615 | ]) |
| 590 | 616 | ||
| 617 | + def preprocess_inputs(self, batch, **kwargs): | ||
| 618 | + return batch["input"], batch["labels"], {} | ||
| 619 | + | ||
| 591 | def forward(self, x): | 620 | def forward(self, x): |
| 592 | for layer in self.layers: | 621 | for layer in self.layers: |
| 593 | x = layer(x) | 622 | x = layer(x) |
| @@ -614,7 +643,7 @@ def test_compiled_routes_share_graphs_across_layers_modes_and_microbatches( | |||
| 614 | engine = object.__new__(AnticipatoryTrainingEngine) | 643 | engine = object.__new__(AnticipatoryTrainingEngine) |
| 615 | engine.trainer = SimpleNamespace( | 644 | engine.trainer = SimpleNamespace( |
| 616 | model_parts=[module], device=torch.device(device), ntokens_seen=0, | 645 | model_parts=[module], device=torch.device(device), ntokens_seen=0, |
| 617 | - train_context=nullcontext, | 646 | + train_context=nullcontext, parallel_dims=SimpleNamespace(), config=SimpleNamespace(parallelism=SimpleNamespace()), |
| 618 | post_dataloading_process=lambda inputs, labels: (inputs["input"], labels, {}), | 647 | post_dataloading_process=lambda inputs, labels: (inputs["input"], labels, {}), |
| 619 | ) | 648 | ) |
| 620 | return engine | 649 | return engine |
| @@ -765,7 +794,7 @@ def test_capture_compile_failure_preserves_upstream_entry_and_state(): | |||
| 765 | engine = object.__new__(AnticipatoryTrainingEngine) | 794 | engine = object.__new__(AnticipatoryTrainingEngine) |
| 766 | engine.trainer = SimpleNamespace( | 795 | engine.trainer = SimpleNamespace( |
| 767 | model_parts=[model], device=torch.device("cpu"), ntokens_seen=7, | 796 | model_parts=[model], device=torch.device("cpu"), ntokens_seen=7, |
| 768 | - train_context=nullcontext, | 797 | + train_context=nullcontext, parallel_dims=SimpleNamespace(), config=SimpleNamespace(parallelism=SimpleNamespace()), |
| 769 | post_dataloading_process=lambda inputs, labels: (inputs["input"], labels, {}), | 798 | post_dataloading_process=lambda inputs, labels: (inputs["input"], labels, {}), |
| 770 | ) | 799 | ) |
| 771 | batch = ({"input": torch.ones(1, 3, 2)}, torch.zeros(1)) | 800 | batch = ({"input": torch.ones(1, 3, 2)}, torch.zeros(1)) |
| @@ -811,7 +840,7 @@ def test_compiled_capture_preserves_hooks_and_rng(): | |||
| 811 | engine = object.__new__(AnticipatoryTrainingEngine) | 840 | engine = object.__new__(AnticipatoryTrainingEngine) |
| 812 | engine.trainer = SimpleNamespace( | 841 | engine.trainer = SimpleNamespace( |
| 813 | model_parts=[model], device=torch.device("cpu"), ntokens_seen=7, | 842 | model_parts=[model], device=torch.device("cpu"), ntokens_seen=7, |
| 814 | - train_context=nullcontext, | 843 | + train_context=nullcontext, parallel_dims=SimpleNamespace(), config=SimpleNamespace(parallelism=SimpleNamespace()), |
| 815 | post_dataloading_process=lambda inputs, labels: (inputs["input"], labels, {}), | 844 | post_dataloading_process=lambda inputs, labels: (inputs["input"], labels, {}), |
| 816 | ) | 845 | ) |
| 817 | batch = ({"input": torch.tensor([[[2.0, -2.0]]])}, torch.zeros(1)) | 846 | batch = ({"input": torch.tensor([[[2.0, -2.0]]])}, torch.zeros(1)) |
| @@ -924,7 +953,7 @@ def test_compiled_capture_keeps_disabled_hooks_outside_graph(monkeypatch, full_a | |||
| 924 | engine = object.__new__(AnticipatoryTrainingEngine) | 953 | engine = object.__new__(AnticipatoryTrainingEngine) |
| 925 | engine.trainer = SimpleNamespace( | 954 | engine.trainer = SimpleNamespace( |
| 926 | model_parts=[model], device=torch.device("cpu"), ntokens_seen=7, | 955 | model_parts=[model], device=torch.device("cpu"), ntokens_seen=7, |
| 927 | - train_context=nullcontext, | 956 | + train_context=nullcontext, parallel_dims=SimpleNamespace(), config=SimpleNamespace(parallelism=SimpleNamespace()), |
| 928 | post_dataloading_process=lambda inputs, labels: (inputs["input"], labels, {}), | 957 | post_dataloading_process=lambda inputs, labels: (inputs["input"], labels, {}), |
| 929 | ) | 958 | ) |
| 930 | batch = ({"input": torch.tensor([[[2.0, -2.0]]])}, torch.zeros(1)) | 959 | batch = ({"input": torch.tensor([[[2.0, -2.0]]])}, torch.zeros(1)) |
| @@ -0,0 +1,161 @@ | |||
| 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 | +"""Real token-sharded Gloo routing through initialization, capture and replay.""" | ||
| 7 | + | ||
| 8 | +import torch | ||
| 9 | +import torch.distributed as dist | ||
| 10 | +import torch.multiprocessing as mp | ||
| 11 | +import torch.nn.functional as F | ||
| 12 | +from torch.distributed.device_mesh import init_device_mesh | ||
| 13 | +from torch.distributed.tensor import DTensor, Replicate, Shard, distribute_tensor | ||
| 14 | + | ||
| 15 | +from torchtitan_npu.extensions.experiment.anticipatory_routing.router import build_routing_cache | ||
| 16 | +from torchtitan_npu.models.deepseek_v4_1.moe import DeepSeekV41Router | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def _router(): | ||
| 20 | + from torchtitan.models.common.linear import Linear | ||
| 21 | + from torchtitan.models.common.moe import GroupedExperts, MoE, RoutedExperts | ||
| 22 | + | ||
| 23 | + from torchtitan_npu.patches.torchtitan.models.common.token_dispatcher import LocalTokenDispatcher | ||
| 24 | + | ||
| 25 | + config = MoE.Config( | ||
| 26 | + num_experts=4, | ||
| 27 | + router=DeepSeekV41Router.Config( | ||
| 28 | + num_experts=4, | ||
| 29 | + gate=Linear.Config(in_features=4, out_features=4), | ||
| 30 | + top_k=2, | ||
| 31 | + sorted_topk=True, | ||
| 32 | + route_norm=True, | ||
| 33 | + route_scale=1.4, | ||
| 34 | + ), | ||
| 35 | + routed_experts=RoutedExperts.Config( | ||
| 36 | + inner_experts=GroupedExperts.Config(dim=4, hidden_dim=4, num_experts=4), | ||
| 37 | + token_dispatcher=LocalTokenDispatcher.Config(num_experts=4, top_k=2), | ||
| 38 | + ), | ||
| 39 | + ) | ||
| 40 | + with torch.random.fork_rng(devices=[]): | ||
| 41 | + result = config.router.build() | ||
| 42 | + assert isinstance(result, DeepSeekV41Router) | ||
| 43 | + return result | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _replay_worker(rank, rendezvous): | ||
| 47 | + from torchtitan.distributed.utils import set_spmd_backend | ||
| 48 | + | ||
| 49 | + torch.set_num_threads(1) | ||
| 50 | + set_spmd_backend("partial_dtensor") | ||
| 51 | + dist.init_process_group("gloo", init_method=f"file://{rendezvous}", rank=rank, world_size=2) | ||
| 52 | + cache = None | ||
| 53 | + try: | ||
| 54 | + mesh = init_device_mesh("cpu", (2,), mesh_dim_names=("tp",)) | ||
| 55 | + inputs = torch.tensor( | ||
| 56 | + [ | ||
| 57 | + [1.0, 0.2, -0.5, 0.7], | ||
| 58 | + [-0.3, 1.4, 0.6, -0.2], | ||
| 59 | + [0.8, -0.7, 1.1, 0.4], | ||
| 60 | + [-0.9, 0.1, 0.3, 1.5], | ||
| 61 | + [0.4, 0.9, -1.2, 0.5], | ||
| 62 | + [1.3, -0.4, 0.2, -0.6], | ||
| 63 | + ] | ||
| 64 | + ) | ||
| 65 | + capture_weight = torch.tensor( | ||
| 66 | + [[0.7, -0.2, 0.5, 0.1], [-0.4, 0.8, 0.2, -0.6], [0.3, 0.1, -0.7, 0.9], [-0.8, -0.5, 0.6, 0.4]] | ||
| 67 | + ) | ||
| 68 | + router = _router() | ||
| 69 | + router.gate.weight = torch.nn.Parameter(distribute_tensor(capture_weight.clone(), mesh, [Replicate()])) | ||
| 70 | + sharded_inputs = distribute_tensor(inputs.clone(), mesh, [Shard(0)]).requires_grad_() | ||
| 71 | + cache = build_routing_cache([router], index_store_dtype="int16", device=torch.device("cpu")) | ||
| 72 | + key = router._anticipatory_key | ||
| 73 | + buffer = cache.replay_buffers[key] | ||
| 74 | + dense_capture = F.linear(inputs, capture_weight).sigmoid() | ||
| 75 | + expected_ids = torch.tensor( | ||
| 76 | + [sorted(range(4), key=lambda expert: row[expert], reverse=True)[:2] for row in dense_capture.tolist()] | ||
| 77 | + ) | ||
| 78 | + row = slice(rank * 3, (rank + 1) * 3) | ||
| 79 | + with torch.no_grad(): | ||
| 80 | + cache.begin_initialization() | ||
| 81 | + try: | ||
| 82 | + _, initial_ids, _ = router(sharded_inputs) | ||
| 83 | + finally: | ||
| 84 | + cache.reset() | ||
| 85 | + assert isinstance(initial_ids, DTensor) | ||
| 86 | + assert initial_ids.shape == (6, 2) and initial_ids.placements == (Shard(0),) | ||
| 87 | + torch.testing.assert_close(initial_ids.full_tensor(), expected_ids, rtol=0, atol=0) | ||
| 88 | + assert buffer.indices.shape == buffer.capture_indices.shape == (3, 2) | ||
| 89 | + assert not isinstance(buffer.indices, DTensor) | ||
| 90 | + slot = {} | ||
| 91 | + cache.begin_capture(slot) | ||
| 92 | + try: | ||
| 93 | + router(sharded_inputs) | ||
| 94 | + cache.save_captured_routes() | ||
| 95 | + finally: | ||
| 96 | + cache.reset() | ||
| 97 | + assert slot[key].shape == (3, 2) and slot[key].dtype == torch.int16 | ||
| 98 | + torch.testing.assert_close(slot[key].long(), expected_ids[row], rtol=0, atol=0) | ||
| 99 | + # The live top-2 changes to its complement, so replay cannot pass by | ||
| 100 | + # accidentally returning the newly computed IDs or old gate scores. | ||
| 101 | + router.gate.weight.to_local().copy_(-capture_weight) | ||
| 102 | + | ||
| 103 | + cache.begin_training([slot]) | ||
| 104 | + cache.select(0) | ||
| 105 | + selected, replay_ids, scores = router(sharded_inputs) | ||
| 106 | + assert isinstance(replay_ids, DTensor) | ||
| 107 | + assert replay_ids.device_mesh == mesh and replay_ids.placements == (Shard(0),) | ||
| 108 | + assert replay_ids.shape == (6, 2) and replay_ids.to_local().shape == (3, 2) | ||
| 109 | + torch.testing.assert_close(replay_ids.full_tensor(), expected_ids, rtol=0, atol=0) | ||
| 110 | + live_scores = F.linear(inputs, -capture_weight).sigmoid() | ||
| 111 | + assert not torch.equal(live_scores.topk(2, -1).indices, expected_ids) | ||
| 112 | + reference_selected = live_scores.gather(-1, expected_ids) | ||
| 113 | + reference_selected = reference_selected / (reference_selected.sum(-1, keepdim=True) + 1e-20) * 1.4 | ||
| 114 | + torch.testing.assert_close(scores.full_tensor(), live_scores, rtol=1e-6, atol=1e-7) | ||
| 115 | + torch.testing.assert_close(selected.full_tensor(), reference_selected, rtol=1e-6, atol=1e-7) | ||
| 116 | + upstream = torch.tensor([[0.3, -0.6], [1.2, 0.7], [-0.4, 1.1], [0.8, -0.2], [-0.9, 0.5], [1.4, -1.0]]) | ||
| 117 | + (selected.to_local() * upstream[row]).sum().backward() | ||
| 118 | + | ||
| 119 | + reference_inputs = inputs.double().requires_grad_() | ||
| 120 | + reference_weight = (-capture_weight).double().requires_grad_() | ||
| 121 | + reference_scores = F.linear(reference_inputs, reference_weight).sigmoid().gather(-1, expected_ids) | ||
| 122 | + reference_scores = reference_scores / (reference_scores.sum(-1, keepdim=True) + 1e-20) * 1.4 | ||
| 123 | + (reference_scores * upstream.double()).sum().backward() | ||
| 124 | + assert sharded_inputs.grad.placements == (Shard(0),) | ||
| 125 | + torch.testing.assert_close( | ||
| 126 | + sharded_inputs.grad.full_tensor(), reference_inputs.grad.float(), rtol=2e-6, atol=2e-7 | ||
| 127 | + ) | ||
| 128 | + torch.testing.assert_close( | ||
| 129 | + router.gate.weight.grad.full_tensor(), reference_weight.grad.float(), rtol=2e-6, atol=2e-7 | ||
| 130 | + ) | ||
| 131 | + finally: | ||
| 132 | + if cache is not None: | ||
| 133 | + cache.reset() | ||
| 134 | + dist.destroy_process_group() | ||
| 135 | + | ||
| 136 | + | ||
| 137 | +def test_anticipatory_replay_preserves_dtensor_ids_and_current_score_gradients(tmp_path): | ||
| 138 | + mp.spawn(_replay_worker, args=(str(tmp_path / "rendezvous"),), nprocs=2, join=True) | ||
| 139 | + | ||
| 140 | + | ||
| 141 | +def test_cache_wraps_dynamic_router_but_not_v4_hash_router(): | ||
| 142 | + from torchtitan.models.common.linear import Linear | ||
| 143 | + from torchtitan.models.deepseek_v4.moe import DeepSeekV4Router | ||
| 144 | + | ||
| 145 | + gate = Linear.Config(in_features=4, out_features=4) | ||
| 146 | + with torch.random.fork_rng(devices=[]): | ||
| 147 | + hash_router = DeepSeekV4Router.Config( | ||
| 148 | + num_experts=4, gate=gate, top_k=2, vocab_size=8, layer_id=0, n_hash_layers=1 | ||
| 149 | + ).build() | ||
| 150 | + dynamic_router = _router() | ||
| 151 | + model = torch.nn.ModuleList([hash_router, dynamic_router]) | ||
| 152 | + hash_selection = hash_router._select_experts | ||
| 153 | + dynamic_selection = dynamic_router._select_experts | ||
| 154 | + | ||
| 155 | + cache = build_routing_cache([model], index_store_dtype="int16", device=torch.device("cpu")) | ||
| 156 | + | ||
| 157 | + assert hash_router._select_experts == hash_selection | ||
| 158 | + assert not hasattr(hash_router, "_anticipatory_cache") | ||
| 159 | + assert dynamic_router._select_experts is not dynamic_selection | ||
| 160 | + assert dynamic_router._anticipatory_cache is cache | ||
| 161 | + assert list(cache.replay_buffers) == [dynamic_router._anticipatory_key] | ||
| @@ -50,10 +50,10 @@ torchtitan_stub.__path__ = [] | |||
| 50 | components_stub = types.ModuleType("torchtitan.components") | 50 | components_stub = types.ModuleType("torchtitan.components") |
| 51 | components_stub.__path__ = [] | 51 | components_stub.__path__ = [] |
| 52 | torchtitan_stub.components = components_stub | 52 | torchtitan_stub.components = components_stub |
| 53 | -checkpoint_stub = types.ModuleType("torchtitan.components.checkpoint") | 53 | +checkpoint_stub = types.ModuleType("torchtitan.components.checkpointer") |
| 54 | checkpoint_stub.AsyncMode = _AsyncMode | 54 | checkpoint_stub.AsyncMode = _AsyncMode |
| 55 | checkpoint_stub.CheckpointManager = _CheckpointManager | 55 | checkpoint_stub.CheckpointManager = _CheckpointManager |
| 56 | -components_stub.checkpoint = checkpoint_stub | 56 | +components_stub.checkpointer = checkpoint_stub |
| 57 | observability_stub = types.ModuleType("torchtitan.observability") | 57 | observability_stub = types.ModuleType("torchtitan.observability") |
| 58 | observability_stub.structured_logger = types.SimpleNamespace(log_trace_span=lambda name: lambda function: function) | 58 | observability_stub.structured_logger = types.SimpleNamespace(log_trace_span=lambda name: lambda function: function) |
| 59 | torchtitan_stub.observability = observability_stub | 59 | torchtitan_stub.observability = observability_stub |
| @@ -78,7 +78,7 @@ with patch.dict( | |||
| 78 | { | 78 | { |
| 79 | "torchtitan": torchtitan_stub, | 79 | "torchtitan": torchtitan_stub, |
| 80 | "torchtitan.components": components_stub, | 80 | "torchtitan.components": components_stub, |
| 81 | - "torchtitan.components.checkpoint": checkpoint_stub, | 81 | + "torchtitan.components.checkpointer": checkpoint_stub, |
| 82 | "torchtitan.observability": observability_stub, | 82 | "torchtitan.observability": observability_stub, |
| 83 | "torchtitan.tools": tools_stub, | 83 | "torchtitan.tools": tools_stub, |
| 84 | "torchtitan.tools.utils": utils_stub, | 84 | "torchtitan.tools.utils": utils_stub, |
| @@ -273,6 +273,7 @@ def test_dedicated_mesh_is_not_recursively_recreated(ep_process_group, monkeypat | |||
| 273 | source_mesh = _FakeMesh(source_group) | 273 | source_mesh = _FakeMesh(source_group) |
| 274 | dedicated_mesh = _FakeMesh(dedicated_group) | 274 | dedicated_mesh = _FakeMesh(dedicated_group) |
| 275 | ep_process_group._EP_MESHES["source"] = dedicated_mesh | 275 | ep_process_group._EP_MESHES["source"] = dedicated_mesh |
| 276 | + monkeypatch.setattr(ep_process_group, "_is_fake_group", lambda group: False) | ||
| 276 | monkeypatch.setattr( | 277 | monkeypatch.setattr( |
| 277 | ep_process_group, | 278 | ep_process_group, |
| 278 | "_create_separate_ep_mesh", | 279 | "_create_separate_ep_mesh", |
| @@ -11,6 +11,20 @@ import pytest | |||
| 11 | from torchtitan_npu.extensions.torchtitan import trainer as trainer_module | 11 | from torchtitan_npu.extensions.torchtitan import trainer as trainer_module |
| 12 | 12 | ||
| 13 | 13 | ||
| 14 | +def test_trainer_config_revalidates_after_swap_optimizer_override(): | ||
| 15 | + from torchtitan.config.override import OverrideConfig, apply_overrides | ||
| 16 | + | ||
| 17 | + from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | ||
| 18 | + from torchtitan_npu.override.common.optimizer import OptimizerStateSwapContainer | ||
| 19 | + | ||
| 20 | + config = deepseek_v4_debugmodel() | ||
| 21 | + apply_overrides(OverrideConfig(imports=["torchtitan_npu.override.common.optimizer.swap_optimizer"]), config) | ||
| 22 | + | ||
| 23 | + config.__post_init__() | ||
| 24 | + | ||
| 25 | + assert isinstance(config.optimizer, OptimizerStateSwapContainer.Config) | ||
| 26 | + | ||
| 27 | + | ||
| 14 | @pytest.mark.parametrize( | 28 | @pytest.mark.parametrize( |
| 15 | "allow_hf32", | 29 | "allow_hf32", |
| 16 | [False, True], | 30 | [False, True], |
| @@ -0,0 +1,101 @@ | |||
| 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 contextlib import ExitStack | ||
| 7 | +from copy import deepcopy | ||
| 8 | + | ||
| 9 | +import numpy as np | ||
| 10 | +import pytest | ||
| 11 | +import torch | ||
| 12 | + | ||
| 13 | +from tests.unit_tests.models.common.text_data_utils import IntegerTextTokenizer, aligned_text_config | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def test_grain_loader_keeps_document_alignment_labels_and_positions(tmp_path): | ||
| 17 | + dataset = tmp_path / "data.json" | ||
| 18 | + dataset.write_text('{"text":"3 4"}\n{"text":"5"}\n') | ||
| 19 | + config = aligned_text_config(dataset, alignment=4) | ||
| 20 | + loader = config.build( | ||
| 21 | + dp_world_size=1, | ||
| 22 | + dp_rank=0, | ||
| 23 | + tokenizer=IntegerTextTokenizer(), | ||
| 24 | + max_context_length=4, | ||
| 25 | + num_tokens_per_batch=8, | ||
| 26 | + ) | ||
| 27 | + | ||
| 28 | + try: | ||
| 29 | + inputs, labels = next(iter(loader)) | ||
| 30 | + finally: | ||
| 31 | + loader.close() | ||
| 32 | + | ||
| 33 | + torch.testing.assert_close(inputs["input"], torch.tensor([1, 3, 4, 0, 1, 5, 0, 0])) | ||
| 34 | + torch.testing.assert_close(labels, torch.tensor([3, 4, 2, -100, 5, 2, -100, -100])) | ||
| 35 | + torch.testing.assert_close(inputs["positions"], torch.tensor([0, 1, 2, 3, 0, 1, 2, 3])) | ||
| 36 | + assert inputs["num_valid_tokens"] == 5 | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +@pytest.mark.parametrize("token_budget", (4, 8), ids=("one-context", "two-contexts")) | ||
| 40 | +def test_long_document_positions_follow_context_boundaries(tmp_path, token_budget): | ||
| 41 | + dataset = tmp_path / "data.json" | ||
| 42 | + dataset.write_text('{"text":"3"}\n{"text":"4 5 6 7 8"}\n') | ||
| 43 | + loader = aligned_text_config(dataset).build( | ||
| 44 | + dp_world_size=1, | ||
| 45 | + dp_rank=0, | ||
| 46 | + tokenizer=IntegerTextTokenizer(), | ||
| 47 | + max_context_length=4, | ||
| 48 | + num_tokens_per_batch=token_budget, | ||
| 49 | + ) | ||
| 50 | + try: | ||
| 51 | + batches = list(loader) | ||
| 52 | + finally: | ||
| 53 | + loader.close() | ||
| 54 | + | ||
| 55 | + expected_positions = [[0, 1, 0, 1], [0, 1, 0, 1]] if token_budget == 4 else [[0, 1, 0, 1, 2, 3, 0, 1]] | ||
| 56 | + expected_inputs = [[1, 3, 1, 4], [5, 6, 7, 8]] if token_budget == 4 else [[1, 3, 1, 4, 5, 6, 7, 8]] | ||
| 57 | + expected_labels = [[3, 2, 4, 5], [6, 7, 8, 2]] if token_budget == 4 else [[3, 2, 4, 5, 6, 7, 8, 2]] | ||
| 58 | + assert len(batches) == len(expected_positions) | ||
| 59 | + for (inputs, labels), positions, tokens, targets in zip( | ||
| 60 | + batches, expected_positions, expected_inputs, expected_labels, strict=True | ||
| 61 | + ): | ||
| 62 | + assert inputs["positions"].tolist() == positions | ||
| 63 | + assert inputs["input"].tolist() == tokens | ||
| 64 | + assert labels.tolist() == targets | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +@pytest.mark.parametrize("rank", (0, 1), ids=("dp-rank-0", "dp-rank-1")) | ||
| 68 | +def test_map_loader_partitions_shards_and_restores_pending_pack(tmp_path, rank): | ||
| 69 | + dataset = tmp_path / "data.json" | ||
| 70 | + dataset.write_text("".join(f'{{"text":"{token}"}}\n' for token in range(10, 18))) | ||
| 71 | + config = aligned_text_config(dataset, repeat=True) | ||
| 72 | + kwargs = dict( | ||
| 73 | + dp_world_size=2, | ||
| 74 | + dp_rank=rank, | ||
| 75 | + tokenizer=IntegerTextTokenizer(), | ||
| 76 | + max_context_length=6, | ||
| 77 | + num_tokens_per_batch=6, | ||
| 78 | + ) | ||
| 79 | + with ExitStack() as cleanup: | ||
| 80 | + original = config.build(**kwargs) | ||
| 81 | + cleanup.callback(original.close) | ||
| 82 | + restored = config.build(**kwargs) | ||
| 83 | + cleanup.callback(restored.close) | ||
| 84 | + iterator = iter(original) | ||
| 85 | + prefix = [next(iterator), next(iterator)] | ||
| 86 | + restored.load_state_dict(deepcopy(original.state_dict())) | ||
| 87 | + tail = [next(iterator), next(iterator)] | ||
| 88 | + resumed = iter(restored) | ||
| 89 | + for expected_inputs, expected_labels in tail: | ||
| 90 | + actual_inputs, actual_labels = next(resumed) | ||
| 91 | + torch.testing.assert_close(actual_labels, expected_labels, rtol=0, atol=0) | ||
| 92 | + assert actual_inputs.keys() == expected_inputs.keys() | ||
| 93 | + for key in expected_inputs: | ||
| 94 | + torch.testing.assert_close( | ||
| 95 | + torch.as_tensor(actual_inputs[key]), torch.as_tensor(expected_inputs[key]), rtol=0, atol=0 | ||
| 96 | + ) | ||
| 97 | + | ||
| 98 | + shard = np.arange(10 + rank * 4, 14 + rank * 4) | ||
| 99 | + expected = np.tile(shard, 3) | ||
| 100 | + actual = [token for inputs, _ in (*prefix, *tail) for token in inputs["input"][1::2].tolist()] | ||
| 101 | + assert actual == expected.tolist() | ||
Rtests/unit_tests/models/common/test_packing.py→tests/unit_tests/models/common/test_alignment.py+16-2
| @@ -5,11 +5,14 @@ | |||
| 5 | 5 | ||
| 6 | """The shared packing-grid checks: one contract for the loader and every CP entry.""" | 6 | """The shared packing-grid checks: one contract for the loader and every CP entry.""" |
| 7 | 7 | ||
| 8 | +from types import SimpleNamespace | ||
| 9 | + | ||
| 8 | import pytest | 10 | import pytest |
| 9 | import torch | 11 | import torch |
| 10 | 12 | ||
| 11 | -from torchtitan_npu.models.common.packing import ( | 13 | +from torchtitan_npu.models.common.alignment import ( |
| 12 | compression_alignment, | 14 | compression_alignment, |
| 15 | + require_dataloader_alignment, | ||
| 13 | require_document_alignment, | 16 | require_document_alignment, |
| 14 | require_per_doc_alignment, | 17 | require_per_doc_alignment, |
| 15 | ) | 18 | ) |
| @@ -52,7 +55,18 @@ def test_require_per_doc_alignment_checks_the_cli_value(): | |||
| 52 | assert require_per_doc_alignment(128, (1, 4, 128), 1) == 128 | 55 | assert require_per_doc_alignment(128, (1, 4, 128), 1) == 128 |
| 53 | assert require_per_doc_alignment(256, (1, 4, 128), 2) == 256 | 56 | assert require_per_doc_alignment(256, (1, 4, 128), 2) == 256 |
| 54 | assert require_per_doc_alignment(1024, (1, 4, 128), 4) == 512 | 57 | assert require_per_doc_alignment(1024, (1, 4, 128), 4) == 512 |
| 55 | - with pytest.raises(ValueError, match=r"--dataloader.per_doc_alignment=128") as exc: | 58 | + with pytest.raises(ValueError, match=r"per-document alignment \(128\)") as exc: |
| 56 | require_per_doc_alignment(128, (1, 4, 128), 2) | 59 | require_per_doc_alignment(128, (1, 4, 128), 2) |
| 57 | assert "multiple of 256" in str(exc.value) | 60 | assert "multiple of 256" in str(exc.value) |
| 58 | assert "cp_degree=2" in str(exc.value) | 61 | assert "cp_degree=2" in str(exc.value) |
| 62 | + | ||
| 63 | + | ||
| 64 | +def test_dataloader_alignment_checks_grain_processor_and_direct_loader(): | ||
| 65 | + processor = SimpleNamespace(per_doc_alignment=256) | ||
| 66 | + grain_loader = SimpleNamespace(dataset=SimpleNamespace(dataset=SimpleNamespace(processor=processor))) | ||
| 67 | + direct_loader = SimpleNamespace(per_doc_alignment=256) | ||
| 68 | + for loader in (grain_loader, direct_loader): | ||
| 69 | + require_dataloader_alignment(loader, (1, 4, 128), 2) | ||
| 70 | + processor.per_doc_alignment = 128 | ||
| 71 | + with pytest.raises(ValueError, match="multiple of 256"): | ||
| 72 | + require_dataloader_alignment(grain_loader, (1, 4, 128), 2) | ||
| @@ -71,7 +71,9 @@ def _worker(rank: int, port: int) -> None: | |||
| 71 | 71 | ||
| 72 | group = dist.group.WORLD | 72 | group = dist.group.WORLD |
| 73 | tokens = torch.arange(_ROW).reshape(1, -1) + 100 | 73 | tokens = torch.arange(_ROW).reshape(1, -1) + 100 |
| 74 | - positions = torch.cat([torch.arange(length) for length in _LENGTHS]).reshape(1, -1) | 74 | + # The folded row's positions are flat; the exchanged streams keep the |
| 75 | + # packed row's ``[1, ...]`` container the production restore addresses. | ||
| 76 | + positions = torch.cat([torch.arange(length) for length in _LENGTHS]) | ||
| 75 | labels = tokens + 1 | 77 | labels = tokens + 1 |
| 76 | slab = slice(rank * _SLAB, (rank + 1) * _SLAB) | 78 | slab = slice(rank * _SLAB, (rank + 1) * _SLAB) |
| 77 | 79 | ||
| @@ -91,12 +93,12 @@ def _worker(rank: int, port: int) -> None: | |||
| 91 | expected_positions = torch.cat( | 93 | expected_positions = torch.cat( |
| 92 | [torch.arange(rank * (length // _CP), (rank + 1) * (length // _CP)) for length in _LENGTHS] | 94 | [torch.arange(rank * (length // _CP), (rank + 1) * (length // _CP)) for length in _LENGTHS] |
| 93 | ).reshape(1, -1) | 95 | ).reshape(1, -1) |
| 94 | - assert torch.equal(_to_chunks(positions[:, slab], plan, group=group), expected_positions) | 96 | + assert torch.equal(_to_chunks(positions[slab], plan, group=group), expected_positions) |
| 95 | 97 | ||
| 96 | # The restore is the exact inverse, its positions come from the entry, and its backward is | 98 | # The restore is the exact inverse, its positions come from the entry, and its backward is |
| 97 | # the reverse exchange. | 99 | # the reverse exchange. |
| 98 | assert torch.equal(to_slab(moved, plan, group=group), tokens[:, slab]) | 100 | assert torch.equal(to_slab(moved, plan, group=group), tokens[:, slab]) |
| 99 | - assert torch.equal(entry.position_k, slab_positions(row.swa_k.cu_seqlens, _CP, rank, _SLAB)) | 101 | + assert torch.equal(entry.position_k, slab_positions(row.swa_k.cu_seqlens, _CP, rank, _SLAB).squeeze(0)) |
| 100 | 102 | ||
| 101 | x = (torch.randn(1, _SLAB, 3, dtype=torch.float64) + 10.0 * rank).requires_grad_() | 103 | x = (torch.randn(1, _SLAB, 3, dtype=torch.float64) + 10.0 * rank).requires_grad_() |
| 102 | slabbed = to_slab(x, plan, group=group) | 104 | slabbed = to_slab(x, plan, group=group) |
| @@ -0,0 +1,39 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 2 | +# | ||
| 3 | +# This source code is licensed under the BSD-style license found in the | ||
| 4 | +# LICENSE file in the root directory of this source tree. | ||
| 5 | + | ||
| 6 | + | ||
| 7 | +from torchtitan.components.data import ( | ||
| 8 | + ConcatThenSplitPackingConfig, | ||
| 9 | + GrainDataLoader, | ||
| 10 | + HuggingFaceRandomAccessSource, | ||
| 11 | + SingleDatasetConfig, | ||
| 12 | +) | ||
| 13 | + | ||
| 14 | +from torchtitan_npu.models.common.alignment import AlignedTextProcessor | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +def aligned_text_config(path, *, alignment=2, repeat=False): | ||
| 18 | + return GrainDataLoader.Config( | ||
| 19 | + dataset=ConcatThenSplitPackingConfig( | ||
| 20 | + dataset=SingleDatasetConfig( | ||
| 21 | + source=HuggingFaceRandomAccessSource.Config( | ||
| 22 | + path="json", | ||
| 23 | + split="train", | ||
| 24 | + load_dataset_kwargs={"data_files": str(path)}, | ||
| 25 | + ), | ||
| 26 | + processor=AlignedTextProcessor.Config(per_doc_alignment=alignment), | ||
| 27 | + post_filters=(lambda sample: sample is not None,), | ||
| 28 | + ), | ||
| 29 | + ), | ||
| 30 | + shuffle=False, | ||
| 31 | + repeat=repeat, | ||
| 32 | + ) | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +class IntegerTextTokenizer: | ||
| 36 | + """CPU fixture for whitespace-separated integer tokens, BOS=1 and EOS=2.""" | ||
| 37 | + | ||
| 38 | + def encode(self, text, *, add_bos, add_eos): | ||
| 39 | + return ([1] if add_bos else []) + [int(token) for token in text.split()] + ([2] if add_eos else []) | ||
| @@ -56,7 +56,7 @@ def _clean_aux_loss_state(): | |||
| 56 | 56 | ||
| 57 | 57 | ||
| 58 | def _masks(): | 58 | def _masks(): |
| 59 | - return create_varlen_metadata_for_document(_POSITIONS) | 59 | + return create_varlen_metadata_for_document(_POSITIONS.reshape(-1)) |
| 60 | 60 | ||
| 61 | 61 | ||
| 62 | def _document_of(row: int) -> int: | 62 | def _document_of(row: int) -> int: |
| @@ -143,7 +143,7 @@ def _indexer_config() -> Indexer.Config: | |||
| 143 | wk=Linear.Config(in_features=8, out_features=_INDEX_HEAD_DIM), | 143 | wk=Linear.Config(in_features=8, out_features=_INDEX_HEAD_DIM), |
| 144 | k_norm=LayerNorm.Config(normalized_shape=_INDEX_HEAD_DIM), | 144 | k_norm=LayerNorm.Config(normalized_shape=_INDEX_HEAD_DIM), |
| 145 | weights_proj=Linear.Config(in_features=8, out_features=_INDEX_HEADS), | 145 | weights_proj=Linear.Config(in_features=8, out_features=_INDEX_HEADS), |
| 146 | - rope=CosSinRoPE.Config(dim=_ROPE_HEAD_DIM, max_seq_len=_TOKENS, theta=10000.0), | 146 | + rope=CosSinRoPE.Config(dim=_ROPE_HEAD_DIM, max_context_length=_TOKENS, theta=10000.0), |
| 147 | ) | 147 | ) |
| 148 | 148 | ||
| 149 | 149 | ||
| @@ -337,7 +337,7 @@ def test_the_shipped_layers_dispatch_to_a_varlen_mask(): | |||
| 337 | layer_cfg = model_registry("debugmodel").model.layers[0] | 337 | layer_cfg = model_registry("debugmodel").model.layers[0] |
| 338 | owner = SimpleNamespace(config=SimpleNamespace(first_attention=layer_cfg.attention)) | 338 | owner = SimpleNamespace(config=SimpleNamespace(first_attention=layer_cfg.attention)) |
| 339 | 339 | ||
| 340 | - masks = DeepSeekV32Model.get_attention_masks(owner, _POSITIONS) | 340 | + masks = DeepSeekV32Model.get_attention_masks(owner, _POSITIONS.reshape(-1)) |
| 341 | 341 | ||
| 342 | assert isinstance(layer_cfg.attention.inner_attention, SparseInnerAttention.Config) | 342 | assert isinstance(layer_cfg.attention.inner_attention, SparseInnerAttention.Config) |
| 343 | assert issubclass(SparseInnerAttention.Config, VarlenAttention.Config) | 343 | assert issubclass(SparseInnerAttention.Config, VarlenAttention.Config) |
| @@ -30,7 +30,7 @@ def _masks(num_tokens: int): | |||
| 30 | Positions that reset to zero start a document, hence the increasing positions here: the | 30 | Positions that reset to zero start a document, hence the increasing positions here: the |
| 31 | selection's numbering and the keys' rows then coincide, which is what these cases compare. | 31 | selection's numbering and the keys' rows then coincide, which is what these cases compare. |
| 32 | """ | 32 | """ |
| 33 | - return create_varlen_metadata_for_document(torch.arange(num_tokens).unsqueeze(0)) | 33 | + return create_varlen_metadata_for_document(torch.arange(num_tokens)) |
| 34 | 34 | ||
| 35 | 35 | ||
| 36 | _COEFF = 2.0 | 36 | _COEFF = 2.0 |
| @@ -36,9 +36,9 @@ from torchtitan_npu.override.deepseek_v3_2.sparse_attn.ascendc import AscSparseI | |||
| 36 | from torchtitan_npu.patches.torchtitan.distributed.varlen_cp import CPVarlenMetadata | 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 | 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 row: the headtail load balancer needs a | 39 | +# Two documents of four tokens in one packed row: the headtail load balancer |
| 40 | -# sequence length divisible by ``2 * cp`` for the two-rank case below. | 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]]) | 41 | +_POSITIONS = torch.tensor([0, 1, 2, 3, 0, 1, 2, 3]) |
| 42 | _SEQ_LEN = 8 | 42 | _SEQ_LEN = 8 |
| 43 | _CU_SEQ = [0, 4, 8] | 43 | _CU_SEQ = [0, 4, 8] |
| 44 | _NO_CP_DIMS = SimpleNamespace(cp_enabled=False, get_mesh=lambda name: None) | 44 | _NO_CP_DIMS = SimpleNamespace(cp_enabled=False, get_mesh=lambda name: None) |
| @@ -82,7 +82,7 @@ def _model_config(n_layers: int = 3, *, ascendc: bool = False) -> DeepSeekV32Mod | |||
| 82 | router_score_func="softmax", | 82 | router_score_func="softmax", |
| 83 | moe_comm_backend="standard", | 83 | moe_comm_backend="standard", |
| 84 | non_blocking_capacity_factor=None, | 84 | non_blocking_capacity_factor=None, |
| 85 | - rope=ComplexRoPE.Config(dim=8, max_seq_len=_SEQ_LEN, theta=10000.0, original_seq_len=_SEQ_LEN), | 85 | + rope=ComplexRoPE.Config(dim=8, max_context_length=_SEQ_LEN, theta=10000.0, original_seq_len=_SEQ_LEN), |
| 86 | index_n_heads=4, | 86 | index_n_heads=4, |
| 87 | index_head_dim=8, | 87 | index_head_dim=8, |
| 88 | index_topk=4, | 88 | index_topk=4, |
| @@ -138,10 +138,12 @@ def test_preprocess_inputs_hands_the_map_to_the_forward(): | |||
| 138 | model = _model_config(n_layers=1).build() | 138 | model = _model_config(n_layers=1).build() |
| 139 | 139 | ||
| 140 | _, _, extra_kwargs = model.preprocess_inputs( | 140 | _, _, extra_kwargs = model.preprocess_inputs( |
| 141 | - {"input": torch.zeros(1, _SEQ_LEN, dtype=torch.int64), "positions": _POSITIONS}, | 141 | + { |
| 142 | - torch.zeros(1, _SEQ_LEN, dtype=torch.int64), | 142 | + "input": torch.zeros(_SEQ_LEN, dtype=torch.int64), |
| 143 | + "labels": torch.zeros(_SEQ_LEN, dtype=torch.int64), | ||
| 144 | + "positions": _POSITIONS, | ||
| 145 | + }, | ||
| 143 | parallel_dims=_NO_CP_DIMS, | 146 | parallel_dims=_NO_CP_DIMS, |
| 144 | - device=torch.device("cpu"), | ||
| 145 | parallelism=_NO_SPMD, | 147 | parallelism=_NO_SPMD, |
| 146 | ) | 148 | ) |
| 147 | 149 | ||
| @@ -0,0 +1,99 @@ | |||
| 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 | +"""Real recipe selection and Grain packing with a fixed chat-encoding oracle.""" | ||
| 7 | + | ||
| 8 | +import json | ||
| 9 | +from contextlib import ExitStack | ||
| 10 | +from copy import deepcopy | ||
| 11 | + | ||
| 12 | +import grain | ||
| 13 | +import pytest | ||
| 14 | +import torch | ||
| 15 | +from torchtitan.components.data import FirstFitPackingConfig, GrainDataLoader, SingleDatasetConfig | ||
| 16 | +from torchtitan.components.tokenizer import HuggingFaceTokenizer | ||
| 17 | + | ||
| 18 | +from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4EncoderConfig | ||
| 19 | +from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor | ||
| 20 | +from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash_sft | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class _StubEncoder: | ||
| 24 | + """Each integer prompt identifies one six-token conversation.""" | ||
| 25 | + | ||
| 26 | + def encode_messages_with_assistant_mask(self, messages, tokenizer, eos_id): | ||
| 27 | + base = int(messages[0]["content"]) | ||
| 28 | + return "", list(range(base, base + 6)), [False, False, True, True, True, True] | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +@pytest.fixture | ||
| 32 | +def sft_recipe(tmp_path, monkeypatch): | ||
| 33 | + monkeypatch.setattr(DSV4EncoderConfig, "build", lambda self, path: _StubEncoder()) | ||
| 34 | + path = tmp_path / "chat.jsonl" | ||
| 35 | + path.write_text( | ||
| 36 | + "".join( | ||
| 37 | + json.dumps({"messages": [{"role": "user", "content": str(base)}, {"role": "assistant", "content": "ok"}]}) | ||
| 38 | + + "\n" | ||
| 39 | + for base in range(10, 90, 10) | ||
| 40 | + ) | ||
| 41 | + ) | ||
| 42 | + config = deepseek_v4_flash_sft(dataset_path=str(path)) | ||
| 43 | + assert isinstance(config.dataloader, GrainDataLoader.Config) | ||
| 44 | + config.dataloader.shuffle = False | ||
| 45 | + config.dataloader.read_options = grain.ReadOptions(num_threads=2, prefetch_buffer_size=4) | ||
| 46 | + assert isinstance(config.dataloader, GrainDataLoader.Config) | ||
| 47 | + assert isinstance(config.dataloader.dataset, FirstFitPackingConfig) | ||
| 48 | + assert isinstance(config.dataloader.dataset.dataset, SingleDatasetConfig) | ||
| 49 | + assert isinstance(config.dataloader.dataset.dataset.processor, DeepSeekV4ChatProcessor.Config) | ||
| 50 | + assert config.dataloader.dataset.dataset.processor.per_doc_alignment == 128 | ||
| 51 | + return config.dataloader | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def test_sft_recipe_builds_aligned_supervised_batches(sft_recipe): | ||
| 55 | + loader = sft_recipe.build( | ||
| 56 | + dp_world_size=1, | ||
| 57 | + dp_rank=0, | ||
| 58 | + tokenizer=HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3"), | ||
| 59 | + max_context_length=128, | ||
| 60 | + num_tokens_per_batch=256, | ||
| 61 | + ) | ||
| 62 | + try: | ||
| 63 | + inputs, labels = next(iter(loader)) | ||
| 64 | + finally: | ||
| 65 | + loader.close() | ||
| 66 | + | ||
| 67 | + assert inputs["input"].tolist() == list(range(10, 15)) + [0] * 123 + list(range(20, 25)) + [0] * 123 | ||
| 68 | + assert labels.tolist() == [-100, 12, 13, 14, 15] + [-100] * 123 + [-100, 22, 23, 24, 25] + [-100] * 123 | ||
| 69 | + assert inputs["positions"].tolist() == list(range(128)) * 2 | ||
| 70 | + assert inputs["num_valid_tokens"] == 8 | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +@pytest.mark.parametrize("rank", (0, 1), ids=("dp-rank-0", "dp-rank-1")) | ||
| 74 | +def test_sft_grain_restores_packing_and_prefetch_across_epoch(sft_recipe, rank): | ||
| 75 | + kwargs = dict( | ||
| 76 | + dp_world_size=2, | ||
| 77 | + dp_rank=rank, | ||
| 78 | + tokenizer=HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3"), | ||
| 79 | + max_context_length=128, | ||
| 80 | + num_tokens_per_batch=384, | ||
| 81 | + ) | ||
| 82 | + with ExitStack() as cleanup: | ||
| 83 | + original = sft_recipe.build(**kwargs) | ||
| 84 | + cleanup.callback(original.close) | ||
| 85 | + restored = sft_recipe.build(**kwargs) | ||
| 86 | + cleanup.callback(restored.close) | ||
| 87 | + first, _ = next(iter(original)) | ||
| 88 | + assert first["input"][::128].tolist() == ([10, 20, 30] if rank == 0 else [50, 60, 70]) | ||
| 89 | + state = json.loads(json.dumps(deepcopy(original.state_dict()))) | ||
| 90 | + restored.load_state_dict(state) | ||
| 91 | + for _ in range(4): | ||
| 92 | + expected_inputs, expected_labels = next(iter(original)) | ||
| 93 | + inputs, labels = next(iter(restored)) | ||
| 94 | + torch.testing.assert_close(labels, expected_labels, rtol=0, atol=0) | ||
| 95 | + assert inputs.keys() == expected_inputs.keys() | ||
| 96 | + for key in inputs: | ||
| 97 | + torch.testing.assert_close( | ||
| 98 | + torch.as_tensor(inputs[key]), torch.as_tensor(expected_inputs[key]), rtol=0, atol=0 | ||
| 99 | + ) | ||
| @@ -1,61 +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 | -"""The SFT chat dataset pads every conversation to the compression grid. | ||
| 7 | - | ||
| 8 | -The V4 stack pools ``lcm(compress_ratios)`` tokens into one compressed entry and the | ||
| 9 | -plan builder refuses a stream whose documents are not a multiple of that grid, so the | ||
| 10 | -chat path must pad like the C4 text path does: the conversation tokens stay a prefix, | ||
| 11 | -the pads carry ``IGNORE_INDEX`` labels, and the positions buffer keeps running. | ||
| 12 | -""" | ||
| 13 | - | ||
| 14 | -import pytest | ||
| 15 | -from datasets import Dataset | ||
| 16 | -from torchtitan.components.loss import IGNORE_INDEX | ||
| 17 | -from torchtitan.components.tokenizer import HuggingFaceTokenizer | ||
| 18 | - | ||
| 19 | -from torchtitan_npu.models.deepseek_v4.chat_dataset import DeepSeekV4ChatDataset, _sft_messages | ||
| 20 | - | ||
| 21 | -_TOKENS = [10, 11, 12, 13, 14] | ||
| 22 | -_MASK = [False, False, True, True, True] | ||
| 23 | -_SAMPLE = {"messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "ok"}]} | ||
| 24 | - | ||
| 25 | - | ||
| 26 | -class _StubEncoder: | ||
| 27 | - """A deterministic stand-in for the V4 chat encoder (no tokenizer asset needed).""" | ||
| 28 | - | ||
| 29 | - def encode_messages_with_assistant_mask(self, messages, tokenizer, eos_id): | ||
| 30 | - return None, _TOKENS, _MASK | ||
| 31 | - | ||
| 32 | - | ||
| 33 | -def _dataset(*, seq_len: int, per_doc_alignment: int) -> DeepSeekV4ChatDataset: | ||
| 34 | - return DeepSeekV4ChatDataset( | ||
| 35 | - dataset=Dataset.from_list([_SAMPLE]), | ||
| 36 | - tokenizer=HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3"), | ||
| 37 | - sample_processor=_sft_messages, | ||
| 38 | - seq_len=seq_len, | ||
| 39 | - dp_rank=0, | ||
| 40 | - dp_world_size=1, | ||
| 41 | - infinite=False, | ||
| 42 | - chat_encoder=_StubEncoder(), | ||
| 43 | - per_doc_alignment=per_doc_alignment, | ||
| 44 | - ) | ||
| 45 | - | ||
| 46 | - | ||
| 47 | -def test_chat_sample_is_padded_to_the_compression_grid(): | ||
| 48 | - dataset = _dataset(seq_len=256, per_doc_alignment=128) | ||
| 49 | - input_ids, label_ids = dataset._tokenize_sample(_SAMPLE) | ||
| 50 | - | ||
| 51 | - # The conversation is a prefix; the pads are appended with IGNORE labels. | ||
| 52 | - assert input_ids[:4] == _TOKENS[:-1] | ||
| 53 | - assert label_ids[:4] == [IGNORE_INDEX, 12, 13, 14] | ||
| 54 | - assert len(input_ids) == len(label_ids) == 128 | ||
| 55 | - assert input_ids[4:] == [0] * 124 | ||
| 56 | - assert label_ids[4:] == [IGNORE_INDEX] * 124 | ||
| 57 | - | ||
| 58 | - | ||
| 59 | -def test_chat_dataset_rejects_a_seq_len_off_the_alignment(): | ||
| 60 | - with pytest.raises(ValueError, match="must be a multiple of per_doc_alignment"): | ||
| 61 | - _dataset(seq_len=130, per_doc_alignment=128) | ||
| @@ -0,0 +1,109 @@ | |||
| 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 | +"""Conversation semantics independent of the external DSV4 encoding asset.""" | ||
| 7 | + | ||
| 8 | +import json | ||
| 9 | +from copy import deepcopy | ||
| 10 | + | ||
| 11 | +import grain | ||
| 12 | +import numpy as np | ||
| 13 | +import pytest | ||
| 14 | +from torchtitan.components.data import DatasetBuildContext | ||
| 15 | +from torchtitan.components.tokenizer import HuggingFaceTokenizer | ||
| 16 | + | ||
| 17 | +from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4EncoderConfig | ||
| 18 | +from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +class _StubEncoder: | ||
| 22 | + """Fixed token/mask oracle; records messages at the encoding boundary.""" | ||
| 23 | + | ||
| 24 | + def __init__(self): | ||
| 25 | + self.tokens = [10, 11, 12, 13, 14, 15] | ||
| 26 | + self.mask = [False, False, True, True, True, True] | ||
| 27 | + self.messages = None | ||
| 28 | + | ||
| 29 | + def encode_messages_with_assistant_mask(self, messages, tokenizer, eos_id): | ||
| 30 | + self.messages = messages | ||
| 31 | + return "", self.tokens, self.mask | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +@pytest.fixture | ||
| 35 | +def processor_and_encoder(monkeypatch): | ||
| 36 | + encoder = _StubEncoder() | ||
| 37 | + monkeypatch.setattr(DSV4EncoderConfig, "build", lambda self, path: encoder) | ||
| 38 | + context = DatasetBuildContext( | ||
| 39 | + tokenizer=HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3"), | ||
| 40 | + max_context_length=8, | ||
| 41 | + num_tokens_per_batch=16, | ||
| 42 | + read_options=grain.ReadOptions(num_threads=0), | ||
| 43 | + ) | ||
| 44 | + processor = DeepSeekV4ChatProcessor.Config(per_doc_alignment=8).build(context=context) | ||
| 45 | + return processor, encoder | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +def test_chat_processor_shifts_supervision_then_aligns(processor_and_encoder): | ||
| 49 | + processor, _ = processor_and_encoder | ||
| 50 | + sample = {"messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "ok"}]} | ||
| 51 | + | ||
| 52 | + sequence = processor(sample, np.random.default_rng(0)) | ||
| 53 | + | ||
| 54 | + assert sequence.input_ids.tolist() == [10, 11, 12, 13, 14, 0, 0, 0] | ||
| 55 | + assert sequence.labels.tolist() == [-100, 12, 13, 14, 15, -100, -100, -100] | ||
| 56 | + assert sequence.positions is None | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def test_chat_processor_preserves_tools_and_normalizes_reminders_without_mutation(processor_and_encoder): | ||
| 60 | + processor, encoder = processor_and_encoder | ||
| 61 | + messages = [ | ||
| 62 | + {"role": "developer", "content": "use tools"}, | ||
| 63 | + {"role": "user", "content": "hi"}, | ||
| 64 | + {"role": "assistant", "content": "call"}, | ||
| 65 | + {"role": "tool", "content": "result"}, | ||
| 66 | + {"role": "assistant", "content": "ok"}, | ||
| 67 | + {"role": "last_reminder", "content": "remember"}, | ||
| 68 | + ] | ||
| 69 | + sample = {"messages": json.dumps(messages), "tools": '[{"name":"search"}]'} | ||
| 70 | + original = deepcopy(sample) | ||
| 71 | + | ||
| 72 | + sequence = processor(sample, np.random.default_rng(0)) | ||
| 73 | + | ||
| 74 | + assert sequence is not None | ||
| 75 | + assert sample == original | ||
| 76 | + assert encoder.messages[0] == {"role": "developer", "content": "use tools", "tools": [{"name": "search"}]} | ||
| 77 | + assert encoder.messages[-1] == {"role": "latest_reminder", "content": "remember"} | ||
| 78 | + assert encoder.messages[1:5] == messages[1:5] | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +@pytest.mark.parametrize("case", ("oversized", "all-masked"), ids=("oversized", "all-masked")) | ||
| 82 | +def test_chat_processor_drops_unusable_conversations(processor_and_encoder, case): | ||
| 83 | + processor, encoder = processor_and_encoder | ||
| 84 | + if case == "oversized": | ||
| 85 | + encoder.tokens = list(range(10)) | ||
| 86 | + encoder.mask = [True] * 10 | ||
| 87 | + else: | ||
| 88 | + encoder.mask = [False] * len(encoder.tokens) | ||
| 89 | + | ||
| 90 | + sequence = processor({"messages": [{"role": "assistant", "content": "ok"}]}, np.random.default_rng(0)) | ||
| 91 | + | ||
| 92 | + assert sequence is None | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def test_chat_processor_accepts_exact_context_boundary(processor_and_encoder): | ||
| 96 | + processor, encoder = processor_and_encoder | ||
| 97 | + encoder.tokens = list(range(9)) | ||
| 98 | + encoder.mask = [False, False] + [True] * 7 | ||
| 99 | + | ||
| 100 | + sequence = processor({"messages": [{"role": "assistant", "content": "ok"}]}, np.random.default_rng(0)) | ||
| 101 | + | ||
| 102 | + assert sequence.input_ids.tolist() == list(range(8)) | ||
| 103 | + assert sequence.labels.tolist() == [-100, 2, 3, 4, 5, 6, 7, 8] | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +def test_chat_processor_rejects_unknown_role(processor_and_encoder): | ||
| 107 | + processor, _ = processor_and_encoder | ||
| 108 | + with pytest.raises(ValueError, match="Unsupported DeepSeek-V4 role"): | ||
| 109 | + processor({"messages": [{"role": "unknown", "content": "hi"}]}, np.random.default_rng(0)) | ||
| @@ -1,3 +1,8 @@ | |||
| 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 | + | ||
| 1 | """DSV4 host-logic CPU tests: the AscendC metadata layer, the packed layout, | 6 | """DSV4 host-logic CPU tests: the AscendC metadata layer, the packed layout, |
| 2 | the compressor/indexer/attention numerics, and the ported DSA semantics. | 7 | the compressor/indexer/attention numerics, and the ported DSA semantics. |
| 3 | 8 | ||
| @@ -166,7 +171,7 @@ def manual_compress(x, md, comp, ratio): | |||
| 166 | entry's own ratio. Every document is a whole number of blocks, so the row's flat | 171 | entry's own ratio. Every document is a whole number of blocks, so the row's flat |
| 167 | fold and this per-document pass address the same blocks. | 172 | fold and this per-document pass address the same blocks. |
| 168 | """ | 173 | """ |
| 169 | - flat_x = x.flatten(0, 1).float() | 174 | + flat_x = x.float() |
| 170 | out = [] | 175 | out = [] |
| 171 | for qs, qe in pairwise(md.swa_k.cu_seqlens.tolist()): | 176 | for qs, qe in pairwise(md.swa_k.cu_seqlens.tolist()): |
| 172 | c_len = (qe - qs) // ratio | 177 | c_len = (qe - qs) // ratio |
| @@ -188,7 +193,7 @@ def manual_compress(x, md, comp, ratio): | |||
| 188 | score = torch.cat([score_prev, score[:, :, HD:]], dim=1) | 193 | score = torch.cat([score_prev, score[:, :, HD:]], dim=1) |
| 189 | kv = (kv * score.softmax(dim=1)).sum(dim=1) | 194 | kv = (kv * score.softmax(dim=1)).sum(dim=1) |
| 190 | out.append(comp.norm(kv.to(x.dtype))) | 195 | out.append(comp.norm(kv.to(x.dtype))) |
| 191 | - return torch.cat(out).view(md.batch_size, -1, HD) | 196 | + return torch.cat(out).view(-1, HD) |
| 192 | 197 | ||
| 193 | 198 | ||
| 194 | def _pool_blocks_where(comp, block_tokens, block_positions, overlap_valid, dtype, ratio): | 199 | def _pool_blocks_where(comp, block_tokens, block_positions, overlap_valid, dtype, ratio): |
| @@ -219,7 +224,7 @@ def _pool_blocks_where(comp, block_tokens, block_positions, overlap_valid, dtype | |||
| 219 | 224 | ||
| 220 | def _positions_for(doc_lens): | 225 | def _positions_for(doc_lens): |
| 221 | """A packed row whose documents have the given lengths (positions reset).""" | 226 | """A packed row whose documents have the given lengths (positions reset).""" |
| 222 | - return torch.cat([torch.arange(length) for length in doc_lens]).unsqueeze(0) | 227 | + return torch.cat([torch.arange(length) for length in doc_lens]) |
| 223 | 228 | ||
| 224 | 229 | ||
| 225 | def _positions_from(cu): | 230 | def _positions_from(cu): |
| @@ -257,8 +262,7 @@ def _assert_rounding_floor(diff, scale, *, ulps: int = 4): | |||
| 257 | assert diff.max().item() <= ulps * _EPS32 * scale, (diff.max().item(), scale) | 262 | assert diff.max().item() <= ulps * _EPS32 * scale, (diff.max().item(), scale) |
| 258 | 263 | ||
| 259 | 264 | ||
| 260 | -@pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"]) | 265 | +def test_compressor_numerics_ratio4(inputs): |
| 261 | -def test_compressor_numerics_ratio4(inputs, batch_size): | ||
| 262 | """C4A pooling vs the independent manual reference. | 266 | """C4A pooling vs the independent manual reference. |
| 263 | 267 | ||
| 264 | The residual must sit at the fp32 rounding floor: the two paths project | 268 | The residual must sit at the fp32 rounding floor: the two paths project |
| @@ -271,65 +275,24 @@ def test_compressor_numerics_ratio4(inputs, batch_size): | |||
| 271 | while still flagging any multi-ulp arithmetic regression. | 275 | while still flagging any multi-ulp arithmetic regression. |
| 272 | """ | 276 | """ |
| 273 | dsv4, md, x, pos = inputs | 277 | dsv4, md, x, pos = inputs |
| 274 | - x = x.reshape(batch_size, -1, DIM).requires_grad_() | 278 | + x = x.squeeze(0).requires_grad_() |
| 275 | - pos = pos.reshape(batch_size, -1) | ||
| 276 | comp4 = build_compressor(dsv4, 4) | 279 | comp4 = build_compressor(dsv4, 4) |
| 277 | cmp4 = comp4(x, pos, cu_seqlens=md[4].swa_k.cu_seqlens) | 280 | cmp4 = comp4(x, pos, cu_seqlens=md[4].swa_k.cu_seqlens) |
| 278 | # Four 128-token documents: 4 * 128 // 4 whole blocks over the row. | 281 | # Four 128-token documents: 4 * 128 // 4 whole blocks over the row. |
| 279 | - assert cmp4.shape == (batch_size, 128 // batch_size, 16) | 282 | + assert cmp4.shape == (128, 16) |
| 280 | ref = manual_compress(x, md[4], comp4, 4).reshape_as(cmp4) | 283 | ref = manual_compress(x, md[4], comp4, 4).reshape_as(cmp4) |
| 281 | _assert_rounding_floor((cmp4 - ref).abs(), ref.abs().max().item()) | 284 | _assert_rounding_floor((cmp4 - ref).abs(), ref.abs().max().item()) |
| 282 | - # Reframing the same document stream must preserve its exact backward, including | ||
| 283 | - # nonuniform upstream gradients. The independent per-document oracle above checks math. | ||
| 284 | - packed = comp4(x.reshape(1, -1, DIM), pos.reshape(1, -1), cu_seqlens=md[4].swa_k.cu_seqlens) | ||
| 285 | - upstream = torch.linspace(-0.25, 0.75, cmp4.numel()).reshape_as(cmp4) | ||
| 286 | - parameters = (x, *comp4.parameters()) | ||
| 287 | - for actual, expected in zip( | ||
| 288 | - torch.autograd.grad((cmp4 * upstream).sum(), parameters), | ||
| 289 | - torch.autograd.grad((packed.reshape_as(cmp4) * upstream).sum(), parameters), | ||
| 290 | - strict=True, | ||
| 291 | - ): | ||
| 292 | - torch.testing.assert_close(actual, expected, rtol=0, atol=0) | ||
| 293 | 285 | ||
| 294 | 286 | ||
| 295 | -@pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"]) | 287 | +def test_compressor_numerics_ratio128(inputs): |
| 296 | -def test_compressor_numerics_ratio128(inputs, batch_size): | ||
| 297 | """C128A pools every whole 128-block of the row, one per document here.""" | 288 | """C128A pools every whole 128-block of the row, one per document here.""" |
| 298 | dsv4, md, x, pos = inputs | 289 | dsv4, md, x, pos = inputs |
| 299 | - x = x.reshape(batch_size, -1, DIM).requires_grad_() | 290 | + x = x.squeeze(0).requires_grad_() |
| 300 | - pos = pos.reshape(batch_size, -1) | ||
| 301 | comp128 = build_compressor(dsv4, 128) | 291 | comp128 = build_compressor(dsv4, 128) |
| 302 | cmp128 = comp128(x, pos, cu_seqlens=md[128].swa_k.cu_seqlens) | 292 | cmp128 = comp128(x, pos, cu_seqlens=md[128].swa_k.cu_seqlens) |
| 303 | - assert cmp128.shape == (batch_size, 4 // batch_size, 16) | 293 | + assert cmp128.shape == (4, 16) |
| 304 | ref = manual_compress(x, md[128], comp128, 128).reshape_as(cmp128) | 294 | ref = manual_compress(x, md[128], comp128, 128).reshape_as(cmp128) |
| 305 | _assert_rounding_floor((cmp128 - ref).abs(), ref.abs().max().item()) | 295 | _assert_rounding_floor((cmp128 - ref).abs(), ref.abs().max().item()) |
| 306 | - # Reframing the same document stream must preserve its exact backward, including | ||
| 307 | - # nonuniform upstream gradients. The independent per-document oracle above checks math. | ||
| 308 | - packed = comp128(x.reshape(1, -1, DIM), pos.reshape(1, -1), cu_seqlens=md[128].swa_k.cu_seqlens) | ||
| 309 | - upstream = torch.linspace(-0.25, 0.75, cmp128.numel()).reshape_as(cmp128) | ||
| 310 | - parameters = (x, *comp128.parameters()) | ||
| 311 | - for actual, expected in zip( | ||
| 312 | - torch.autograd.grad((cmp128 * upstream).sum(), parameters), | ||
| 313 | - torch.autograd.grad((packed.reshape_as(cmp128) * upstream).sum(), parameters), | ||
| 314 | - strict=True, | ||
| 315 | - ): | ||
| 316 | - torch.testing.assert_close(actual, expected, rtol=0, atol=0) | ||
| 317 | - | ||
| 318 | - | ||
| 319 | -@pytest.mark.parametrize("operation", ["selection", "student-logits"]) | ||
| 320 | -def test_reference_indexer_refuses_mbs_above_one(dsv4, operation): | ||
| 321 | - idx_q = torch.randn(2, 8, 2, DIM) | ||
| 322 | - idx_k = torch.randn(2, 2, DIM) | ||
| 323 | - idx_w = torch.randn(2, 8, 2) | ||
| 324 | - cu_seq_q = torch.tensor([0, 8, 16], dtype=torch.int32) | ||
| 325 | - cu_seq_k = torch.tensor([0, 2, 4], dtype=torch.int32) | ||
| 326 | - | ||
| 327 | - with pytest.raises(ValueError, match="MBS>1 is currently supported only by the fused path"): | ||
| 328 | - if operation == "selection": | ||
| 329 | - dsv4.compressor.select_compressed_slots(idx_q, idx_k, idx_w, cu_seq_q, cu_seq_k, 1) | ||
| 330 | - else: | ||
| 331 | - picks = torch.zeros(2, 8, 1, dtype=torch.int64) | ||
| 332 | - dsv4.compressor.student_logits_at_picks(idx_q, idx_k, idx_w, picks, cu_seq_q, cu_seq_k) | ||
| 333 | 296 | ||
| 334 | 297 | ||
| 335 | def test_attention_numerics_ratio4_single_block_documents(dsv4): | 298 | def test_attention_numerics_ratio4_single_block_documents(dsv4): |
| @@ -337,9 +300,9 @@ def test_attention_numerics_ratio4_single_block_documents(dsv4): | |||
| 337 | cu = torch.tensor([0, 4, 8], dtype=torch.int32) | 300 | cu = torch.tensor([0, 4, 8], dtype=torch.int32) |
| 338 | md_s = _metadata_for(dsv4, cu, (4,))[4] | 301 | md_s = _metadata_for(dsv4, cu, (4,))[4] |
| 339 | comp_s = build_compressor(dsv4, 4) | 302 | comp_s = build_compressor(dsv4, 4) |
| 340 | - cmp_s = comp_s(torch.randn(1, 8, DIM), _positions_from(cu), cu_seqlens=md_s.swa_k.cu_seqlens) | 303 | + cmp_s = comp_s(torch.randn(8, DIM), _positions_from(cu), cu_seqlens=md_s.swa_k.cu_seqlens) |
| 341 | # Two documents of exactly one block each: two compressed entries. | 304 | # Two documents of exactly one block each: two compressed entries. |
| 342 | - assert cmp_s.shape == (1, 2, 16) | 305 | + assert cmp_s.shape == (2, 16) |
| 343 | core_s = dsv4.attention.CompressedSparseInnerAttention( | 306 | core_s = dsv4.attention.CompressedSparseInnerAttention( |
| 344 | dsv4.attention.CompressedSparseInnerAttention.Config( | 307 | dsv4.attention.CompressedSparseInnerAttention.Config( |
| 345 | window_size=8, | 308 | window_size=8, |
| @@ -350,16 +313,16 @@ def test_attention_numerics_ratio4_single_block_documents(dsv4): | |||
| 350 | ) | 313 | ) |
| 351 | with torch.no_grad(): | 314 | with torch.no_grad(): |
| 352 | sparse_s = dsv4.compressor.select_compressed_slots( | 315 | sparse_s = dsv4.compressor.select_compressed_slots( |
| 353 | - torch.randn(1, 8, 4, 8), | 316 | + torch.randn(8, 4, 8), |
| 354 | - torch.randn(1, 2, 8), | 317 | + torch.randn(2, 8), |
| 355 | - torch.randn(1, 8, 4), | 318 | + torch.randn(8, 4), |
| 356 | md_s.swa_k.cu_seqlens, | 319 | md_s.swa_k.cu_seqlens, |
| 357 | md_s.cmp_k.cu_seqlens, | 320 | md_s.cmp_k.cu_seqlens, |
| 358 | 4, | 321 | 4, |
| 359 | ) | 322 | ) |
| 360 | out_s = core_s( | 323 | out_s = core_s( |
| 361 | - torch.randn(1, 8, 3, HD), | 324 | + torch.randn(8, 3, HD), |
| 362 | - torch.randn(1, 8, HD), | 325 | + torch.randn(8, HD), |
| 363 | torch.randn(3), | 326 | torch.randn(3), |
| 364 | cmp_k=cmp_s, | 327 | cmp_k=cmp_s, |
| 365 | topk_indices=sparse_s, | 328 | topk_indices=sparse_s, |
| @@ -367,9 +330,9 @@ def test_attention_numerics_ratio4_single_block_documents(dsv4): | |||
| 367 | ) | 330 | ) |
| 368 | # A document's block is complete only at its last token, so the first three queries have | 331 | # A document's block is complete only at its last token, so the first three queries have |
| 369 | # nothing to select and the last token of each document is the one that can. | 332 | # nothing to select and the last token of each document is the one that can. |
| 370 | - assert (sparse_s[0, :3] == -1).all() | 333 | + assert (sparse_s[:3] == -1).all() |
| 371 | - assert (sparse_s[0, 3:] >= 0).any() | 334 | + assert (sparse_s[3:] >= 0).any() |
| 372 | - assert out_s.shape == (1, 8, 3, HD) and torch.isfinite(out_s).all() | 335 | + assert out_s.shape == (8, 3, HD) and torch.isfinite(out_s).all() |
| 373 | 336 | ||
| 374 | 337 | ||
| 375 | def _gradient_case(dsv4, ratio=4): | 338 | def _gradient_case(dsv4, ratio=4): |
| @@ -3,7 +3,19 @@ | |||
| 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 | +from dataclasses import replace | ||
| 7 | + | ||
| 6 | import torch | 8 | import torch |
| 9 | +from torchtitan.components.data import ( | ||
| 10 | + ConcatThenSplitPackingConfig, | ||
| 11 | + GrainDataLoader, | ||
| 12 | + HuggingFaceRandomAccessSource, | ||
| 13 | + SingleDatasetConfig, | ||
| 14 | +) | ||
| 15 | + | ||
| 16 | +from tests.unit_tests.models.common.text_data_utils import IntegerTextTokenizer | ||
| 17 | +from torchtitan_npu.models.common.alignment import AlignedTextProcessor | ||
| 18 | +from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | ||
| 7 | 19 | ||
| 8 | 20 | ||
| 9 | def test_debugmodel_uses_the_documented_per_layer_compression_ratios(): | 21 | def test_debugmodel_uses_the_documented_per_layer_compression_ratios(): |
| @@ -95,43 +107,49 @@ def test_dataloader_pads_documents_to_the_compression_alignment(): | |||
| 95 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | 107 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel |
| 96 | 108 | ||
| 97 | config = deepseek_v4_debugmodel() | 109 | config = deepseek_v4_debugmodel() |
| 98 | - assert config.dataloader.per_doc_alignment == 128 | 110 | + assert isinstance(config.dataloader, GrainDataLoader.Config) |
| 99 | - assert config.training.seq_len % config.dataloader.per_doc_alignment == 0 | 111 | + assert isinstance(config.dataloader.dataset, ConcatThenSplitPackingConfig) |
| 112 | + assert isinstance(config.dataloader.dataset.dataset, SingleDatasetConfig) | ||
| 113 | + assert isinstance(config.dataloader.dataset.dataset.processor, AlignedTextProcessor.Config) | ||
| 114 | + alignment = config.dataloader.dataset.dataset.processor.per_doc_alignment | ||
| 115 | + assert alignment == 128 | ||
| 116 | + assert config.training.max_context_length % alignment == 0 | ||
| 100 | 117 | ||
| 101 | 118 | ||
| 102 | -def test_aligned_dataloader_only_inserts_pads(): | 119 | +def test_aligned_dataloader_only_inserts_pads(tmp_path): |
| 103 | - """Alignment must not drop, reorder or rewrite real tokens. | 120 | + path = tmp_path / "text.jsonl" |
| 121 | + path.write_text('{"text":"3 4"}\n{"text":"5"}\n') | ||
| 122 | + recipe = deepseek_v4_debugmodel() | ||
| 123 | + assert isinstance(recipe.dataloader, GrainDataLoader.Config) | ||
| 124 | + recipe.dataloader.shuffle = False | ||
| 125 | + recipe.dataloader.repeat = False | ||
| 126 | + packing = recipe.dataloader.dataset | ||
| 127 | + assert isinstance(packing, ConcatThenSplitPackingConfig) | ||
| 128 | + assert isinstance(packing.dataset, SingleDatasetConfig) | ||
| 129 | + recipe.dataloader.dataset = replace( | ||
| 130 | + packing, | ||
| 131 | + dataset=replace( | ||
| 132 | + packing.dataset, | ||
| 133 | + source=HuggingFaceRandomAccessSource.Config( | ||
| 134 | + path="json", split="train", load_dataset_kwargs={"data_files": str(path)} | ||
| 135 | + ), | ||
| 136 | + ), | ||
| 137 | + ) | ||
| 138 | + loader = recipe.dataloader.build( | ||
| 139 | + tokenizer=IntegerTextTokenizer(), | ||
| 140 | + dp_world_size=1, | ||
| 141 | + dp_rank=0, | ||
| 142 | + max_context_length=128, | ||
| 143 | + num_tokens_per_batch=256, | ||
| 144 | + ) | ||
| 145 | + try: | ||
| 146 | + batches = list(loader) | ||
| 147 | + finally: | ||
| 148 | + loader.close() | ||
| 104 | 149 | ||
| 105 | - The aligned loader is the plain loader plus per-document padding: stripping | 150 | + assert len(batches) == 1 |
| 106 | - the pads (their labels are ``IGNORE_INDEX``) must give the plain loader's | 151 | + inputs, labels = batches[0] |
| 107 | - stream, token for token. That makes the ST loss shift a packing-density | 152 | + assert inputs["input"].tolist() == [1, 3, 4] + [0] * 125 + [1, 5] + [0] * 126 |
| 108 | - (and row-cut placement) effect rather than a data rewrite. | 153 | + assert labels.tolist() == [3, 4, 2] + [-100] * 125 + [5, 2] + [-100] * 126 |
| 109 | - """ | 154 | + assert inputs["positions"].tolist() == list(range(128)) * 2 |
| 110 | - import torch | 155 | + assert inputs["num_valid_tokens"] == 5 |
| 111 | - from torchtitan.components.loss import IGNORE_INDEX | ||
| 112 | - from torchtitan.components.tokenizer import HuggingFaceTokenizer | ||
| 113 | - from torchtitan_npu.patches.torchtitan.hf_datasets.text_datasets import AlignedTextDataset | ||
| 114 | - | ||
| 115 | - tokenizer = HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3") | ||
| 116 | - | ||
| 117 | - def rows(alignment): | ||
| 118 | - dataset = AlignedTextDataset( | ||
| 119 | - dataset_name="c4_test", | ||
| 120 | - dataset_path="tests/assets/c4_test", | ||
| 121 | - tokenizer=tokenizer, | ||
| 122 | - seq_len=1024, | ||
| 123 | - per_doc_alignment=alignment, | ||
| 124 | - infinite=True, | ||
| 125 | - ) | ||
| 126 | - rows_out = [] | ||
| 127 | - for index, (sample, labels) in enumerate(dataset): | ||
| 128 | - if index == 2: | ||
| 129 | - break | ||
| 130 | - rows_out.append((sample["input"], labels)) | ||
| 131 | - return torch.cat([row[0] for row in rows_out]), torch.cat([row[1] for row in rows_out]) | ||
| 132 | - | ||
| 133 | - plain_ids, _ = rows(1) | ||
| 134 | - aligned_ids, aligned_labels = rows(128) | ||
| 135 | - real_ids = aligned_ids[aligned_labels != IGNORE_INDEX] | ||
| 136 | - assert (aligned_labels == IGNORE_INDEX).sum() > 0 | ||
| 137 | - assert torch.equal(real_ids, plain_ids[: real_ids.numel()]) | ||
| @@ -29,7 +29,7 @@ _WINDOW, _SCALE, _TOPK = 8, 0.25, 8 | |||
| 29 | 29 | ||
| 30 | def _metadata(dsv4, cu): | 30 | def _metadata(dsv4, cu): |
| 31 | """One entry per geometry, the way each layer's own config builds it.""" | 31 | """One entry per geometry, the way each layer's own config builds it.""" |
| 32 | - positions = torch.cat([torch.arange(end - start) for start, end in pairwise(cu.tolist())]).unsqueeze(0) | 32 | + positions = torch.cat([torch.arange(end - start) for start, end in pairwise(cu.tolist())]) |
| 33 | return {ratio: dsv4.metadata.build_v4_metadata(positions, ratio, cu_seq_q=cu) for ratio in _RATIOS} | 33 | return {ratio: dsv4.metadata.build_v4_metadata(positions, ratio, cu_seq_q=cu) for ratio in _RATIOS} |
| 34 | 34 | ||
| 35 | 35 | ||
| @@ -50,9 +50,9 @@ def _inputs(ratio, cu, seed=0): | |||
| 50 | torch.manual_seed(seed) | 50 | torch.manual_seed(seed) |
| 51 | seqlen, heads = int(cu[-1]), 3 | 51 | seqlen, heads = int(cu[-1]), 3 |
| 52 | n_cmp = 0 if ratio == 1 else seqlen // ratio | 52 | n_cmp = 0 if ratio == 1 else seqlen // ratio |
| 53 | - q = torch.randn(1, seqlen, heads, HD) | 53 | + q = torch.randn(seqlen, heads, HD) |
| 54 | - swa_k = torch.randn(1, seqlen, HD) | 54 | + swa_k = torch.randn(seqlen, HD) |
| 55 | - cmp_k = None if n_cmp == 0 else torch.randn(1, n_cmp, HD) | 55 | + cmp_k = None if n_cmp == 0 else torch.randn(n_cmp, HD) |
| 56 | return q, swa_k, cmp_k, torch.randn(heads) | 56 | return q, swa_k, cmp_k, torch.randn(heads) |
| 57 | 57 | ||
| 58 | 58 | ||
| @@ -80,9 +80,9 @@ def test_the_core_reads_only_the_packed_offsets(dsv4): | |||
| 80 | q, swa_k, cmp_k, sink = _inputs(4, _SHORT) | 80 | q, swa_k, cmp_k, sink = _inputs(4, _SHORT) |
| 81 | torch.manual_seed(2) | 81 | torch.manual_seed(2) |
| 82 | picks = dsv4.compressor.select_compressed_slots( | 82 | picks = dsv4.compressor.select_compressed_slots( |
| 83 | - torch.randn(1, seqlen, 4, 8), | 83 | + torch.randn(seqlen, 4, 8), |
| 84 | - torch.randn(1, seqlen // 4, 8), | 84 | + torch.randn(seqlen // 4, 8), |
| 85 | - torch.randn(1, seqlen, 4), | 85 | + torch.randn(seqlen, 4), |
| 86 | common[4].swa_k.cu_seqlens, | 86 | common[4].swa_k.cu_seqlens, |
| 87 | common[4].cmp_k.cu_seqlens, | 87 | common[4].cmp_k.cu_seqlens, |
| 88 | _TOPK, | 88 | _TOPK, |
| @@ -91,7 +91,7 @@ def test_the_core_reads_only_the_packed_offsets(dsv4): | |||
| 91 | with torch.no_grad(): | 91 | with torch.no_grad(): |
| 92 | out = _core(dsv4, 4)(q, swa_k, sink, cmp_k=cmp_k, topk_indices=picks, attention_metadata=common[4]) | 92 | out = _core(dsv4, 4)(q, swa_k, sink, cmp_k=cmp_k, topk_indices=picks, attention_metadata=common[4]) |
| 93 | 93 | ||
| 94 | - assert out.shape == (1, seqlen, 3, HD) and torch.isfinite(out).all() | 94 | + assert out.shape == (seqlen, 3, HD) and torch.isfinite(out).all() |
| 95 | 95 | ||
| 96 | 96 | ||
| 97 | def test_hca_slots_stay_inside_the_query_document(dsv4): | 97 | def test_hca_slots_stay_inside_the_query_document(dsv4): |
| @@ -124,7 +124,7 @@ def test_the_teacher_exit_is_reserved_and_inert(dsv4): | |||
| 124 | with_lse, lse = _core(dsv4, 128, return_lse=True)(q, swa_k, sink, cmp_k=cmp_k, attention_metadata=metadata[128]) | 124 | with_lse, lse = _core(dsv4, 128, return_lse=True)(q, swa_k, sink, cmp_k=cmp_k, attention_metadata=metadata[128]) |
| 125 | 125 | ||
| 126 | assert torch.equal(plain, with_lse) | 126 | assert torch.equal(plain, with_lse) |
| 127 | - assert lse.shape == (1, 3, seqlen) and torch.isfinite(lse).all() | 127 | + assert lse.shape == (3, seqlen) and torch.isfinite(lse).all() |
| 128 | 128 | ||
| 129 | 129 | ||
| 130 | def test_the_reference_core_ignores_the_selector_scores(dsv4): | 130 | def test_the_reference_core_ignores_the_selector_scores(dsv4): |
| @@ -134,14 +134,14 @@ def test_the_reference_core_ignores_the_selector_scores(dsv4): | |||
| 134 | q, swa_k, cmp_k, sink = _inputs(4, _SHORT) | 134 | q, swa_k, cmp_k, sink = _inputs(4, _SHORT) |
| 135 | torch.manual_seed(3) | 135 | torch.manual_seed(3) |
| 136 | picks = dsv4.compressor.select_compressed_slots( | 136 | picks = dsv4.compressor.select_compressed_slots( |
| 137 | - torch.randn(1, seqlen, 4, 8), | 137 | + torch.randn(seqlen, 4, 8), |
| 138 | - torch.randn(1, seqlen // 4, 8), | 138 | + torch.randn(seqlen // 4, 8), |
| 139 | - torch.randn(1, seqlen, 4), | 139 | + torch.randn(seqlen, 4), |
| 140 | common[4].swa_k.cu_seqlens, | 140 | common[4].swa_k.cu_seqlens, |
| 141 | common[4].cmp_k.cu_seqlens, | 141 | common[4].cmp_k.cu_seqlens, |
| 142 | _TOPK, | 142 | _TOPK, |
| 143 | ) | 143 | ) |
| 144 | - scores = torch.randn(1, seqlen, picks.shape[-1], requires_grad=True) | 144 | + scores = torch.randn(seqlen, picks.shape[-1], requires_grad=True) |
| 145 | 145 | ||
| 146 | with torch.no_grad(): | 146 | with torch.no_grad(): |
| 147 | without = _core(dsv4, 4)(q, swa_k, sink, cmp_k=cmp_k, topk_indices=picks, attention_metadata=common[4]) | 147 | without = _core(dsv4, 4)(q, swa_k, sink, cmp_k=cmp_k, topk_indices=picks, attention_metadata=common[4]) |
| @@ -203,8 +203,8 @@ def test_registry_model_forward_backward_freezes_base_and_differentiates_adapter | |||
| 203 | model = spec.model.build() | 203 | model = spec.model.build() |
| 204 | model.init_states() | 204 | model.init_states() |
| 205 | model = spec.parallelize_fn(model, **parallelize_kwargs) | 205 | model = spec.parallelize_fn(model, **parallelize_kwargs) |
| 206 | - inputs = torch.arange(128).reshape(1, 128) | 206 | + inputs = torch.arange(128) |
| 207 | - inputs, _, kwargs = preprocess(model, inputs, inputs, torch.arange(128).reshape(1, 128)) | 207 | + inputs, _, kwargs = preprocess(model, inputs, inputs, torch.arange(128)) |
| 208 | output = model(inputs, **kwargs) | 208 | output = model(inputs, **kwargs) |
| 209 | assert torch.isfinite(output).all() | 209 | assert torch.isfinite(output).all() |
| 210 | output.float().square().mean().backward() | 210 | output.float().square().mean().backward() |
| @@ -243,10 +243,10 @@ def test_shared_parallelization_and_optimizer_hook_preserve_training_mode( | |||
| 243 | from torch.utils.checkpoint import checkpoint, create_selective_checkpoint_contexts | 243 | from torch.utils.checkpoint import checkpoint, create_selective_checkpoint_contexts |
| 244 | from functools import partial | 244 | from functools import partial |
| 245 | 245 | ||
| 246 | - q = torch.randn(1, 4, 2, 3, requires_grad=True) | 246 | + q = torch.randn(4, 2, 3, requires_grad=True) |
| 247 | - k = torch.randn(1, 2, 3, requires_grad=True) | 247 | + k = torch.randn(2, 3, requires_grad=True) |
| 248 | - w = torch.randn(1, 4, 2, requires_grad=True) | 248 | + w = torch.randn(4, 2, requires_grad=True) |
| 249 | - picks = torch.tensor([[0, 1]] * 4, dtype=torch.int64).view(1, 4, 2) | 249 | + picks = torch.tensor([[0, 1]] * 4, dtype=torch.int64) |
| 250 | cu_seqlens = torch.tensor([0, 4], dtype=torch.int32) | 250 | cu_seqlens = torch.tensor([0, 4], dtype=torch.int32) |
| 251 | cu_seqlens_k = torch.tensor([0, 2], dtype=torch.int32) | 251 | cu_seqlens_k = torch.tensor([0, 2], dtype=torch.int32) |
| 252 | context = partial(create_selective_checkpoint_contexts, list(ac.build().get_save_ops())) | 252 | context = partial(create_selective_checkpoint_contexts, list(ac.build().get_save_ops())) |
| @@ -263,11 +263,11 @@ def test_shared_parallelization_and_optimizer_hook_preserve_training_mode( | |||
| 263 | ) | 263 | ) |
| 264 | expected = torch.stack( | 264 | expected = torch.stack( |
| 265 | [ | 265 | [ |
| 266 | - (torch.einsum("hd,d->h", q[0, token], k[0, pick]).relu() * w[0, token]).sum() | 266 | + (torch.einsum("hd,d->h", q[token], k[pick]).relu() * w[token]).sum() |
| 267 | for token in range(4) | 267 | for token in range(4) |
| 268 | for pick in (0, 1) | 268 | for pick in (0, 1) |
| 269 | ] | 269 | ] |
| 270 | - ).view(1, 4, 2) | 270 | + ).view(4, 2) |
| 271 | torch.testing.assert_close(actual, expected) | 271 | torch.testing.assert_close(actual, expected) |
| 272 | for result, reference in zip( | 272 | for result, reference in zip( |
| 273 | torch.autograd.grad(actual.sum(), (q, k, w)), | 273 | torch.autograd.grad(actual.sum(), (q, k, w)), |
| @@ -44,13 +44,15 @@ def _assert_gradients_match(actual, expected, variables, *, rtol=1e-5, atol=1e-6 | |||
| 44 | torch.testing.assert_close(result, reference, rtol=rtol, atol=atol) | 44 | torch.testing.assert_close(result, reference, rtol=rtol, atol=atol) |
| 45 | 45 | ||
| 46 | 46 | ||
| 47 | -def _grouped_mm(*, A, B_t, offs): | 47 | +def _grouped_mm(*, A, weight_EOI, offs): |
| 48 | + # The upstream seam casts and transposes the stored-orientation weight itself. | ||
| 49 | + weight_EOI = weight_EOI.bfloat16() | ||
| 48 | outputs = [] | 50 | outputs = [] |
| 49 | start = 0 | 51 | start = 0 |
| 50 | for expert, end in enumerate(offs.tolist()): | 52 | for expert, end in enumerate(offs.tolist()): |
| 51 | - outputs.append(A[start:end] @ B_t[expert]) | 53 | + outputs.append(A[start:end] @ weight_EOI[expert].transpose(-2, -1)) |
| 52 | start = end | 54 | start = end |
| 53 | - return torch.cat(outputs) if outputs else A.new_empty((0, B_t.shape[-1])) | 55 | + return torch.cat(outputs) if outputs else A.new_empty((0, weight_EOI.shape[-2])) |
| 54 | 56 | ||
| 55 | 57 | ||
| 56 | _GroupedLoRAExperts = lora.grouped_lora_class(moe.GroupedExperts) | 58 | _GroupedLoRAExperts = lora.grouped_lora_class(moe.GroupedExperts) |
| @@ -61,8 +63,8 @@ class _CpuGroupedLoRAExperts(_GroupedLoRAExperts): | |||
| 61 | class Config(_GroupedLoRAExperts.Config): | 63 | class Config(_GroupedLoRAExperts.Config): |
| 62 | pass | 64 | pass |
| 63 | 65 | ||
| 64 | - def _grouped_mm(self, *, A, B_t, offs): | 66 | + def _grouped_mm(self, *, A, weight_EOI, offs): |
| 65 | - return _grouped_mm(A=A, B_t=B_t, offs=offs) | 67 | + return _grouped_mm(A=A, weight_EOI=weight_EOI, offs=offs) |
| 66 | 68 | ||
| 67 | 69 | ||
| 68 | def _build_cpu_grouped_lora_module() -> _CpuGroupedLoRAExperts: | 70 | def _build_cpu_grouped_lora_module() -> _CpuGroupedLoRAExperts: |
| @@ -110,10 +112,11 @@ def _per_expert_lora_reference(module, inputs, counts, scores, limit): | |||
| 110 | 112 | ||
| 111 | 113 | ||
| 112 | def test_indexer_scores_and_gradients_with_checkpoint(forward_with_checkpoint): | 114 | def test_indexer_scores_and_gradients_with_checkpoint(forward_with_checkpoint): |
| 113 | - query = torch.randn(1, 4, 2, 3, requires_grad=True) | 115 | + # The folded call form: one packed row, ``[T, H, D]`` queries against ``[N, D]`` keys. |
| 114 | - key = torch.randn(1, 2, 3, requires_grad=True) | 116 | + query = torch.randn(4, 2, 3, requires_grad=True) |
| 115 | - weight = torch.randn(1, 4, 2, requires_grad=True) | 117 | + key = torch.randn(2, 3, requires_grad=True) |
| 116 | - picks = torch.tensor([[0, 1]] * 4, dtype=torch.int64).view(1, 4, 2) | 118 | + weight = torch.randn(4, 2, requires_grad=True) |
| 119 | + picks = torch.tensor([[0, 1]] * 4, dtype=torch.int64) | ||
| 117 | cu_seqlens = torch.tensor([0, 4], dtype=torch.int32) | 120 | cu_seqlens = torch.tensor([0, 4], dtype=torch.int32) |
| 118 | cu_seqlens_k = torch.tensor([0, 2], dtype=torch.int32) | 121 | cu_seqlens_k = torch.tensor([0, 2], dtype=torch.int32) |
| 119 | actual = forward_with_checkpoint( | 122 | actual = forward_with_checkpoint( |
| @@ -121,11 +124,11 @@ def test_indexer_scores_and_gradients_with_checkpoint(forward_with_checkpoint): | |||
| 121 | ) | 124 | ) |
| 122 | expected = torch.stack( | 125 | expected = torch.stack( |
| 123 | [ | 126 | [ |
| 124 | - (torch.einsum("hd,d->h", query[0, token], key[0, pick]).relu() * weight[0, token]).sum() | 127 | + (torch.einsum("hd,d->h", query[token], key[pick]).relu() * weight[token]).sum() |
| 125 | for token in range(4) | 128 | for token in range(4) |
| 126 | for pick in (0, 1) | 129 | for pick in (0, 1) |
| 127 | ] | 130 | ] |
| 128 | - ).view(1, 4, 2) | 131 | + ).view(4, 2) |
| 129 | torch.testing.assert_close(actual, expected) | 132 | torch.testing.assert_close(actual, expected) |
| 130 | _assert_gradients_match(actual, expected, (query, key, weight)) | 133 | _assert_gradients_match(actual, expected, (query, key, weight)) |
| 131 | 134 | ||
| @@ -41,7 +41,7 @@ def _converted_debug_model() -> torch.nn.Module: | |||
| 41 | @pytest.mark.parametrize("checkpointed", [False, True]) | 41 | @pytest.mark.parametrize("checkpointed", [False, True]) |
| 42 | def test_muon_group_is_non_empty_and_every_member_has_a_compute_layout(monkeypatch, checkpointed): | 42 | def test_muon_group_is_non_empty_and_every_member_has_a_compute_layout(monkeypatch, checkpointed): |
| 43 | from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper | 43 | from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper |
| 44 | - from torchtitan.components.checkpoint_utils import canonical_fqn | 44 | + from torchtitan.components.checkpointer.utils import canonical_fqn |
| 45 | 45 | ||
| 46 | base_spec = model_registry("debugmodel", num_mtp_layers=1) | 46 | base_spec = model_registry("debugmodel", num_mtp_layers=1) |
| 47 | profile = _dsv4_muon_profile(base_spec) | 47 | profile = _dsv4_muon_profile(base_spec) |
| @@ -16,7 +16,7 @@ from torch import distributed as dist, multiprocessing as mp | |||
| 16 | from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper | 16 | from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper |
| 17 | from torch.distributed.device_mesh import init_device_mesh | 17 | from torch.distributed.device_mesh import init_device_mesh |
| 18 | from torch.distributed.tensor import Shard, distribute_tensor | 18 | from torch.distributed.tensor import Shard, distribute_tensor |
| 19 | -from torchtitan.components.checkpoint import ModelWrapper | 19 | +from torchtitan.components.checkpointer import ModelWrapper |
| 20 | from torchtitan_npu.models.deepseek_v4 import lora, peft, state_dict_adapter | 20 | from torchtitan_npu.models.deepseek_v4 import lora, peft, state_dict_adapter |
| 21 | from tests.unit_tests.models.deepseek_v4.lora_test_utils import _adapter_with_converter | 21 | from tests.unit_tests.models.deepseek_v4.lora_test_utils import _adapter_with_converter |
| 22 | 22 | ||
| @@ -22,20 +22,20 @@ _RATIO = 4 | |||
| 22 | _DOC = 8 # three documents of eight tokens: two compressed slots each | 22 | _DOC = 8 # three documents of eight tokens: two compressed slots each |
| 23 | _CU = torch.tensor([0, _DOC, 2 * _DOC, 3 * _DOC], dtype=torch.int32) | 23 | _CU = torch.tensor([0, _DOC, 2 * _DOC, 3 * _DOC], dtype=torch.int32) |
| 24 | # Per row, the picks in the selection's own numbering; the middle document pads its second slot. | 24 | # Per row, the picks in the selection's own numbering; the middle document pads its second slot. |
| 25 | -_PICKS = torch.tensor([[0, 1]] * _DOC + [[0, -1]] * _DOC + [[1, -1]] * _DOC, dtype=torch.int64).view(1, -1, 2) | 25 | +_PICKS = torch.tensor([[0, 1]] * _DOC + [[0, -1]] * _DOC + [[1, -1]] * _DOC, dtype=torch.int64).view(-1, 2) |
| 26 | 26 | ||
| 27 | 27 | ||
| 28 | def _metadata(dsv4): | 28 | def _metadata(dsv4): |
| 29 | - positions = torch.cat([torch.arange(end - start) for start, end in pairwise(_CU.tolist())]).unsqueeze(0) | 29 | + positions = torch.cat([torch.arange(end - start) for start, end in pairwise(_CU.tolist())]) |
| 30 | return dsv4.metadata.build_v4_metadata(positions, _RATIO, cu_seq_q=_CU) | 30 | return dsv4.metadata.build_v4_metadata(positions, _RATIO, cu_seq_q=_CU) |
| 31 | 31 | ||
| 32 | 32 | ||
| 33 | def _inputs(seqlen, seed=0): | 33 | def _inputs(seqlen, seed=0): |
| 34 | torch.manual_seed(seed) | 34 | torch.manual_seed(seed) |
| 35 | return ( | 35 | return ( |
| 36 | - torch.randn(1, seqlen, 2, DIM, dtype=torch.float64), | 36 | + torch.randn(seqlen, 2, DIM, dtype=torch.float64), |
| 37 | - torch.randn(1, seqlen // _RATIO, DIM, dtype=torch.float64), | 37 | + torch.randn(seqlen // _RATIO, DIM, dtype=torch.float64), |
| 38 | - torch.randn(1, seqlen, 2, dtype=torch.float64), | 38 | + torch.randn(seqlen, 2, dtype=torch.float64), |
| 39 | ) | 39 | ) |
| 40 | 40 | ||
| 41 | 41 | ||
| @@ -54,21 +54,21 @@ def test_student_logits_rescore_a_document_local_selection(dsv4): | |||
| 54 | 54 | ||
| 55 | scores = _rescore(dsv4, metadata, idx_q, idx_k, idx_w, _PICKS) | 55 | scores = _rescore(dsv4, metadata, idx_q, idx_k, idx_w, _PICKS) |
| 56 | 56 | ||
| 57 | - expected = torch.full((1, seqlen, 2), -torch.inf, dtype=torch.float64) | 57 | + expected = torch.full((seqlen, 2), -torch.inf, dtype=torch.float64) |
| 58 | for token in range(seqlen): | 58 | for token in range(seqlen): |
| 59 | start = int(starts[token // _DOC]) | 59 | start = int(starts[token // _DOC]) |
| 60 | - for slot, local in enumerate(_PICKS[0, token].tolist()): | 60 | + for slot, local in enumerate(_PICKS[token].tolist()): |
| 61 | if local < 0: | 61 | if local < 0: |
| 62 | continue | 62 | continue |
| 63 | - dot = torch.einsum("hd,d->h", idx_q[0, token], idx_k[0, start + local]) | 63 | + dot = torch.einsum("hd,d->h", idx_q[token], idx_k[start + local]) |
| 64 | - expected[0, token, slot] = (dot.relu() * idx_w[0, token]).sum() | 64 | + expected[token, slot] = (dot.relu() * idx_w[token]).sum() |
| 65 | 65 | ||
| 66 | torch.testing.assert_close(scores, expected, rtol=1e-12, atol=1e-12) | 66 | torch.testing.assert_close(scores, expected, rtol=1e-12, atol=1e-12) |
| 67 | # The marking agrees with the selection slot for slot: only -1 is un-scored. | 67 | # The marking agrees with the selection slot for slot: only -1 is un-scored. |
| 68 | assert torch.equal(torch.isfinite(scores), _PICKS >= 0) | 68 | assert torch.equal(torch.isfinite(scores), _PICKS >= 0) |
| 69 | # Reading the same pick row-wide would score document 0's entry instead. | 69 | # Reading the same pick row-wide would score document 0's entry instead. |
| 70 | - row_wide = (torch.einsum("hd,d->h", idx_q[0, _DOC], idx_k[0, 0]).relu() * idx_w[0, _DOC]).sum() | 70 | + row_wide = (torch.einsum("hd,d->h", idx_q[_DOC], idx_k[0]).relu() * idx_w[_DOC]).sum() |
| 71 | - assert not torch.isclose(scores[0, _DOC, 0], row_wide) | 71 | + assert not torch.isclose(scores[_DOC, 0], row_wide) |
| 72 | 72 | ||
| 73 | 73 | ||
| 74 | def test_the_rescore_carries_the_indexer_gradient(dsv4): | 74 | def test_the_rescore_carries_the_indexer_gradient(dsv4): |
| @@ -95,7 +95,7 @@ def test_a_document_without_a_pick_gets_no_indexer_gradient(dsv4): | |||
| 95 | metadata = _metadata(dsv4) | 95 | metadata = _metadata(dsv4) |
| 96 | seqlen = int(_CU[-1]) | 96 | seqlen = int(_CU[-1]) |
| 97 | picks = torch.full_like(_PICKS, -1) | 97 | picks = torch.full_like(_PICKS, -1) |
| 98 | - picks[:, :_DOC] = 0 | 98 | + picks[:_DOC] = 0 |
| 99 | idx_q, idx_k, idx_w = (tensor.clone().requires_grad_(True) for tensor in _inputs(seqlen)) | 99 | idx_q, idx_k, idx_w = (tensor.clone().requires_grad_(True) for tensor in _inputs(seqlen)) |
| 100 | 100 | ||
| 101 | _rescore(dsv4, metadata, idx_q, idx_k, idx_w, picks).sum().backward() | 101 | _rescore(dsv4, metadata, idx_q, idx_k, idx_w, picks).sum().backward() |
| @@ -128,7 +128,7 @@ def test_lightning_indexer_returns_the_selection_and_its_scores(dsv4): | |||
| 128 | 128 | ||
| 129 | picks, scores = module(idx_q, idx_k, idx_w, attention_metadata=metadata) | 129 | picks, scores = module(idx_q, idx_k, idx_w, attention_metadata=metadata) |
| 130 | 130 | ||
| 131 | - assert picks.shape == (1, seqlen, 2) and picks.dtype == torch.int32 | 131 | + assert picks.shape == (seqlen, 2) and picks.dtype == torch.int32 |
| 132 | assert scores.shape == picks.shape | 132 | assert scores.shape == picks.shape |
| 133 | # The reference emits the selection operator's order; only the set and the ``-1`` | 133 | # The reference emits the selection operator's order; only the set and the ``-1`` |
| 134 | # marking are part of the shared contract. | 134 | # marking are part of the shared contract. |
| @@ -155,7 +155,7 @@ def test_lightning_indexer_returns_the_selection_and_its_scores(dsv4): | |||
| 155 | 155 | ||
| 156 | 156 | ||
| 157 | def test_lightning_indexer_refuses_a_geometry_without_a_compressed_pool(dsv4): | 157 | def test_lightning_indexer_refuses_a_geometry_without_a_compressed_pool(dsv4): |
| 158 | - positions = torch.cat([torch.arange(end - start) for start, end in pairwise(_CU.tolist())]).unsqueeze(0) | 158 | + positions = torch.cat([torch.arange(end - start) for start, end in pairwise(_CU.tolist())]) |
| 159 | metadata = dsv4.metadata.build_v4_metadata(positions, 1) | 159 | metadata = dsv4.metadata.build_v4_metadata(positions, 1) |
| 160 | module = dsv4.compressor.LightningIndexer(dsv4.compressor.LightningIndexer.Config(index_topk=2)) | 160 | module = dsv4.compressor.LightningIndexer(dsv4.compressor.LightningIndexer.Config(index_topk=2)) |
| 161 | idx_q, idx_k, idx_w = _inputs(int(_CU[-1])) | 161 | idx_q, idx_k, idx_w = _inputs(int(_CU[-1])) |
| @@ -50,7 +50,7 @@ def _positions(*documents: int) -> torch.Tensor: | |||
| 50 | flat: list[int] = [] | 50 | flat: list[int] = [] |
| 51 | for length in documents: | 51 | for length in documents: |
| 52 | flat += list(range(length)) | 52 | flat += list(range(length)) |
| 53 | - return torch.tensor([flat]) | 53 | + return torch.tensor(flat) |
| 54 | 54 | ||
| 55 | 55 | ||
| 56 | def _row(positions: torch.Tensor, *, ratio: int = _RATIO): | 56 | def _row(positions: torch.Tensor, *, ratio: int = _RATIO): |
| @@ -68,7 +68,7 @@ def _entry(positions: torch.Tensor, *, ratio: int = _RATIO): | |||
| 68 | 68 | ||
| 69 | 69 | ||
| 70 | def _masks(bounds: list[int], cp_size: int = 1, cp_rank: int = 0, ratio: int = _RATIO): | 70 | def _masks(bounds: list[int], cp_size: int = 1, cp_rank: int = 0, ratio: int = _RATIO): |
| 71 | - positions = torch.cat([torch.arange(end - begin) for begin, end in pairwise(bounds)]).unsqueeze(0) | 71 | + positions = torch.cat([torch.arange(end - begin) for begin, end in pairwise(bounds)]) |
| 72 | entry = _entry(positions, ratio=ratio) | 72 | entry = _entry(positions, ratio=ratio) |
| 73 | if cp_size == 1: | 73 | if cp_size == 1: |
| 74 | return entry | 74 | return entry |
| @@ -315,7 +315,7 @@ def _compressor(ratio: int = _RATIO) -> Compressor: | |||
| 315 | def _carry(module: Compressor, exchange: CarryExchange, x, positions, cu_seqlens): | 315 | def _carry(module: Compressor, exchange: CarryExchange, x, positions, cu_seqlens): |
| 316 | """The call site's composition: exchange -> compress -> trim.""" | 316 | """The call site's composition: exchange -> compress -> trim.""" |
| 317 | carry = exchange(x, positions, cu_seqlens) | 317 | carry = exchange(x, positions, cu_seqlens) |
| 318 | - out = module(carry.x, carry.positions, cu_seqlens=carry.cu_seqlens) | 318 | + out = module(carry.x.squeeze(0), carry.positions.squeeze(0), cu_seqlens=carry.cu_seqlens).unsqueeze(0) |
| 319 | if carry.trim: | 319 | if carry.trim: |
| 320 | out = out.narrow(1, carry.trim, out.size(1) - carry.trim) | 320 | out = out.narrow(1, carry.trim, out.size(1) - carry.trim) |
| 321 | return out | 321 | return out |
| @@ -361,7 +361,9 @@ def test_the_carry_reproduces_the_whole_row_pool(cp_size, monkeypatch): | |||
| 361 | total = 16 * ratio | 361 | total = 16 * ratio |
| 362 | doc_len = total // 2 | 362 | doc_len = total // 2 |
| 363 | bounds = [0, doc_len, total] | 363 | bounds = [0, doc_len, total] |
| 364 | - positions = torch.cat([torch.arange(end - begin) for begin, end in pairwise(bounds)]).unsqueeze(0) | 364 | + # The production call site (compressor.py) hands the exchange one row at a |
| 365 | + # time: ``[1, rows, D]`` tokens with ``[1, rows]`` positions. | ||
| 366 | + positions = torch.cat([torch.arange(end - begin) for begin, end in pairwise(bounds)])[None, :] | ||
| 365 | cu = torch.tensor(bounds, dtype=torch.int32) | 367 | cu = torch.tensor(bounds, dtype=torch.int32) |
| 366 | module = _compressor(ratio) | 368 | module = _compressor(ratio) |
| 367 | generator = torch.Generator().manual_seed(11) | 369 | generator = torch.Generator().manual_seed(11) |
| @@ -369,7 +371,7 @@ def test_the_carry_reproduces_the_whole_row_pool(cp_size, monkeypatch): | |||
| 369 | slab = total // cp_size | 371 | slab = total // cp_size |
| 370 | 372 | ||
| 371 | with torch.no_grad(): | 373 | with torch.no_grad(): |
| 372 | - global_pool = module(x, positions, cu_seqlens=cu) | 374 | + global_pool = module(x.squeeze(0), positions.reshape(-1), cu_seqlens=cu).unsqueeze(0) |
| 373 | assert global_pool.shape == (1, total // ratio, _HEAD_DIM) | 375 | assert global_pool.shape == (1, total // ratio, _HEAD_DIM) |
| 374 | 376 | ||
| 375 | def fake_all_to_all(send, *, output_split_sizes, input_split_sizes, group): | 377 | def fake_all_to_all(send, *, output_split_sizes, input_split_sizes, group): |
| @@ -34,7 +34,7 @@ _INDEX_N_HEADS, _INDEX_HEAD_DIM, _INDEX_TOPK, _WINDOW = 2, 8, 16, 128 | |||
| 34 | 34 | ||
| 35 | 35 | ||
| 36 | def _positions_for(doc_lens) -> torch.Tensor: | 36 | def _positions_for(doc_lens) -> torch.Tensor: |
| 37 | - return torch.cat([torch.arange(length) for length in doc_lens]).unsqueeze(0) | 37 | + return torch.cat([torch.arange(length) for length in doc_lens]) |
| 38 | 38 | ||
| 39 | 39 | ||
| 40 | def _model_config(ratios: tuple[int, ...], *, ascendc: bool, geometry: dict | None = None): | 40 | def _model_config(ratios: tuple[int, ...], *, ascendc: bool, geometry: dict | None = None): |
| @@ -100,6 +100,19 @@ def _entry(model, ratio: int = 4, positions=None): | |||
| 100 | return matches[0] | 100 | return matches[0] |
| 101 | 101 | ||
| 102 | 102 | ||
| 103 | +def test_model_config_accepts_cp_with_aligned_documents(): | ||
| 104 | + from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | ||
| 105 | + | ||
| 106 | + config = deepseek_v4_debugmodel() | ||
| 107 | + config.parallelism.context_parallel_degree = 2 | ||
| 108 | + config.parallelism.spmd_backend = "spmd_types" | ||
| 109 | + config.dataloader.dataset.dataset.processor.per_doc_alignment = 256 | ||
| 110 | + | ||
| 111 | + config.model_spec.model.update_from_config(config=config) | ||
| 112 | + | ||
| 113 | + assert all(layer.attention.inner_attention.sharding_config is not None for layer in config.model_spec.model.layers) | ||
| 114 | + | ||
| 115 | + | ||
| 103 | def test_entries_are_built_per_geometry(): | 116 | def test_entries_are_built_per_geometry(): |
| 104 | """One entry per (backend class, ratio), and every layer dispatches by its own key.""" | 117 | """One entry per (backend class, ratio), and every layer dispatches by its own key.""" |
| 105 | model = _model_config((1, 1, 4, 128), ascendc=False).build() | 118 | model = _model_config((1, 1, 4, 128), ascendc=False).build() |
| @@ -122,7 +135,11 @@ def test_entries_are_built_per_geometry(): | |||
| 122 | 135 | ||
| 123 | @pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"]) | 136 | @pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"]) |
| 124 | def test_attention_without_cp_matches_independent_samples(batch_size, monkeypatch): | 137 | def test_attention_without_cp_matches_independent_samples(batch_size, monkeypatch): |
| 125 | - """No-CP attention must preserve independent batch rows and their gradients.""" | 138 | + """No-CP attention must preserve independent document rows and their gradients. |
| 139 | + | ||
| 140 | + The folded row packs what used to be batch samples as documents, so the | ||
| 141 | + oracle applies the same initialized layer to each document separately. | ||
| 142 | + """ | ||
| 126 | seq_len = 8 | 143 | seq_len = 8 |
| 127 | with torch.random.fork_rng(devices=[]): | 144 | with torch.random.fork_rng(devices=[]): |
| 128 | torch.manual_seed(42) | 145 | torch.manual_seed(42) |
| @@ -132,45 +149,52 @@ def test_attention_without_cp_matches_independent_samples(batch_size, monkeypatc | |||
| 132 | 149 | ||
| 133 | def cpu_window_attention(q, swa_k, attn_sink, *, attention_metadata, **kwargs): | 150 | def cpu_window_attention(q, swa_k, attn_sink, *, attention_metadata, **kwargs): |
| 134 | # The fused kernel is unavailable on CPU, while attn-gym's packed reference | 151 | # The fused kernel is unavailable on CPU, while attn-gym's packed reference |
| 135 | - # explicitly rejects B > 1. Isolate only that kernel with dense causal math; | 152 | + # addresses one row. Isolate only that kernel with per-document dense |
| 136 | - # RoPE and all input/output projections remain production code. | 153 | + # causal math; RoPE and all input/output projections remain production code. |
| 137 | del kwargs | 154 | del kwargs |
| 138 | assert attention_metadata.cp is None | 155 | assert attention_metadata.cp is None |
| 139 | - scores = torch.einsum("bshd,btd->bhst", q, swa_k) * attention.inner_attention.softmax_scale | 156 | + cu = attention_metadata.q.cu_seqlens.to(torch.long).tolist() |
| 140 | - causal = torch.ones(seq_len, seq_len, dtype=torch.bool).tril() | 157 | + total = q.size(0) |
| 141 | - scores = scores.masked_fill(~causal, float("-inf")) | 158 | + scores = torch.einsum("thd,sd->ths", q.float(), swa_k.float()) * attention.inner_attention.softmax_scale |
| 142 | - sink = attn_sink[None, :, None, None].expand(*scores.shape[:-1], 1) | 159 | + allow = torch.zeros(total, total, dtype=torch.bool) |
| 160 | + for start, end in zip(cu[:-1], cu[1:], strict=False): | ||
| 161 | + allow[start:end, start:end] = torch.ones(end - start, end - start, dtype=torch.bool).tril() | ||
| 162 | + scores = scores.masked_fill(~allow[:, None, :], float("-inf")) | ||
| 163 | + sink = attn_sink[None, :, None].expand(*scores.shape[:-1], 1) | ||
| 143 | probabilities = torch.cat((scores, sink), dim=-1).softmax(dim=-1)[..., :-1] | 164 | probabilities = torch.cat((scores, sink), dim=-1).softmax(dim=-1)[..., :-1] |
| 144 | - return torch.einsum("bhst,btd->bshd", probabilities, swa_k) | 165 | + return torch.einsum("ths,sd->thd", probabilities, swa_k) |
| 145 | 166 | ||
| 146 | monkeypatch.setattr(attention.inner_attention, "forward", cpu_window_attention) | 167 | monkeypatch.setattr(attention.inner_attention, "forward", cpu_window_attention) |
| 147 | - values = torch.linspace(-1.0, 1.0, batch_size * seq_len * _DIM).reshape(batch_size, seq_len, _DIM) | 168 | + values = torch.linspace(-1.0, 1.0, batch_size * seq_len * _DIM).reshape(batch_size * seq_len, _DIM) |
| 148 | x = values.clone().requires_grad_() | 169 | x = values.clone().requires_grad_() |
| 149 | - positions = torch.arange(seq_len).expand(batch_size, -1) | 170 | + positions = _positions_for((seq_len,) * batch_size) |
| 150 | entry = model._get_attention_metadata(positions)[attention.attention_metadata_key] | 171 | entry = model._get_attention_metadata(positions)[attention.attention_metadata_key] |
| 151 | - assert entry.batch_size == batch_size | 172 | + # The folded row is one packed row: ``batch_size`` is its own count, not the |
| 152 | - # At one degree the query frame is the row's own grid and every row is a document here; | 173 | + # number of documents that were packed into it. |
| 153 | - # the KV frame addresses that same row. | 174 | + assert entry.batch_size == 1 |
| 175 | + # At one degree the query frame is the row's own grid and every document is a | ||
| 176 | + # batch sample here; the KV frame addresses that same row. | ||
| 154 | assert entry.q.cu_seqlens.tolist() == [row * seq_len for row in range(batch_size + 1)] | 177 | assert entry.q.cu_seqlens.tolist() == [row * seq_len for row in range(batch_size + 1)] |
| 155 | assert entry.swa_k.cu_seqlens.tolist() == entry.q.cu_seqlens.tolist() | 178 | assert entry.swa_k.cu_seqlens.tolist() == entry.q.cu_seqlens.tolist() |
| 156 | parameters = tuple(attention.parameters()) | 179 | parameters = tuple(attention.parameters()) |
| 157 | upstream = torch.linspace(0.25, 1.25, x.numel()).reshape_as(x) | 180 | upstream = torch.linspace(0.25, 1.25, x.numel()).reshape_as(x) |
| 158 | 181 | ||
| 159 | output = attention(x, entry, positions) | 182 | output = attention(x, entry, positions) |
| 160 | - assert output.shape == (batch_size, seq_len, _DIM) | 183 | + assert output.shape == (batch_size * seq_len, _DIM) |
| 161 | gradients = torch.autograd.grad((output * upstream).sum(), (x, *parameters)) | 184 | gradients = torch.autograd.grad((output * upstream).sum(), (x, *parameters)) |
| 162 | 185 | ||
| 163 | - # Distinct batch samples have no cross-row attention. Applying the same initialized | 186 | + # Distinct documents have no cross-row attention. Applying the same initialized |
| 164 | # layer to each document separately supplies the batch-composition oracle, including | 187 | # layer to each document separately supplies the batch-composition oracle, including |
| 165 | # the sum of the individual parameter gradients for the same scalar objective. | 188 | # the sum of the individual parameter gradients for the same scalar objective. |
| 166 | expected_outputs, expected_input_gradients = [], [] | 189 | expected_outputs, expected_input_gradients = [], [] |
| 167 | expected_parameter_gradients = [torch.zeros_like(parameter) for parameter in parameters] | 190 | expected_parameter_gradients = [torch.zeros_like(parameter) for parameter in parameters] |
| 168 | for row in range(batch_size): | 191 | for row in range(batch_size): |
| 169 | - sample = values[row : row + 1].clone().requires_grad_() | 192 | + slab = slice(row * seq_len, (row + 1) * seq_len) |
| 170 | - sample_positions = positions[row : row + 1] | 193 | + sample = values[slab].clone().requires_grad_() |
| 194 | + sample_positions = _positions_for((seq_len,)) | ||
| 171 | sample_entry = model._get_attention_metadata(sample_positions)[attention.attention_metadata_key] | 195 | sample_entry = model._get_attention_metadata(sample_positions)[attention.attention_metadata_key] |
| 172 | expected = attention(sample, sample_entry, sample_positions) | 196 | expected = attention(sample, sample_entry, sample_positions) |
| 173 | - sample_gradients = torch.autograd.grad((expected * upstream[row : row + 1]).sum(), (sample, *parameters)) | 197 | + sample_gradients = torch.autograd.grad((expected * upstream[slab]).sum(), (sample, *parameters)) |
| 174 | expected_outputs.append(expected) | 198 | expected_outputs.append(expected) |
| 175 | expected_input_gradients.append(sample_gradients[0]) | 199 | expected_input_gradients.append(sample_gradients[0]) |
| 176 | for accumulated, gradient in zip(expected_parameter_gradients, sample_gradients[1:], strict=True): | 200 | for accumulated, gradient in zip(expected_parameter_gradients, sample_gradients[1:], strict=True): |
| @@ -0,0 +1,68 @@ | |||
| 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 | +"""Registered mHC backbone with fixed boundaries for the not-yet-folded attention/MoE.""" | ||
| 7 | + | ||
| 8 | +from dataclasses import dataclass | ||
| 9 | + | ||
| 10 | +import torch | ||
| 11 | +from torchtitan.protocols.module import Module | ||
| 12 | + | ||
| 13 | +from torchtitan_npu.models.deepseek_v4_1 import model_registry | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +class AttentionBoundaryStub(Module): | ||
| 17 | + @dataclass(kw_only=True, slots=True) | ||
| 18 | + class Config(Module.Config): | ||
| 19 | + pass | ||
| 20 | + | ||
| 21 | + attention_metadata_key = "mhc_boundary" | ||
| 22 | + | ||
| 23 | + def __init__(self, config): | ||
| 24 | + super().__init__() | ||
| 25 | + | ||
| 26 | + def forward(self, x, positions, attention_metadata, **state): | ||
| 27 | + return ( | ||
| 28 | + x.tanh() * 0.75, | ||
| 29 | + *(state[key] for key in ("cmp_k", "idx_k", "topk_indices", "topk_scores", "candidates")), | ||
| 30 | + ) | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +class MoEBoundaryStub(Module): | ||
| 34 | + @dataclass(kw_only=True, slots=True) | ||
| 35 | + class Config(Module.Config): | ||
| 36 | + pass | ||
| 37 | + | ||
| 38 | + def __init__(self, config): | ||
| 39 | + super().__init__() | ||
| 40 | + | ||
| 41 | + def forward(self, x, *, image_mask=None): | ||
| 42 | + return torch.nn.functional.silu(x) * 0.5 - 0.125 | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def build_mhc_boundary_model(*, dim=4, vocab_size=11): | ||
| 46 | + config = model_registry("deepseek_v4_1_debugmodel_text").model | ||
| 47 | + config.dim = config.tok_embeddings.embedding_dim = config.lm_head.in_features = dim | ||
| 48 | + config.vocab_size = config.tok_embeddings.num_embeddings = config.lm_head.out_features = vocab_size | ||
| 49 | + config.norm.normalized_shape = dim | ||
| 50 | + config.n_layers = 2 | ||
| 51 | + config.layers = config.layers[:2] | ||
| 52 | + config.compress_ratios = (0, 0) | ||
| 53 | + for layer in config.layers: | ||
| 54 | + layer.engram = None | ||
| 55 | + layer.attention = AttentionBoundaryStub.Config() | ||
| 56 | + layer.moe = MoEBoundaryStub.Config() | ||
| 57 | + layer.attention_norm.normalized_shape = layer.ffn_norm.normalized_shape = dim | ||
| 58 | + layer.hc_attn_pre.dim = layer.hc_ffn_pre.dim = dim | ||
| 59 | + layer.hc_attn_pre.sinkhorn_iters = layer.hc_ffn_pre.sinkhorn_iters = 4 | ||
| 60 | + with torch.random.fork_rng(devices=[]): | ||
| 61 | + model = config.build() | ||
| 62 | + generator = torch.Generator().manual_seed(68) | ||
| 63 | + with torch.no_grad(): | ||
| 64 | + for name, parameter in model.named_parameters(): | ||
| 65 | + parameter.copy_(torch.randn(parameter.shape, generator=generator) * 0.15) | ||
| 66 | + if "norm.weight" in name or name.endswith("hc_scale"): | ||
| 67 | + parameter.add_(0.8) | ||
| 68 | + return model | ||
| @@ -0,0 +1,42 @@ | |||
| 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 | +"""FP64, per-token reference arithmetic for the V4.1 mHC CPU tests.""" | ||
| 7 | + | ||
| 8 | +import torch | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +def hc_post_reference(y, residual, post, comb): | ||
| 12 | + y, residual, post, comb = (value.double() for value in (y, residual, post, comb)) | ||
| 13 | + branches = residual.shape[-2] | ||
| 14 | + return torch.stack( | ||
| 15 | + [ | ||
| 16 | + post[..., q, None] * y + sum(comb[..., m, q, None] * residual[..., m, :] for m in range(branches)) | ||
| 17 | + for q in range(branches) | ||
| 18 | + ], | ||
| 19 | + dim=-2, | ||
| 20 | + ) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def hc_pre_reference(x, incoming, state, *, sinkhorn_iters, hc_eps, norm_eps): | ||
| 24 | + weight, base, scale = (state[name].double() for name in ("hc_fn", "hc_base", "hc_scale")) | ||
| 25 | + branches = x.shape[-2] | ||
| 26 | + outputs = [] | ||
| 27 | + for token, previous in zip(x.double(), incoming.double(), strict=True): | ||
| 28 | + flat = token.reshape(-1) | ||
| 29 | + rms = (sum(value * value for value in flat) / flat.numel() + norm_eps).sqrt() | ||
| 30 | + logits = torch.stack([sum(a * b for a, b in zip(row, flat, strict=True)) for row in weight]) / rms | ||
| 31 | + pre = torch.sigmoid(logits[:branches] * scale[0] + base[:branches]) + hc_eps | ||
| 32 | + post = 2 * torch.sigmoid(logits[branches : 2 * branches] * scale[1] + base[branches : 2 * branches]) | ||
| 33 | + comb = (logits[2 * branches :] * scale[2] + base[2 * branches :]).reshape(branches, branches) | ||
| 34 | + comb = torch.stack([(row - row.max()).exp() for row in comb]) | ||
| 35 | + comb = torch.stack([row / row.sum() + hc_eps for row in comb]) | ||
| 36 | + comb = torch.stack([column / (column.sum() + hc_eps) for column in comb.unbind(1)], dim=1) | ||
| 37 | + for _ in range(sinkhorn_iters - 1): | ||
| 38 | + comb = torch.stack([row / (row.sum() + hc_eps) for row in comb]) | ||
| 39 | + comb = torch.stack([column / (column.sum() + hc_eps) for column in comb.unbind(1)], dim=1) | ||
| 40 | + collapsed = sum(previous[m] * token[m] for m in range(branches)) | ||
| 41 | + outputs.append((collapsed, pre, post, comb)) | ||
| 42 | + return tuple(torch.stack(values) for values in zip(*outputs, strict=True)) | ||
| @@ -86,10 +86,8 @@ def preprocess(model, tokens, labels, positions, *, parallel_dims=None, parallel | |||
| 86 | ``input_dict``, exactly as the trainer hands them over. | 86 | ``input_dict``, exactly as the trainer hands them over. |
| 87 | """ | 87 | """ |
| 88 | inputs, labels, extra_kwargs = model.preprocess_inputs( | 88 | inputs, labels, extra_kwargs = model.preprocess_inputs( |
| 89 | - {"input": tokens, "positions": positions, **batch}, | 89 | + {"input": tokens, "labels": labels, "positions": positions, **batch}, |
| 90 | - labels, | ||
| 91 | parallel_dims=_NO_CP_DIMS if parallel_dims is None else parallel_dims, | 90 | parallel_dims=_NO_CP_DIMS if parallel_dims is None else parallel_dims, |
| 92 | - device=tokens.device, | ||
| 93 | parallelism=_NO_SPMD if parallelism is None else parallelism, | 91 | parallelism=_NO_SPMD if parallelism is None else parallelism, |
| 94 | ) | 92 | ) |
| 95 | assert "attention_metadata" in extra_kwargs, "expected the attention backends to build the metadata map" | 93 | assert "attention_metadata" in extra_kwargs, "expected the attention backends to build the metadata map" |
| @@ -136,24 +134,20 @@ def install_doc_chunk_cp_shard(monkeypatch) -> None: | |||
| 136 | """ | 134 | """ |
| 137 | import torchtitan_npu.patches.torchtitan.models.common.decoder as decoder_patch | 135 | import torchtitan_npu.patches.torchtitan.models.common.decoder as decoder_patch |
| 138 | 136 | ||
| 139 | - def shard( | 137 | + def shard(batch, input_sharding, cp_mesh, load_balancer_type=None, ptrr_mask_key=None): |
| 140 | - cp_mesh, | 138 | + del input_sharding, ptrr_mask_key |
| 141 | - inputs, | 139 | + positions = batch.get("positions") |
| 142 | - attention_masks, | ||
| 143 | - load_balancer_type=None, | ||
| 144 | - input_seq_dim=1, | ||
| 145 | - ptrr_mask_key=None, | ||
| 146 | - *, | ||
| 147 | - positions=None, | ||
| 148 | - ): | ||
| 149 | - del attention_masks, ptrr_mask_key | ||
| 150 | if load_balancer_type != DOC_CHUNK_LAYOUT or positions is None: | 140 | if load_balancer_type != DOC_CHUNK_LAYOUT or positions is None: |
| 151 | raise AssertionError("the CPU stand-in only reproduces the doc-chunk layout") | 141 | raise AssertionError("the CPU stand-in only reproduces the doc-chunk layout") |
| 152 | - slab = inputs[0].size(input_seq_dim) // cp_mesh.size() | 142 | + slab = positions.numel() // cp_mesh.size() |
| 153 | permutation = doc_chunk_permutation(document_starts(positions), cp_mesh.size(), slab) | 143 | permutation = doc_chunk_permutation(document_starts(positions), cp_mesh.size(), slab) |
| 154 | lo = cp_mesh.get_local_rank() * slab | 144 | lo = cp_mesh.get_local_rank() * slab |
| 155 | held = permutation[0][lo : lo + slab] | 145 | held = permutation[0][lo : lo + slab] |
| 156 | - moved = tuple(torch.index_select(tensor, input_seq_dim, held) for tensor in inputs) | 146 | + return { |
| 157 | - return moved, None | 147 | + key: torch.index_select(value, 0, held) |
| 148 | + if isinstance(value, torch.Tensor) and value.ndim and value.size(0) == positions.numel() | ||
| 149 | + else value | ||
| 150 | + for key, value in batch.items() | ||
| 151 | + } | ||
| 158 | 152 | ||
| 159 | - monkeypatch.setattr(decoder_patch, "cp_shard", shard) | 153 | + monkeypatch.setattr(decoder_patch, "prepare_context_parallel_input", shard) |
| @@ -82,10 +82,10 @@ def test_student_logits_rescore_a_document_local_selection() -> None: | |||
| 82 | cu_seqlens = torch.tensor([0, 4, 8], dtype=torch.int32) | 82 | cu_seqlens = torch.tensor([0, 4, 8], dtype=torch.int32) |
| 83 | cu_seqlens_k = torch.tensor([0, 2, 4], dtype=torch.int32) | 83 | cu_seqlens_k = torch.tensor([0, 2, 4], dtype=torch.int32) |
| 84 | num_tokens, heads, dim, topk = 8, 2, 3, 2 | 84 | num_tokens, heads, dim, topk = 8, 2, 3, 2 |
| 85 | - torch.manual_seed(0) | 85 | + generator = torch.Generator().manual_seed(0) |
| 86 | - idx_q = torch.randn(1, num_tokens, heads, dim, dtype=torch.float64) | 86 | + idx_q = torch.randn(num_tokens, heads, dim, dtype=torch.float64, generator=generator, requires_grad=True) |
| 87 | - idx_k = torch.randn(1, cu_seqlens_k[-1].item(), dim, dtype=torch.float64) | 87 | + idx_k = torch.randn(cu_seqlens_k[-1].item(), dim, dtype=torch.float64, generator=generator, requires_grad=True) |
| 88 | - weights = torch.randn(1, num_tokens, heads, dtype=torch.float64) | 88 | + weights = torch.randn(num_tokens, heads, dtype=torch.float64, generator=generator, requires_grad=True) |
| 89 | 89 | ||
| 90 | # Per row, ``(local id, the pool entry it names)``: padding in both slots and documents. | 90 | # Per row, ``(local id, the pool entry it names)``: padding in both slots and documents. |
| 91 | picks = [ | 91 | picks = [ |
| @@ -98,24 +98,29 @@ def test_student_logits_rescore_a_document_local_selection() -> None: | |||
| 98 | [(1, 3), (1, 3)], | 98 | [(1, 3), (1, 3)], |
| 99 | [(0, 2), (1, 3)], | 99 | [(0, 2), (1, 3)], |
| 100 | ] | 100 | ] |
| 101 | - local_BLK = torch.tensor([[[local for local, _ in row] for row in picks]]) | 101 | + local_BLK = torch.tensor([[local for local, _ in row] for row in picks]) |
| 102 | 102 | ||
| 103 | scores_BLK = _student_logits(idx_q, idx_k, weights, local_BLK, cu_seqlens, cu_seqlens_k) | 103 | scores_BLK = _student_logits(idx_q, idx_k, weights, local_BLK, cu_seqlens, cu_seqlens_k) |
| 104 | 104 | ||
| 105 | - expected_BLK = torch.full((1, num_tokens, topk), -torch.inf, dtype=torch.float64) | 105 | + expected_BLK = torch.full((num_tokens, topk), -torch.inf, dtype=torch.float64) |
| 106 | for token, row in enumerate(picks): | 106 | for token, row in enumerate(picks): |
| 107 | for slot, (local, entry) in enumerate(row): | 107 | for slot, (local, entry) in enumerate(row): |
| 108 | if local < 0: | 108 | if local < 0: |
| 109 | continue | 109 | continue |
| 110 | - dot = torch.einsum("hd,d->h", idx_q[0, token], idx_k[0, entry]) | 110 | + dot = torch.einsum("hd,d->h", idx_q[token], idx_k[entry]) |
| 111 | - expected_BLK[0, token, slot] = (dot.relu() * weights[0, token]).sum() | 111 | + expected_BLK[token, slot] = (dot.relu() * weights[token]).sum() |
| 112 | 112 | ||
| 113 | torch.testing.assert_close(scores_BLK, expected_BLK, rtol=1e-12, atol=1e-12) | 113 | torch.testing.assert_close(scores_BLK, expected_BLK, rtol=1e-12, atol=1e-12) |
| 114 | + upstream = torch.arange(1, num_tokens * topk + 1, dtype=torch.float64).reshape(num_tokens, topk) | ||
| 115 | + actual_gradients = torch.autograd.grad(scores_BLK, (idx_q, idx_k, weights), upstream, retain_graph=True) | ||
| 116 | + expected_gradients = torch.autograd.grad(expected_BLK, (idx_q, idx_k, weights), upstream) | ||
| 117 | + for actual, expected in zip(actual_gradients, expected_gradients, strict=True): | ||
| 118 | + torch.testing.assert_close(actual, expected, rtol=1e-12, atol=1e-12) | ||
| 114 | # Marking agrees with the indices slot for slot: ``-1`` is the only un-scored slot. | 119 | # Marking agrees with the indices slot for slot: ``-1`` is the only un-scored slot. |
| 115 | assert torch.equal(torch.isfinite(scores_BLK), local_BLK >= 0) | 120 | assert torch.equal(torch.isfinite(scores_BLK), local_BLK >= 0) |
| 116 | # Row 4 is document 1's first token: reading its local 0 row-wide would score entry 0. | 121 | # Row 4 is document 1's first token: reading its local 0 row-wide would score entry 0. |
| 117 | - row_wide = (torch.einsum("hd,d->h", idx_q[0, 4], idx_k[0, 0]).relu() * weights[0, 4]).sum() | 122 | + row_wide = (torch.einsum("hd,d->h", idx_q[4], idx_k[0]).relu() * weights[4]).sum() |
| 118 | - assert not torch.isclose(scores_BLK[0, 4, 0], row_wide) | 123 | + assert not torch.isclose(scores_BLK[4, 0], row_wide) |
| 119 | 124 | ||
| 120 | 125 | ||
| 121 | def test_v41_config_uses_specialized_attention_with_explicit_ownership() -> None: | 126 | def test_v41_config_uses_specialized_attention_with_explicit_ownership() -> None: |
| @@ -29,8 +29,8 @@ from torchtitan_npu.models.deepseek_v4_1 import ( | |||
| 29 | from torchtitan_npu.models.deepseek_v4_1.attention import CompressedSparseInnerAttention2 | 29 | from torchtitan_npu.models.deepseek_v4_1.attention import CompressedSparseInnerAttention2 |
| 30 | from torchtitan_npu.models.deepseek_v4_1.indexer import REUSE | 30 | from torchtitan_npu.models.deepseek_v4_1.indexer import REUSE |
| 31 | 31 | ||
| 32 | -_TOKENS = torch.arange(128).remainder(32).unsqueeze(0) | 32 | +_TOKENS = torch.arange(128).remainder(32) |
| 33 | -_POSITIONS = torch.arange(128).unsqueeze(0) | 33 | +_POSITIONS = torch.arange(128) |
| 34 | # Block return slots: (x, pre_mix, cmp_k, idx_k, topk_indices, topk_scores, candidates). | 34 | # Block return slots: (x, pre_mix, cmp_k, idx_k, topk_indices, topk_scores, candidates). |
| 35 | _CMP_K, _IDX_K, _TOPK, _TOPK_SCORES, _CANDIDATES = 2, 3, 4, 5, 6 | 35 | _CMP_K, _IDX_K, _TOPK, _TOPK_SCORES, _CANDIDATES = 2, 3, 4, 5, 6 |
| 36 | 36 | ||
| @@ -60,8 +60,10 @@ def _tiny_debug_model(monkeypatch): | |||
| 60 | return make_config(**kwargs) | 60 | return make_config(**kwargs) |
| 61 | 61 | ||
| 62 | monkeypatch.setattr(registry, "_make_v41_config", tiny_config) | 62 | monkeypatch.setattr(registry, "_make_v41_config", tiny_config) |
| 63 | - config = registry.model_registry("deepseek_v4_1_debugmodel").model | 63 | + config = registry.model_registry("deepseek_v4_1_debugmodel_text").model |
| 64 | config.vocab_size = config.tok_embeddings.num_embeddings = config.lm_head.out_features = 64 | 64 | config.vocab_size = config.tok_embeddings.num_embeddings = config.lm_head.out_features = 64 |
| 65 | + for layer in config.layers: | ||
| 66 | + layer.engram = None | ||
| 65 | with torch.random.fork_rng(devices=[]): | 67 | with torch.random.fork_rng(devices=[]): |
| 66 | model = build_cpu_model(config) | 68 | model = build_cpu_model(config) |
| 67 | return model, config | 69 | return model, config |
| @@ -220,7 +222,7 @@ def test_metadata_document_boundaries_restart_per_packed_document(monkeypatch) - | |||
| 220 | row are the override tests' subject. | 222 | row are the override tests' subject. |
| 221 | """ | 223 | """ |
| 222 | model, _ = _tiny_debug_model(monkeypatch) | 224 | model, _ = _tiny_debug_model(monkeypatch) |
| 223 | - positions = torch.tensor([[0, 1, 2, 3, 0, 1, 2, 3, 0, 1]], dtype=torch.long) | 225 | + positions = torch.tensor([0, 1, 2, 3, 0, 1, 2, 3, 0, 1], dtype=torch.long) |
| 224 | tokens = torch.zeros_like(positions) | 226 | tokens = torch.zeros_like(positions) |
| 225 | 227 | ||
| 226 | _, _, extra = preprocess(model, tokens, tokens, positions) | 228 | _, _, extra = preprocess(model, tokens, tokens, positions) |
| @@ -250,14 +252,14 @@ def test_weightless_compressor_passes_the_container_through(monkeypatch) -> None | |||
| 250 | assert not list(compressor.parameters()) | 252 | assert not list(compressor.parameters()) |
| 251 | 253 | ||
| 252 | # A window-only layer owns nothing and is handed nothing. | 254 | # A window-only layer owns nothing and is handed nothing. |
| 253 | - returned, latent = model.layers["0"].attention.compressor(torch.zeros(1, 128, config.dim), _POSITIONS) | 255 | + returned, latent = model.layers["0"].attention.compressor(torch.zeros(128, config.dim), _POSITIONS) |
| 254 | assert returned is None | 256 | assert returned is None |
| 255 | assert latent is None | 257 | assert latent is None |
| 256 | 258 | ||
| 257 | # A reuse layer hands back the very container it was given, with no latent. | 259 | # A reuse layer hands back the very container it was given, with no latent. |
| 258 | - handed = torch.zeros(1, 64, config.layers[3].attention.head_dim) | 260 | + handed = torch.zeros(64, config.layers[3].attention.head_dim) |
| 259 | returned, latent = model.layers["3"].attention.compressor( | 261 | returned, latent = model.layers["3"].attention.compressor( |
| 260 | - torch.zeros(1, 128, config.dim), | 262 | + torch.zeros(128, config.dim), |
| 261 | _POSITIONS, | 263 | _POSITIONS, |
| 262 | handed, | 264 | handed, |
| 263 | ) | 265 | ) |
| @@ -335,15 +337,15 @@ def test_weightless_indexer_passes_the_selection_through(monkeypatch) -> None: | |||
| 335 | if int(layer_id) not in index_sources: | 337 | if int(layer_id) not in index_sources: |
| 336 | assert not list(indexer.parameters()) | 338 | assert not list(indexer.parameters()) |
| 337 | 339 | ||
| 338 | - hidden = torch.zeros(1, 128, config.dim) | 340 | + hidden = torch.zeros(128, config.dim) |
| 339 | - qr = torch.zeros(1, 128, config.layers[0].attention.q_lora_rank) | 341 | + qr = torch.zeros(128, config.layers[0].attention.q_lora_rank) |
| 340 | 342 | ||
| 341 | # A window-only layer owns nothing and is handed nothing. | 343 | # A window-only layer owns nothing and is handed nothing. |
| 342 | assert model.layers["0"].attention.indexer(hidden, qr, _POSITIONS, None) == (None, None, None, None) | 344 | assert model.layers["0"].attention.indexer(hidden, qr, _POSITIONS, None) == (None, None, None, None) |
| 343 | 345 | ||
| 344 | # A reuse layer hands back the very tensors it was given. | 346 | # A reuse layer hands back the very tensors it was given. |
| 345 | - shared_key = torch.zeros(1, 64, config.layers[4].attention.indexer.index_head_dim) | 347 | + shared_key = torch.zeros(64, config.layers[4].attention.indexer.index_head_dim) |
| 346 | - shared_selection = torch.zeros(1, 128, 4, dtype=torch.long) | 348 | + shared_selection = torch.zeros(128, 4, dtype=torch.long) |
| 347 | returned = model.layers["4"].attention.indexer( | 349 | returned = model.layers["4"].attention.indexer( |
| 348 | hidden, | 350 | hidden, |
| 349 | qr, | 351 | qr, |
| @@ -363,7 +365,7 @@ def test_reuse_layer_without_the_shared_tensor_fails_loudly(monkeypatch) -> None | |||
| 363 | model, config = _tiny_debug_model(monkeypatch) | 365 | model, config = _tiny_debug_model(monkeypatch) |
| 364 | _, _, kwargs = preprocess(model, _TOKENS, _TOKENS, _POSITIONS) | 366 | _, _, kwargs = preprocess(model, _TOKENS, _TOKENS, _POSITIONS) |
| 365 | attention_metadata = layer_metadata(model.layers["3"], kwargs) | 367 | attention_metadata = layer_metadata(model.layers["3"], kwargs) |
| 366 | - hidden = torch.zeros(1, _TOKENS.shape[1], config.dim) | 368 | + hidden = torch.zeros(_TOKENS.numel(), config.dim) |
| 367 | 369 | ||
| 368 | # A layer that reuses the compressed KV must be handed one. | 370 | # A layer that reuses the compressed KV must be handed one. |
| 369 | with pytest.raises(AssertionError, match="reuses the compressed KV"): | 371 | with pytest.raises(AssertionError, match="reuses the compressed KV"): |
| @@ -377,5 +379,5 @@ def test_reuse_layer_without_the_shared_tensor_fails_loudly(monkeypatch) -> None | |||
| 377 | hidden, | 379 | hidden, |
| 378 | _POSITIONS, | 380 | _POSITIONS, |
| 379 | attention_metadata, | 381 | attention_metadata, |
| 380 | - cmp_k=torch.zeros(1, _TOKENS.shape[1], head_dim), | 382 | + cmp_k=torch.zeros(_TOKENS.numel(), head_dim), |
| 381 | ) | 383 | ) |
| @@ -27,7 +27,7 @@ def _window_metadata(bounds: list[int]): | |||
| 27 | ``cu_seq_k`` there to the row's own boundaries: the core addresses the row with these | 27 | ``cu_seq_k`` there to the row's own boundaries: the core addresses the row with these |
| 28 | offsets and never reaches for a pooled axis, so this is the whole contract it consumes. | 28 | offsets and never reaches for a pooled axis, so this is the whole contract it consumes. |
| 29 | """ | 29 | """ |
| 30 | - positions = torch.cat([torch.arange(end - begin) for begin, end in pairwise(bounds)]).unsqueeze(0) | 30 | + positions = torch.cat([torch.arange(end - begin) for begin, end in pairwise(bounds)]) |
| 31 | # Only the row matters here: the builder reads the positions, not this geometry. | 31 | # Only the row matters here: the builder reads the positions, not this geometry. |
| 32 | config = CompressedSparseInnerAttention2.Config(window_size=8, softmax_scale=0.5, compress_ratio=0) | 32 | config = CompressedSparseInnerAttention2.Config(window_size=8, softmax_scale=0.5, compress_ratio=0) |
| 33 | metadata = config.build_attention_metadata(positions) | 33 | metadata = config.build_attention_metadata(positions) |
| @@ -43,16 +43,16 @@ def _dense_window_reference(q, kv, sink, bounds, window, scale): | |||
| 43 | Written out longhand, independent of the core's helpers: the sink is one more logit in | 43 | Written out longhand, independent of the core's helpers: the sink is one more logit in |
| 44 | the denominator and contributes nothing to the value. | 44 | the denominator and contributes nothing to the value. |
| 45 | """ | 45 | """ |
| 46 | - _, tokens, heads, dim = q.shape | 46 | + tokens, heads, dim = q.shape |
| 47 | out = torch.zeros(tokens, heads, dim, dtype=q.dtype) | 47 | out = torch.zeros(tokens, heads, dim, dtype=q.dtype) |
| 48 | for begin, end in pairwise(bounds): | 48 | for begin, end in pairwise(bounds): |
| 49 | for position in range(begin, end): | 49 | for position in range(begin, end): |
| 50 | first = max(begin, position - window + 1) | 50 | first = max(begin, position - window + 1) |
| 51 | - keys = kv[0, first : position + 1] | 51 | + keys = kv[first : position + 1] |
| 52 | - scores = (q[0, position] @ keys.transpose(0, 1)) * scale | 52 | + scores = (q[position] @ keys.transpose(0, 1)) * scale |
| 53 | probs = torch.cat((scores, sink[:, None]), dim=1).softmax(dim=1) | 53 | probs = torch.cat((scores, sink[:, None]), dim=1).softmax(dim=1) |
| 54 | out[position] = probs[:, : keys.shape[0]] @ keys | 54 | out[position] = probs[:, : keys.shape[0]] @ keys |
| 55 | - return out.unsqueeze(0) | 55 | + return out |
| 56 | 56 | ||
| 57 | 57 | ||
| 58 | @pytest.mark.parametrize("window", [1, 2, 8], ids=["self-only", "partial", "whole-document"]) | 58 | @pytest.mark.parametrize("window", [1, 2, 8], ids=["self-only", "partial", "whole-document"]) |
| @@ -60,10 +60,10 @@ def test_window_only_layer_matches_an_explicit_reference(window): | |||
| 60 | bounds = [0, 4, 10, 12] # three documents of 4, 6 and 2 tokens | 60 | bounds = [0, 4, 10, 12] # three documents of 4, 6 and 2 tokens |
| 61 | metadata = _window_metadata(bounds) | 61 | metadata = _window_metadata(bounds) |
| 62 | scale, heads, head_dim = 0.5, 2, 4 | 62 | scale, heads, head_dim = 0.5, 2, 4 |
| 63 | - torch.manual_seed(0) | 63 | + generator = torch.Generator().manual_seed(0) |
| 64 | - q = torch.randn(1, bounds[-1], heads, head_dim) | 64 | + q = torch.randn(bounds[-1], heads, head_dim, generator=generator) |
| 65 | - kv = torch.randn(1, bounds[-1], head_dim) | 65 | + kv = torch.randn(bounds[-1], head_dim, generator=generator) |
| 66 | - sink = torch.randn(heads) | 66 | + sink = torch.randn(heads, generator=generator) |
| 67 | 67 | ||
| 68 | core = attention.CompressedSparseInnerAttention2.Config( | 68 | core = attention.CompressedSparseInnerAttention2.Config( |
| 69 | window_size=window, | 69 | window_size=window, |
| @@ -81,10 +81,10 @@ def test_window_only_layer_does_not_leak_across_documents(): | |||
| 81 | bounds = [0, 4, 10] | 81 | bounds = [0, 4, 10] |
| 82 | metadata = _window_metadata(bounds) | 82 | metadata = _window_metadata(bounds) |
| 83 | window, scale, heads, head_dim = 8, 0.5, 2, 4 # window >= every document: nothing is truncated | 83 | window, scale, heads, head_dim = 8, 0.5, 2, 4 # window >= every document: nothing is truncated |
| 84 | - torch.manual_seed(1) | 84 | + generator = torch.Generator().manual_seed(1) |
| 85 | - q = torch.randn(1, bounds[-1], heads, head_dim) | 85 | + q = torch.randn(bounds[-1], heads, head_dim, generator=generator) |
| 86 | - kv = torch.randn(1, bounds[-1], head_dim) | 86 | + kv = torch.randn(bounds[-1], head_dim, generator=generator) |
| 87 | - sink = torch.randn(heads) | 87 | + sink = torch.randn(heads, generator=generator) |
| 88 | 88 | ||
| 89 | core = attention.CompressedSparseInnerAttention2.Config( | 89 | core = attention.CompressedSparseInnerAttention2.Config( |
| 90 | window_size=window, | 90 | window_size=window, |
| @@ -94,8 +94,48 @@ def test_window_only_layer_does_not_leak_across_documents(): | |||
| 94 | out = core(q, kv, sink, metadata, cmp_k=None, topk_indices=None) | 94 | out = core(q, kv, sink, metadata, cmp_k=None, topk_indices=None) |
| 95 | 95 | ||
| 96 | bumped = kv.clone() | 96 | bumped = kv.clone() |
| 97 | - bumped[0, bounds[1] :] += 10.0 # disturb every later document | 97 | + bumped[bounds[1] :] += 10.0 # disturb every later document |
| 98 | out_bumped = core(q, bumped, sink, metadata, cmp_k=None, topk_indices=None) | 98 | out_bumped = core(q, bumped, sink, metadata, cmp_k=None, topk_indices=None) |
| 99 | 99 | ||
| 100 | first_document = slice(0, bounds[1]) | 100 | first_document = slice(0, bounds[1]) |
| 101 | - torch.testing.assert_close(out[0, first_document], out_bumped[0, first_document], rtol=0, atol=0) | 101 | + torch.testing.assert_close(out[first_document], out_bumped[first_document], rtol=0, atol=0) |
| 102 | + | ||
| 103 | + | ||
| 104 | +@pytest.mark.parametrize("ratio", (1, 2), ids=("uncompressed-pool", "compressed-pool")) | ||
| 105 | +def test_sparse_attention_outputs_and_gradients_match_dense_document_reference(ratio): | ||
| 106 | + generator = torch.Generator().manual_seed(71) | ||
| 107 | + bounds = [0, 4, 8] | ||
| 108 | + positions = torch.tensor([0, 1, 2, 3, 0, 1, 2, 3]) | ||
| 109 | + config = CompressedSparseInnerAttention2.Config(window_size=2, softmax_scale=0.5, compress_ratio=ratio) | ||
| 110 | + core = config.build() | ||
| 111 | + metadata = config.build_attention_metadata(positions) | ||
| 112 | + q = torch.randn(8, 2, 4, generator=generator, requires_grad=True) | ||
| 113 | + local = torch.randn(8, 4, generator=generator, requires_grad=True) | ||
| 114 | + compressed = torch.randn(8 // ratio, 4, generator=generator, requires_grad=True) | ||
| 115 | + sink = torch.randn(2, generator=generator, requires_grad=True) | ||
| 116 | + picks = torch.full((8, 2), -1, dtype=torch.long) | ||
| 117 | + for begin, end in pairwise(bounds): | ||
| 118 | + for token in range(begin, end): | ||
| 119 | + complete = (token - begin + 1) // ratio | ||
| 120 | + visible = list(range(max(0, complete - 2), complete))[::-1] | ||
| 121 | + picks[token, : len(visible)] = torch.tensor(visible, dtype=torch.long) | ||
| 122 | + | ||
| 123 | + actual = core(q, local, sink, metadata, cmp_k=compressed, topk_indices=picks) | ||
| 124 | + reference_inputs = [x.detach().double().requires_grad_() for x in (q, local, compressed, sink)] | ||
| 125 | + rq, rl, rc, rs = reference_inputs | ||
| 126 | + outputs = [] | ||
| 127 | + for begin, end in pairwise(bounds): | ||
| 128 | + for token in range(begin, end): | ||
| 129 | + selected = [begin // ratio + int(i) for i in picks[token] if i >= 0] | ||
| 130 | + keys = torch.cat((rl[max(begin, token - 1) : token + 1], rc[selected])) | ||
| 131 | + scores = rq[token] @ keys.t() * 0.5 | ||
| 132 | + probabilities = torch.cat((scores, rs[:, None]), dim=-1).softmax(-1) | ||
| 133 | + outputs.append(probabilities[:, :-1] @ keys) | ||
| 134 | + expected = torch.stack(outputs) | ||
| 135 | + upstream = torch.randn(actual.shape, generator=generator) | ||
| 136 | + gradients = torch.autograd.grad(actual, (q, local, compressed, sink), upstream) | ||
| 137 | + reference_gradients = torch.autograd.grad(expected, reference_inputs, upstream.double()) | ||
| 138 | + | ||
| 139 | + torch.testing.assert_close(actual, expected.float(), rtol=2e-5, atol=2e-6) | ||
| 140 | + for gradient, reference in zip(gradients, reference_gradients, strict=True): | ||
| 141 | + torch.testing.assert_close(gradient, reference.float(), rtol=2e-5, atol=2e-6) | ||
| @@ -34,7 +34,7 @@ def test_plain_weights_use_routed_experts_and_track_empty_experts(): | |||
| 34 | calls = [] | 34 | calls = [] |
| 35 | handle = moe.routed_experts.register_forward_hook(lambda module, args, output: calls.append(output)) | 35 | handle = moe.routed_experts.register_forward_hook(lambda module, args, output: calls.append(output)) |
| 36 | try: | 36 | try: |
| 37 | - x = torch.linspace(-1, 1, 24).reshape(1, 3, 8).requires_grad_() | 37 | + x = torch.linspace(-1, 1, 24).reshape(3, 8).requires_grad_() |
| 38 | out = moe(x) | 38 | out = moe(x) |
| 39 | assert len(calls) == 1 | 39 | assert len(calls) == 1 |
| 40 | torch.testing.assert_close(moe.tokens_per_expert_E, torch.tensor([3.0, 3.0, 0.0, 0.0])) | 40 | torch.testing.assert_close(moe.tokens_per_expert_E, torch.tensor([3.0, 3.0, 0.0, 0.0])) |
| @@ -101,10 +101,10 @@ def test_v41_moe_rides_the_common_stack_with_an_opt_in_vision_bias(): | |||
| 101 | top_k=2, | 101 | top_k=2, |
| 102 | score_func="sigmoid", | 102 | score_func="sigmoid", |
| 103 | ) | 103 | ) |
| 104 | - assert not plain.vision_enabled and not plain.sorted_topk | 104 | + assert type(plain) is TokenChoiceTopKRouter.Config |
| 105 | with torch.random.fork_rng(devices=[]): | 105 | with torch.random.fork_rng(devices=[]): |
| 106 | plain_router = build_cpu_model(plain) | 106 | plain_router = build_cpu_model(plain) |
| 107 | - assert plain_router.bias_vl is None | 107 | + assert not hasattr(plain_router, "bias_vl") |
| 108 | 108 | ||
| 109 | x_BLD = torch.linspace(-1, 1, 24).reshape(1, 3, 8) | 109 | x_BLD = torch.linspace(-1, 1, 24).reshape(1, 3, 8) |
| 110 | image_mask = torch.tensor([[True, False, True]]) | 110 | image_mask = torch.tensor([[True, False, True]]) |
| @@ -124,11 +124,11 @@ def test_trainer_config_rejects_a_ratio_table_shorter_than_the_stack(): | |||
| 124 | # Positive control: the registered table is accepted by the same entry point, so a | 124 | # Positive control: the registered table is accepted by the same entry point, so a |
| 125 | # check that always raised would not pass this test. | 125 | # check that always raised would not pass this test. |
| 126 | registered = deepseek_v4_1_debugmodel_multimodal() | 126 | registered = deepseek_v4_1_debugmodel_multimodal() |
| 127 | - registered.training.seq_len = 512 | 127 | + registered.training.max_context_length = 512 |
| 128 | registered.model_spec.model.update_from_config(config=registered) | 128 | registered.model_spec.model.update_from_config(config=registered) |
| 129 | 129 | ||
| 130 | config = deepseek_v4_1_debugmodel_multimodal() | 130 | config = deepseek_v4_1_debugmodel_multimodal() |
| 131 | - config.training.seq_len = 512 | 131 | + config.training.max_context_length = 512 |
| 132 | model_config = config.model_spec.model | 132 | model_config = config.model_spec.model |
| 133 | model_config.compress_ratios = model_config.compress_ratios[:-1] | 133 | model_config.compress_ratios = model_config.compress_ratios[:-1] |
| 134 | with pytest.raises(ValueError, match="compress_ratios must match n_layers"): | 134 | with pytest.raises(ValueError, match="compress_ratios must match n_layers"): |
| @@ -0,0 +1,49 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# | ||
| 3 | +# This source code is licensed under the BSD-style license found in the | ||
| 4 | +# LICENSE file in the root directory of this source tree. | ||
| 5 | + | ||
| 6 | +import pytest | ||
| 7 | +import torch | ||
| 8 | +import torch.nn.functional as F | ||
| 9 | + | ||
| 10 | +from torchtitan_npu.models.deepseek_v4_1 import model_registry | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +@pytest.mark.parametrize("layer_id", [2, 20], ids=["ratio-two", "ratio-one"]) | ||
| 14 | +def test_compressor_pooling_outputs_and_gradients_match_explicit_groups(layer_id): | ||
| 15 | + config = model_registry("deepseek_v4_1_debugmodel_text").model.layers[layer_id].attention.compressor | ||
| 16 | + with torch.random.fork_rng(devices=[]): | ||
| 17 | + compressor = config.build() | ||
| 18 | + compressor.init_states(buffer_device=torch.device("cpu")) | ||
| 19 | + generator = torch.Generator().manual_seed(51) | ||
| 20 | + x = torch.randn(8, config.wkv.in_features, generator=generator, requires_grad=True) | ||
| 21 | + positions = torch.tensor([0, 1, 2, 3, 0, 1, 2, 3]) | ||
| 22 | + | ||
| 23 | + rotated, latent = compressor(x_TD=x, positions_T=positions) | ||
| 24 | + | ||
| 25 | + projected = F.linear(x, compressor.wkv.weight) | ||
| 26 | + ratio = config.compress_ratio | ||
| 27 | + groups = [] | ||
| 28 | + for start in range(0, x.size(0), ratio): | ||
| 29 | + values = projected[start : start + ratio] | ||
| 30 | + if ratio > 1: | ||
| 31 | + gates = F.linear(x[start : start + ratio], compressor.wgate.weight).float().softmax(0) | ||
| 32 | + values = (values.float() * gates).sum(0) | ||
| 33 | + else: | ||
| 34 | + values = values[0] | ||
| 35 | + groups.append(values) | ||
| 36 | + pooled = torch.stack(groups) | ||
| 37 | + expected_latent = pooled * (pooled.square().mean(-1, keepdim=True) + config.norm.eps).rsqrt() | ||
| 38 | + expected_latent = expected_latent * compressor.norm.weight | ||
| 39 | + group_positions = torch.tensor([int(positions[start]) for start in range(0, x.size(0), ratio)]) | ||
| 40 | + expected_rotated = compressor.rope(expected_latent.unsqueeze(1), positions=group_positions).squeeze(1) | ||
| 41 | + upstream = torch.randn(rotated.shape, generator=generator) | ||
| 42 | + inputs = (x, *compressor.parameters()) | ||
| 43 | + actual_gradients = torch.autograd.grad(rotated, inputs, upstream, retain_graph=True) | ||
| 44 | + expected_gradients = torch.autograd.grad(expected_rotated, inputs, upstream) | ||
| 45 | + | ||
| 46 | + torch.testing.assert_close(latent, expected_latent, rtol=2e-5, atol=2e-6) | ||
| 47 | + torch.testing.assert_close(rotated, expected_rotated, rtol=2e-5, atol=2e-6) | ||
| 48 | + for actual, expected in zip(actual_gradients, expected_gradients, strict=True): | ||
| 49 | + torch.testing.assert_close(actual, expected, rtol=2e-4, atol=2e-5) | ||
| @@ -48,7 +48,7 @@ def _positions(*documents: int) -> torch.Tensor: | |||
| 48 | flat: list[int] = [] | 48 | flat: list[int] = [] |
| 49 | for length in documents: | 49 | for length in documents: |
| 50 | flat += list(range(length)) | 50 | flat += list(range(length)) |
| 51 | - return torch.tensor([flat]) | 51 | + return torch.tensor(flat) |
| 52 | 52 | ||
| 53 | 53 | ||
| 54 | def _bounds(cu: list[int]) -> torch.Tensor: | 54 | def _bounds(cu: list[int]) -> torch.Tensor: |
| @@ -14,6 +14,7 @@ import torch | |||
| 14 | import torch.nn.functional as F | 14 | import torch.nn.functional as F |
| 15 | from torchtitan.config.manager import ConfigManager | 15 | from torchtitan.config.manager import ConfigManager |
| 16 | 16 | ||
| 17 | +from tests.unit_tests.models.deepseek_v4_1.preprocess_utils import cp_parallel_dims, tiny_v41_model | ||
| 17 | from torchtitan_npu.config import OptimizerConfig | 18 | from torchtitan_npu.config import OptimizerConfig |
| 18 | from torchtitan_npu.models.deepseek_v4_1 import ( | 19 | from torchtitan_npu.models.deepseek_v4_1 import ( |
| 19 | EngramArgs, | 20 | EngramArgs, |
| @@ -36,7 +37,7 @@ def _preserve_rng(): | |||
| 36 | yield | 37 | yield |
| 37 | 38 | ||
| 38 | 39 | ||
| 39 | -def _build_engram(): | 40 | +def _build_engram(token_id_map_path=None): |
| 40 | config = _make_engram_configs( | 41 | config = _make_engram_configs( |
| 41 | hidden_size=8, | 42 | hidden_size=8, |
| 42 | hc_mult=4, | 43 | hc_mult=4, |
| @@ -48,6 +49,7 @@ def _build_engram(): | |||
| 48 | num_heads_per_ngram=2, | 49 | num_heads_per_ngram=2, |
| 49 | pad_id=2, | 50 | pad_id=2, |
| 50 | require_token_id_map=False, | 51 | require_token_id_map=False, |
| 52 | + token_id_map_path=token_id_map_path, | ||
| 51 | ), | 53 | ), |
| 52 | )[1] | 54 | )[1] |
| 53 | engram = config.build() | 55 | engram = config.build() |
| @@ -55,38 +57,38 @@ def _build_engram(): | |||
| 55 | return engram | 57 | return engram |
| 56 | 58 | ||
| 57 | 59 | ||
| 58 | -def _numpy_hash_reference(table, input_ids): | 60 | +def _numpy_hash_reference(table, input_ids, positions=None, *, image_mask=None, token_history=None): |
| 59 | - tokens = input_ids.numpy().astype(np.int64, copy=False) | 61 | + """Scalar N-gram oracle, independent of the production shift construction.""" |
| 60 | - B, L = tokens.shape | 62 | + mapping = table.token_id_map.numpy() |
| 61 | - shifts = [] | 63 | + tokens = mapping[input_ids.numpy()] |
| 62 | - for distance in range(max(table.ngram_orders)): | 64 | + history = mapping[token_history.numpy()] if token_history is not None else np.empty(0, dtype=np.int64) |
| 63 | - shifted = np.full((B, L), table.pad_id, dtype=np.int64) | 65 | + pad = mapping[table.pad_id] |
| 64 | - if distance == 0: | 66 | + rows = [] |
| 65 | - shifted = tokens | 67 | + for index in range(len(tokens)): |
| 66 | - else: | 68 | + head_rows = [] |
| 67 | - shifted[:, distance:] = tokens[:, :-distance] | 69 | + head = 0 |
| 68 | - shifts.append(shifted) | 70 | + for order in table.ngram_orders: |
| 69 | - | 71 | + mixed = np.int64(0) |
| 70 | - multipliers = table.hash_multipliers.numpy() | 72 | + for distance in range(order): |
| 71 | - sizes = table.head_vocab_sizes.numpy() | 73 | + source = index - distance |
| 72 | - offsets = table.offsets.numpy() | 74 | + token = tokens[source] if source >= 0 else history[source] if source >= -len(history) else pad |
| 73 | - hashes = [] | 75 | + if positions is not None and positions[index] < distance: |
| 74 | - table_idx = 0 | 76 | + token = pad |
| 75 | - for order in table.ngram_orders: | 77 | + if image_mask is not None and image_mask[max(0, source) : index + 1].any(): |
| 76 | - mixed = shifts[0] * multipliers[0] | 78 | + token = pad |
| 77 | - for distance in range(1, order): | 79 | + mixed = np.bitwise_xor(mixed, token * table.hash_multipliers[distance].item()) |
| 78 | - mixed = np.bitwise_xor(mixed, shifts[distance] * multipliers[distance]) | 80 | + for _ in range(table.num_heads): |
| 79 | - end = table_idx + table.num_heads | 81 | + head_rows.append(mixed % table.head_vocab_sizes[head].item() + table.offsets[head].item()) |
| 80 | - hashes.append(mixed[..., None] % sizes[table_idx:end] + offsets[table_idx:end]) | 82 | + head += 1 |
| 81 | - table_idx = end | 83 | + rows.append(head_rows) |
| 82 | - return torch.from_numpy(np.concatenate(hashes, axis=-1)) | 84 | + return torch.tensor(rows, dtype=torch.int64) |
| 83 | 85 | ||
| 84 | 86 | ||
| 85 | def _official_demo_forward_reference(engram, hidden, input_ids, positions): | 87 | def _official_demo_forward_reference(engram, hidden, input_ids, positions): |
| 86 | """Independent, branch-by-branch port of the public Engram demo.""" | 88 | """Independent, branch-by-branch port of the public Engram demo.""" |
| 87 | table = engram.table | 89 | table = engram.table |
| 88 | - hashes = _numpy_hash_reference(table, input_ids) | 90 | + hashes = _numpy_hash_reference(table, input_ids, positions) |
| 89 | - memory = F.embedding(hashes, table.weight).flatten(2) | 91 | + memory = F.embedding(hashes, table.weight).flatten(1) |
| 90 | D, M = engram.gate.hidden_size, engram.gate.num_branches | 92 | D, M = engram.gate.hidden_size, engram.gate.num_branches |
| 91 | # the fused projection holds each branch's key first, then the shared value | 93 | # the fused projection holds each branch's key first, then the shared value |
| 92 | key_rows, value_rows = engram.gate.wkv.split([M * D, D], dim=0) | 94 | key_rows, value_rows = engram.gate.wkv.split([M * D, D], dim=0) |
| @@ -102,7 +104,7 @@ def _official_demo_forward_reference(engram, hidden, input_ids, positions): | |||
| 102 | engram.gate.norm_eps, | 104 | engram.gate.norm_eps, |
| 103 | ) | 105 | ) |
| 104 | query = F.rms_norm( | 106 | query = F.rms_norm( |
| 105 | - hidden[:, :, branch], | 107 | + hidden[:, branch], |
| 106 | (engram.gate.hidden_size,), | 108 | (engram.gate.hidden_size,), |
| 107 | engram.gate.q_weight[branch], | 109 | engram.gate.q_weight[branch], |
| 108 | engram.gate.norm_eps, | 110 | engram.gate.norm_eps, |
| @@ -110,52 +112,103 @@ def _official_demo_forward_reference(engram, hidden, input_ids, positions): | |||
| 110 | logits = (key * query).sum(-1) / math.sqrt(engram.gate.hidden_size) | 112 | logits = (key * query).sum(-1) / math.sqrt(engram.gate.hidden_size) |
| 111 | logits = logits.abs().clamp_min(1e-6).sqrt() * logits.sign() | 113 | logits = logits.abs().clamp_min(1e-6).sqrt() * logits.sign() |
| 112 | gated.append(logits.sigmoid().unsqueeze(-1) * values) | 114 | gated.append(logits.sigmoid().unsqueeze(-1) * values) |
| 113 | - return hidden + torch.stack(gated, dim=2) | 115 | + return hidden + torch.stack(gated, dim=1) |
| 114 | 116 | ||
| 115 | 117 | ||
| 116 | def test_hash_resets_ngram_context_at_packed_document_boundary(): | 118 | def test_hash_resets_ngram_context_at_packed_document_boundary(): |
| 117 | table = _build_engram().table | 119 | table = _build_engram().table |
| 118 | - packed_ids = torch.tensor([[4, 5, 9, 10]], dtype=torch.int64) | 120 | + packed_ids = torch.tensor([4, 5, 9, 10], dtype=torch.int64) |
| 119 | - packed_positions = torch.tensor([[0, 1, 0, 1]], dtype=torch.int64) | 121 | + packed_positions = torch.tensor([0, 1, 0, 1], dtype=torch.int64) |
| 120 | packed_hashes = table.hash(packed_ids, packed_positions) | 122 | packed_hashes = table.hash(packed_ids, packed_positions) |
| 121 | 123 | ||
| 122 | - second_document = torch.tensor([[9, 10]], dtype=torch.int64) | 124 | + second_document = torch.tensor([9, 10], dtype=torch.int64) |
| 123 | - document_positions = torch.tensor([[0, 1]], dtype=torch.int64) | 125 | + document_positions = torch.tensor([0, 1], dtype=torch.int64) |
| 124 | document_hashes = table.hash(second_document, document_positions) | 126 | document_hashes = table.hash(second_document, document_positions) |
| 125 | - torch.testing.assert_close(packed_hashes[:, 2:], document_hashes, rtol=0, atol=0) | 127 | + torch.testing.assert_close(packed_hashes[2:], document_hashes, rtol=0, atol=0) |
| 128 | + | ||
| 129 | + | ||
| 130 | +@pytest.mark.parametrize( | ||
| 131 | + "ids,positions,history,image_mask", | ||
| 132 | + [ | ||
| 133 | + ([4], [0], None, None), | ||
| 134 | + ([4, 4, 5, 4, 4], [0, 1, 0, 1, 2], None, None), | ||
| 135 | + ([4, 5], [1, 2], [9], None), | ||
| 136 | + ([4, 5], [5, 6], [7, 8, 9, 10, 11], None), | ||
| 137 | + ([4, 5], [0, 1], [7, 8, 9], None), | ||
| 138 | + ([4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6], None, [False, True, True, False, False, False, False]), | ||
| 139 | + ], | ||
| 140 | + ids=["short", "repeated-packed", "short-history", "long-history", "reset-history", "image-span"], | ||
| 141 | +) | ||
| 142 | +def test_hash_with_compressed_tokens_matches_scalar_ngram_oracle(tmp_path, ids, positions, history, image_mask): | ||
| 143 | + mapping_path = tmp_path / "token_map.npy" | ||
| 144 | + np.save(mapping_path, np.array([(i * 5 + 3) % 11 for i in range(32)], dtype=np.int64)) | ||
| 145 | + table = _build_engram(str(mapping_path)).table | ||
| 146 | + ids, positions = torch.tensor(ids), torch.tensor(positions) | ||
| 147 | + history = torch.tensor(history) if history is not None else None | ||
| 148 | + image_mask = torch.tensor(image_mask) if image_mask is not None else None | ||
| 149 | + | ||
| 150 | + actual = table.hash(ids, positions, token_history=history, image_mask=image_mask) | ||
| 151 | + expected = _numpy_hash_reference(table, ids, positions, token_history=history, image_mask=image_mask) | ||
| 152 | + | ||
| 153 | + torch.testing.assert_close(actual, expected, rtol=0, atol=0) | ||
| 154 | + fetched = table(ids, positions, token_history=history, image_mask=image_mask) | ||
| 155 | + torch.testing.assert_close(fetched, F.embedding(expected, table.weight).flatten(1), rtol=0, atol=0) | ||
| 156 | + | ||
| 157 | + | ||
| 158 | +def test_token_history_requires_positions_and_text_only(): | ||
| 159 | + table = _build_engram().table | ||
| 160 | + ids, history = torch.tensor([4, 5]), torch.tensor([1]) | ||
| 161 | + with pytest.raises(ValueError, match="document-relative positions"): | ||
| 162 | + table.hash(ids, token_history=history) | ||
| 163 | + with pytest.raises(ValueError, match="text-only"): | ||
| 164 | + table.hash(ids, torch.arange(2), token_history=history, image_mask=torch.zeros(2, dtype=torch.bool)) | ||
| 126 | 165 | ||
| 127 | 166 | ||
| 128 | def test_per_row_history_and_one_window_state_the_same_rows(): | 167 | def test_per_row_history_and_one_window_state_the_same_rows(): |
| 129 | """Two history contracts, one meaning: the tokens before the local rows. | 168 | """Two history contracts, one meaning: the tokens before the local rows. |
| 130 | 169 | ||
| 131 | - ``[B, H]`` states one window shared by every local row (what a contiguous shard hands over); | 170 | + ``[H]`` states one window shared by every local row; ``[T, H]`` states each token's |
| 132 | - ``[B, L, H]`` states each row's own predecessors (what a document-parallel layout produces). | 171 | + own predecessors in the document-parallel layout. |
| 133 | Where both can express the same rows they must hash identically. | 172 | Where both can express the same rows they must hash identically. |
| 134 | """ | 173 | """ |
| 135 | table = _build_engram().table | 174 | table = _build_engram().table |
| 136 | - ids = torch.tensor([[9, 10]], dtype=torch.int64) | 175 | + ids = torch.tensor([9, 10], dtype=torch.int64) |
| 137 | - positions = torch.tensor([[0, 1]], dtype=torch.int64) | 176 | + positions = torch.tensor([0, 1], dtype=torch.int64) |
| 138 | 177 | ||
| 139 | # Two n-gram orders, so a row looks two tokens back: the window carries both distances. | 178 | # Two n-gram orders, so a row looks two tokens back: the window carries both distances. |
| 140 | - window = table.hash(ids, positions, token_history=torch.tensor([[9, 9]], dtype=torch.int64)) | 179 | + window = table.hash(ids, positions, token_history=torch.tensor([9, 9], dtype=torch.int64)) |
| 141 | - per_row = table.hash(ids, positions, token_history=torch.tensor([[[9, 9], [9, 9]]], dtype=torch.int64)) | 180 | + per_row = table.hash(ids, positions, token_history=torch.tensor([[9, 9], [9, 9]], dtype=torch.int64)) |
| 142 | torch.testing.assert_close(window, per_row, rtol=0, atol=0) | 181 | torch.testing.assert_close(window, per_row, rtol=0, atol=0) |
| 143 | 182 | ||
| 144 | # The first row starts its document, so its entries are masked either way; giving it another | 183 | # The first row starts its document, so its entries are masked either way; giving it another |
| 145 | # document's tail changes nothing, which is the mask the per-row contract relies on. | 184 | # document's tail changes nothing, which is the mask the per-row contract relies on. |
| 146 | - other_tail = table.hash(ids, positions, token_history=torch.tensor([[[5, 5], [9, 9]]], dtype=torch.int64)) | 185 | + other_tail = table.hash(ids, positions, token_history=torch.tensor([[5, 5], [9, 9]], dtype=torch.int64)) |
| 147 | torch.testing.assert_close(window, other_tail, rtol=0, atol=0) | 186 | torch.testing.assert_close(window, other_tail, rtol=0, atol=0) |
| 148 | 187 | ||
| 149 | 188 | ||
| 189 | + | ||
| 190 | +def test_doc_chunk_engram_history_matches_full_document_hashes(monkeypatch): | ||
| 191 | + model, _ = tiny_v41_model(monkeypatch) | ||
| 192 | + model.engram_history_size = 2 | ||
| 193 | + tokens = torch.arange(24) | ||
| 194 | + positions = torch.cat((torch.arange(8), torch.arange(16))) | ||
| 195 | + local_rows = torch.tensor([4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23]) | ||
| 196 | + | ||
| 197 | + history = model._engram_row_history(tokens, positions, cp_parallel_dims(2, 1)) | ||
| 198 | + table = _build_engram().table | ||
| 199 | + expected = table.hash(tokens, positions)[local_rows] | ||
| 200 | + actual = table.hash(tokens[local_rows], positions[local_rows], token_history=history) | ||
| 201 | + torch.testing.assert_close(actual, expected, rtol=0, atol=0) | ||
| 202 | + | ||
| 150 | def test_forward_backward_matches_official_demo_dataflow(): | 203 | def test_forward_backward_matches_official_demo_dataflow(): |
| 151 | with torch.random.fork_rng(devices=[]): | 204 | with torch.random.fork_rng(devices=[]): |
| 152 | torch.manual_seed(3) | 205 | torch.manual_seed(3) |
| 153 | engram = _build_engram() | 206 | engram = _build_engram() |
| 154 | reference = copy.deepcopy(engram) | 207 | reference = copy.deepcopy(engram) |
| 155 | - hidden = torch.randn(2, 9, 4, 8, requires_grad=True) | 208 | + hidden = torch.randn(9, 4, 8, requires_grad=True) |
| 156 | reference_hidden = hidden.detach().clone().requires_grad_() | 209 | reference_hidden = hidden.detach().clone().requires_grad_() |
| 157 | - input_ids = torch.randint(0, 32, (2, 9)) | 210 | + input_ids = torch.randint(0, 32, (9,)) |
| 158 | - positions = torch.arange(9).expand(2, -1) | 211 | + positions = torch.arange(9) |
| 159 | actual = engram(hidden, input_ids, positions) | 212 | actual = engram(hidden, input_ids, positions) |
| 160 | expected = _official_demo_forward_reference(reference, reference_hidden, input_ids, positions) | 213 | expected = _official_demo_forward_reference(reference, reference_hidden, input_ids, positions) |
| 161 | torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-5) | 214 | torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-5) |
| @@ -178,29 +231,29 @@ def test_bfloat16_gate_keeps_normalization_and_residual_in_fp32(): | |||
| 178 | torch.manual_seed(31) | 231 | torch.manual_seed(31) |
| 179 | engram = _build_engram().to(dtype=torch.bfloat16) | 232 | engram = _build_engram().to(dtype=torch.bfloat16) |
| 180 | reference = copy.deepcopy(engram) | 233 | reference = copy.deepcopy(engram) |
| 181 | - hidden = torch.randn(2, 17, 4, 8, dtype=torch.bfloat16, requires_grad=True) | 234 | + hidden = torch.randn(17, 4, 8, dtype=torch.bfloat16, requires_grad=True) |
| 182 | reference_hidden = hidden.detach().clone().requires_grad_() | 235 | reference_hidden = hidden.detach().clone().requires_grad_() |
| 183 | - input_ids = torch.randint(0, 32, (2, 17)) | 236 | + input_ids = torch.randint(0, 32, (17,)) |
| 184 | with torch.no_grad(): | 237 | with torch.no_grad(): |
| 185 | engram.gate.q_weight.uniform_(0.25, 1.75) | 238 | engram.gate.q_weight.uniform_(0.25, 1.75) |
| 186 | engram.gate.k_weight.uniform_(0.25, 1.75) | 239 | engram.gate.k_weight.uniform_(0.25, 1.75) |
| 187 | reference.gate.load_state_dict(engram.gate.state_dict()) | 240 | reference.gate.load_state_dict(engram.gate.state_dict()) |
| 188 | 241 | ||
| 189 | actual = engram(hidden, input_ids) | 242 | actual = engram(hidden, input_ids) |
| 190 | - memory = F.embedding(_numpy_hash_reference(reference.table, input_ids), reference.table.weight).flatten(2) | 243 | + memory = F.embedding(_numpy_hash_reference(reference.table, input_ids), reference.table.weight).flatten(1) |
| 191 | kv = F.linear(memory.to(hidden.dtype), reference.gate.wkv).float() | 244 | kv = F.linear(memory.to(hidden.dtype), reference.gate.wkv).float() |
| 192 | keys, value = kv.split([32, 8], dim=-1) | 245 | keys, value = kv.split([32, 8], dim=-1) |
| 193 | gated = [] | 246 | gated = [] |
| 194 | for branch, key in enumerate(keys.split(8, dim=-1)): | 247 | for branch, key in enumerate(keys.split(8, dim=-1)): |
| 195 | query = F.rms_norm( | 248 | query = F.rms_norm( |
| 196 | - reference_hidden[:, :, branch].float(), (8,), reference.gate.q_weight[branch].float(), engram.gate.norm_eps | 249 | + reference_hidden[:, branch].float(), (8,), reference.gate.q_weight[branch].float(), engram.gate.norm_eps |
| 197 | ) | 250 | ) |
| 198 | key = F.rms_norm(key, (8,), reference.gate.k_weight[branch].float(), engram.gate.norm_eps) | 251 | key = F.rms_norm(key, (8,), reference.gate.k_weight[branch].float(), engram.gate.norm_eps) |
| 199 | dot = (query * key).sum(-1) / math.sqrt(8) | 252 | dot = (query * key).sum(-1) / math.sqrt(8) |
| 200 | magnitude = dot.abs().clamp_min(1e-6).sqrt() | 253 | magnitude = dot.abs().clamp_min(1e-6).sqrt() |
| 201 | gate = torch.where(dot >= 0, magnitude, -magnitude).sigmoid() | 254 | gate = torch.where(dot >= 0, magnitude, -magnitude).sigmoid() |
| 202 | gated.append(gate.unsqueeze(-1) * value) | 255 | gated.append(gate.unsqueeze(-1) * value) |
| 203 | - expected = (reference_hidden.float() + torch.stack(gated, dim=2)).to(hidden.dtype) | 256 | + expected = (reference_hidden.float() + torch.stack(gated, dim=1)).to(hidden.dtype) |
| 204 | 257 | ||
| 205 | torch.testing.assert_close(actual, expected, rtol=0, atol=0) | 258 | torch.testing.assert_close(actual, expected, rtol=0, atol=0) |
| 206 | upstream_grad = torch.randn_like(actual) | 259 | upstream_grad = torch.randn_like(actual) |
| @@ -223,9 +276,9 @@ def test_zero_dot_gate_uses_positive_clamped_sqrt(): | |||
| 223 | engram.gate.wkv.zero_() | 276 | engram.gate.wkv.zero_() |
| 224 | engram.gate.wkv[-8:].fill_(1 / engram.gate.wkv.shape[1]) | 277 | engram.gate.wkv[-8:].fill_(1 / engram.gate.wkv.shape[1]) |
| 225 | engram.gate.q_weight.zero_() | 278 | engram.gate.q_weight.zero_() |
| 226 | - hidden = torch.zeros(1, 2, 4, 8, requires_grad=True) | 279 | + hidden = torch.zeros(2, 4, 8, requires_grad=True) |
| 227 | 280 | ||
| 228 | - output = engram(hidden, torch.tensor([[4, 5]])) | 281 | + output = engram(hidden, torch.tensor([4, 5])) |
| 229 | 282 | ||
| 230 | # Zero dot maps to sigmoid(sqrt(1e-6)), rather than sigmoid(0). | 283 | # Zero dot maps to sigmoid(sqrt(1e-6)), rather than sigmoid(0). |
| 231 | expected_gate = 1 / (1 + math.exp(-0.001)) | 284 | expected_gate = 1 / (1 + math.exp(-0.001)) |
| @@ -267,14 +320,14 @@ def test_released_v41_geometry_builds_published_logical_tables(): | |||
| 267 | 320 | ||
| 268 | def test_image_tokens_reset_hash_history_and_receive_no_residual_gradient(): | 321 | def test_image_tokens_reset_hash_history_and_receive_no_residual_gradient(): |
| 269 | engram = _build_engram() | 322 | engram = _build_engram() |
| 270 | - ids = torch.tensor([[1, 4, 5, 6, 7, 8]]) | 323 | + ids = torch.tensor([1, 4, 5, 6, 7, 8]) |
| 271 | - positions = torch.arange(6).unsqueeze(0) | 324 | + positions = torch.arange(6) |
| 272 | - mask = torch.tensor([[False, True, True, False, False, False]]) | 325 | + mask = torch.tensor([False, True, True, False, False, False]) |
| 273 | hashes = engram.table.hash(ids, positions, image_mask=mask) | 326 | hashes = engram.table.hash(ids, positions, image_mask=mask) |
| 274 | # Text suffix after an image must hash exactly like a new document. | 327 | # Text suffix after an image must hash exactly like a new document. |
| 275 | - expected = engram.table.hash(ids[:, 3:], torch.arange(3).unsqueeze(0)) | 328 | + expected = engram.table.hash(ids[3:], torch.arange(3)) |
| 276 | - torch.testing.assert_close(hashes[:, 3:], expected, rtol=0, atol=0) | 329 | + torch.testing.assert_close(hashes[3:], expected, rtol=0, atol=0) |
| 277 | - hidden = torch.randn(1, 6, 4, 8, requires_grad=True) | 330 | + hidden = torch.randn(6, 4, 8, requires_grad=True) |
| 278 | output = engram(hidden, ids, positions, image_mask=mask) | 331 | output = engram(hidden, ids, positions, image_mask=mask) |
| 279 | torch.testing.assert_close(output[mask], hidden[mask], rtol=0, atol=0) | 332 | torch.testing.assert_close(output[mask], hidden[mask], rtol=0, atol=0) |
| 280 | output[mask].sum().backward() | 333 | output[mask].sum().backward() |
| @@ -295,7 +348,7 @@ def test_explicit_disable_preserves_selected_optimizer(optimizer): | |||
| 295 | "--no-engram-enabled", | 348 | "--no-engram-enabled", |
| 296 | "--optimizer.name", | 349 | "--optimizer.name", |
| 297 | optimizer, | 350 | optimizer, |
| 298 | - "--training.seq-len", | 351 | + "--training.num-tokens-per-microbatch-per-dp-rank", |
| 299 | "512", | 352 | "512", |
| 300 | ] | 353 | ] |
| 301 | ) | 354 | ) |
| @@ -320,7 +373,7 @@ def test_model_config_accepts_parameterized_engram_override(fused_attention): | |||
| 320 | 373 | ||
| 321 | config = deepseek_v4_1_debugmodel_text() | 374 | config = deepseek_v4_1_debugmodel_text() |
| 322 | config.hf_assets_path = "tests/assets/deepseek_v3" | 375 | config.hf_assets_path = "tests/assets/deepseek_v3" |
| 323 | - config.training.seq_len = 512 | 376 | + config.training.num_tokens_per_microbatch_per_dp_rank = 512 |
| 324 | config.override.imports = [ | 377 | config.override.imports = [ |
| 325 | ( | 378 | ( |
| 326 | "torchtitan_npu.override.deepseek_v4_1.engram.host_offload_mxfp8", | 379 | "torchtitan_npu.override.deepseek_v4_1.engram.host_offload_mxfp8", |
| @@ -11,7 +11,7 @@ from types import SimpleNamespace | |||
| 11 | 11 | ||
| 12 | import pytest | 12 | import pytest |
| 13 | import torch | 13 | import torch |
| 14 | -from torch.utils.checkpoint import checkpoint, DefaultDeviceType | 14 | +from torch.utils.checkpoint import DefaultDeviceType, checkpoint |
| 15 | 15 | ||
| 16 | from torchtitan_npu.extensions.torchtitan.components.optimizer import optimizer as host_mod | 16 | from torchtitan_npu.extensions.torchtitan.components.optimizer import optimizer as host_mod |
| 17 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable | 17 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable |
| @@ -73,6 +73,79 @@ def test_local_sparse_training_and_checkpoint_match_embedding(monkeypatch, recom | |||
| 73 | optimizer.load_state_dict(states) | 73 | optimizer.load_state_dict(states) |
| 74 | 74 | ||
| 75 | 75 | ||
| 76 | +def test_token_forward_microbatch_clipping_and_sparse_adam_match_embedding(): | ||
| 77 | + from torchtitan.components.optimizer import ParamGroupConfig | ||
| 78 | + | ||
| 79 | + table = table_config().build() | ||
| 80 | + table._init_self_buffers(buffer_device=torch.device("cpu")) | ||
| 81 | + with torch.no_grad(): | ||
| 82 | + table.weight.copy_(torch.arange(48).view(12, 4) / 16) | ||
| 83 | + initial_weight = table.weight.detach().clone() | ||
| 84 | + reference = torch.nn.Embedding.from_pretrained(initial_weight.clone(), freeze=False, sparse=True) | ||
| 85 | + model = torch.nn.Module() | ||
| 86 | + model.add_module("table", table) | ||
| 87 | + optimizer = host_mod.HostSparseOptimizersContainer.Config( | ||
| 88 | + lr=0.05, | ||
| 89 | + weight_decay=0.0, | ||
| 90 | + implementation="for-loop", | ||
| 91 | + param_groups=[ | ||
| 92 | + ParamGroupConfig(pattern="table.weight", optimizer_name="SparseAdam", optimizer_kwargs={"lr": 0.05}), | ||
| 93 | + ], | ||
| 94 | + ).build(model_parts=[model]) | ||
| 95 | + ref_optimizer = torch.optim.SparseAdam(reference.parameters(), lr=0.05) | ||
| 96 | + | ||
| 97 | + for step in range(2): | ||
| 98 | + for microbatch, tokens in enumerate(([4, 4, 4, 5], [4, 5, 4, 4])): | ||
| 99 | + ids, positions = torch.tensor(tokens), torch.arange(4) | ||
| 100 | + row_ids = table.hash(ids, positions) | ||
| 101 | + output = table(ids, positions) | ||
| 102 | + expected = reference(row_ids).flatten(1) | ||
| 103 | + torch.testing.assert_close(output, expected, rtol=0, atol=0) | ||
| 104 | + upstream = torch.arange(output.numel()).reshape_as(output).float() / 8 + step + microbatch | ||
| 105 | + output.backward(upstream) | ||
| 106 | + expected.backward(upstream) | ||
| 107 | + pending = table.pending_sparse_grad() | ||
| 108 | + ref_grad = reference.weight.grad.coalesce() | ||
| 109 | + assert table.weight.grad is None | ||
| 110 | + torch.testing.assert_close(pending.indices(), ref_grad.indices(), rtol=0, atol=0) | ||
| 111 | + torch.testing.assert_close(pending.values(), ref_grad.values(), rtol=0, atol=0) | ||
| 112 | + | ||
| 113 | + expected_norm = ref_grad.values().square().sum().sqrt() | ||
| 114 | + expected_scale = torch.clamp(1.0 / (expected_norm + 1e-6), max=1.0) | ||
| 115 | + norm = host_mod.clip_grad_norm_with_host_sparse_tables( | ||
| 116 | + [], | ||
| 117 | + 1.0, | ||
| 118 | + tables=[table], | ||
| 119 | + clipper=torch.nn.utils.clip_grad_norm_, | ||
| 120 | + ) | ||
| 121 | + reference.weight.grad = torch.sparse_coo_tensor( | ||
| 122 | + ref_grad.indices(), | ||
| 123 | + ref_grad.values() * expected_scale, | ||
| 124 | + ref_grad.shape, | ||
| 125 | + ).coalesce() | ||
| 126 | + torch.testing.assert_close(norm, expected_norm, rtol=0, atol=0) | ||
| 127 | + torch.testing.assert_close( | ||
| 128 | + table.pending_sparse_grad().values(), | ||
| 129 | + reference.weight.grad.values(), | ||
| 130 | + rtol=0, | ||
| 131 | + atol=0, | ||
| 132 | + ) | ||
| 133 | + optimizer.step() | ||
| 134 | + ref_optimizer.step() | ||
| 135 | + torch.testing.assert_close(table.weight, reference.weight, rtol=0, atol=0) | ||
| 136 | + actual_state = optimizer.optimizers[0].state[table.weight] | ||
| 137 | + expected_state = ref_optimizer.state[reference.weight] | ||
| 138 | + assert actual_state["step"] == expected_state["step"] == step + 1 | ||
| 139 | + for name in ("exp_avg", "exp_avg_sq"): | ||
| 140 | + torch.testing.assert_close(actual_state[name], expected_state[name], rtol=0, atol=0) | ||
| 141 | + untouched = torch.ones(table.num_embeddings, dtype=torch.bool) | ||
| 142 | + untouched[ref_grad.indices()[0]] = False | ||
| 143 | + torch.testing.assert_close(table.weight[untouched], initial_weight[untouched], rtol=0, atol=0) | ||
| 144 | + optimizer.zero_grad(set_to_none=True) | ||
| 145 | + ref_optimizer.zero_grad(set_to_none=True) | ||
| 146 | + assert table.pending_sparse_grad() is None and table.weight.grad is None | ||
| 147 | + | ||
| 148 | + | ||
| 76 | def _ramp(rows): | 149 | def _ramp(rows): |
| 77 | return torch.arange(rows * _DIM, dtype=torch.float32).reshape(rows, _DIM) | 150 | return torch.arange(rows * _DIM, dtype=torch.float32).reshape(rows, _DIM) |
| 78 | 151 | ||
| @@ -183,11 +256,11 @@ def test_trainer_clip_aborts_before_nonfinite_correction(monkeypatch, overflow_s | |||
| 183 | def test_training_step_preserves_parent_context_and_sparse_clipping(monkeypatch, anticipatory): | 256 | def test_training_step_preserves_parent_context_and_sparse_clipping(monkeypatch, anticipatory): |
| 184 | from torchtitan.components.optimizer import ParamGroupConfig | 257 | from torchtitan.components.optimizer import ParamGroupConfig |
| 185 | from torchtitan.distributed import utils as dist_utils | 258 | from torchtitan.distributed import utils as dist_utils |
| 186 | - from torchtitan.trainer import Trainer | ||
| 187 | from torchtitan.models.common.linear import Linear | 259 | from torchtitan.models.common.linear import Linear |
| 260 | + from torchtitan.models.common.moe import TokenChoiceTopKRouter | ||
| 261 | + from torchtitan.trainer import Trainer | ||
| 188 | 262 | ||
| 189 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig | 263 | from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig |
| 190 | - from torchtitan_npu.extensions.experiment.anticipatory_routing.router import AnticipatoryHashRouter | ||
| 191 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule | 264 | from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule |
| 192 | from torchtitan_npu.models.deepseek_v4_1.config_registry import DeepSeekV41Trainer | 265 | from torchtitan_npu.models.deepseek_v4_1.config_registry import DeepSeekV41Trainer |
| 193 | from torchtitan_npu.models.deepseek_v4_1.indexer import FULL | 266 | from torchtitan_npu.models.deepseek_v4_1.indexer import FULL |
| @@ -196,6 +269,9 @@ def test_training_step_preserves_parent_context_and_sparse_clipping(monkeypatch, | |||
| 196 | class RoutingModel(torch.nn.Module): | 269 | class RoutingModel(torch.nn.Module): |
| 197 | """CPU fixture whose initialization forward visits the real router.""" | 270 | """CPU fixture whose initialization forward visits the real router.""" |
| 198 | 271 | ||
| 272 | + def preprocess_inputs(self, batch, **kwargs): | ||
| 273 | + return batch["input"], batch["labels"], {} | ||
| 274 | + | ||
| 199 | def forward(self, input_ids): | 275 | def forward(self, input_ids): |
| 200 | return self.router((input_ids.float() + 1).unsqueeze(-1))[0] | 276 | return self.router((input_ids.float() + 1).unsqueeze(-1))[0] |
| 201 | 277 | ||
| @@ -205,7 +281,9 @@ def test_training_step_preserves_parent_context_and_sparse_clipping(monkeypatch, | |||
| 205 | with torch.no_grad(): | 281 | with torch.no_grad(): |
| 206 | model.table.weight.fill_(1) | 282 | model.table.weight.fill_(1) |
| 207 | optimizer = host_mod.HostSparseOptimizersContainer.Config( | 283 | optimizer = host_mod.HostSparseOptimizersContainer.Config( |
| 208 | - lr=0.1, weight_decay=0.0, implementation="for-loop", | 284 | + lr=0.1, |
| 285 | + weight_decay=0.0, | ||
| 286 | + implementation="for-loop", | ||
| 209 | param_groups=[ | 287 | param_groups=[ |
| 210 | ParamGroupConfig(pattern="table.weight", optimizer_name="SparseAdam"), | 288 | ParamGroupConfig(pattern="table.weight", optimizer_name="SparseAdam"), |
| 211 | ParamGroupConfig(pattern="dense", optimizer_name="AdamW"), | 289 | ParamGroupConfig(pattern="dense", optimizer_name="AdamW"), |
| @@ -214,41 +292,50 @@ def test_training_step_preserves_parent_context_and_sparse_clipping(monkeypatch, | |||
| 214 | trainer = object.__new__(DeepSeekV41Trainer) | 292 | trainer = object.__new__(DeepSeekV41Trainer) |
| 215 | trainer.model_parts, trainer.optimizers = [model], optimizer | 293 | trainer.model_parts, trainer.optimizers = [model], optimizer |
| 216 | model.selector = AscSelector.Config( | 294 | model.selector = AscSelector.Config( |
| 217 | - mode=FULL, compress_ratio=1, num_index_heads=1, index_head_dim=4, index_topk=1, | 295 | + mode=FULL, |
| 296 | + compress_ratio=1, | ||
| 297 | + num_index_heads=1, | ||
| 298 | + index_head_dim=4, | ||
| 299 | + index_topk=1, | ||
| 218 | ).build() | 300 | ).build() |
| 219 | - model.router = AnticipatoryHashRouter.Config( | 301 | + model.router = TokenChoiceTopKRouter.Config( |
| 220 | - num_experts=2, top_k=1, gate=Linear.Config(in_features=1, out_features=2), | 302 | + num_experts=2, |
| 303 | + top_k=1, | ||
| 304 | + gate=Linear.Config(in_features=1, out_features=2), | ||
| 221 | ).build() | 305 | ).build() |
| 222 | with torch.no_grad(): | 306 | with torch.no_grad(): |
| 223 | model.router.gate.weight.copy_(torch.tensor([[1.0], [-1.0]])) | 307 | model.router.gate.weight.copy_(torch.tensor([[1.0], [-1.0]])) |
| 224 | trainer._indexer_selectors = [model.selector] | 308 | trainer._indexer_selectors = [model.selector] |
| 225 | trainer.config = SimpleNamespace( | 309 | trainer.config = SimpleNamespace( |
| 226 | training=SimpleNamespace(disable_cuda_graphs=True, max_norm=1.0, steps=2), | 310 | training=SimpleNamespace(disable_cuda_graphs=True, max_norm=1.0, steps=2), |
| 311 | + parallelism=SimpleNamespace(), | ||
| 227 | anticipatory=AnticipatoryRoutingConfig(enable=anticipatory), | 312 | anticipatory=AnticipatoryRoutingConfig(enable=anticipatory), |
| 228 | checkpoint=SimpleNamespace(interval=1, keep_latest_k=0), | 313 | checkpoint=SimpleNamespace(interval=1, keep_latest_k=0), |
| 229 | ) | 314 | ) |
| 230 | trainer.parallel_dims = SimpleNamespace( | 315 | trainer.parallel_dims = SimpleNamespace( |
| 231 | - dp_enabled=False, pp_enabled=False, ep_enabled=False, dp_cp_enabled=False, | 316 | + dp_enabled=False, |
| 317 | + pp_enabled=False, | ||
| 318 | + ep_enabled=False, | ||
| 319 | + dp_cp_enabled=False, | ||
| 232 | get_optional_mesh=lambda name: None, | 320 | get_optional_mesh=lambda name: None, |
| 233 | ) | 321 | ) |
| 234 | trainer.device = torch.device("cpu") | 322 | trainer.device = torch.device("cpu") |
| 235 | - trainer.step = trainer.num_pipeline_parallel_microbatches = 1 | 323 | + trainer.step = trainer.num_pp_microbatches = 1 |
| 324 | + trainer.sdc_replayer = None | ||
| 236 | trainer.gradient_accumulation_steps = 2 | 325 | trainer.gradient_accumulation_steps = 2 |
| 237 | trainer.ntokens_seen = 1 | 326 | trainer.ntokens_seen = 1 |
| 238 | trainer.train_context = nullcontext | 327 | trainer.train_context = nullcontext |
| 239 | 328 | ||
| 240 | - def preprocess(inputs, labels): | ||
| 241 | - trainer.ntokens_seen += labels.numel() | ||
| 242 | - return inputs["input"], labels, {} | ||
| 243 | - | ||
| 244 | - trainer.post_dataloading_process = preprocess | ||
| 245 | events, metrics = [], [] | 329 | events, metrics = [], [] |
| 246 | trainer.lr_schedulers = SimpleNamespace(get_metrics=lambda: {}, step=lambda: events.append("lr")) | 330 | trainer.lr_schedulers = SimpleNamespace(get_metrics=lambda: {}, step=lambda: events.append("lr")) |
| 247 | - trainer.checkpointer = SimpleNamespace(maybe_wait_for_staging=lambda: events.append("staging"), save=lambda *a: True) | 331 | + trainer.checkpointer = SimpleNamespace( |
| 332 | + maybe_wait_for_staging=lambda: events.append("staging"), save=lambda *a: True | ||
| 333 | + ) | ||
| 248 | trainer.metrics_processor = SimpleNamespace( | 334 | trainer.metrics_processor = SimpleNamespace( |
| 249 | should_log=lambda step: True, | 335 | should_log=lambda step: True, |
| 250 | log=lambda *args, **kwargs: metrics.append(args), | 336 | log=lambda *args, **kwargs: metrics.append(args), |
| 251 | - ntokens_since_last_log=0, data_loading_times=[], | 337 | + ntokens_since_last_log=0, |
| 338 | + data_loading_times=[], | ||
| 252 | ) | 339 | ) |
| 253 | trainer._sdc = SimpleNamespace(finalize_sdc_step=lambda: events.append("sdc")) | 340 | trainer._sdc = SimpleNamespace(finalize_sdc_step=lambda: events.append("sdc")) |
| 254 | 341 | ||
| @@ -256,8 +343,8 @@ def test_training_step_preserves_parent_context_and_sparse_clipping(monkeypatch, | |||
| 256 | """Two fixed CPU batches for the schedule's initial training step.""" | 343 | """Two fixed CPU batches for the schedule's initial training step.""" |
| 257 | 344 | ||
| 258 | def __iter__(self): | 345 | def __iter__(self): |
| 259 | - yield {"input": torch.tensor([0])}, torch.tensor([-100]) | 346 | + yield {"input": torch.tensor([0]), "num_valid_tokens": 0}, torch.tensor([-100]) |
| 260 | - yield {"input": torch.tensor([0, 1])}, torch.tensor([1, 2]) | 347 | + yield {"input": torch.tensor([0, 1]), "num_valid_tokens": 2}, torch.tensor([1, 2]) |
| 261 | 348 | ||
| 262 | def state_dict(self): | 349 | def state_dict(self): |
| 263 | return {} | 350 | return {} |
| @@ -270,6 +357,7 @@ def test_training_step_preserves_parent_context_and_sparse_clipping(monkeypatch, | |||
| 270 | # Both microbatches, including unsupervised positions, must be counted | 357 | # Both microbatches, including unsupervised positions, must be counted |
| 271 | # before the first fused selector consumes the step denominator. | 358 | # before the first fused selector consumes the step denominator. |
| 272 | assert model.selector.num_global_queries.item() == 3 | 359 | assert model.selector.num_global_queries.item() == 3 |
| 360 | + assert kwargs["global_valid_tokens"].item() == 2 | ||
| 273 | if anticipatory: | 361 | if anticipatory: |
| 274 | assert trainer.anticipatory_schedule.engine.in_step | 362 | assert trainer.anticipatory_schedule.engine.in_step |
| 275 | loss = (3 * model.dense.sum() + 4 * model.table._distributed_lookup(input_dict["input"])[0, 0]) / 2 | 363 | loss = (3 * model.dense.sum() + 4 * model.table._distributed_lookup(input_dict["input"])[0, 0]) / 2 |
| @@ -294,7 +382,7 @@ def test_training_step_preserves_parent_context_and_sparse_clipping(monkeypatch, | |||
| 294 | assert engine.last_global_loss == 7.0 and not engine.in_step and not engine.failed | 382 | assert engine.last_global_loss == 7.0 and not engine.in_step and not engine.failed |
| 295 | assert trainer.metrics_processor.ntokens_since_last_log == 3 | 383 | assert trainer.metrics_processor.ntokens_since_last_log == 3 |
| 296 | assert trainer.ntokens_seen == 1 # Initialization must not credit training tokens. | 384 | assert trainer.ntokens_seen == 1 # Initialization must not credit training tokens. |
| 297 | - buffer = model.router._anticipatory_replay_buffer | 385 | + buffer = trainer.anticipatory_schedule.cache.replay_buffers[model.router._anticipatory_key] |
| 298 | torch.testing.assert_close(buffer.indices, torch.zeros(1, 1, dtype=torch.int64)) | 386 | torch.testing.assert_close(buffer.indices, torch.zeros(1, 1, dtype=torch.int64)) |
| 299 | assert events == expected_events | 387 | assert events == expected_events |
| 300 | assert metrics == [(1, 7.0, 7.0, 5.0)] | 388 | assert metrics == [(1, 7.0, 7.0, 5.0)] |
| @@ -309,3 +397,31 @@ def test_training_step_preserves_parent_context_and_sparse_clipping(monkeypatch, | |||
| 309 | assert Trainer.train_step is original_step | 397 | assert Trainer.train_step is original_step |
| 310 | assert Trainer.train_step.__globals__["dist_utils"] is dist_utils | 398 | assert Trainer.train_step.__globals__["dist_utils"] is dist_utils |
| 311 | assert dist_utils.clip_grad_norm_ is dense_clip | 399 | assert dist_utils.clip_grad_norm_ is dense_clip |
| 400 | + | ||
| 401 | + | ||
| 402 | +def test_lora_host_table_accepts_folded_parent_keywords_without_frozen_autograd(): | ||
| 403 | + # LoRA is optional, so import its adapter only for this parent-signature contract. | ||
| 404 | + from torchtitan_npu.models.deepseek_v4_1.lora import _LoRAHostEngramTable | ||
| 405 | + | ||
| 406 | + table = _LoRAHostEngramTable.Config( | ||
| 407 | + vocab_size=16, | ||
| 408 | + layer_id=0, | ||
| 409 | + ngram_orders=(2,), | ||
| 410 | + num_heads=1, | ||
| 411 | + head_vocab_sizes=(11,), | ||
| 412 | + embedding_dim=4, | ||
| 413 | + num_embeddings=12, | ||
| 414 | + require_token_id_map=False, | ||
| 415 | + pin_memory=False, | ||
| 416 | + ).build() | ||
| 417 | + table._init_self_buffers(buffer_device=torch.device("cpu")) | ||
| 418 | + with torch.no_grad(): | ||
| 419 | + table.weight.copy_(torch.arange(48).view(12, 4) / 16) | ||
| 420 | + table.weight.requires_grad_(False) | ||
| 421 | + tokens, positions = torch.tensor([3, 4, 3, 4]), torch.arange(4) | ||
| 422 | + | ||
| 423 | + output = table(input_ids_T=tokens, positions_T=positions) | ||
| 424 | + | ||
| 425 | + expected = table.weight[table.hash(tokens, positions)].flatten(1) | ||
| 426 | + torch.testing.assert_close(output, expected, rtol=0, atol=0) | ||
| 427 | + assert not output.requires_grad | ||
| @@ -26,10 +26,11 @@ import torch | |||
| 26 | from torchtitan_npu.models.deepseek_v4_1 import model_registry | 26 | from torchtitan_npu.models.deepseek_v4_1 import model_registry |
| 27 | 27 | ||
| 28 | 28 | ||
| 29 | -class _NoParameters: | 29 | +class _NoParameters(torch.nn.Module): |
| 30 | """Parameter-free model stand-in for attention-only arithmetic tests.""" | 30 | """Parameter-free model stand-in for attention-only arithmetic tests.""" |
| 31 | 31 | ||
| 32 | def __init__(self, n_layers): | 32 | def __init__(self, n_layers): |
| 33 | + super().__init__() | ||
| 33 | self.layers = {str(idx): _NoEngramLayer() for idx in range(n_layers)} | 34 | self.layers = {str(idx): _NoEngramLayer() for idx in range(n_layers)} |
| 34 | 35 | ||
| 35 | def named_parameters(self): | 36 | def named_parameters(self): |
Rtorchtitan_npu/models/deepseek_v4/chat_dataset.py→torchtitan_npu/models/deepseek_v4/chat_processor.py+39-92