Repository navigation
vision encoders non sp - #6043
Conversation
|
@claude review this PR |
|
Claude finished @anijain2305's task in 3m 58s —— View job Request changes: encoder blocks are replayed by activation remat during backward, which runs outside |
There was a problem hiding this comment.
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
torchtitan/distributed/spmd_types.py:88-102-- remat replay of encoder blocks runs outsidedisable_dense_sp: encoderlayersare wrapped byactivation_remat.apply(encoder)(multimodal.py:94,kimi_k3/model.py:275). The fix is to also enter it inVisionTransformerBlock.forward, or to add aRecomputeStateHook. One existing encoder typecheck test should also run under SP + TP=2 + full remat.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, sinceRowParallelLinearis covered elsewhere.tests/unit_tests/cpu/models/common/test_linear.py:332-- theColumnParallelLinear-under-disable_dense_sptest 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
dstof eachspmd.redistributeis 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'sremat.checkpointon encoder blocks. The decoderlayersaren't affected, because they don't run underdisable_dense_sp. - Async TP.
AsyncTensorParallelTransformnow converts the encoder'sRowParallelLinearconfigs (the removedtest_async_transform_skips_invariant_row_parallel_linearused 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_dstfor 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/.
| 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 |
There was a problem hiding this comment.
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-scattersP -> S(0)where the forward all-reducedP -> I. The recomputed tensor has the wrong shape and placement. - Async TP, even with the default save-all policy:
AsyncRowParallelLineartakes the fused-reduce-scatter branch during replay. That branch declares different regions (linearonly, notp_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): |
There was a problem hiding this comment.
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]) |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
8ee779d to
b8672c0
Compare
|
@claude review this PR |
|
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 |
There was a problem hiding this comment.
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_sptest: removed. The restore test is now single-process.- Loss comparison: still open (item 2).
Must fix
- PR description is stale. It still lists
TestColumnParallelLinearWithDenseSPDisabled, which this commit removed. It doesn't mention thatVisionTransformerBlock.forwardenters the scope, or why (remat replay). Please update the "What changed" and "Testing" sections to match the commit message. - "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.
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-- theAsyncColumnParallelLinearfallback 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_maskand namedlocal_compileregions 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,
AsyncRowParallelLinearreplays take the same fallback branch, with the samelinearandtp_reduceregions, 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): |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| # 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() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
sg, let's stick with this for now
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]>
Summary (human-written)
Introduce a
disable_dense_spcontext 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 isspelled out separately:
InvariantRowParallelLinearis a copy ofRowParallelLinearwhose onlychange is reducing
P -> Iinstead ofP -> S(0) if SP else I.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_inputinstead ofadding more
Invariant*variants or asrc=override.Example (TP=2, decoder SP on).
What changed
Non-SP regions
disable_dense_sp()context manager (torchtitan/distributed/spmd_types.py):spmd_dense_sp_enabled()is False inside it, and the registered setting isrestored on exit.
forwardrun under it:Qwen35VisionEncoder,MoonViTEncoder(Kimi K2.5 and K3) andNaViTEncoder(Muse Spark and MuseGlimmer). Their mergers and projectors run inside the same
forward.Fewer special classes
InvariantRowParallelLinearis removed. The encoders' attentionproj, MLPfc2and merger/projector output useRowParallelLinear, which reducesP -> Ithere. Same forward, bias handling and remat regions(
<fqn>.linear,<fqn>.tp_reduce). The quantization converter and testsare updated.
inv_freqand the rotary output) is declaredTP-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_dstentry is gone.Async TP
AsyncTensorParallelTransformconverts everyRowParallelLinear/ColumnParallelLinearconfig, which now includes the encoders' rowprojections. 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->RowParallelLinearrename in the Qwen3.5, Kimi K2.5/K3 and Muse Sparkflavors and in the tests.
Alternatives considered
Invariant*): every TP block an encoderuses needs a copy, and every transform that matches on class (async TP,
quantization, LoRA) has to know about each copy.
src=spmd.Itomaybe_gather_tp_inputat encoder call sites: thelayout is a property of the region, not of each call.
AsyncTensorParallelTransformby FQN: theruntime fallback keys off the same SP state the module already uses, and
also covers any other non-SP region.
User-facing changes
InvariantRowParallelLinear.Config(...)RowParallelLinear.Config(...), inside a module whose forward runs underdisable_dense_sp()@disable_dense_sp()if its activations are not sequence-shardedNumerics
No collective changes: the encoder runs the same ops in the same order.
RowParallelLinearunderdisable_dense_sptakes the same path as the oldInvariantRowParallelLinear(the forwards differ only in the reductiontarget, now
Iin both).End-to-end loss comparison: TODO.
Testing
test_row_parallel_output_is_invariant_with_dense_sp_disabled: with decoderSP registered,
RowParallelLinearinsidedisable_dense_spreducesP -> I. It catches an encoder row projection that reduce-scatters.test_async_row_parallel_falls_back_with_dense_sp_disabled: the same forAsyncRowParallelLinear. It catches async TP fusing a reduce-scatter insidethe encoder.
TestColumnParallelLinearWithDenseSPDisabled(2 ranks, strict typecheck):ColumnParallelLinearon a TP-Invariant input underdisable_dense_sp,with decoder SP on and off, matches the unsharded output and gradients. It
fails with an
SpmdTypeErrorif the context manager is removed.disable_dense_sprestores the registered setting, also when the bodyraises.
quantization and transform tests: 157 pass.
test_lora_model_buildsandtest_nvfp4_hf_export_strips_buffersfail the same way on main in the devenvironment.
Known issues / follow-ups
flavors), [spmd] Make decoder embedding and final-norm TP collectives explicit #5802 (decoder embedding / final norm), [spmd] Make vision encoder TP and CP collectives explicit #5803 (vision encoder TP
collectives, which uses
ColumnParallelLinearinside these non-SPregions).