Repository navigation
[AutoTP] Support tied embeddings for row-parallel output-head training - #8680
Conversation
…ut-head training The row-parallel output-head tie check scanned the module tree during the replacement walk. When a tied embedding matched a partition_config spec, it was sliced into a new Parameter before lm_head was visited, so the check no longer saw the tie and the head was sharded while the embedding kept a separate copy. Snapshot weight ties from the original model in __init__ and consult that snapshot instead. Signed-off-by: Jin, Youzhi <[email protected]>
bf0a8b5 to
f96d8bb
Compare
Row-parallel output-head training rejected a weight tied to the input embedding. Shard every tied nn.Embedding along the same hidden dimension with a new HiddenParallelEmbedding that reuses the head's weight shard and all-gathers each token's slices into the replicated activation. Tied embeddings are skipped by _slice_embedding so traversal order cannot break the tie, and all tie partners are validated before the shared weight is partitioned. Signed-off-by: Jin, Youzhi <[email protected]>
| name=embed_full_name, | ||
| tp_meta=self.tp_meta) | ||
| # Guards re-entry when the replacement walk later reaches this module. | ||
| setattr(hidden_parallel_embedding, "replaced", True) |
There was a problem hiding this comment.
Every test that exercises the tied row-parallel output head registers embed_tokens before lm_head, and in those fixtures the guard setattr(hidden_parallel_embedding, "replaced", True) is never consulted — the embedding is protected by _tied_row_parallel_embedding_ids instead. (A tie alias reached later in the walk does consult it, but no such fixture uses a row-parallel head.)
When the head is visited first the guard becomes load-bearing: _replace_with_config then dispatches the freshly installed HiddenParallelEmbedding (2-dim weight, not an nn.Embedding) into _create_row_parallel_layer and wraps it a second time, and the replaced flag is the only check that stops it — without it embed_tokens ends up as a LinearAllreduce.
A head-first OutputModel case would cover it.
There was a problem hiding this comment.
Good catch — added a head-first parametrization in 12ae314. It fails without the replaced guard (embed_tokens becomes LinearAllreduce) and passes with it.
|
Thanks for your help with the merge, @delock. I checked the latest run and found two failing cases, which I’ve reproduced. I’m investigating whether they’re due to a bug or rounding differences. |
My suspicion is that this is a precision-related issue. I was able to reproduce the failure with TF32 enabled, but it did not occur when I forced FP32. I’m not sure what the exact CI environment is, though. I suggest we first address the timeout in @delock Thanks |
Looks like modal is hitting 5400 sec (1.5 hour limit). Let's watch another nightly run to see what is the actual finish time. It is 1h08m on Oct-4. |
## Problem Since deepspeedai#8680 landed, `modal-torch-latest / DeepSpeedAI CI` has failed for every merge-queue entry that runs this test on Modal's L40S runners (deepspeedai#8794, deepspeedai#8701, deepspeedai#8670). Example: [run 38009529440](https://github.com/deepspeedai/DeepSpeed/actions/runs/38009529440/job/114086150257). ``` FAILED tests/unit/v1/autotp/test_autotp_training.py::TestTiedRowParallelOutputHeadTraining::test_training_matches_unsharded_reference[35-3-False-0] FAILED tests/unit/v1/autotp/test_autotp_training.py::TestTiedRowParallelOutputHeadTraining::test_training_matches_unsharded_reference[35-3-True-0] Mismatched elements: 1 / 670 (0.1%) Greatest absolute difference: 1.1173542588949203e-06 at index (1, 1, 45) (up to 1e-06 allowed) ``` deepspeedai#8680's own merge-queue run and the next nightly run both used the AWS fallback, where the test passes, so the failure wasn't caught there. ## Root cause The row-parallel head (`LinearAllreduceWithReplicatedInput`) slices the hidden vector, computes a partial matmul on each rank, and all-reduces the partial logits. The reference is one unsharded fp32 matmul, and the two summation orders round differently. The tied head uses the embedding's N(0,1) weights, so logits reach about 14, where one fp32 ulp is about 1e-6. Logits that are near zero through cancellation can therefore differ by more than `atol=1e-6`. Even the fp32 reference differs from a float64 ground truth by up to 2.2e-6. ## Fix Use torch.testing's default fp32 tolerance (`atol=1e-5`, `rtol=1.3e-6`) for every fp32 `assert_close` in `test_autotp_training.py`. That covers 17 checks, including both row-parallel logits checks, and matches the 19 fp32 checks in the file that already use the default. The half-precision tolerances in `run_tp_layer_fwd_bwd` are unchanged. The default is enough for what these tests check: - The sharding bugs they target (wrong shard offset, missing all-reduce, dropped tied-gradient contribution, tied weights drifting apart) move values by 0.1 to 10. - A simulated precision regression (all-reduce inputs rounded to bf16) still fails every check it failed under the old tolerances. The one exception is the SGD-update check, which can't detect it under either tolerance. - The custom values were tighter than the default only for values below about 1, and looser for larger ones such as the losses. ## Evidence (2x H200) - In a sweep of 40 init seeds, every parametrization of the tied test has seeds that fail the old logits check (worst ratio to the allowed tolerance: 1.19). Under the default, the worst case uses under 30% of the limit. - Changing only the seed to 8199 reproduces the CI failure: `[35-3-False-0]` and `[35-3-True-0]` fail with `1 / 670` mismatched and `1.25e-06 (up to 1e-06 allowed)`. - Every other changed check stays under 3% of the default limit, recorded per call across the 4 affected test classes. ## Testing Hardware: 2x NVIDIA H200, torch 2.12.0+cu130, Python 3.12. - `pytest tests/unit/v1/autotp/test_autotp_training.py -k "TestRowParallelOutputHeadTraining or TestTiedRowParallelOutputHeadTraining"`: 8 passed. - `pytest tests/unit/v1/autotp/test_autotp_training.py -m sequential -k "TestTiedEmbeddingAliasesAndFallback or TestTiedVocabParallelLMHead"`: 30 passed. - Seed-8199 reproduction, which fails before this change: passes with the default logits tolerance. - `pre-commit run --files tests/unit/v1/autotp/test_autotp_training.py`: passed. No L40S is available locally. This PR's merge-queue run selects this test file, so it will check the fix on Modal's L40S runners unless the run falls back to AWS. --------- Signed-off-by: Hongwei Chen <[email protected]> Co-authored-by: Copilot <[email protected]>
deepspeedai#8859) # AutoTP: shard an untied input embedding along the vocabulary (`vocab_parallel_embedding`) **Part of:** deepspeedai#8672 (Q4 2026 roadmap), "Enable training of large scale models". ## Summary `vocab_parallel_lm_head` (deepspeedai#8309, deepspeedai#8582) shards an input embedding only when it is tied to the output layer. An untied input embedding stays replicated on every tensor-parallel rank: on Qwen2.5-72B at TP 8 it is 1.25B of each GPU's 10.18B parameters (12%), with its gradient, master copy and Adam states, and its gradient is the last one produced in backward. This PR adds `tensor_parallel.vocab_parallel_embedding` (default `false`): AutoTP replaces the model's untied `nn.Embedding` by the existing `VocabParallelEmbedding` (1/tp of the rows per rank, masked lookup, sum over the TP group). ```json "tensor_parallel": { "autotp_size": 8, "vocab_parallel_embedding": true } ``` The option works on all three AutoTP partitioning paths (HuggingFace `tp_plan`, `partition_config` or `preset_model`, and the heuristic path), at ZeRO 0 to 3, and with models built under `deepspeed.zero.Init`. The vocabulary is split evenly over the ranks, like the vocabulary-parallel head. A tied embedding is sharded with its output head instead: | Tied embedding, output head | With `vocab_parallel_embedding: true` | |---|---| | vocabulary-parallel (`vocab_parallel_lm_head`) | no change: the embedding already shares the head's shard | | row-parallel (`partition_config` ROW spec, deepspeedai#8538, deepspeedai#8680) | no change: the embedding already shares the head's shard | | replicated | `NotImplementedError`, rather than untie the embedding from its head | The option raises a `ValueError` when a `partition_config` spec has already partitioned the embedding, and when the DeepCompile `autotp` pass is enabled (that pass rewrites only linear layers). ## Results Qwen2.5-72B, 4 nodes x 8 H200 (EFA), AutoTP 8 x ZeRO-1 over 4, micro-batch 2, 64 x 8,192 tokens per step, bf16 with fp32 master weights and Adam states, no recompute, Liger kernels for RMSNorm, rotary embedding and SwiGLU (applied by our benchmark script); the two runs in one allocation, with this code in our study tree (together with the AutoTP sequence-sharding changes, which are separate PRs): | | Without | With | |---|---|---| | Step time | 15.88 s | 15.77 s | | Peak memory (rank 0) | 114.1 GiB | 107.0 GiB | | Embedding parameters per GPU | 1.25B | 0.16B | | Gradient reduce after the last backward (`wall_clock_breakdown`) | 89 ms | 44 ms | These runs used the first revision of this PR. The review fixes do not change this configuration: with 8 key-value heads at TP 8, the old and the new split both give 19,008 rows per rank, and the run used ZeRO-1 without `zero.Init`. ## Duplicate check Searched issues and pull requests on 2026-11-18 for `vocab_parallel_embedding`, "untied embedding AutoTP", `VocabParallelEmbedding` and `embedding_rowwise`. deepspeedai#8309 and deepspeedai#8582 shard a tied embedding with a vocabulary-parallel head, deepspeedai#8538 and deepspeedai#8680 a tied embedding with a row-parallel head, deepspeedai#8294 converts the HuggingFace `embedding_rowwise` entry, and deepspeedai#8173 (closed RFC) discusses sharding output layers. None shards an untied input embedding. ## The change | File | Change | |---|---| | `deepspeed/module_inject/auto_tp.py` (+46) | `AutoTP._replace_untied_input_embedding()`: replaces every registration of `model.get_input_embeddings()` by a `VocabParallelEmbedding`, split evenly over the ranks. It gathers a `zero.Init` weight with `_gather_zero3_params`, which records the replacement for the optimizer remap. It returns `None` when AutoTP has already replaced the embedding with a tensor-parallel layer (tied to a sharded head). It raises when the embedding weight is shared with another module, or was already partitioned by a matching spec | | `deepspeed/runtime/engine.py` (+25, -1) | calls it in `finalize_autotp`, before the replicated-gradient hooks are registered, when the option is set; the heuristic path builds an `AutoTP` for it; rejects the DeepCompile `autotp` pass before any module is replaced | | `deepspeed/runtime/tensor_parallel/config.py` (+8) | the option | | `docs/_pages/config-json.md`, `docs/_tutorials/autotp-training.md` | the option, and an "Untied Input Embedding" section | | `tests/unit/v1/autotp/test_autotp_training.py` (+213) | `TestVocabParallelEmbedding` (16 tests) | ### Changes after the first review - A tied embedding that a row-parallel head has already sharded (`HiddenParallelEmbedding`) is left as it is, instead of raising. - An embedding already partitioned by a matching `partition_config` spec raises a `ValueError`, instead of being split a second time along the vocabulary. - The DeepCompile `autotp` pass raises a `ValueError` at initialize, instead of failing later in `engine.compile()`. - Models built under `deepspeed.zero.Init` work; before, the split of the empty ZeRO-3 placeholder raised. - The vocabulary is split evenly. Before, the HuggingFace plan and `partition_config` paths split it by key-value head count: 44 and 22 rows for 3 key-value heads at TP 2, and 0 rows on ranks 8 to 15 for 8 key-value heads at TP 16. - Every name under which the model registers the embedding module gets the sharded module. - The sharding moved from a function in `layers.py` to an `AutoTP` method, so that it uses the model's `tp_meta` (including `tp_grain_size`) and the ZeRO-3 gather on every path. ## Tests `TestVocabParallelEmbedding` (2 ranks, AutoTP 2, a 2-layer Llama with 3 key-value heads and a 66-token vocabulary, built from a config): - `test_matches_single_device_training` (8 cases: HF `tp_plan` at ZeRO 0, 1, 2, 3 and ZeRO-3 with `zero.Init`; HF `tp_plan` with `vocab_parallel_lm_head: true`; `preset_model: llama`; the heuristic path): the input embedding becomes a `VocabParallelEmbedding` with 33 of the 66 rows. With tokens from both halves of the vocabulary, the losses of 2 SGD steps match the unsharded model, and the gathered embedding weight matches the unsharded model's after them. - `test_tied_embedding_keeps_the_shard_of_its_output_head` (vocabulary-parallel and row-parallel head): the embedding keeps sharing the head's weight, and training matches the unsharded model. - `test_replaces_every_registration_of_the_embedding`: a second name for the embedding module gets the sharded module. - `test_universal_checkpoint_rebuilds_the_embedding`: the universal checkpoint metadata rebuilds the full embedding from the shards. - `test_save_load_round_trip_preserves_loss` (ZeRO-1): a checkpoint restores the loss in a model built with another seed. - `test_rejects_conflicting_request` (3 cases): a tied embedding with a replicated head, a `partition_config` spec that matches the embedding, and the DeepCompile `autotp` pass. Without the fixes (the first revision merged with master), 11 of the 16 tests fail: the 7 `test_matches_single_device_training` cases on the HF plan and `partition_config` paths (44 and 22 rows; with `zero.Init` the split raises), the row-parallel tied case, the alias case, and the spec and DeepCompile rejections. The changed code runs inside `deepspeed.initialize` with AutoTP, so every test file that initializes an engine with AutoTP was run. All runs are on this branch with master 4a9efc1 merged. GPU: 1 node of 8 NVIDIA H200 (driver 595.112.07), pytest 8.3.5, transformers 5.15.1, torch 2.8.0+cu126 unless noted. CPU: the CPU accelerator with the gloo backend and `LOCAL_SIZE=4`, torch 2.8.0+cu126. | Test files | Where, torch | Result | |---|---|---| | `unit/v1/autotp/test_autotp_training.py` (includes the 16 `TestVocabParallelEmbedding` tests) | GPU | 60 passed, 2 skipped (the existing BF16-optimizer overflow skips) | | the same file, `-m sequential` | GPU | 66 passed | | `TestVocabParallelEmbedding` on the first revision merged with master (control) | GPU | 11 failed, 5 passed, as listed above | | `unit/v1/autotp/test_tp_plan_e2e.py`, `test_tp_plan_real_models.py`, `test_autotp_custom_patterns.py`, `test_autotp_multiple_models.py`, `unit/module_inject/test_tp_partition_config_path.py` | GPU | 96 passed | | `unit/compile/test_tp_compile.py`; the same with `-m sequential` | GPU | 19 passed; 9 passed | | `unit/checkpoint/test_autotp_uc_checkpoint.py`, `test_zero_affine.py` | GPU | 74 passed | | `unit/v1/ops/muon/test_per_head_muon_accelerator.py`, `unit/v1/sequence_parallelism/test_liger_vocab_parallel_cross_entropy.py`, `unit/v1/test_hybrid_engine_rollout_v1.py` | GPU | 60 passed, 5 skipped (4 need `liger_kernel`, which is not installed here or in CI; 1 needs `DEEPSPEED_PRETRAINED_ROLLOUT_MODEL`) | | `unit/v1/moe/test_autoep_unit.py`, `test_autoep_autotp_checkpoint.py`, `test_autoep_autotp_deepcompile_reject.py`, `test_autoep_autotp_folding_config.py`, `test_autoep_autotp_runtime.py`, `test_autoep_checkpoint.py` | GPU | 304 passed, 7 skipped (cases that run only with `DEEPSPEED_RUN_H100_TESTS=1`) | | `unit/v1/moe/test_autoep_autotp_grad_parity.py` with `DEEPSPEED_RUN_H100_TESTS=1` | GPU | 20 passed | | `unit/v1/moe/test_autoep_autotp_sharded_attention.py`; the same with `-m sequential` | GPU | 69 passed; 2 passed | | `unit/v1/moe/test_autoep_expert_activation.py` | GPU, torch 2.9.1+cu128 (on torch 2.8 the backward of `torch._grouped_mm` can stall with an empty expert, also on master) | 96 passed, 12 skipped (the file's own skip: "with Triton installed, this form's grouped path needs CUDA tensors") | | `test_autotp_training.py`, default set; `-m sequential` | CPU | 60 passed, 2 skipped; 66 passed | | `test_tp_plan_e2e.py`, `test_tp_plan_real_models.py`, `test_autotp_custom_patterns.py`, `test_autotp_multiple_models.py`, `test_tp_partition_config_path.py`, `test_autotp_uc_checkpoint.py` | CPU | 143 passed | | `test_zero_affine.py` | CPU | 27 passed | No test failed outside the control row. `pre-commit run --files` passes on every changed file. ## Compatibility | Cell | Validated | |---|---| | AutoTP 2, ZeRO 0, 1, 2, 3, fp32 (unit tests, HF `tp_plan` path) | yes | | ZeRO-3 with the model built under `deepspeed.zero.Init` | yes (unit test) | | `partition_config` (`preset_model: llama`) and heuristic paths, ZeRO-1 | yes (unit tests) | | Untied embedding with `vocab_parallel_lm_head: true` | yes (unit test, ZeRO-0 and heuristic ZeRO-1) | | Tied embedding with a vocabulary-parallel or a row-parallel head | yes, unchanged (unit tests) | | Checkpoint save / load (ZeRO-1) and universal checkpoint metadata | yes (unit tests) | | Universal checkpoint conversion end to end (`ds_to_universal`), HF export with `save_16bit_model` | not run | | AutoTP 8 + ZeRO-1, bf16, Qwen2.5-72B, 4 nodes | yes, first revision (see Results) | | bf16 / fp16 in the unit tests | not run (fp32 only) | | Optimizer or parameter offload | not run | | DeepCompile `autotp` pass | rejected with `ValueError` | | Models whose `get_input_embeddings()` is not an `nn.Embedding` | rejected with `ValueError` | | Accelerators other than CUDA | not run on device; the new tests also pass on CPU with 2 gloo processes | ## AI assistance This change, its tests and this description were prepared with AI assistance (Claude). --------- Signed-off-by: pengdurice <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Follow-up to #8538 (part of #8173).
Summary
Row-parallel output-head training (#8538) rejected an
lm_head/embed_outwhose weight is tied tothe input embedding, and that rejection could be bypassed silently (see Bug below). This PR fixes
the bug and supports the tied case by sharding the tied
nn.Embeddingalong the same hiddendimension as the row-parallel head, so both share one physical per-rank shard.
Bug: tie silently broken when the embedding is visited first
The tie was detected by scanning
self.module.modules()during the replacement walk. The walkvisits
embed_tokensbeforelm_head, so whenpartition_configalso matches the embedding,_slice_embeddingswaps it for a new module with a new Parameter first. By the timelm_headwaschecked, no other module aliased its weight, the check passed, and the head was sharded while the
embedding kept a separate copy — with no error.
Fixed by snapshotting weight ties from the original, pre-replacement model in
AutoTP.__init__,following the approach the vocab-parallel path already takes for the same ordering issue
(introduced in #8309, now
_tied_vocab_parallel_embedding_ids).Changes
HiddenParallelEmbedding(layers.py): looks up each token's hidden-dimension slice andall-gathers the slices into the replicated activation (
GatherFromTensorParallelRegion, souneven hidden shards work). When tied, it reuses the row-parallel head's already-sharded weight
Parameterand partition sizes; its universal-checkpoint metadata matchesLinearAllreduce's.padding_idx,scale_grad_by_freq, and Gemma3's scaled embedding are preserved;max_norm,sparse, and other custom forwards are rejected.AutoTP(auto_tp.py):tied to a row-parallel training head so
_slice_embeddingleaves them alone regardless oftraversal order.
_create_row_parallel_layervalidates all tie partners before partitioning the sharedweight, then replaces every tied embedding alias with a
HiddenParallelEmbedding. A tie to anon-
nn.Embeddingmodule still raises; a conflicting explicit embedding spec is supersededwith a warning.
autotp-training.mddescribes the tied path and notes thatvocab_parallel_lm_headisusually preferable for tied models, since a row-parallel head all-reduces full vocabulary logits.
Not changed: untied embeddings that match a spec still go through
_slice_embedding, whoseun-gathered hidden slice is intentional for per-head embeddings such as T5's
relative_attention_bias.Tests
test_tp_partition_config_path.py): tie is shared with/without an embedding specvisited first (the embedding-spec case reproduces the bug above on master); rejection for
non-embedding ties and
max_normleaves the model untouched; Gemma3 scaled lookup matches theoriginal module.
TestTiedRowParallelOutputHeadTraining, 2 GPUs): three optimizer steps against anunsharded reference comparing logits, the full tied gradient (lookup + projection
contributions), and updated weights, covering even/uneven hidden (32/35),
padding_idx,embedding-spec ordering, and ZeRO-0/2; universal-checkpoint affine map rebuilds the tied weight
from uneven shards. Mutation check: detaching the embedding's weight in the lookup fails all
four training cases.
tests/unit/module_inject/andtests/unit/v1/autotp/: 225 passed, 12 skipped on3x NVIDIA GeForce RTX 5090 D.