Repository navigation
Adopt Local Map Wrapper for Inner Attention - #2557
Conversation
| v, DTensor | ||
| ), "q, k, v should all be DTensors" | ||
| if self._local_map_fn is None: | ||
| self._local_map_fn = local_map( |
There was a problem hiding this comment.
@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
There was a problem hiding this comment.
yes, this makes sense. Some comments
-
Instead of
_InnerAttentionLocalMap, we should just implement this logic intoModule. 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. -
We will have to ensure
torch.compiledoesn't break. So try with--compile.enable.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Or can we inherit Module and call them LocalMapModule?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
for context managers, we can manually call with __enter__() and __exit__()
There was a problem hiding this comment.
@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
There was a problem hiding this comment.
Directly replacing forward with wrapped forward work, #2621.
| placements = module._placements | ||
| mesh = module._device_mesh |
There was a problem hiding this comment.
may not exist if args[0] is not DTensor?
|
|
||
|
|
||
| class VarlenAttentionWrapper(torch.nn.Module): | ||
| def _to_local(x: Any) -> Any: |
There was a problem hiding this comment.
can define inline? doesn't need to be at root level.
There was a problem hiding this comment.
I mimic six's way D83451817, but moving inline sounds better.
| def __init__(self) -> None: | ||
| super().__init__() | ||
| self.register_forward_pre_hook( | ||
| LocalMapModule._pre_hook, with_kwargs=True, prepend=True |
There was a problem hiding this comment.
any reason why prepend=True?
There was a problem hiding this comment.
@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
There was a problem hiding this comment.
@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
| return x | ||
|
|
||
|
|
||
| class LocalMapModule(Module): |
There was a problem hiding this comment.
| 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
- in TP mesh, things are Shard on head dim. This is fine.
- on CP mesh, q is Shard and kv are Replicate. The reason you can assume kv grad are also Replicate is because CP API internally does this reduce-scatter for us https://github.com/pytorch/pytorch/blob/main/torch/distributed/tensor/experimental/_context_parallel/_cp_custom_ops.py#L37, which is fine for now
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)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
oh, that's right -- if that's the case, can we assert every placement to be Shard?
There was a problem hiding this comment.
yes, this is what I am doing in the local map approach. Let me roll back and add explicitly assertion to Shard for now
| self.register_forward_hook(LocalMapModule._post_hook) | ||
|
|
||
| @staticmethod | ||
| def _pre_hook(module, args, kwargs): |
There was a problem hiding this comment.
give it more meaningful name, e.g. _inputs_to_local, _outputs_from_local
|
|
||
| # 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": |
There was a problem hiding this comment.
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
844c107 to
2d06f2e
Compare
There was a problem hiding this comment.
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
| # 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 |
There was a problem hiding this comment.
Let's create an util for setting common compiler flags in distributed/compiler.py.
There was a problem hiding this comment.
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.
|
thanks for the command! the loss should match exactly with baseline |
| # 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 |
There was a problem hiding this comment.
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.
|
|
||
|
|
||
| class VarlenAttentionWrapper(Module): | ||
| class LocalMapModule(Module): |
There was a problem hiding this comment.
| 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), |
There was a problem hiding this comment.
is it better if we assert they all have the same placements
There was a problem hiding this comment.
I thought L103 does it? we checked q/k/v are Shard.
| v: torch.Tensor, | ||
| **kwargs, | ||
| ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: | ||
| return self._forward_local(q, k, v, **kwargs) |
There was a problem hiding this comment.
why having this indirection?
There was a problem hiding this comment.
oops Claude indeed complicates this, removed!
| f"LocalMapModule requires Shard placements, " | ||
| f"but {name} has placement {p}" | ||
| ) | ||
| if self._local_map_fn is None: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
We already check placements at L105 for each call?
There was a problem hiding this comment.
you didn't check Shard(0) / Shard(1) / Shard(2) / ...
There was a problem hiding this comment.
added! thanks for the catch
| # 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 |
There was a problem hiding this comment.
do you only need to set this for MoE?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_denseandapply_compile_sparasein 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
| import torch | ||
|
|
||
|
|
||
| def set_common_compiler_flags() -> None: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
9835dce to
5d45172
Compare
| # 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), ( |
There was a problem hiding this comment.
after full dtensor rewrite, DP mesh will be included, where qkv will be Shard(0) on DP mesh -- please leave a TODO
| # 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 |
There was a problem hiding this comment.
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_denseandapply_compile_sparasein 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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
@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)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
for llama3 which use |
98f4818 to
926078a
Compare
This reverts commit 26cdceb.
0fda2b9 to
d14b720
Compare
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 ```
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 ```
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 ```
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 ```
This is a continuation of work in #2480 by @pianpwk
Summary
__call__to wrap
nn.Module.__call__with local_map, converting TP DTensor inputsto local tensors before any
forward_pre_hookfires, and wrappingoutputs back to DTensor after all
forward_hookscomplete. Placementsand device mesh are inferred from the input DTensors at runtime.
LocalMapModulehandle theTP/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.
Test