Repository navigation
[transformers_modeling_backend] Make TP collectives explicit - #5805
Conversation
09831a3 to
46ae22c
Compare
46ae22c to
65e89ff
Compare
65e89ff to
e2a6d1e
Compare
e2a6d1e to
c4599ca
Compare
c4599ca to
f21854b
Compare
f21854b to
f24f035
Compare
f24f035 to
d902716
Compare
|
@claude review |
|
Claude finished @anijain2305's task in 4m 24s —— View job Approve -- please address the items before merging: review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The change is needed: #5807 removes implicit ShardingConfig redistribution, so without this PR the Transformers backend would lose its TP collectives. The collectives it issues match the old path one for one. Remaining items are local: fill in the PR description, and fold the embedding mixin into the existing _VocabShardEmbedding.
What this PR does. HF modules keep their own forward, so the backend used to get its TP collectives from ShardingConfig src -> dst redistribution, which is async. The PR now swaps each boundary module to a cached subclass with a mixin that calls spmd.redistribute directly:
_GatherTPInputall-gathers the SP input ofself_attn, the dense MLP, andlm_head._ReduceTPOutputreduces (or reduce-scatters) the output ofo_proj/down_proj._VocabParallelEmbeddingruns the masked lookup inlocal_mapand then reduces.
The configs now declare only the layout at each boundary.
Example (o_proj under TP2+SP):
before: o_proj._sharding_config = {out_src: P, out_dst: SP layout}
-> Module wrapper: spmd_redistribute_per_axis(P -> S(1), async_op=True)
after: o_proj._sharding_config = {out_src: SP layout} # assert only
o_proj.__class__ = (_ReduceTPOutput, <HF Linear Module>)
-> mixin: spmd.redistribute(out, tp_group, src=P, dst=S(1)) # sync
Must fix
- PR description is empty. Every section, including "Summary (human-written)", is still the template placeholder. The commit message already has the content for Why / What changed / Numerics. Please copy it in and add:
hf_sharding.py:153--_VocabParallelEmbeddingstacks a mixin on top of_VocabShardEmbedding, which exists only to return the unreduced lookup, and that class's docstring is now stale. Fold the mixin into_VocabShardEmbedding.forward(see inline).
Should consider
hf_sharding.py:179--_add_tp_boundaryrepeats the_make_module_classcache-and-swap pattern. Move it intomodule_conversion.py(see inline).hf_sharding.py:385-- question: how was the TP-without-SP numerics run done, givenenable_sp=tp_enabled(see inline)?- The no-op
in_dst == in_src/out_dst == out_srcentries that remain (flex kernel:339, norm:510-512, rope:563) issue no collectives. #5807 presumably deletes them with the fields. If not, delete them here so this file stops using the dst fields entirely.
Details
- Equivalence checked against
Module._redistribute_inputs/_outputs(models/base/module.py:571-667): each mixin issues the same single TP-axisS(1)/S(0) -> RorP -> S(1)/I/Rredistribute withbackward_options={"op_dtype": x.dtype}. CP and DP were no-op axes at these boundaries before. - Ordering: the input
assert_typeagainstin_srcstill runs before the mixin gathers. The outputassert_typeagainst the newout_srcruns after the mixin reduces. - Signature:
_cache_pos_arg_namesusesinspect.signature(type(self).forward). Thefunctools.wrapswrapper exposes the HF signature through__wrapped__, so positional-to-name mapping is preserved. - Remat: the redistribution was not in a remat region before and is not in one now. Behavior under
activation_remat.applyis unchanged. - Alternatives considered: forward pre/post hooks would run outside
forward_with_redistribution, so the src asserts would see the wrong layout. Converting to coreColumnParallelLinear/RowParallelLineardoesn't fit either, because they reduce on token dim 0 while HF keeps(B, S, D)with sequence on dim 1. So a class swap is a reasonable mechanism here.
Not verified: bitwise parity and TPS (needs GPUs).
| class _VocabParallelEmbedding: | ||
| """Mixin reducing the TP-``Partial`` vocab-sharded lookup to ``_tp_output_dst``. | ||
|
|
||
| The masked lookup runs in a local-SPMD region (TP-replicated token ids in, | ||
| TP-partial embeddings out); the reduction runs outside it. | ||
| """ | ||
|
|
||
| _tp_output_dst: spmd.PerMeshAxisSpmdType | ||
|
|
||
| def forward(self, input: torch.Tensor) -> torch.Tensor: | ||
| tokens = _hf_activation_placement(tp=spmd.R) | ||
| partial = _hf_activation_placement(tp=spmd.P) | ||
| output = spmd.local_map( | ||
| in_types=((tokens.local_type, tokens.partition_spec),), | ||
| out_types=(partial.local_type, partial.partition_spec), | ||
| )( | ||
| super().forward # pyrefly: ignore [missing-attribute] | ||
| )( | ||
| input | ||
| ) | ||
| return _maybe_redistribute_tp(output, src=spmd.P, dst=self._tp_output_dst) |
There was a problem hiding this comment.
Splits one job across two classes and two files. convert_hf_to_module already swaps every nn.Embedding to _VocabShardEmbedding (module_conversion.py:32), whose only purpose is to return the unreduced TP-Partial lookup. This mixin is then swapped in on top of it to add the local_map and the reduction. So the embedding forward now goes through _VocabParallelEmbedding (mixin) -> _VocabShardEmbedding -> core VocabParallelEmbedding, three near-identical names for one lookup. Also, _VocabShardEmbedding's docstring ("the embedding's sharding config owns the reduction instead") is now wrong.
Smallest fix: move this forward body (the local_map around lookup_vocab_shard plus _maybe_redistribute_tp) into _VocabShardEmbedding.forward. Keep the current no-TP behavior, set _tp_output_dst on the instance where set_hf_sharding_configs builds the config, and delete this mixin and its _add_tp_boundary call. Update the docstring to say the class owns the reduction.
| _tp_boundary_class_cache: dict[tuple[type, type], type] = {} | ||
|
|
||
|
|
||
| def _add_tp_boundary(module: nn.Module, mixin: type, **attrs: object) -> None: | ||
| """Swap ``module`` to a cached subclass of its class with ``mixin`` first. | ||
|
|
||
| Like ``convert_hf_to_module``, this keeps module state and state_dict keys. | ||
| The subclass ``forward`` reports the HF signature: ``Module`` maps | ||
| positional inputs to its sharding config by parameter name. | ||
| """ | ||
| cls = type(module) | ||
| key = (mixin, cls) | ||
| if key not in _tp_boundary_class_cache: | ||
| mixin_forward = mixin.forward | ||
|
|
||
| @functools.wraps(cls.forward) | ||
| def forward(self, *args, **kwargs): | ||
| return mixin_forward(self, *args, **kwargs) | ||
|
|
||
| _tp_boundary_class_cache[key] = type( | ||
| cls.__name__, (mixin, cls), {"forward": forward} | ||
| ) | ||
| module.__class__ = _tp_boundary_class_cache[key] | ||
| for name, value in attrs.items(): | ||
| setattr(module, name, value) |
There was a problem hiding this comment.
Should consider: this is a second copy of the class-swap machinery that module_conversion.py already owns (_module_class_cache + _make_module_class do the same "cached type(cls.__name__, bases, ...), then assign __class__"). Consider moving it next to _make_module_class so all __class__ swaps (and their caches) live in one module. That is where the "keeps module state and state_dict keys" invariant is documented.
| "hidden_states": _hf_activation_placement(tp=spmd.R), | ||
| }, | ||
| ) | ||
| if enable_sp: |
There was a problem hiding this comment.
Question: parallelize.py:161 passes enable_sp=parallelism_context.tp_enabled, so with TP > 1 SP is always on in this backend. That makes the enable_sp=False + TP branches unreachable: no gather, P -> I in _set_row_parallel, P -> R for the embedding. The commit message reports bitwise parity for "dense debug model at TP2 ... without SP". How was that configuration run? If it needed a local hack, please say so in the description. If the non-SP TP path really can't be reached, the else destinations here and in _set_row_parallel / the embedding are untested code.
d902716 to
62188b7
Compare
62188b7 to
9892e16
Compare
9892e16 to
b321658
Compare
b321658 to
1f3f9f2
Compare
|
@claude review this PR |
|
Claude finished @anijain2305's task in 3m 20s —— View job Approve -- the earlier must-fix items are fixed; two optional cleanups remain: review |
bc5f0ef to
5d14b13
Compare
There was a problem hiding this comment.
Verdict: Approve -- the earlier must-fix items are fixed at bc5f0ef, and I found no new correctness problems. The two remaining items are optional cleanups.
What this PR does. HF modules keep their own forward. The backend used to get its TP collectives from implicit, async ShardingConfig src -> dst redistribution, which #5807 removes. The PR now issues each collective explicitly:
- a cached mixin subclass (
add_forward_mixin) all-gathers the SP inputs ofself_attn, the dense MLP, andlm_head; - the same mechanism reduce-scatters the row-parallel
o_proj/down_projoutputs; HFVocabParallelEmbeddingdoes its masked lookup in alocal_mapand then reduces.
The configs now only declare the layout at each boundary.
Example (o_proj under TP2+SP):
before: {out_src: P, out_dst: SP} -> Module wrapper: redistribute P -> S(1), async_op=True
after: {out_src: SP} -> _ReduceTPOutput: spmd.redistribute(P -> S(1)) (sync)
Earlier review, at HEAD
- PR description empty: fixed (stack context, async -> sync, and the untested TP-without-SP path are all covered).
- Embedding mixin stacked on
_VocabShardEmbedding: fixed (oneHFVocabParallelEmbeddingowns the lookup and the reduction). - Duplicate class-swap cache: fixed (
add_forward_mixinis now inmodule_conversion.py). - TP-without-SP question: answered. The path can't be reached, and the follow-up is noted in the description.
Should consider
module_conversion.py:80-- function-local import to break a newmodule_conversion<->hf_shardingcycle. Everynn.Embeddingbecomes vocab-parallel, but onlytok_embeddingsis configured for it. Swap the class ontok_embeddingsinset_hf_sharding_configsinstead.test_embedding.py:215-- the test calls the private core_lookup_vocab_shard, so the new HFlocal_maptypes and the reduction have no CPU coverage. Callembedding(tokens)on a(1, 1, 4)mesh instead.
Details
- Equivalence with the old path: each mixin issues the same single TP-axis redistribute as
Module._redistribute_inputs/_outputs(models/base/module.py), withbackward_options={"op_dtype": x.dtype}. CP and DP are no-ops at these boundaries. - Removing
local_spmd=Truefrom the embedding config: without TP it is now a plain global-modeF.embedding, the same as coretoken_embedding_sharding_config(nolocal_spmd). - Why not reuse core helpers:
HFVocabParallelEmbeddingkeeps its own_tp_output_dstand does not use core'sspmd_dense_sp_enabled(), because this backend derives SP fromtp_enabledrather thanparallelism_context.sp_enabled. Coremaybe_gather_tp_input/RowParallelLinearwork on token dim 0, while HF keeps sequence on dim 1, so reusing them doesn't fit. - Still open, deferred by the author: the unreachable non-SP destinations (
P -> I,P -> R), and the no-opin_dst == in_srcentries that #5807 deletes.
Not verified: bitwise loss/grad_norm parity and the TPS impact of going synchronous (both need GPUs).
| from torchtitan.experiments.transformers_modeling_backend.hf_sharding import ( | ||
| HFVocabParallelEmbedding, | ||
| ) | ||
|
|
||
| for child in model.children(): | ||
| if type(child) is nn.Embedding: | ||
| child.__class__ = _VocabShardEmbedding | ||
| child.__class__ = HFVocabParallelEmbedding | ||
| elif not isinstance(child, Module): |
There was a problem hiding this comment.
Should consider: this function-local import is only here to break a cycle. hf_sharding imports add_forward_mixin from this module at the top level, and this module imports HFVocabParallelEmbedding from hf_sharding. It also gives every plain nn.Embedding in the tree the vocab-parallel class. Only model.tok_embeddings gets the vocab-sharded weight and _tp_output_dst, though, so under TP any other embedding would fail in forward with an AttributeError.
Smaller alternative: drop the nn.Embedding special case here, so embeddings go through _make_module_class like every other module. Then in set_hf_sharding_configs (hf_sharding.py:229), right where _tp_output_dst is set, do model.tok_embeddings.__class__ = HFVocabParallelEmbedding. That removes the cycle and the lazy import, and the vocab-parallel class goes only on the embedding that is actually vocab-sharded. The padding test would then swap the class itself instead of relying on convert_hf_to_module.
| # The masked vocab-shard lookup, before the reduction that | ||
| # HFVocabParallelEmbedding.forward adds. | ||
| with set_current_spmd_mesh(mesh): | ||
| partial_output = embedding(tokens) | ||
| partial_output = embedding._lookup_vocab_shard(tokens) |
There was a problem hiding this comment.
Should consider: calling the private core _lookup_vocab_shard skips everything this PR adds to the HF embedding: the local_map in/out types (_HF_TOKEN_IDS / _HF_PARTIAL_EMBEDDINGS, with CP on dim 1) and the P -> R reduction. As far as I can tell, this CPU test is the only one of this backend that runs in CI (the experiment's own tests/ only run in the 8-GPU job), so that new forward has no CPU coverage.
Instead, use a (dp, cp, tp) = (1, 1, 4) mesh like test_vocab_parallel_embedding_parity below, set embedding._tp_output_dst = spmd.R, call embedding(tokens), and delete the manual dist.all_reduce. The test stays the same size and covers the new code path.
5d14b13 to
0741ed5
Compare
| output = self._local_hf_lookup_vocab_shard(input) | ||
| return _redistribute_tp(output, src=spmd.P, dst=self._tp_output_dst) | ||
|
|
||
| @spmd.local_map( |
There was a problem hiding this comment.
It was local_spmd=True earlier in the sharding config.
0741ed5 to
fbfed41
Compare
|
@claude review |
|
Claude finished @anijain2305's task in 2m 17s —— View job Approve: no new problems at HEAD; two optional cleanups from the last review are still open. Review |
There was a problem hiding this comment.
Verdict: Approve -- HEAD (fbfed41) adds no new correctness problems, and the collectives still match the old implicit path one for one. Two optional cleanups from the last review are still open.
What this PR does. HF modules keep their own forward. The backend used to get its TP collectives from the implicit, async ShardingConfig src -> dst redistribution, which #5807 removes. This PR issues each collective explicitly:
override_forwardswaps a module to a cached subclass. The override all-gathers the SP input ofself_attn, the dense MLP, andlm_head, and reduce-scatters the row-parallelo_proj/down_projoutputs.HFVocabParallelEmbeddingruns the masked lookup in alocal_map, then reduces.
Example (self_attn under TP2+SP, called as self_attn(hidden_states=h, ...)):
Module wrapper: assert h is (DP S(0), seq on (CP, TP)) # in_src, unchanged
_GatherTPInput.forward(self, hidden_states=h, ...): # binds by name
h = spmd.redistribute(h, tp_group, S(1) -> R) # sync all-gather
HF attention forward(h, ...)
Changes since the last review
_GatherTPInputnow bindshidden_statesas its first parameter and asserts TP. I checked this againstModule._redistribute_inputs(models/base/module.py:584-625): keyword inputs stay keywords, and positional ones stay positional, so bothself_attn(hidden_states=...)andmlp(x)/lm_head(x)bind correctly. Keeping_ReduceTPOutputinstalled without TP or SP is also correct: TP-without-SP still needsP -> I, while the gather is not needed there.- Re the
local_spmd=Truereply onhf_sharding.py:189: agreed. Under TP, thelocal_mapdecorator replaces the old local region with the same in/out types (tp=Rids in,tp=Pout). Without TP, the embedding now runs core's global-modeF.embeddinginstead of a local region, the same as coreVocabParallelEmbedding. Neither run in the description covers that path (both use TP). Thetransformers_modeling_backend_dense_cp+ppintegration test (CP without TP) does.
Should consider (still open from the last review)
module_conversion.py:82-- the function-local import breaks amodule_conversion<->hf_shardingcycle. It also gives everynn.Embeddingthe vocab-parallel class, but onlytok_embeddingsgets_tp_output_dst. Swap the class ontok_embeddingsinset_hf_sharding_configsinstead.test_embedding.py:215-- the test calls the private_lookup_vocab_shard, so the HFlocal_maptypes and the reduction have no CPU coverage. Callembedding(tokens)on a(1, 1, 4)mesh with_tp_output_dst = spmd.Rinstead.
Details
override_forwardMRO: the new class is(override, cls). Thefunctools.wrapswrapper makesinspect.signaturein_cache_pos_arg_namessee the HF signature, andsuper().forwardinside the override resolves to the HF forward. Stacking two overrides on one module would also work, but no module gets two today.HFVocabParallelEmbeddingvs core: it duplicates coreVocabParallelEmbedding.forward, differing only in thelocal_maptypes (HF keeps(B, S)with CP on dim 1) and the_tp_output_dstsource. Keeping it in the experiment, rather than adding a hook to core, follows the "don't bend shared code for one consumer" rule.- Deferred by the author: the unreachable TP-without-SP destinations, and the no-op
in_dst == in_srcentries that #5807 deletes.
Not verified: bitwise loss/grad_norm parity at HEAD, the no-TP CP path (dense_cp+pp), and the TPS impact of synchronous collectives (all need GPUs).
fbfed41 to
a365b6f
Compare
a365b6f to
ca3c847
Compare
The Transformers modeling backend relied on ShardingConfig src -> dst redistribution for all of its TP boundaries. HF modules keep their own forward, so the experiment now issues each TP collective explicitly: - HFVocabParallelEmbedding (the class convert_hf_to_module swaps every nn.Embedding to): the masked lookup runs in an explicit local_map, then TP P -> S(1) (reduce-scatter on the sequence dim) under SP, P -> R otherwise. - _GatherTPInput (a forward override) on self_attn, the dense MLP and lm_head under SP: S(1) -> R (S(0) -> R for lm_head), an all-gather. - _ReduceTPOutput on the row-parallel o_proj / down_proj: P -> S(1) under SP, P -> I otherwise. The two forward overrides are added with module_conversion.override_forward, which swaps the module to a cached subclass (the same class swap convert_hf_to_module uses; module state and state_dict keys are unchanged). The swapped forward keeps the HF signature (functools.wraps) because Module maps positional inputs to the sharding config by parameter name. The configs now only declare boundary layouts. Each explicit collective is exactly the single TP-axis redistribute the implicit path issued; CP and DP layouts do not change at these boundaries. The implicit path used async_op=True, these are synchronous. This backend always enables SP with TP (parallelize.py passes enable_sp=tp_enabled), so the TP-without-SP destinations are not reachable. Numerics: bitwise-identical loss and grad_norm vs. main (deterministic, seed 42, 10 steps) for the dense debug model at TP2 (SP), and for transformers_backend_moe_fsdp_tp_ep_cp (8 GPUs). The FSDP+TP+PP recipe fails on the test machine before and after this change (PP schedule API mismatch with the local PyTorch build).
ca3c847 to
f968d89
Compare
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
Get rid of implicit redistribution. Yay!!
## Why
`ShardingConfig` could insert collectives implicitly: when a module's
`in_dst_shardings` / `out_dst_shardings` differed from its
`in_src_shardings` /
`out_src_shardings`, the `Module` wrapper redistributed the tensor at
the
boundary (`spmd_redistribute_per_axis`, async). Those collectives were
invisible
in model code, easy to add by accident, and ran with `async_op=True`
(#5915
tracks a gradient bug in that path).
The earlier PRs in this stack moved every such collective into explicit
`spmd.redistribute` calls in module forwards (#5802 decoder embedding
and final
norm, #5803 multimodal encoders, #5805 Transformers backend, #5806 the
post-scatter restore). After them, every remaining `dst` entry equals
its `src`
counterpart, so the boundary redistribution never fires. This PR removes
the
machinery, so a new config can't silently reintroduce an implicit
collective.
**Example (a module boundary).**
```
before: ShardingConfig(in_src_shardings={"x": S(0)}, in_dst_shardings={"x": R})
-> Module wrapper: spmd_redistribute_per_axis(S(0) -> R, async_op=True)
after: ShardingConfig(input_shardings={"x": S(0)}) # asserted only
-> forward: x = spmd.redistribute(x, tp_group, src=S(0), dst=R)
```
## What changed
**Core**
- `ShardingConfig` drops `in_dst_shardings` and `out_dst_shardings`. It
only
declares layouts: parameter/buffer placements and the activation types
at
the boundary.
- With no dst side left, `in_src_shardings` / `out_src_shardings` are
renamed
to `input_shardings` / `output_shardings` (review), at every call site.
- `Module._parallelize` wraps `forward` with boundary checks only
(`_assert_input_types` / `_assert_output_type`, under SPMD type
checking)
and builds local-SPMD regions from `input_shardings` /
`output_shardings`.
- `spmd_redistribute_per_axis`, `spmd_validate_redistributions` and the
async
module-boundary collective path are deleted from
`distributed/spmd_types.py`.
**Configs**
- The redundant `src == dst` entries are removed from the core sharding
helpers (`decoder_sharding.py`, `vision_encoder_sharding.py`), the
Qwen3.5,
Kimi K3, DeepSeek-V4, Muse Spark and Muse Glimmer sharding files, the
Muse
Spark CP-replicate transform, `NVFP4Linear`, and the Transformers
backend's
`hf_sharding.py`.
**Docs**
- MoE `SHARDING.md`, the Transformers backend `add_moe_model` skill and
the
inner-attention docstring described boundary redistribution; they now
describe the explicit collectives. (The MoE collectives were already
explicit in `MoE.forward` on main; the doc was out of date.)
**Mechanical, skimmable:** the field rename across models, configs,
tests and docs; tests drop asserts on the removed fields, and the
tests of the deleted helpers (`test_parallelism_context.py`) are
removed.
## Alternatives considered
- **Keep `dst` fields but assert `dst == src`**: keeps a field whose
only
valid value is a copy of another, and the type still suggests the config
can
move data.
- **Keep the machinery as an opt-in**: a second way to issue collectives
is exactly what the stack removes; out-of-tree code can call
`spmd.redistribute` in its forward.
## User-facing changes
| Before | After |
| --- | --- |
| `ShardingConfig(..., in_dst_shardings=..., out_dst_shardings=...)` |
`TypeError` at construction; declare the layout in `input_shardings` /
`output_shardings` and call `spmd.redistribute` in `forward` for any
layout change |
| `ShardingConfig(in_src_shardings=..., out_src_shardings=...)` |
`ShardingConfig(input_shardings=..., output_shardings=...)` |
| Boundary collectives ran async (`async_op=True`) | No boundary
collectives; the explicit ones in model code are synchronous |
Out-of-tree modules that relied on boundary redistribution must issue
the
collective themselves; a config that still sets the removed fields fails
loudly instead of silently getting a collective.
## Numerics
Seed 42, deterministic, 10 steps; loss and grad_norm bitwise identical
to main
(`scripts/loss_compare.py --assert-equal`):
- llama3: TP2+SP, TP2 without SP, TP2+CP2;
- qwen3: TP2+SP;
- deepseek_v3 with MTP: TP2+EP2, with and without SP;
- gpt_oss: TP2+EP2;
- deepseek_v4: FSDP;
- Transformers backend: dense debug model TP2 (with SP; this backend
always
enables SP with TP), and MoE FSDP+TP+EP+CP (8 GPUs).
Qwen3.5 and Kimi K2.5 (`kimi_k2_7`, `KimiK25Model`; debug models with a
vision encoder), full model
forward + backward at TP2 with SP on and off: output and all gradients
bitwise
identical to the previous commit.
## Testing
- CPU unit tests for the touched modules pass; tests of the deleted
helpers
are removed with them.
## Known issues / follow-ups
- Top of the explicit-collectives stack (#6035, #5802, #5803, #5805,
#5806,
#5807).
- Follow-ups from review: issue the `lm_head` gather from `lm_head`
itself
(TODO in `Decoder._pre_lm_head_norm_and_gather`); build text flavors as
a
`Decoder` and drop `keep_vision_encoder`.
Summary (human-written)
Why
The Transformers modeling backend got all of its TP collectives from
ShardingConfigsrc -> dst redistribution: HF modules keep their ownforward, so the module wrapper inserted the all-gathers and reductions attheir boundaries. #5807 (top of this stack) removes implicit redistribution
from
ShardingConfig, so without this PR the backend would lose its TPcollectives. This PR issues each one explicitly, one for one with the old
path.
The implicit path also issued these collectives with
async_op=True; #5915tracks the async-collective gradient bug in that path. The explicit
collectives here are synchronous.
Example (
o_projunder TP2+SP).What changed
Explicit TP collectives (
hf_sharding.py)HFVocabParallelEmbedding, the classconvert_hf_to_moduleswaps everynn.Embeddingto: under TP the masked lookup runs in alocal_map(TP-replicated token ids in, TP-partial embeddings out), then the class
reduces it to
_tp_output_dst, whichset_hf_sharding_configssets(
P -> S(1), a reduce-scatter on the sequence dim, under SP). Without TP itis a plain lookup.
_GatherTPInputonself_attn, the dense MLP andlm_headunder SP:S(1) -> R(S(0) -> Rforlm_head), an all-gather._ReduceTPOutputon the row-parallelo_proj/down_proj:P -> S(1)under SP.
Class swap (
module_conversion.py)override_forward(module, override, **attrs)runsoverride.forwardinplace of the module's forward (the override reaches the original through
super()), by swapping the module to a cached subclass, next toconvert_hf_to_module's own class swap; module state and state_dict keys areunchanged. The subclass
forwardkeeps the HF signature (
functools.wraps), becauseModulemaps positionalinputs to the sharding config by parameter name.
Mechanical, skimmable:
_VocabShardEmbeddingbecomesHFVocabParallelEmbedding(moved tohf_sharding.py, it now owns thereduction); the HF padding test calls the lookup directly, as the old
forwarddid.Alternatives considered
add_moe_modelskill tells contributors not to use forward hooks forlayout conversion; the class swap is the mechanism the backend already
uses.
the converted embedding: three near-identical classes for one lookup.
User-facing changes
async_op=True)The collectives themselves are unchanged. Any compute overlap the async path
gave before the first use of a gathered or reduced tensor is gone. TPS was not
measured.
Numerics
Bitwise-identical loss and grad_norm vs. main (deterministic, seed 42, 10
steps,
scripts/loss_compare.py --assert-equal):transformers_backend_moe_fsdp_tp_ep_cp(8 GPUs).The FSDP+TP+PP recipe fails on the test machine before and after this change
(PP schedule API mismatch with the local PyTorch build).
Testing
test_hf_sharding.pyand the HF embedding padding test(
test_vocab_parallel_padding_forward_backward) pass on CPU.parallelize.pypassesenable_sp=parallelism_context.tp_enabled), so the TP-without-SPdestinations (
P -> Ifor row-parallel outputs,P -> Rfor the embedding)are not reachable, and the earlier "TP2 without SP" run was in fact a second
SP run. Either honor
parallelism.enable_sequence_parallelhere or dropthose branches (follow-up).
Known issues / follow-ups
in_dst == in_src/out_dst == out_srcentries left inhf_sharding.py(flex kernel, norms, rope) issue no collectives; [spmd] Remove implicit ShardingConfig redistribution #5807deletes them together with the fields.