Skip to content

Qwen3 TP + CP with local_map region - #2480

Closed
pianpwk wants to merge 3 commits into
gh/pianpwk/2/basefrom
gh/pianpwk/2/head
Closed

pianpwk wants to merge 3 commits into
gh/pianpwk/2/basefrom
gh/pianpwk/2/head

Conversation

@pianpwk

@pianpwk pianpwk commented Mar 4, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Fixes #2446 by using local_map region for CP

[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Mar 4, 2026
…CP hook

Qwen3 uses colwise_parallel(use_local_output=False) for wq/wk/wv to keep
q/k/v as DTensors through q_norm/k_norm (SequenceParallel). When CP is also
enabled, the CP attention hook on inner_attention expects plain tensors, not
TP-mesh DTensors, causing an AssertionError.

Fix: register a pre-forward hook on inner_attention (when CP is enabled) that
calls .to_local() on DTensor args before the CP hook runs. This cleanly
separates the TP and CP DTensor domains while preserving the autograd chain.


ghstack-source-id: d7bfc4b
Pull-Request: #2480
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 4, 2026
Comment thread torchtitan/models/qwen3/parallelize.py Outdated
them here. This hook must be registered before the CP hook.
"""
new_args = tuple(
arg.to_local() if isinstance(arg, DTensor) else arg for arg in args

ghost Mar 4, 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.

No we shouldn't do this. to_local() should always come with grad_placement, which is hard to make generic.

Maybe you can use local_map explicitly around CP region inside Attention.

[ghstack-poisoned]
inner_attn,
# Single output: wrap in tuple so local_map sees Tuple[PlacementType]
out_placements=(shard_heads,),
in_placements=(shard_heads, shard_heads, shard_heads),

ghost Mar 4, 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.

what about placements for other args passed into inner attention? do we need to consider them?

self.inner_attention(

ghost Mar 9, 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.

looks like they're non-Tensor args that local_map will flatten away, while BlockMask/VarlenMetadata isn't supported yet; qwen CP only supports SDPA backend. Adding a note there

ghost Mar 9, 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.

I believe CP with Flex attention will be enabled by @fegin soon. Not sure about what's the gap for CP + varlen attention.

# boundary. TP's use_local_output=False produces DTensor q/k/v, but CP
# hooks expect plain tensors. local_map handles this with correct
# grad_placements for backward pass.
if parallel_dims.tp_enabled and parallel_dims.cp_enabled:

ghost Mar 4, 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.

do we need to check if use_local_output=False for TP?

ghost Mar 9, 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.

hmm I can't find a clean way to check this

ghost Mar 9, 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.

ic, maybe we can just assume we always use full DTensor for TP, then we need to land #2149 first?

@pianpwk

ghost commented Mar 4, 2026

Copy link
Copy Markdown
Contributor Author

sorry, please ignore the PR in its current state, everything's from Claude. will put more thought into this

@fatih-uzlmz

ghost commented Mar 5, 2026

Copy link
Copy Markdown
Contributor

Hey @pianpwk thanks for getting this started! I was actually looking into this exact issue earlier today and trying to solve it locally. If you don't mind, I’d love to try taking a crack at implementing the local_map fix that @tianyu-l requested in a new PR. Lmk if that works for you :)

@wwwjn wwwjn mentioned this pull request Mar 6, 2026
@wwwjn

ghost commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

@pianpwk Do you wanna refine this PR and we can land it as a workaround before full DTensor mode?

from torchtitan.tools.logging import logger


class _LocalMapInnerAttention(nn.Module):

ghost Mar 4, 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.

This is also useful for torchtitan + vllm as we have to manually patch vllm's attention kernel now which also requires a plain tensor

ghost Mar 9, 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.

can we move this function outside qwen3 as it is useful in general?

…cal before CP hook"

Qwen3 uses colwise_parallel(use_local_output=False) for wq/wk/wv to keep
q/k/v as DTensors through q_norm/k_norm (SequenceParallel). When CP is also
enabled, the CP attention hook on inner_attention expects plain tensors, not
TP-mesh DTensors, causing an AssertionError.

Fix: register a pre-forward hook on inner_attention (when CP is enabled) that
calls .to_local() on DTensor args before the CP hook runs. This cleanly
separates the TP and CP DTensor domains while preserving the autograd chain.

[ghstack-poisoned]
@pianpwk pianpwk changed the title Fix Qwen3 TP + CP composition by converting DTensors to local before CP hook Qwen3 TP + CP with local_map region Mar 9, 2026
@pianpwk
pianpwk marked this pull request as ready for review March 9, 2026 19:29
@pianpwk
pianpwk requested review from fegin and wconstab as code owners March 9, 2026 19:29
inner_attn,
# Single output: wrap in tuple so local_map sees Tuple[PlacementType]
out_placements=(shard_heads,),
in_placements=(shard_heads, shard_heads, shard_heads),

ghost Mar 9, 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.

I believe CP with Flex attention will be enabled by @fegin soon. Not sure about what's the gap for CP + varlen attention.

from torchtitan.tools.logging import logger


class _LocalMapInnerAttention(nn.Module):

ghost Mar 9, 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.

can we move this function outside qwen3 as it is useful in general?

# boundary. TP's use_local_output=False produces DTensor q/k/v, but CP
# hooks expect plain tensors. local_map handles this with correct
# grad_placements for backward pass.
if parallel_dims.tp_enabled and parallel_dims.cp_enabled:

ghost Mar 9, 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.

ic, maybe we can just assume we always use full DTensor for TP, then we need to land #2149 first?

for block in model.layers.values():
attn = block.attention # pyrefly: ignore [missing-attribute]
# Workaround: cuDNN SDPA backward has a stride mismatch bug with CP.
# Exclude cuDNN until PyTorch fix lands.

ghost Mar 9, 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.

do you know what PR is the fix? can you link it in comment?

ghost Mar 9, 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.

Still an open issue: pytorch/pytorch#176915 (comment)

SDPBackend.MATH,
]
)
attn.inner_attention = (

ghost Mar 9, 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.

wont this override L187?

ghost Mar 9, 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 think this should be fine? L187 was meant to override this class' backend attribute, which is wrapped over:

class ScaledDotProductAttentionWrapper(torch.nn.Module):
"""Wrapper around `F.scaled_dot_product_attention` to make it CP compatible.
This wrapper is needed because `F.scaled_dot_product_attention` is not
a torch.nn.Module, and thus cannot be applied with _ContextParallel.
We need to wrap it into a torch.nn.Module.
Note:
The forward function must have q, k, v as the first three arguments to be
compatible with _ContextParallel.
"""
sdpa_backends: list[SDPBackend] = []
def __init__(self) -> None:
super().__init__()
if not self.sdpa_backends:
self.sdpa_backends = [
SDPBackend.CUDNN_ATTENTION,
SDPBackend.FLASH_ATTENTION,
SDPBackend.MATH,
]

ghost Mar 9, 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.

ic, my bad. It was a little bit confusing since we are overriding attn.inner_attention. But indeed the backend attribute for the real attn.inner_attention(L195) should be updated.



class _LocalMapInnerAttention(nn.Module):
"""Wraps inner_attention with local_map for TP + CP composition.

ghost Mar 11, 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.

Instead of making it only supports TP+CP, can we make it generic and support arbitrary tensor / dtensor inputs -- e.g. every inner_attention wrapper (flex, varlen, sdpa) should inherit an InnerAttentionWrapper which does this local_map treatment. cc @acisseJZhong this aligns with our idea of using local_map for attention in full DTensor.

ghost Mar 11, 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.

just synced with @fegin we should do this to make local_map work with every attention.

ghost Mar 11, 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.

every inner_attention wrapper (flex, varlen, sdpa)

Does SDPA support Dtensor input already?

ghost Mar 11, 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.

Does SDPA support Dtensor input already?

Yes, so it's not absolutely necessary. But unifying the interface with local_map sounds cleaner in torchtitan.

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.

5 participants