Skip to content

refactor: migrate V4.1 CSA2 to the module family architecture - #1606

Merged
xingleixu123 merged 1 commit into
mindspore-ai:masterfrom
xuxl1008:refactor/v41-csa2-module-family
Nov 21, 2026
Merged

xingleixu123 merged 1 commit into
mindspore-ai:masterfrom
xuxl1008:refactor/v41-csa2-module-family

Conversation

@xuxl1008

@xuxl1008 xuxl1008 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Paired: GitHub #1606 ↔ GitCode !1980

What type of PR is this?
/kind refactor

What does this PR do / why do we need it:

Migrate DeepSeek-V4.1 CSA2 to the common module-family architecture. Split attention, compression, Indexer selection, auxiliary KL, document layout and parallel scheduling out of shared_compressed_dsa_attention.py, and remove the model adapter's second wrapper around attention forward.

The public entry point is hyper_parallel.components.modules.CompressedSparseAttention2. The family selects local/CP implementations from the topology and reference/fused implementations through use_fused_ops. Common TP/SP boundaries handle input/output redistribution; intermediate head reductions are bound separately. Fusion and Indexer load balancing still require TP=1 and reject unsupported configurations explicitly.

Responsibilities and execution boundaries

File Responsibility
compressed_sparse_attention2_family.py Implementation selection, complete parameter/port layouts, validation and parallel binding
compressed_sparse_attention2.py Shared forward, local attention, projections, V4.1 RoPE and shared-state protocol
compressor.py Non-overlapping compression projections, pooling and normalization; CP subclasses exchange boundary rows
indexer.py CSA2Indexer projections, shared-key production/consumption and discrete selection
indexer_kl_loss.py Owner-side teacher/KL, reference gradients and native KL dispatch
document_layout.py Document boundaries, local compression blocks and prepared packed inputs; no implicit communication launch
cp_compressed_sparse_attention2.py CP launch/wait stages, Indexer dispatch and intermediate TP head reductions

Existing module-family builders, TP/SP boundaries, CPContext, collectives, sequence dispatch, Indexer balancing, functional operator adapters and checkpoint infrastructure remain part of the execution path. The architecture and diagrams are described in #1627.

Compressor and Indexer remain actual submodule calls, so their projections execute inside the scopes managed by FSDP and activation checkpointing. Source replacement preserves Parameter/buffer identity, buffer persistence, trainability, child training modes and checkpoint keys. Direct construction retains the HF V4 parameter construction order; this family implements the V4.1 algorithm.

Additional changes:

  • Adopt the public RMSNorm family at four normalization sites. The default reference path preserves FP32 normalization and cast-before-weight order, including unit-scale initialization after meta materialization. Fused normalization is independently selectable.
  • Centralize recomputation publication suppression in shared-state publish_* methods. Validation traces record actual publications only.
  • Remove _DeferredBankLaunch: launch main KV explicitly after Index K submission, store the actual handle and wait at consumption. Preserve the existing communication dependencies.
  • Remove the obsolete attention module, CP adapter wrapper and generated model artifacts. Update model/runtime registration, validation, tests, YAML and codegen inputs to the new entry point.
  • Document all parameter shapes and TP placements, output-group sharding, Full/Reindex/Reuse ownership, TP/SP boundaries, intermediate head SUM, CP/EP replication and independent FSDP storage sharding in the module README.

Configuration

plan_overrides:
  - match: "model.layers.*.self_attn"
    replace:
      kind: module
      implementation:
        _target_: hyper_parallel.components.modules.CompressedSparseAttention2
        use_fused_ops: true
        main_kv_comm: all_to_all_v
        indexer_load_balance: greedy
        indexer_balance_block_size: 2048

Remove the old attention *.self_attn.forward replacement and tp_divide_attrs: [num_groups] to avoid duplicate wrapping and sharding. Full/Reindex/Reuse roles, natural-document isolation, candidate restrictions, teacher/KL formulas and Q chunking retain their existing semantics.

Position and runtime-validation fixes from #1553

  • Decouple physical CP query addresses from RoPE positions. CP rank, degree and local length determine physical row ranges; document-reset RoPE is already represented by the supplied cos/sin. Packed-boundary checks and communication addresses remain intact.
  • Derive runtime shared-state requirements from the final model's actual roles and configuration, including checkpoint wrappers. A four-layer crop with candidates disabled and no Reindex no longer requires nonexistent candidate or Index K consumption events. Missing sources, invalid ordering and duplicate publications still fail. Other models retain the static contract unless they opt into the resolver.

Which issue(s) this PR fixes:

Refs #1627 and #1553. Module-family foundation: #1523. MLA/GQA comparison: #1587. Related optimizer-state issue: #1585.

Test Plan and Test result: What scenarios were tested, and what were the verification results (function, performance, reliability, etc.)?

Module and distributed numerical checks

  • 184 related CPU unit tests passed during the review update, covering shared attention, packed/graph inputs, KL, recomputation contracts, TP scores, model integration, codegen, RMSNorm and family imports.
  • Against the pre-review snapshot on the same upstream base: CPU/Gloo CP8 with none+AG+r2, zigzag+A2AV+r2, greedy+AG+r1 and hybrid+A2AV+r2, plus CPU TP2 with SP off/on. Outputs, TopK, input gradients and all parameter gradients matched with rtol=0, atol=0.
  • NPU/HCCL CP2: the same four modes on a fused Full→Reindex→Reuse chain with odd-length packed documents matched bitwise. The zigzag/A2AV/r2 chain also matched between ordinary execution and whole-attention recomputation.
  • Reference RMSNorm matched the previous HF normalization in FP32/BF16 outputs and input/scale gradients. Meta initialization, parameter identity, layout ownership and independent fused selection were checked. This does not claim bitwise parity for fused normalization.
  • Shared-state replay preserved published tensors, offsets and IDs without duplicate trace events.

Trainer, TP and multi-source role chains

The following comparisons used pre-refactor master 7db2d93fb734a216e3e3580bb63e800534d5fc51 and the measured PR revision 7a040f386bd622b016ee6cab30d1489e2e6b924a, with identical topology, weights, data and precision.

Scenario Configuration Result
Eight-layer role chain SWA, SWA, Full(r2), Reindex(r2), Reuse(r2), Full(r1), Reindex(r1), Reuse(r1); CP2; odd packed documents crossing compression boundaries; two sources; none+AG and zigzag+A2AV Bitwise parity on CPU FP32 and NPU BF16 with the three fused adapters
Role-chain recomputation All attention layers checkpointed; existing Full/Reindex selection exclusion retained Outputs, TopK, banks, input gradients and all parameter gradients matched bitwise
Document-reset positions CPU CP2; identical document-local cos/sin; old wrapper received physical positions only for its validation Bitwise parity in ordinary and replayed execution
Real DeepSeek text Trainer Four layers, width divided by four, 16 experts, 2048 tokens, TP1/CP2/EP2/DP2, FSDP2/EDP2, GAS1, AdamW, three fused adapters, main A2AV Ten updates per implementation; all four ranks matched bitwise at every step
Real VLM Trainer Same text configuration plus two vision layers, real COCO images/captions, decoding/preprocessing, dynamic packing and the existing full checkpoint policy Ten updates per implementation; all four ranks matched bitwise at every step
TP2+EP2 Four layers, real indexed DeepSeek data, 1024 tokens, CP1, AdamW; SP off/no recomputation and SP on/full recomputation Both configurations matched bitwise for ten updates
TP2×CP2×EP2 Four devices, SP on, full recomputation, main A2AV, FSDP/EDP shard size 1 Ten updates per implementation; 40 rank-step pairs matched bitwise

Trainer checks compared every input, actual parameter gradient, updated parameter/buffer, loss, gradient norm and learning rate using raw tensor-byte hashes. Text covered 4,080 gradient pairs and 4,720 parameter/buffer pairs; VLM covered 5,120 and 5,920 respectively. Experts, routers, Engram, vision encoder and aligner produced nonzero gradients. All final runs exited normally. KL was not recorded as a separate scalar; all Indexer gradients and updates were compared.

The candidate used this PR's runtime contract directly. The old-master baseline received only equivalent validation-condition and checkpoint-wrapper recognition fixes, without changes to attention, communication or optimizer mathematics.

TP runs used the supported reference path (use_fused_ops=false). Native TP score/teacher reduction was not added. The Trainer's existing full checkpoint policy still excludes Full source attention; whole-attention checkpointing was tested separately in the role-chain experiment.

Environment: Torch/Torch-NPU 2.12.0, CANN 9.2.0, Transformers 5.13.1 and Ascend 910B3. The fused adapters used the existing v41_training_transformer vendor dated 2026-09-23. This is not evidence that the CANN 9.2 built-in SMLA metadata supports ratio 2. These diagnostic runs included CPU tensor copies/hashing and are not performance measurements.

Rebase and follow-up checks

Rebased onto master@9d9d06539700f0088ba3f9722a0ce9efdd52a8d4 without conflicts. At that revision the production Python code matched the measured revision above; the additional change was the sharding README. Thirty real-module layout configurations (five roles × TP1/2/4 × SP off/on), 100 related CPU tests, documentation links and catalog checks passed. Test counts from separate rounds overlap and should not be added together.

The 2026-11-20 follow-up rebases onto master@1d489a70 (including the public EP cleanup). Local execution of the CPU CP8 smoke test exposed an obsolete deepcopy(model) in the test setup: public RMSNorm family members retain immutable build metadata that is not pickleable. The test now constructs an independent model and strictly loads the same state before conversion. Output, gradient and optimizer-update assertions and the gate level are unchanged. The launcher passed locally with both Torch 2.10 and 2.12. The remote build's earlier pytest exit code 4 did not include worker-level diagnostics, so the remote rerun is still required to establish whether it has an additional collection/environment failure. Common torchrun/logging utilities were not changed.

Remote build #1882 subsequently passed that CPU smoke stage, code checks and compilation. Its UT stage reported three additional legacy whole-module deepcopy failures in the V4.1 compressor, shifted-mHC/DSpark, and native auxiliary-loss tests. These setups now also construct independent modules and strictly load matching state. All 21 tests in the two affected test files pass locally, with all existing output/gradient assertions retained. The final revision includes both the CP8 setup fix and these three setup fixes; the remote rerun remains the final gate check.

Validation boundaries

The full 40-layer training model, released deep Reindex layers in an end-to-end run, joint TP with nontrivial FSDP parameter sharding, MegaMoE/MegaGate, encoder parallelism, static graphs and full distributed checkpoint save/resume remain outside the completed matrix. No new performance claim is made.

Issue #1585 F3 is a pre-existing training-parameter/checkpoint problem: with KL disabled, Indexer parameters remain in optimizer groups without initialized state. A CPU Full→Reindex→Reuse probe trained three steps, restored into a fresh model/optimizer and compared the fourth update. The original implementation failed for both nested and flattened state formats; excluding or statically freezing inactive Indexer parameters restored both formats with bitwise-identical subsequent updates and unchanged model checkpoint keys. This is not a full NPU/FSDP restore result. The permanent-KL-off fix is submitted separately in #1639; this refactor does not change trainability or relax strict loading.

Self-checklist:

  • Module-family design and interfaces await maintainer review.
  • Affected entry points, configuration, documentation and shared execution dependencies are covered.
  • Related tests and numerical checks are recorded with their actual scope and remaining gaps.

@xuxl1008
xuxl1008 force-pushed the refactor/v41-csa2-module-family branch from 1e8b366 to 4d9726a Compare November 19, 2026 07:58
@xuxl1008

Copy link
Copy Markdown
Contributor Author

/check-pr

@xuxl1008

Copy link
Copy Markdown
Contributor Author

/retest

@mindspore-ai-bot

Copy link
Copy Markdown

🔵 The pipeline #1805 is running. Please wait a moment... (Link)

@mindspore-ai-bot

Copy link
Copy Markdown
Project Name Build_Stage Build Result Details
Hyper-parallel_Github_Gate - ❌ FAILURE 1805
Check_Pylint FAILURE 1805

@mindspore-ai-bot

Copy link
Copy Markdown

@xuxl1008, your gate pipeline failed at the code check stage. You can configure some code check tools locally following the (pre-push quick guide), to enable automatic checking when you push your code every time. Tools included are: Check_CMakelint, Check_Codespell, Check_Cpplint, Check_Lizard, Check_Pylint, Check_ClangFormat, Check_ShellCheck.

@xuxl1008

Copy link
Copy Markdown
Contributor Author

/retest

@mindspore-ai-bot

Copy link
Copy Markdown

🔵 The pipeline #1889 is running. Please wait a moment... (Link)

@mindspore-ai-bot

Copy link
Copy Markdown
Project Name Build_Stage Build Result Details(Full/Incremental) Detail
Coverage Line Coverage ❌ FAILURE 77%/72% Link

@mindspore-ai-bot

Copy link
Copy Markdown
Platform Type Module Excution Time Time Limit
- distributed_data 315.651s 450.0s
- activation_memory 382.908s 375.0s
- shard 175.469s 300.0s
- pipeline_parallel 589.887s 675.0s
- accuracy 89.747s 120.0s
- auto_models 91.412s 150.0s
- optimizer 268.44s 300.0s
- clip_grad 90.012s 120.0s
- fully_shard 320.209s 600.0s
- dtensor 70.452s 120.0s
- process_group 79.087s 90.0s
- llama3_examples 84.112s 120.0s
- swap_optimizer 344.793s 300.0s
- distributed_checkpoint 85.625s 120.0s
- context_parallel 81.033s 240.0s
- tensor_parallel 221.101s 300.0s
- init_weights 71.143s 118.75s
- expert_parallel 89.27125s 200.0s
- multicore 4.2305s 120.0s

@mindspore-ai-bot

Copy link
Copy Markdown
Project Name Build_Stage Build Result Details
Hyper-parallel_Github_Gate - ❌ FAILURE 1882
UT_TEST FAILURE 1882
Smoke_CPU_X86_CentOS_Level0 FAILURE 1889

@mindspore-ai-bot

Copy link
Copy Markdown
Project Name Build_Stage Build Result Details(Full/Incremental) Detail
Coverage Line Coverage ❌ FAILURE 77%/72% Link

@mindspore-ai-bot

Copy link
Copy Markdown
Platform Type Module Excution Time Time Limit
- distributed_data 341.376s 450.0s
- activation_memory 418.533s 375.0s
- shard 185.247s 300.0s
- pipeline_parallel 743.124s 675.0s
- fully_shard 441.467s 600.0s
- accuracy 115.506s 120.0s
- optimizer 337.469s 300.0s
- clip_grad 125.906s 120.0s
- auto_models 105.059s 150.0s
- llama3_examples 110.392s 120.0s
- process_group 110.299s 90.0s
- swap_optimizer 395.224s 300.0s
- context_parallel 89.739s 240.0s
- distributed_checkpoint 90.239s 120.0s
- tensor_parallel 246.571s 300.0s
- expert_parallel 95.09875s 200.0s
- dtensor 85.039s 120.0s
- init_weights 87.367s 118.75s
- multicore 4.52412s 120.0s

@mindspore-ai-bot

Copy link
Copy Markdown
Project Name Build_Stage Build Result Details
Hyper-parallel_Github_Gate - ❌ FAILURE 1889
UT_TEST FAILURE 1882
Smoke_CPU_X86_CentOS_Level0 FAILURE 1889

@xuxl1008

Copy link
Copy Markdown
Contributor Author

/retest

@mindspore-ai-bot

Copy link
Copy Markdown

🔵 The pipeline #1895 is running. Please wait a moment... (Link)

@mindspore-ai-bot

Copy link
Copy Markdown
Project Name Build_Stage Build Result Details(Full/Incremental) Detail
Coverage Line Coverage ✅ SUCCESS 77%/73% Link

@mindspore-ai-bot

Copy link
Copy Markdown
Project Name Build_Stage Build Result Details
Hyper-parallel_Github_Gate - ✅ SUCCESS 1895

@xingleixu123
xingleixu123 merged commit e02966f into mindspore-ai:master Nov 21, 2026
4 of 22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants