Skip to content

[transformers_modeling_backend] Make TP collectives explicit - #5805

Merged
anijain2305 merged 1 commit into
explicit-vision-tp-collectivesfrom
explicit-hf-backend-collectives
Nov 13, 2026
Merged

anijain2305 merged 1 commit into
explicit-vision-tp-collectivesfrom
explicit-hf-backend-collectives

Conversation

@anijain2305

@anijain2305 anijain2305 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

The Transformers modeling backend got all of its TP collectives from
ShardingConfig src -> dst redistribution: HF modules keep their own
forward, so the module wrapper inserted the all-gathers and reductions at
their boundaries. #5807 (top of this stack) removes implicit redistribution
from ShardingConfig, so without this PR the backend would lose its TP
collectives. This PR issues each one explicitly, one for one with the old
path.

The implicit path also issued these collectives with async_op=True; #5915
tracks the async-collective gradient bug in that path. The explicit
collectives here are synchronous.

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}   # asserted only
        override_forward(o_proj, _ReduceTPOutput)
        -> override: spmd.redistribute(out, tp_group, src=P, dst=S(1))   # sync

What changed

Explicit TP collectives (hf_sharding.py)

  • HFVocabParallelEmbedding, the class convert_hf_to_module swaps every
    nn.Embedding to: under TP the masked lookup runs in a local_map
    (TP-replicated token ids in, TP-partial embeddings out), then the class
    reduces it to _tp_output_dst, which set_hf_sharding_configs sets
    (P -> S(1), a reduce-scatter on the sequence dim, under SP). Without TP it
    is a plain lookup.
  • _GatherTPInput 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.
  • The sharding configs now only declare the layout at each boundary.

Class swap (module_conversion.py)

  • override_forward(module, override, **attrs) runs override.forward in
    place of the module's forward (the override reaches the original through
    super()), by swapping the module to a cached subclass, next to
    convert_hf_to_module's own class swap; module state and state_dict keys are
    unchanged. The subclass forward
    keeps the HF signature (functools.wraps), because Module maps positional
    inputs to the sharding config by parameter name.

Mechanical, skimmable: _VocabShardEmbedding becomes
HFVocabParallelEmbedding (moved to hf_sharding.py, it now owns the
reduction); the HF padding test calls the lookup directly, as the old
forward did.

Alternatives considered

  • Forward pre/post hooks instead of the class swap: the backend's
    add_moe_model skill tells contributors not to use forward hooks for
    layout conversion; the class swap is the mechanism the backend already
    uses.
  • Keep the embedding reduction in a separate forward override on top of
    the converted embedding: three near-identical classes for one lookup.

User-facing changes

Before After
Forward TP boundary collectives are async (async_op=True) They are synchronous

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):

  • dense debug model, TP2 with SP;
  • 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.py and the HF embedding padding test
    (test_vocab_parallel_padding_forward_backward) pass on CPU.
  • This backend always enables SP with TP (parallelize.py passes
    enable_sp=parallelism_context.tp_enabled), so the TP-without-SP
    destinations (P -> I for row-parallel outputs, P -> R for the embedding)
    are not reachable, and the earlier "TP2 without SP" run was in fact a second
    SP run. Either honor parallelism.enable_sequence_parallel here or drop
    those branches (follow-up).

Known issues / follow-ups

@anijain2305
anijain2305 added this pull request to stack #5808 November 4, 2026 06:59
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 4, 2026
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from 09831a3 to 46ae22c Compare November 4, 2026 07:14
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from 46ae22c to 65e89ff Compare November 6, 2026 22:44
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from 65e89ff to e2a6d1e Compare November 6, 2026 23:05
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from e2a6d1e to c4599ca Compare November 6, 2026 23:10
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from c4599ca to f21854b Compare November 6, 2026 23:35
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from f21854b to f24f035 Compare November 6, 2026 23:49
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from f24f035 to d902716 Compare November 7, 2026 00:06
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @anijain2305's task in 4m 24s —— View job


Approve -- please address the items before merging: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • _GatherTPInput all-gathers the SP input of self_attn, the dense MLP, and lm_head.
  • _ReduceTPOutput reduces (or reduce-scatters) the output of o_proj / down_proj.
  • _VocabParallelEmbedding runs the masked lookup in local_map and 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

  1. 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:
    • the stack context: #5807 removes implicit redistribution, and #5915 is the async-collective gradient bug.
    • that forward boundary collectives become synchronous (async_op=True -> default). Collectives are unchanged, but any compute overlap before first use is gone. Say whether you measured TPS.
  2. hf_sharding.py:153 -- _VocabParallelEmbedding stacks 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_boundary repeats the _make_module_class cache-and-swap pattern. Move it into module_conversion.py (see inline).
  • hf_sharding.py:385 -- question: how was the TP-without-SP numerics run done, given enable_sp=tp_enabled (see inline)?
  • The no-op in_dst == in_src / out_dst == out_src entries 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-axis S(1)/S(0) -> R or P -> S(1)/I/R redistribute with backward_options={"op_dtype": x.dtype}. CP and DP were no-op axes at these boundaries before.
  • Ordering: the input assert_type against in_src still runs before the mixin gathers. The output assert_type against the new out_src runs after the mixin reduces.
  • Signature: _cache_pos_arg_names uses inspect.signature(type(self).forward). The functools.wraps wrapper 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.apply is unchanged.
  • Alternatives considered: forward pre/post hooks would run outside forward_with_redistribution, so the src asserts would see the wrong layout. Converting to core ColumnParallelLinear / RowParallelLinear doesn'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).

Comment on lines +153 to +173
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +176 to +200
_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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from d902716 to 62188b7 Compare November 11, 2026 20:21
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from 62188b7 to 9892e16 Compare November 11, 2026 20:38
@anijain2305
anijain2305 removed this pull request from stack #5808 November 11, 2026 20:40
@anijain2305
anijain2305 added this pull request to stack #6036 November 11, 2026 20:40
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from 9892e16 to b321658 Compare November 12, 2026 00:03
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from b321658 to 1f3f9f2 Compare November 12, 2026 00:12
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @anijain2305's task in 3m 20s —— View job


Approve -- the earlier must-fix items are fixed; two optional cleanups remain: review

@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from bc5f0ef to 5d14b13 Compare November 12, 2026 23:25

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 of self_attn, the dense MLP, and lm_head;
  • the same mechanism reduce-scatters the row-parallel o_proj / down_proj outputs;
  • HFVocabParallelEmbedding does its masked lookup in a local_map and 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 (one HFVocabParallelEmbedding owns the lookup and the reduction).
  • Duplicate class-swap cache: fixed (add_forward_mixin is now in module_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 new module_conversion <-> hf_sharding cycle. Every nn.Embedding becomes vocab-parallel, but only tok_embeddings is configured for it. Swap the class on tok_embeddings in set_hf_sharding_configs instead.
  • test_embedding.py:215 -- the test calls the private core _lookup_vocab_shard, so the new HF local_map types and the reduction have no CPU coverage. Call embedding(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), with backward_options={"op_dtype": x.dtype}. CP and DP are no-ops at these boundaries.
  • Removing local_spmd=True from the embedding config: without TP it is now a plain global-mode F.embedding, the same as core token_embedding_sharding_config (no local_spmd).
  • Why not reuse core helpers: HFVocabParallelEmbedding keeps its own _tp_output_dst and does not use core's spmd_dense_sp_enabled(), because this backend derives SP from tp_enabled rather than parallelism_context.sp_enabled. Core maybe_gather_tp_input / RowParallelLinear work 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-op in_dst == in_src entries that #5807 deletes.

Not verified: bitwise loss/grad_norm parity and the TPS impact of going synchronous (both need GPUs).

Comment on lines +80 to 87
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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +212 to +215
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from 5d14b13 to 0741ed5 Compare November 12, 2026 23:28
output = self._local_hf_lookup_vocab_shard(input)
return _redistribute_tp(output, src=spmd.P, dst=self._tp_output_dst)

@spmd.local_map(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was local_spmd=True earlier in the sharding config.

@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from 0741ed5 to fbfed41 Compare November 12, 2026 23:38
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review

@anijain2305
anijain2305 marked this pull request as ready for review November 12, 2026 23:39
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 12, 2026
@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_forward swaps a module to a cached subclass. The override all-gathers the SP input of self_attn, the dense MLP, and lm_head, and reduce-scatters the row-parallel o_proj / down_proj outputs.
  • HFVocabParallelEmbedding runs the masked lookup in a local_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

  • _GatherTPInput now binds hidden_states as its first parameter and asserts TP. I checked this against Module._redistribute_inputs (models/base/module.py:584-625): keyword inputs stay keywords, and positional ones stay positional, so both self_attn(hidden_states=...) and mlp(x) / lm_head(x) bind correctly. Keeping _ReduceTPOutput installed without TP or SP is also correct: TP-without-SP still needs P -> I, while the gather is not needed there.
  • Re the local_spmd=True reply on hf_sharding.py:189: agreed. Under TP, the local_map decorator replaces the old local region with the same in/out types (tp=R ids in, tp=P out). Without TP, the embedding now runs core's global-mode F.embedding instead of a local region, the same as core VocabParallelEmbedding. Neither run in the description covers that path (both use TP). The transformers_modeling_backend_dense_cp+pp integration test (CP without TP) does.

Should consider (still open from the last review)

  • module_conversion.py:82 -- the function-local import breaks a module_conversion <-> hf_sharding cycle. It also gives every nn.Embedding the vocab-parallel class, but only tok_embeddings gets _tp_output_dst. Swap the class on tok_embeddings in set_hf_sharding_configs instead.
  • test_embedding.py:215 -- the test calls the private _lookup_vocab_shard, so the HF local_map types and the reduction have no CPU coverage. Call embedding(tokens) on a (1, 1, 4) mesh with _tp_output_dst = spmd.R instead.
Details
  • override_forward MRO: the new class is (override, cls). The functools.wraps wrapper makes inspect.signature in _cache_pos_arg_names see the HF signature, and super().forward inside the override resolves to the HF forward. Stacking two overrides on one module would also work, but no module gets two today.
  • HFVocabParallelEmbedding vs core: it duplicates core VocabParallelEmbedding.forward, differing only in the local_map types (HF keeps (B, S) with CP on dim 1) and the _tp_output_dst source. 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_src entries 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).

@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from a365b6f to ca3c847 Compare November 13, 2026 03:03
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).
@anijain2305
anijain2305 force-pushed the explicit-hf-backend-collectives branch from ca3c847 to f968d89 Compare November 13, 2026 06:56
@anijain2305
anijain2305 merged commit 0f4ecfa into main Nov 13, 2026
anijain2305 added a commit that referenced this pull request Nov 13, 2026
## 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`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants