Skip to content

[spmd_types] FLUX enablement - #3823

Merged
pianpwk merged 9 commits into
mainfrom
gh/pianpwk/58/head
Jul 1, 2026
Merged

pianpwk merged 9 commits into
mainfrom
gh/pianpwk/58/head

Conversation

@pianpwk

@pianpwk pianpwk commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

pianpwk added 2 commits June 29, 2026 15:56
[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 29, 2026
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Jun 29, 2026
ghstack-source-id: 84e96b8
Pull Request resolved: #3823
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Jun 29, 2026
ghstack-source-id: 7891fd6
Pull Request resolved: #3823
qkv_bias: bool = False
inner_attention: ScaledDotProductAttention.Config = field(
default_factory=ScaledDotProductAttention.Config
)

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.

this is so the sharding config can be patched i believe

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


def annotate_dp_cp_params_as_r(model: nn.Module, parallel_dims: ParallelDims) -> None:
# TODO(pianpwk): Infer these from the active SPMD mesh instead.

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.

R@DP-axis inference works with partial annotations, but not yet with empty tensors. working to add that in pytorch

batch_type = {
DP: spmd.S(0),
CP: spmd.R,
}

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.

seems flux multimodal inputs are evenly sharded?

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.

please verify that numerics doesn't change with DP & CP involved

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 needed to patch this to do simple KV allgather instead of the pytorch ring-attention context, but yes with that we get bitwise:

elif isinstance(first, ScaledDotProductAttention):
_enable_context_parallel_dispatcher()
for mod in attention_modules:
original_forward = mod.forward
def _make_cp_forward(orig_fn, mesh):
placement = [Shard(1)]
def cp_forward(q, k, v, **kwargs):
if not isinstance(q, DTensor):
q = DTensor.from_local(q, mesh, placement, run_check=False)
if not isinstance(k, DTensor):
k = DTensor.from_local(k, mesh, placement, run_check=False)
if not isinstance(v, DTensor):
v = DTensor.from_local(v, mesh, placement, run_check=False)
output = orig_fn(q, k, v, **kwargs)
return output.to_local() if isinstance(output, DTensor) else output
return cp_forward

was going to ask if you wanted that added, or an explicit ring-attention impl in titan

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 pretend there's no ring-attention impl.

For the all-gather one, is SDPA supported

  • for full bidirectional masking, if q (sharded) and kv (replicate) don't have the same length, would it just work? I think this is doable, but I'm not sure if sdpa supports that.
  • for full causal, would sharded q and replicate kv just work? I couldn't imagine how indices are aligned.

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.

if q (sharded) and kv (replicate) don't have the same length, would it just work?

Based on doc notation it seems supported... https://docs.pytorch.org/docs/2.12/generated/torch.nn.functional.scaled_dot_product_attention.html

for full causal, would sharded q and replicate kv just work? I couldn't imagine how indices are aligned.

is this concerning FLUX or something else? The callsites in FLUX should all be no-mask right, while other models are on Flex/VarLen I think?

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.

concerning something that doesn't exist in torchtitan

  • if someone uses torchtitan to experiment with causal sdpa with all-gather CP, would they get an error?
  • some graph trainer tests are still on SDPA I believe.

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.

cc @fegin , i'm not sure. I guess we could easily introduce a apply_cp_kv_allgather_to_forward

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.

Full causal won't work today without some mask/bias work. This only works for Flux because it doesn't use causal masks.


q, k = apply_rope(q, k, pe)
attn = self.inner_attention(q, k, v)
attn = self.inner_attention(q, k, v, is_causal=False)

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.

diffusion model?

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.

SelfAttention has this flag=False. I'm not sure why SingleStreamBlock and DoubleStreamBlock don't set it to False. Could you check BFL's official FLUX.1 implementation to 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.

@pianpwk
pianpwk marked this pull request as ready for review June 29, 2026 23:43

q, k = apply_rope(q, k, pe)
attn = self.inner_attention(q, k, v)
attn = self.inner_attention(q, k, v, is_causal=False)

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.

SelfAttention has this flag=False. I'm not sure why SingleStreamBlock and DoubleStreamBlock don't set it to False. Could you check BFL's official FLUX.1 implementation to confirm?

Comment on lines +64 to +66
["cp", "dp_shard", "dp_replicate"]
if config.parallelism.spmd_backend == "spmd_types"
else ["fsdp", "dp_replicate"]

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 there anything particular with the order? (it looks inner -> outer mesh ordered, not sure if matters)

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 the seed offset logic here wants innermost-dim first?

if distinct_seed_meshes:
# Each dimension contributes: local_rank * (product of all previous dimension sizes)
# This guarantees uniqueness like multi-dimensional array indexing
seed_offset = 0
cumulative_size = 1
for distinct_mesh in distinct_seed_meshes:
local_rank = distinct_mesh.get_local_rank()
# Add contribution from this dimension
seed_offset += local_rank * cumulative_size
# Update cumulative size for next dimension
cumulative_size *= distinct_mesh.size()
seed += seed_offset
seed %= 2**64

not 100% sure

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 order doesn't matter. This is used to guarantee that we will get different seed among these dimenions.

batch_type = {
DP: spmd.S(0),
CP: spmd.R,
}

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.

please verify that numerics doesn't change with DP & CP involved

Comment thread torchtitan/models/flux/model/layers.py Outdated
from torchtitan.models.common.attention import ScaledDotProductAttention
from torchtitan.models.common.nn_modules import GELU, LayerNorm, Linear, RMSNorm, SiLU
from torchtitan.models.flux.model.model import (
local_concat_text_image_attention_states,

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 not defining this function in this file? actually in the same forward where this function is used

Comment thread torchtitan/models/flux/model/model.py Outdated
return combined[:, :text_seq_len], combined[:, text_seq_len:]


@spmd.local_map(

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 using local_map, we should annotate in_types

However, according to our previous discussion, this could be an ad hoc local context (instead of introducing a function). Either way is fine to me.

Comment thread torchtitan/models/flux/model/model.py Outdated
return torch.cat((text, image), dim=1)


@spmd.local_map(

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.

similar

[ghstack-poisoned]
Comment thread torchtitan/models/flux/model/layers.py Outdated
),
out_types=spmd.PartitionSpec("dp", "cp", None, None),
)
def local_concat_text_image_attention_states(

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 within the function where it's used?

Comment thread torchtitan/models/flux/model/layers.py Outdated
),
out_types=spmd.PartitionSpec("dp", "cp", None),
)
def local_concat_text_image(text: torch.Tensor, image: torch.Tensor) -> torch.Tensor:

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.

similar

@@ -58,11 +60,16 @@ def __init__(self, config: Config):
# Set random seed, and maybe enable deterministic mode
# (mainly for debugging, expect perf loss).
# For Flux model, we need distinct seed across FSDP ranks to ensure we randomly dropout prompts info in dataloader

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.

See this comment:
given CP shards data after dataloading (this is TRUE, right??), I don't think we need to put CP in this list, regardless of spmd_types or DTensor.

So technically it should be [dp_shard, dp_replicate]

Comment thread torchtitan/models/flux/parallelize.py Outdated
dp_mesh_dims = None
assert dp_mesh is not None
if parallelism.spmd_backend == "spmd_types":
annotate_dp_cp_params_as_r(model, parallel_dims)

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.

wait, these should happen in set_sharding?

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.

where is this function? if you mean ShardingConfig-based, it's a bit plain to annotate everything as R@DP/CP

[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Jun 30, 2026
ghstack-source-id: 2711f29
Pull Request resolved: #3823
set_flux_inner_attention_local_map(block_cfg.inner_attention)


def annotate_dp_cp_params_as_r(model: nn.Module, parallel_dims: ParallelDims) -> 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.

Did you and Ed finally decided not to infer this automatically inside FSDP?

@pianpwk pianpwk Jun 30, 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.

No, we added it, but it only supports the partially-annotated case (TP is on, but not DP/CP), this is the totally unannotated case (param empty, need to look up spmd.current_mesh).

Started trying to extend this in pytorch

Comment thread torchtitan/models/flux/model/layers.py Outdated
),
out_types=spmd.PartitionSpec("dp", "cp", None, None),
)
def local_concat_text_image_attention_states(

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 @spmd.local_map not support annotating an inline embedded function?

If you have to put it as a separate function

Suggested change
def local_concat_text_image_attention_states(
def _local_concat_text_image_attention_states(

[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Jun 30, 2026
ghstack-source-id: 4d62594
Pull Request resolved: #3823
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Jul 1, 2026
ghstack-source-id: 60c4ba3
Pull Request resolved: #3823
Comment thread torchtitan/models/flux/model/model.py Outdated
),
out_types=spmd.PartitionSpec("dp", "cp", None),
)
def local_concat_text_image(text: Tensor, image: Tensor) -> Tensor:

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
def local_concat_text_image(text: Tensor, image: Tensor) -> Tensor:
def _local_concat_text_image(text: Tensor, image: Tensor) -> Tensor:

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.

btw could you answer my question?

Does @spmd.local_map not support annotating an inline embedded function?

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 sorry, dropped a change. should be fine

@pianpwk
pianpwk changed the base branch from gh/pianpwk/58/base to main July 1, 2026 00:44
@pianpwk
pianpwk changed the base branch from main to gh/pianpwk/58/base July 1, 2026 00:45
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Jul 1, 2026
ghstack-source-id: ff75f27
Pull Request resolved: #3823
@pianpwk
pianpwk changed the base branch from gh/pianpwk/58/base to main July 1, 2026 02:28
@pianpwk
pianpwk merged commit 9524278 into main Jul 1, 2026
8 of 11 checks passed
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Jul 15, 2026
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.

3 participants