Skip to content

vision encoders non sp - #6043

Merged
anijain2305 merged 1 commit into
mainfrom
vision-encoders-non-sp
Nov 12, 2026
Merged

anijain2305 merged 1 commit into
mainfrom
vision-encoders-non-sp

Conversation

@anijain2305

@anijain2305 anijain2305 commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Introduce a disable_dense_sp context manager to explicitly turn off SP in encoder region. This flag is used by TP-related collectives, and earlier for encoder we had to use special classes like InvariantRowParallelLinear to work around this issue. Now, this flag helps clean up this, and also makes it easy to add explicit collectives later part of the stack.

Why

Vision encoders are never sequence-parallel: every TP rank runs the whole
encoder on the full patch sequence, so their activations stay TP-Invariant
even when the decoder uses SP. The TP building blocks follow the decoder's SP
setting (spmd_dense_sp_enabled()), so today each encoder-side difference is
spelled out separately:

  • InvariantRowParallelLinear is a copy of RowParallelLinear whose only
    change is reducing P -> I instead of P -> S(0) if SP else I.
  • The vision rope cache is declared TP-Invariant, then converted to Replicate
    at the attention boundary, unlike the decoder's RoPE cache, which is
    Replicate from the start.

Stating "the encoder is a non-SP region" once removes these special cases.
It also lets the explicit encoder collectives later in this stack (#5803) use
the standard ColumnParallelLinear / maybe_gather_tp_input instead of
adding more Invariant* variants or a src= override.

Example (TP=2, decoder SP on).

decoder block:   RowParallelLinear    P -> S(0)   (reduce-scatter)
vision encoder:  before: InvariantRowParallelLinear  P -> I   (separate class)
                 after:  RowParallelLinear under disable_dense_sp()  P -> I

What changed

Non-SP regions

  • New disable_dense_sp() context manager (torchtitan/distributed/spmd_types.py):
    spmd_dense_sp_enabled() is False inside it, and the registered setting is
    restored on exit.
  • The vision encoders' forward run under it: Qwen35VisionEncoder,
    MoonViTEncoder (Kimi K2.5 and K3) and NaViTEncoder (Muse Spark and Muse
    Glimmer). Their mergers and projectors run inside the same forward.

Fewer special classes

  • InvariantRowParallelLinear is removed. The encoders' attention proj, MLP
    fc2 and merger/projector output use RowParallelLinear, which reduces
    P -> I there. Same forward, bias handling and remat regions
    (<fqn>.linear, <fqn>.tp_reduce). The quantization converter and tests
    are updated.
  • The vision rope cache (inv_freq and the rotary output) is declared
    TP-Replicate at its source, like the decoder's RoPE cache. It has no
    gradient, so this only changes its type: the attention boundary no longer
    converts it, and its in_dst entry is gone.

Async TP

  • AsyncTensorParallelTransform converts every RowParallelLinear /
    ColumnParallelLinear config, which now includes the encoders' row
    projections. The async variants always fused a sequence collective. They now
    fall back to the synchronous path when dense SP is disabled, since there is
    nothing to overlap. Without this, async TP would reduce-scatter inside the
    vision encoder.

Mechanical, skimmable: the InvariantRowParallelLinear ->
RowParallelLinear rename in the Qwen3.5, Kimi K2.5/K3 and Muse Spark
flavors and in the tests.

Alternatives considered

  • Keep encoder-specific variants (Invariant*): every TP block an encoder
    uses needs a copy, and every transform that matches on class (async TP,
    quantization, LoRA) has to know about each copy.
  • Pass src=spmd.I to maybe_gather_tp_input at encoder call sites: the
    layout is a property of the region, not of each call.
  • Skip encoder linears in AsyncTensorParallelTransform by FQN: the
    runtime fallback keys off the same SP state the module already uses, and
    also covers any other non-SP region.

User-facing changes

Before After
InvariantRowParallelLinear.Config(...) RowParallelLinear.Config(...), inside a module whose forward runs under disable_dense_sp()
Custom vision encoders inherit the decoder's SP setting Wrap the encoder forward in @disable_dense_sp() if its activations are not sequence-sharded

Numerics

No collective changes: the encoder runs the same ops in the same order.

  • RowParallelLinear under disable_dense_sp takes the same path as the old
    InvariantRowParallelLinear (the forwards differ only in the reduction
    target, now I in both).
  • The rope cache conversion was a type change on a tensor with no gradient.

End-to-end loss comparison: TODO.

Testing

  • test_row_parallel_output_is_invariant_with_dense_sp_disabled: with decoder
    SP registered, RowParallelLinear inside disable_dense_sp reduces
    P -> I. It catches an encoder row projection that reduce-scatters.
  • test_async_row_parallel_falls_back_with_dense_sp_disabled: the same for
    AsyncRowParallelLinear. It catches async TP fusing a reduce-scatter inside
    the encoder.
  • TestColumnParallelLinearWithDenseSPDisabled (2 ranks, strict typecheck):
    ColumnParallelLinear on a TP-Invariant input under disable_dense_sp,
    with decoder SP on and off, matches the unsharded output and gradients. It
    fails with an SpmdTypeError if the context manager is removed.
    disable_dense_sp restores the registered setting, also when the body
    raises.
  • Existing LoRA (vision adapters under typecheck), NaViT encoder typecheck,
    quantization and transform tests: 157 pass. test_lora_model_builds and
    test_nvfp4_hf_export_strips_buffers fail the same way on main in the dev
    environment.

Known issues / follow-ups

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 12, 2026
@github-actions
github-actions Bot requested review from andrewor14 and vkuzo November 12, 2026 00:55
@anijain2305
anijain2305 added this pull request to stack #6044 November 12, 2026 00:55
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 12, 2026
@anijain2305
anijain2305 marked this pull request as draft November 12, 2026 00:56
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 12, 2026
@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 58s —— View job


Request changes: encoder blocks are replayed by activation remat during backward, which runs outside disable_dense_sp, so with TP > 1 and SP on the replayed RowParallelLinear reduce-scatters instead of all-reducing. 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: Request changes -- The design is right, but disable_dense_sp is a dynamic scope, and activation remat replays the encoder blocks during backward, outside that scope.

What this PR does. It adds a disable_dense_sp() context manager that makes spmd_dense_sp_enabled() return False inside it. It wraps the Qwen3.5, MoonViT (K2.5/K3) and NaViT encoder forwards in it, and deletes InvariantRowParallelLinear in favor of plain RowParallelLinear. It also declares the vision rope cache TP-Replicate at its source, and makes the async TP linears fall back to the sync path when dense SP is off. I checked that RowParallelLinear.forward with SP off matches the deleted class line for line.

Example (TP=2, SP on, encoder blocks checkpointed).

forward  (inside encoder.forward -> disable_dense_sp):
  layers.0.attn.proj: RowParallelLinear  P -> I     (all-reduce)
backward (encoder.forward has returned; flag restored to True):
  remat replays layers.0.forward
  layers.0.attn.proj: RowParallelLinear  P -> S(0)  (reduce-scatter)  <- differs from forward

Before this PR, InvariantRowParallelLinear hard-coded dst=I, so the forward and the replay agreed.

Must fix

  1. torchtitan/distributed/spmd_types.py:88-102 -- remat replay of encoder blocks runs outside disable_dense_sp: encoder layers are wrapped by activation_remat.apply(encoder) (multimodal.py:94, kimi_k3/model.py:275). The fix is to also enter it in VisionTransformerBlock.forward, or to add a RecomputeStateHook. One existing encoder typecheck test should also run under SP + TP=2 + full remat.
  2. tests/unit_tests/cpu/models/common/test_linear.py:437 -- (RowParallelLinear, RowParallelLinear): the same case runs twice; drop the loop.

Should consider

  • tests/unit_tests/cpu/quantization/test_quantization.py:94, tests/unit_tests/cpu/models/common/test_lora.py:461 -- the "specialized row parallel" tests no longer test anything specialized. Delete them, since RowParallelLinear is covered elsewhere.
  • tests/unit_tests/cpu/models/common/test_linear.py:332 -- the ColumnParallelLinear-under-disable_dense_sp test has no consumer in this PR; move it to #5803. The 2-rank restore-on-exception test could be single-process, or dropped.
  • PR description: "End-to-end loss comparison: TODO". Please add a TP=2 + SP run of a vision flavor with remat on, which would also exercise item 1.
Details
  • Gate. The problem is real: every TP block an encoder uses needs an Invariant* copy, and every class-matching transform (async TP, quantization, LoRA) has to special-case each copy. A region-level switch is the smaller design and deletes about 80 lines of duplication, so the approach is fine. The issue is only that the region is defined by Python call scope, while torch_remat re-executes the region later.
  • Why only remat. The dst of each spmd.redistribute is evaluated when it's called, and backward functions are captured at forward time, so plain autograd is unaffected. Only code that re-runs Python forward code after the scope exits is affected. Today that's remat.checkpoint on encoder blocks. The decoder layers aren't affected, because they don't run under disable_dense_sp.
  • Async TP. AsyncTensorParallelTransform now converts the encoder's RowParallelLinear configs (the removed test_async_transform_skips_invariant_row_parallel_linear used to pin that they were skipped). The runtime fallback is correct in forward, but it has the same replay exposure as item 1.
  • Rope cache I -> R. It's a buffer with no gradient, and the attention in_dst for it is gone. The NaViT/LoRA typecheck tests cover this according to the PR. I didn't re-run them.

Not verified: the exact failure mode under remat (torch_remat metadata error vs. silently wrong recompute). torch_remat isn't installed here, and I couldn't run GPU/TP tests. A maintainer still needs to review, since this touches torchtitan/distributed/ and models/common/.

Comment on lines +88 to +102
def disable_dense_sp() -> Iterator[None]:
"""Treat the dense region as having no sequence parallelism.

For regions whose activations are never sequence-sharded even when the
decoder uses SP, e.g. vision encoders, whose activations stay
TP-``Invariant``. Inside, ``spmd_dense_sp_enabled()`` is False, so helpers
that follow the decoder residual layout (``maybe_gather_tp_input``,
``RowParallelLinear``) use the non-SP ``Invariant`` layout.
"""
previous = spmd_dense_sp_enabled()
_MESH_TLS.dense_sp_enabled = False
try:
yield
finally:
_MESH_TLS.dense_sp_enabled = previous

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.

Activation remat replays the encoder blocks outside this scope. MultimodalModel.parallelize (torchtitan/models/common/multimodal.py:93-94) and KimiK3Model (kimi_k3/model.py:275) call activation_remat.apply(encoder), which replaces every encoder.layers.<i>.forward with remat.checkpoint(...). Per REMAT.md, remat.checkpoint re-runs the whole block in Python during backward. By then the encoder's forward has returned and this finally has set dense_sp_enabled back to the registered value. So with TP > 1 and SP on, the replayed RowParallelLinear.forward (attention proj, MLP fc2) reads spmd_dense_sp_enabled() == True:

  • Sync TP, with any policy that recomputes *.tp_reduce (e.g. FullActivationRematConfig): the replay reduce-scatters P -> S(0) where the forward all-reduced P -> I. The recomputed tensor has the wrong shape and placement.
  • Async TP, even with the default save-all policy: AsyncRowParallelLinear takes the fused-reduce-scatter branch during replay. That branch declares different regions (linear only, no tp_reduce) than the forward did.

InvariantRowParallelLinear didn't have this problem because its dst didn't depend on ambient state. Unverified: I couldn't run this, so I don't know whether it shows up as a torch_remat metadata-mismatch error or as silently wrong recomputed activations.

Smallest fix: also enter disable_dense_sp() in VisionTransformerBlock.forward (models/common/vision_encoder.py). That's the unit remat.checkpoint wraps, and every encoder here uses it, so replay re-enters the scope. Keep the encoder-level decorator for the merger/projector. Another option is a torch_remat.RecomputeStateHook that captures and restores the flag. Either way, this invariant is unguarded today. Running one existing encoder typecheck test (e.g. NaViT, or the LoRA vision-adapter test) with SP on, TP=2, and FullActivationRematConfig would catch it.

weight_dtensor = distribute_tensor(weight, mesh, (Shard(1),))
local_input = input_dtensor.to_local().detach().requires_grad_()
for linear_cls in (RowParallelLinear, InvariantRowParallelLinear):
for linear_cls in (RowParallelLinear, RowParallelLinear):

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.

This mechanical rename left (RowParallelLinear, RowParallelLinear), so the loop runs the same case twice. Drop the loop and subTest, and test RowParallelLinear once.



@pytest.mark.parametrize("parallel_cls", [InvariantRowParallelLinear])
@pytest.mark.parametrize("parallel_cls", [RowParallelLinear])

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.

With InvariantRowParallelLinear gone, nothing "specialized" is left to preserve. RowParallelLinear is already covered by the parametrized tests at lines 117, 151, 182 and 392. Delete this test. The same goes for test_lora_preserves_specialized_row_parallel_linear (test_lora.py:461). If its LoRA-forward check on a RowParallelLinear isn't covered anywhere else, fold that check into an existing LoRA test.

assert self._row_reduction_dst(linear.build()) == spmd.I


class TestColumnParallelLinearWithDenseSPDisabled(DTensorTestBase):

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.

No encoder in this PR uses ColumnParallelLinear (fc1/qkv are still Linear with vision_colwise_sharding_config). This test guards #5803's consumer, not this PR's, so it should land with #5803. test_disable_dense_sp_restores_the_registered_setting (line 403) spins up a 2-rank process group to check that a context manager restores a thread-local. That's low value as it stands. If you keep it, make it a plain single-process test.

Vision activations are never sequence-sharded: they stay TP-Invariant even
when the decoder uses sequence parallelism. Today that is expressed with
encoder-specific variants of the TP building blocks, e.g.
InvariantRowParallelLinear, a copy of RowParallelLinear that always reduces
P -> I instead of following the decoder's SP setting.

Instead, say it once: add disable_dense_sp(), a context manager that makes
spmd_dense_sp_enabled() False, and run the vision encoders' forward under it
(Qwen3.5, MoonViT for Kimi K2.5 / K3, NaViT for Muse). VisionTransformerBlock
also enters it in its own forward: activation remat checkpoints the encoder
blocks and replays them during backward, after the encoder forward's scope has
exited, and the replay must pick the same TP layout as the forward. The
standard classes then use the non-SP layout inside the encoder:
- InvariantRowParallelLinear is removed; the encoders use RowParallelLinear,
  which reduces P -> I there. Quantization, LoRA and tests follow.
- Async TP converts every RowParallelLinear / ColumnParallelLinear, now
  including the encoders'. AsyncRowParallelLinear and
  AsyncColumnParallelLinear fall back to the synchronous path when dense SP
  is disabled, since there is no sequence collective to overlap.
- The vision rope cache is declared TP-Replicate at its source, like the
  decoder's RoPE cache, instead of TP-Invariant and converted at the
  attention boundary. It has no gradient, so this only changes its type.

No collective changes: the encoder computes the same ops in the same order.

Tests: RowParallelLinear and AsyncRowParallelLinear reduce to Invariant under
disable_dense_sp with decoder SP on; a VisionTransformerBlock called outside
the encoder scope (as remat replay does) still runs with dense SP disabled;
disable_dense_sp restores the registered setting. The quantization and LoRA
"specialized row parallel" tests are removed with the class they covered.
@anijain2305
anijain2305 force-pushed the vision-encoders-non-sp branch from 8ee779d to b8672c0 Compare November 12, 2026 01:26
@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 1m 51s —— View job


Approve, with items to fix before merging: the remat-replay bug from the last review is fixed. Before merging, please update the stale PR description, add the TP=2 + SP + remat loss comparison, and move the new test above the __main__ guard. 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 remat-replay bug from the last review is fixed: VisionTransformerBlock.forward now enters disable_dense_sp() itself. What's left is the PR description, the loss check, and two small test/code moves.

What this PR does. It adds disable_dense_sp(), a context manager that makes spmd_dense_sp_enabled() False. It wraps the Qwen3.5, MoonViT (K2.5/K3) and NaViT encoder forwards, and also VisionTransformerBlock.forward, in it. It deletes InvariantRowParallelLinear in favor of plain RowParallelLinear. It declares the vision rope cache TP-Replicate at its source. And it makes the async TP linears fall back to the sync path when dense SP is off.

Example (TP=2, SP on, encoder blocks checkpointed).

forward:   encoder.forward [scope] -> layers.0.forward [scope] -> attn.proj  P -> I
backward:  remat replays layers.0.forward [scope re-entered]   -> attn.proj  P -> I

activation_remat.apply only checkpoints the layers children (activation_remat.py:129-155). In all four encoders those children are VisionTransformerBlocks, so every replayed region re-enters the scope. The merger/projector only run inside the encoder forward. disable_dense_sp saves and restores the previous value, so nested entry is safe.

Earlier review, at HEAD

  • Remat replay outside the scope: fixed, and guarded by test_vision_block_disables_dense_sp_outside_the_encoder_scope.
  • Duplicate (RowParallelLinear, RowParallelLinear) loop: fixed.
  • "Specialized row parallel" quantization/LoRA tests: removed.
  • ColumnParallelLinear-under-disable_dense_sp test: removed. The restore test is now single-process.
  • Loss comparison: still open (item 2).

Must fix

  1. PR description is stale. It still lists TestColumnParallelLinearWithDenseSPDisabled, which this commit removed. It doesn't mention that VisionTransformerBlock.forward enters the scope, or why (remat replay). Please update the "What changed" and "Testing" sections to match the commit message.
  2. "End-to-end loss comparison: TODO" -- this refactor must give identical loss and grad_norm. Please add a before/after run of one vision flavor with TP=2 + SP + full activation remat (seed 42, deterministic), so the replay path is exercised.
  3. tests/unit_tests/cpu/models/common/test_vision_attention.py:73 -- the new test is below the __main__ guard. Move it above.

Should consider

  • torchtitan/models/common/linear/async_linear.py:309-312 -- the AsyncColumnParallelLinear fallback has no consumer in this PR. Move it to #5803.
Details
  • Gate. Unchanged from the last review. A region-level switch replaces a per-block Invariant* copy that every class-matching transform (async TP, quantization, LoRA) had to special-case. Net -21 LoC.
  • Compile. Vision blocks aren't wholly compiled. Only create_block_mask and named local_compile regions are, so the TLS write in the decorator doesn't run inside a dynamo-traced frame.
  • Async TP. Now that the block enters the scope, AsyncRowParallelLinear replays take the same fallback branch, with the same linear and tp_reduce regions, as the forward did. That resolves the replay exposure noted last time.

Not verified: GPU/TP runs (not available here). A maintainer still needs to review, since this touches torchtitan/distributed/ and models/common/.

unittest.main()


class _RecordDenseSP(torch.nn.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.

The new helper and test sit below the if __name__ == "__main__": unittest.main() guard. pytest still collects them, but python test_vision_attention.py doesn't run them, and the file now reads out of order. Move _RecordDenseSP and the test above the guard. This test guards the remat-replay invariant, so it's worth keeping.

Comment on lines +309 to +312
if not spmd_dense_sp_enabled():
# Without sequence parallelism (e.g. inside a vision encoder, see
# disable_dense_sp) there is no sequence collective to overlap.
return super().forward(input)

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.

Nothing in this PR uses this AsyncColumnParallelLinear fallback: the encoders' fc1/qkv are still Linear with vision_colwise_sharding_config, so AsyncTensorParallelTransform never produces an AsyncColumnParallelLinear inside a disable_dense_sp region. Its consumer is #5803, and that PR also had its test. Please move these four lines there (with the ColumnParallelLinear test) so the fallback lands with code that runs it. The row fallback below does have a consumer and a test.

@anijain2305
anijain2305 marked this pull request as ready for review November 12, 2026 01:32
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 12, 2026
@github-actions
github-actions Bot requested a review from pianpwk November 12, 2026 01:32
@anijain2305
anijain2305 removed this pull request from stack #6044 November 12, 2026 01:40
@anijain2305
anijain2305 added this pull request to stack #6045 November 12, 2026 01:40
# The encoder forward already runs under disable_dense_sp, but activation
# remat replays each block during backward, after that scope has exited.
# Entering it here keeps the replay's TP layout equal to the forward's.
@disable_dense_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.

By then the encoder's forward has returned and this finally has set dense_sp_enabled back to the registered value. So with TP > 1 and SP on, the replayed RowParallelLinear.forward (attention proj, MLP fc2) reads spmd_dense_sp_enabled() == True

what's the smallest region this context need to wrap? I don't think we need to wrap the entire VisionTransformerBlock anyway.

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.

The smallest ones are VisionMLP,VisionAttention, and projections that run after the block - Qwen3.5 PatchMerger, Kimi K2.5 VisionProjector and Kimi K3 KimiK3VisionProjector.

I can move it to these smaller regions, but I worry if we miss a module. Not sure if thats strictly better than the one at the remat boundary (I do agree that its not ideal).

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.

sg, let's stick with this for now

# The encoder forward already runs under disable_dense_sp, but activation
# remat replays each block during backward, after that scope has exited.
# Entering it here keeps the replay's TP layout equal to the forward's.
@disable_dense_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.

sg, let's stick with this for now

@anijain2305
anijain2305 merged commit c6f7828 into main Nov 12, 2026
HJSang added a commit to HJSang/torchtitan that referenced this pull request Nov 17, 2026
Resolve conflicts with pytorch#5893 (expert LoRA merge without a full-weight copy)
and pytorch#6043 (vision encoders non sp): feed _adapter_operands into
_MergeExpertLoRA, and drop the removed InvariantRowParallelLinear import.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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