Skip to content

Adopt Local Map Wrapper for Inner Attention - #2557

Merged
acisseJZhong merged 24 commits into
mainfrom
cp_localmap
Mar 20, 2026
Merged

acisseJZhong merged 24 commits into
mainfrom
cp_localmap

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

This is a continuation of work in #2480 by @pianpwk

Summary

  • Add _InnerAttentionBase base class to attention.py — overrides __call__
    to wrap nn.Module.__call__ with local_map, converting TP DTensor inputs
    to local tensors before any forward_pre_hook fires, and wrapping
    outputs back to DTensor after all forward_hooks complete. Placements
    and device mesh are inferred from the input DTensors at runtime.
  • Enable TP+CP support for Qwen3 by having LocalMapModule handle the
    TP/CP boundary. Qwen3 requires this because it uses use_local_output=False
    on wq/wk/wv (needed for QK norms with SequenceParallel), producing
    DTensors that CP hooks cannot directly consume.
  • Add integration test for Qwen3 FSDP+TP+CP on 8 GPUs.

Test

NCCL_NVLS_ENABLE=0 MODULE=qwen3 CONFIG=qwen3_debugmodel ./run_train.sh --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.context_parallel_degree 2 --compile.enable  --compile.backend eager 

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 11, 2026
@acisseJZhong
acisseJZhong requested a review from pianpwk March 11, 2026 23:59
v, DTensor
), "q, k, v should all be DTensors"
if self._local_map_fn is None:
self._local_map_fn = local_map(

@acisseJZhong acisseJZhong Mar 12, 2026 •

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.

@fegin i had this local_map wrapping around CP pre-forward hook and post-forward hook, so that the local map will handle conversion of Dtensor to plain tensor before the CP pre-forward hook fires. If it's the other way around, i will hit assertion error https://github.com/pytorch/pytorch/blame/main/torch/distributed/tensor/experimental/_context_parallel/_attention.py#L1394

not sure if this is the best way; and maybe you already have some plan on rewriting the CP API for full DTensor

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.

yes, this makes sense. Some comments

  1. Instead of _InnerAttentionLocalMap, we should just implement this logic into Module. This is going to be something we need anyway for MoE. The implementation can be less generic at this point and leave some TODOs that once we integrate the config system with sharding spec, the implementation should be more generic.

  2. We will have to ensure torch.compile doesn't break. So try with --compile.enable.

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.

I realized that these inner wrappers are not Module yet. You can just wrap them with Module with Config to be empty at this moment.

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.

Or can we inherit Module and call them LocalMapModule?

@acisseJZhong acisseJZhong Mar 12, 2026 •

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.

Compile is not working with this super().call approach, Claude tells me that

Why it breaks compile: When dynamo encounters self.inner_attention(xq, xk, xv, ...), it detects that
LocalMapModule has a custom call (not the standard nn.Module.call). Dynamo then tries to trace through
the custom call as a regular Python function. Inside call, the super().call(q, k, v, **kwargs) call
bypasses dynamo's special nn.Module call handling (which normally inlines forward() and properly handles hooks).
This causes FX nodes to be created without proper meta["val"] metadata, leading to the inductor KeyError: 'val'
error.

Not sure how six handles compile with this call override.

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.

I think to_local and from_local on module boundary is fine, because we can still force a pair of them within clear boundary. Would be good to know if it works with spmd_types, which is a context manager.

@xmfan xmfan Mar 13, 2026 •

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.

for context managers, we can manually call with __enter__() and __exit__()

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.

@xmfan there's some limitation due to torch_function, so we can't use enter and exit. This is the current entry point https://fburl.com/code/ypffryqp

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.

@xmfan i changed to hook based approach here 26cdceb but compile still fails. P2234099693

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.

Directly replacing forward with wrapped forward work, #2621.

Comment thread torchtitan/models/common/attention.py Outdated
Comment on lines +120 to +121
placements = module._placements
mesh = module._device_mesh

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.

may not exist if args[0] is not DTensor?

Comment thread torchtitan/models/common/attention.py Outdated


class VarlenAttentionWrapper(torch.nn.Module):
def _to_local(x: Any) -> Any:

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.

can define inline? doesn't need to be at root level.

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.

I mimic six's way D83451817, but moving inline sounds better.

Comment thread torchtitan/models/common/attention.py Outdated
def __init__(self) -> None:
super().__init__()
self.register_forward_pre_hook(
LocalMapModule._pre_hook, with_kwargs=True, prepend=True

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.

any reason why prepend=True?

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.

@acisseJZhong Is there a way to use __call__ with torch.compile? I am worried that hook will cause the order issues, which happened many times before. We didn't have a good way to do this because we could not change nn.Module. But since now we have our own Module, I would prefer using call if possible. torch.compile is definitely the key blocker we need to fix.

cc., @xmfan

@acisseJZhong acisseJZhong Mar 13, 2026 •

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.

@tianyu-l in fact this is the reason I also prefer to have local map wrapping super.call, and solve any compile issues on that. Otherwise for this forward pre hook, and for the CP post forward hook, I need to have prepend=True; to make sure that the hooks I added can wrap around CP hooks.

I would prefer rolling back to my last commit and fix compile problem. 26cdceb @xmfan

Comment thread torchtitan/models/common/attention.py Outdated
return x


class LocalMapModule(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.

Suggested change
class LocalMapModule(Module):
class LocalMapAttention(Module):

The implementation is very restricted, in the sense that

  • input placements and output placements must be the same
  • grad placements of inputs must stay the same. From typing perspective, this is only true for Shard.

Taking Flex all-gather based CP as an example

Let's restrict the scope to Attention, since this is not a general local map module.

Please add detailed docstring. (Ask me / claude if anything is not clear)

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 scope of this LocalMapModule is restricted to Attention because right now we don't have a way to configure local map, which is why this module is put here and everything is fixed.

However, I think this is a good start though to demonstrate how to do module level local map and extend it to a general implementation once our config includes 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.

on CP mesh, q is Shard and kv are Replicate

When I specify local_map/to/from_local, q, k, v should all be Shard on TP mesh.
And later on CP mesh, q, k, v should all be Shard and this is because of CP pre hook and post hook? https://github.com/pytorch/pytorch/blob/4d01cdb5b2a633c45471bdaf8d8d544c4bb2572a/torch/distributed/tensor/experimental/_context_parallel/_attention.py#L1396

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.

oh, that's right -- if that's the case, can we assert every placement to be Shard?

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.

yes, this is what I am doing in the local map approach. Let me roll back and add explicitly assertion to Shard for now

Comment thread torchtitan/models/common/attention.py Outdated
self.register_forward_hook(LocalMapModule._post_hook)

@staticmethod
def _pre_hook(module, args, kwargs):

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.

give it more meaningful name, e.g. _inputs_to_local, _outputs_from_local

Comment thread torchtitan/models/qwen3/parallelize.py Outdated

# TODO: cuDNN SDPA backward has a stride mismatch bug with CP.
# Exclude cuDNN until PyTorch fix lands. See https://github.com/pytorch/pytorch/issues/176915.
if attn_backend == "sdpa":

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.

I don't know how I feel about this workaround.

If we have to do it, don't do per model. Instead, do it in SDPA module, e.g. maybe by override the pre forward hook and subtract cudnn from self.sdpa_backends

@acisseJZhong acisseJZhong mentioned this pull request Mar 13, 2026
@acisseJZhong acisseJZhong added this to the New Feature, Model, Misc milestone Mar 13, 2026
@acisseJZhong acisseJZhong self-assigned this Mar 13, 2026
@acisseJZhong acisseJZhong moved this from Todo to In Progress in TorchTitan Development Mar 13, 2026
@wwwjn wwwjn linked an issue Mar 13, 2026 that may be closed by this pull request
@acisseJZhong
acisseJZhong force-pushed the cp_localmap branch 4 times, most recently from 844c107 to 2d06f2e Compare March 18, 2026 16:50

@fegin fegin 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.

LGTM.

But we should verify the accuracy since you change the compiler flag:

python scripts/loss_compare.py . main --baseline-options="--compile.enable" --test-options="--compile.enable" --assert-equal --no-seed-checkpoint
python scripts/loss_compare.py . main --baseline-module=qwen3 --baseline-config=qwen3_debugmodel --baseline-options="--compile.enable" --test-module=qwen3 --test-config=qwen3_debugmodel --test-options="--compile.enable" --assert-equal --no-seed-checkpoint

Comment thread torchtitan/models/llama4/parallelize.py Outdated
# side-effects in backward, but torch.compile has no easy way to reapply
# python mutations in the backward. Setting this flag accepts this eager
# and compile divergence by skipping reapplication of side effects.
torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True

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.

Let's create an util for setting common compiler flags in distributed/compiler.py.

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.

Also, I think this entire function can be put in distributed/compile.py.
We can have two, one for dense one for sparse. If @weifengpy 's fix is ready, one is enough.

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

thanks for the command! the loss should match exactly with baseline

[LOSS_COMPARE] Summary statistics:
[LOSS_COMPARE] Average baseline loss:  3.1069710278511047
[LOSS_COMPARE] Average test loss: 3.1069710278511047
[LOSS_COMPARE] Average difference:     0.000000

Comment thread torchtitan/models/llama4/parallelize.py Outdated
# side-effects in backward, but torch.compile has no easy way to reapply
# python mutations in the backward. Setting this flag accepts this eager
# and compile divergence by skipping reapplication of side effects.
torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True

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.

Also, I think this entire function can be put in distributed/compile.py.
We can have two, one for dense one for sparse. If @weifengpy 's fix is ready, one is enough.

Comment thread torchtitan/models/common/attention.py Outdated


class VarlenAttentionWrapper(Module):
class LocalMapModule(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.

Suggested change
class LocalMapModule(Module):
class LocalMapAttention(Module):

if self._local_map_fn is None:
self._local_map_fn = local_map(
super().__call__,
in_placements=(q.placements, k.placements, v.placements),

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.

is it better if we assert they all have the same placements

@acisseJZhong acisseJZhong Mar 19, 2026 •

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.

I thought L103 does it? we checked q/k/v are Shard.

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.

same comment

Comment thread torchtitan/models/common/attention.py Outdated
v: torch.Tensor,
**kwargs,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
return self._forward_local(q, k, v, **kwargs)

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.

why having this indirection?

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.

oops Claude indeed complicates this, removed!

f"LocalMapModule requires Shard placements, "
f"but {name} has placement {p}"
)
if self._local_map_fn is None:

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.

IIUC the purpose of having this check is for 2nd, 3rd, ... call to this attention to reuse the _local_map_fn. I guess that's safe in torchtitan setup, where we never change the inputs placements from iteration to iteration, but we could've added a guard before this line.

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.

We already check placements at L105 for each call?

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.

you didn't check Shard(0) / Shard(1) / Shard(2) / ...

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.

added! thanks for the catch

Comment thread torchtitan/distributed/compile.py Outdated
# side-effects in backward, but torch.compile has no easy way to reapply
# python mutations in the backward. Setting this flag accepts this eager
# and compile divergence by skipping reapplication of side effects.
torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True

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.

do you only need to set this for MoE?

@acisseJZhong acisseJZhong Mar 19, 2026 •

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.

capture_scalar_outputs is MoE related but skip_fwd_side_effects_in_bwd_under_checkpoint is not MoE related. Both of them are used in llama4 parallelize plan and graph trainer compile.

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.

Does other model (e.g. llama3, gpt-oss) not need this to work with TP + CP? (Not sure if it's related to use_local_output=False in Qwen3). Btw, I think gpt-oss has an attention which should also be refactored.

In addition, my suggestion is that

  • we have apply_compile_dense and apply_compile_sparase in this file. After Wei's [FSDP2] enable per-param mesh FSDP2 for MoE #2281 we may only need one.
  • refactor each model to call into either one in this function, instead of writing their own or importing from llama3/llama4
  • the dense compile function sets skip_fwd_side_effects_in_bwd_under_checkpoint
  • the sparse compile function sets both

Comment thread torchtitan/distributed/compiler.py Outdated
import torch


def set_common_compiler_flags() -> None:

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 naming of this function is vague -- please check the other comments on how to organize this file -- also nit: we should call it compile.py following torchtitan convention.

@acisseJZhong acisseJZhong Mar 19, 2026 •

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.

I renamed this file to distributed/compile.py.

We can have two, one for dense one for sparse.

didn't get this part, does Wei has a PR?

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.

yes #2281

# qkv are (bs, n_heads, seqlen, head_dim) and must be sharded
# on the n_heads dim (dim 1)
for i, p in enumerate(q.placements):
assert p == Shard(1), (

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.

after full dtensor rewrite, DP mesh will be included, where qkv will be Shard(0) on DP mesh -- please leave a TODO

Comment thread torchtitan/distributed/compile.py Outdated
# side-effects in backward, but torch.compile has no easy way to reapply
# python mutations in the backward. Setting this flag accepts this eager
# and compile divergence by skipping reapplication of side effects.
torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True

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.

Does other model (e.g. llama3, gpt-oss) not need this to work with TP + CP? (Not sure if it's related to use_local_output=False in Qwen3). Btw, I think gpt-oss has an attention which should also be refactored.

In addition, my suggestion is that

  • we have apply_compile_dense and apply_compile_sparase in this file. After Wei's [FSDP2] enable per-param mesh FSDP2 for MoE #2281 we may only need one.
  • refactor each model to call into either one in this function, instead of writing their own or importing from llama3/llama4
  • the dense compile function sets skip_fwd_side_effects_in_bwd_under_checkpoint
  • the sparse compile function sets both

# Needed for torch.compile to avoid graph breaking on dynamic shapes in
# token-choice MoE, but it is experimental.
torch._dynamo.config.capture_scalar_outputs = True
# Skip replaying forward side effects (e.g. RoPE cache updates) during

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.

Where do we have this side effects exactly? Is it not a concern?

Does this change numerics between eager and compile(aot_eager backend), when AC is enabled?

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.

yes this will make eager and compile converges, as noted in the comment.

from @anijain2305

Eager AC replays the forward python side-effects in backward. Many users do not like or need it. They just need the fwd torch ops to be replayed in backward.

Compile AC does not have a way to even replay python side-effects in backward. So it graph breaks. But if a user does not need to replay the python side effect in the backward (which is the case in torchtitan), they can use that flag.

The default is false because we would like to have compile AC and eager AC not diverge w/o user buy-in.

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.

But if a user does not need to replay the python side effect in the backward (which is the case in torchtitan), they can use that flag.

This is saying "does not need", my question is "do we have" any side-effect in eager. I mean if we don't have any side effect, why do we need to toggle this field in the first place?

@acisseJZhong acisseJZhong Mar 19, 2026 •

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.

@anijain2305 might answer better here. I believe we should have side effects in eager(but idk what side effects exactly), and we need to skip when compile is turned on.

If we don't have this flag, we would face compile error

    File "/home/jessicazhong/torchtitan/torchtitan/models/common/decoder.py", line 151, in forward
      h = layer(h, self.freqs_cis, attention_masks, positions)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/home/jessicazhong/pytorch/torch/_dynamo/eval_frame.py", line 468, in __call__
      return super().__call__(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/home/jessicazhong/pytorch/torch/nn/modules/module.py", line 1778, in _wrapped_call_impl
      return self._call_impl(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/home/jessicazhong/pytorch/torch/nn/modules/module.py", line 1884, in _call_impl
      return inner()
             ^^^^^^^
    File "/home/jessicazhong/pytorch/torch/nn/modules/module.py", line 1832, in inner
      result = forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/home/jessicazhong/pytorch/torch/_dynamo/eval_frame.py", line 1046, in compile_wrapper
      raise e.with_traceback(None) from e.__cause__  # User compiler error
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  torch._dynamo.exc.Unsupported: HOP: Unsafe side effect
    Higher Order Operator: torch.utils.checkpoint.checkpoint
    Explanation: Mutating a variable from outside the scope of this HOP is not supported.
    Hint: If the HOP is activation checkpointing (torch.utils.checkpoint.checkpoint), this points to a side effect in forward method. Eager activation checkpointing replays that side-effect while recomputing the forward in the backward. If you are ok with side-effect not replayed in the backward, try setting `torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True`
  
    Developer debug context: Attempted to mutate FSDPManagedNNModuleVariable(ScaledDotProductAttentionWrapper)

@fegin fegin Mar 19, 2026 •

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.

If the Python mutation is safe to ignore (most of the time), then it is okay to set this flag as in the backward we don't need to replay the mutation, we just need to replay the forward ops. It looks like the mutation is from ScaledDotProductAttentionWrapper, which inherits LocalMapWrapper. And LocalMapWrapper call mutate self._local_map_fns. I think that's where the mutation. It is safe to ignore as long as we replay the correct forward ops.

#2621 works without setting this the flag because that PR swaps the forward BEFORE forward is called.

cc., @xmfan, @anijain2305 can confirm.

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.

Claude explains to me that the mutation comes from self._local_map_fn.

In torch.compile, the compiler traces the forward graph.
It sees the self._local_map_fn = ... mutation as a Python
side effect. During AC's backward recompute, compile
needs to replay forward ops but cannot replay arbitrary
Python attribute mutations. The
skip_fwd_side_effects_in_bwd_under_checkpoint flag tells
compile to skip these mutations during backward replay.

Why it's safe to skip: The mutation is a one-time lazy
cache. After the first forward, _local_map_fn is already
set. Skipping it during AC's backward recompute doesn't
affect the computation — the cached function is still
there and used correctly.

However I am wondering if #2621 is simpler, whether we should adopt this approach instead of inheriting from LocalMapWrapper.

@acisseJZhong

acisseJZhong commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Does other model (e.g. llama3, gpt-oss) not need this to work with TP + CP? (Not sure if it's related to use_local_output=False in Qwen3).

for llama3 which use use_local_output=False, we don't have this problem/no need to set any dynamo flags. I tried to set use_local_output=True calling apply_compile_dense and compile works, skip_fwd_side_effects_in_bwd_under_checkpoint=True is necessary for dense models.

@acisseJZhong
acisseJZhong merged commit 34f705b into main Mar 20, 2026
20 of 34 checks passed
mori360 pushed a commit to mori360/torchtitan that referenced this pull request Mar 23, 2026
This is a continuation of work in pytorch#2480 by @pianpwk

  **Summary**
- Add _InnerAttentionBase base class to attention.py — overrides
`__call__`
to wrap `nn.Module.__call__` with local_map, converting TP DTensor
inputs
  to local tensors before any `forward_pre_hook` fires, and wrapping
  outputs back to DTensor after all `forward_hooks` complete. Placements
  and device mesh are inferred from the input DTensors at runtime.
 - Enable TP+CP support for Qwen3 by having `LocalMapModule` handle the
TP/CP boundary. Qwen3 requires this because it uses
use_local_output=False
  on wq/wk/wv (needed for QK norms with SequenceParallel), producing
  DTensors that CP hooks cannot directly consume.
  - Add integration test for Qwen3 FSDP+TP+CP on 8 GPUs.

**Test**
```
NCCL_NVLS_ENABLE=0 MODULE=qwen3 CONFIG=qwen3_debugmodel ./run_train.sh --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.context_parallel_degree 2 --compile.enable  --compile.backend eager
```
pytorch-bot Bot pushed a commit that referenced this pull request Mar 27, 2026
This is a continuation of work in #2480 by @pianpwk 

  **Summary**
- Add _InnerAttentionBase base class to attention.py — overrides
`__call__`
to wrap `nn.Module.__call__` with local_map, converting TP DTensor
inputs
  to local tensors before any `forward_pre_hook` fires, and wrapping
  outputs back to DTensor after all `forward_hooks` complete. Placements
  and device mesh are inferred from the input DTensors at runtime.
 - Enable TP+CP support for Qwen3 by having `LocalMapModule` handle the
TP/CP boundary. Qwen3 requires this because it uses
use_local_output=False
  on wq/wk/wv (needed for QK norms with SequenceParallel), producing
  DTensors that CP hooks cannot directly consume.
  - Add integration test for Qwen3 FSDP+TP+CP on 8 GPUs.

**Test**
```
NCCL_NVLS_ENABLE=0 MODULE=qwen3 CONFIG=qwen3_debugmodel ./run_train.sh --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.context_parallel_degree 2 --compile.enable  --compile.backend eager 
```
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
This is a continuation of work in pytorch#2480 by @pianpwk 

  **Summary**
- Add _InnerAttentionBase base class to attention.py — overrides
`__call__`
to wrap `nn.Module.__call__` with local_map, converting TP DTensor
inputs
  to local tensors before any `forward_pre_hook` fires, and wrapping
  outputs back to DTensor after all `forward_hooks` complete. Placements
  and device mesh are inferred from the input DTensors at runtime.
 - Enable TP+CP support for Qwen3 by having `LocalMapModule` handle the
TP/CP boundary. Qwen3 requires this because it uses
use_local_output=False
  on wq/wk/wv (needed for QK norms with SequenceParallel), producing
  DTensors that CP hooks cannot directly consume.
  - Add integration test for Qwen3 FSDP+TP+CP on 8 GPUs.

**Test**
```
NCCL_NVLS_ENABLE=0 MODULE=qwen3 CONFIG=qwen3_debugmodel ./run_train.sh --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.context_parallel_degree 2 --compile.enable  --compile.backend eager 
```
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
This is a continuation of work in pytorch#2480 by @pianpwk 

  **Summary**
- Add _InnerAttentionBase base class to attention.py — overrides
`__call__`
to wrap `nn.Module.__call__` with local_map, converting TP DTensor
inputs
  to local tensors before any `forward_pre_hook` fires, and wrapping
  outputs back to DTensor after all `forward_hooks` complete. Placements
  and device mesh are inferred from the input DTensors at runtime.
 - Enable TP+CP support for Qwen3 by having `LocalMapModule` handle the
TP/CP boundary. Qwen3 requires this because it uses
use_local_output=False
  on wq/wk/wv (needed for QK norms with SequenceParallel), producing
  DTensors that CP hooks cannot directly consume.
  - Add integration test for Qwen3 FSDP+TP+CP on 8 GPUs.

**Test**
```
NCCL_NVLS_ENABLE=0 MODULE=qwen3 CONFIG=qwen3_debugmodel ./run_train.sh --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.context_parallel_degree 2 --compile.enable  --compile.backend eager 
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu 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.

qwen3 TP + CP bug

4 participants