Skip to content

Add Flex flash backend to flex attention module - #2171

Closed
drisspg wants to merge 1 commit into
mainfrom
drisspg/stack/4
Closed

drisspg wants to merge 1 commit into
mainfrom
drisspg/stack/4

Conversation

@drisspg

@drisspg drisspg commented Dec 22, 2025 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


Summary

command

torchrun --nproc_per_node=1 -m torchtitan.train \
    --job.config-file torchtitan/models/llama3/train_configs/debug_model.toml \
    --model.flavor debugmodel_flex_flash \
    --profiling.enable_profiling \
    --profiling.save_traces_folder ./traces_flash \
    --profiling.profile_freq 5

Misc things

"""
Reproduction: 2D tensor indexing in mask_mod causes ~3.5x slowdown with FLASH backend

When using `tensor[b, idx]` inside a mask_mod, FLASH is ~3.5x slower than
equivalent 1D indexing `tensor_flat[b * S + idx]`. Both produce identical results.

To run: python issue_repro_2d_indexing.py
"""

import torch
from torch.nn.attention.flex_attention import flex_attention, create_block_mask

torch._dynamo.config.automatic_dynamic_shapes = False
flex_compiled = torch.compile(flex_attention)
create_block_mask_compiled = torch.compile(create_block_mask)


def benchmark(fn, warmup=3, iters=100):
    for _ in range(warmup):
        fn()
    torch.cuda.synchronize()

    start = torch.cuda.Event(enable_timing=True)
    end = torch.cuda.Event(enable_timing=True)
    start.record()
    for _ in range(iters):
        fn()
    end.record()
    torch.cuda.synchronize()
    return start.elapsed_time(end) / iters * 1000  # μs


def main():
    B, S, H, D = 8, 8192, 2, 128

    # Create per-batch document IDs (simulating document masking)
    torch.manual_seed(42)
    sequence_indices = torch.zeros(B, S, dtype=torch.int32, device="cuda")
    for b in range(B):
        num_docs = torch.randint(5, 12, (1,)).item()
        eos_positions = torch.sort(torch.randint(100, S - 100, (num_docs,)))[0]
        doc_id, prev = 0, 0
        for pos in eos_positions:
            sequence_indices[b, prev:pos+1] = doc_id
            doc_id += 1
            prev = pos + 1
        sequence_indices[b, prev:] = doc_id

    print(f"Config: B={B}, S={S}, H={H}, D={D}")
    print(f"Documents per sequence: {[(sequence_indices[b].max().item() + 1) for b in range(B)]}")

    def causal(b, h, q_idx, kv_idx):
        return q_idx >= kv_idx

    # 2D indexing (SLOW on FLASH)
    seq_idx_2d = sequence_indices
    def doc_mask_2d(b, h, q_idx, kv_idx):
        return seq_idx_2d[b, q_idx] == seq_idx_2d[b, kv_idx]
    def combined_2d(b, h, q_idx, kv_idx):
        return causal(b, h, q_idx, kv_idx) & doc_mask_2d(b, h, q_idx, kv_idx)

    # 1D flattened indexing (FAST on FLASH)
    seq_idx_flat = sequence_indices.flatten()
    def doc_mask_1d(b, h, q_idx, kv_idx):
        offset = b * S
        return seq_idx_flat[offset + q_idx] == seq_idx_flat[offset + kv_idx]
    def combined_1d(b, h, q_idx, kv_idx):
        return causal(b, h, q_idx, kv_idx) & doc_mask_1d(b, h, q_idx, kv_idx)

    block_mask_2d = create_block_mask_compiled(
        combined_2d, B=B, H=None, Q_LEN=S, KV_LEN=S, device="cuda", BLOCK_SIZE=(256, 128)
    )
    block_mask_1d = create_block_mask_compiled(
        combined_1d, B=B, H=None, Q_LEN=S, KV_LEN=S, device="cuda", BLOCK_SIZE=(256, 128)
    )

    # Correctness tests
    print(f"\nBlock mask sparsity: {block_mask_2d.sparsity():.2f}%")
    print(f"kv_num_blocks equal: {torch.equal(block_mask_2d.kv_num_blocks, block_mask_1d.kv_num_blocks)}")
    print(f"kv_indices equal: {torch.equal(block_mask_2d.kv_indices, block_mask_1d.kv_indices)}")
    assert torch.equal(block_mask_2d.kv_num_blocks, block_mask_1d.kv_num_blocks)
    assert torch.equal(block_mask_2d.kv_indices, block_mask_1d.kv_indices)

    q = torch.randn(B, S, H, D, device="cuda", dtype=torch.bfloat16).transpose(1, 2)
    k = torch.randn(B, S, H, D, device="cuda", dtype=torch.bfloat16).transpose(1, 2)
    v = torch.randn(B, S, H, D, device="cuda", dtype=torch.bfloat16).transpose(1, 2)

    out_2d = flex_compiled(q, k, v, block_mask=block_mask_2d, kernel_options={"BACKEND": "FLASH"})
    out_1d = flex_compiled(q, k, v, block_mask=block_mask_1d, kernel_options={"BACKEND": "FLASH"})
    print(f"Attention output max diff: {(out_2d - out_1d).abs().max().item():.2e}")
    assert torch.allclose(out_2d, out_1d, atol=1e-3, rtol=1e-3)

    # Benchmark
    print("\nBenchmark results:")
    results = {}
    for name, mask in [("2D [b, idx]", block_mask_2d), ("1D [b*S+idx]", block_mask_1d)]:
        for backend in ["FLASH", "TRITON"]:
            def run():
                return flex_compiled(q, k, v, block_mask=mask, kernel_options={"BACKEND": backend})
            time_us = benchmark(run)
            results[(name, backend)] = time_us
            print(f"  {name:15s} {backend:6s}: {time_us:8.2f} μs")

    flash_2d = results[("2D [b, idx]", "FLASH")]
    flash_1d = results[("1D [b*S+idx]", "FLASH")]
    print(f"\nFLASH slowdown from 2D indexing: {flash_2d / flash_1d:.2f}x")


if __name__ == "__main__":
    main()

for forward our 2d indexing code is surprisingly much slower than our 1d case, need to investigate, otherwise we are seein gmuch faster backward at 8192 ~2x for doc masking and equal for fwd. Having to bump the q_len doesnt help here, we are pretty much memory bound for these distributions since the block_mask is basically 80% sparse

A quick look in ncu shows we are register splilling like crazy

drisspg added a commit that referenced this pull request Dec 22, 2025
stack-info: PR: #2171, branch: drisspg/stack/4
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Dec 22, 2025
@drisspg
drisspg marked this pull request as draft December 22, 2025 20:48
drisspg added a commit that referenced this pull request Dec 22, 2025
stack-info: PR: #2171, branch: drisspg/stack/4
@drisspg
drisspg marked this pull request as ready for review December 22, 2025 20:48
Comment thread torchtitan/models/attention.py Outdated
)

def __init__(self, kernel_options: dict | None = None):
super().__init__()

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.

In theory this can/should be runtime args but for now Im just using for global defaults

Comment thread torchtitan/models/llama3/__init__.py Outdated
"debugmodel_flex_flash": TransformerModelArgs(
dim=256,
n_layers=6,
n_heads=2, # head_dim=128, required for Flash backend

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.

64 is also supported, but deepseek mla is currently not

Comment thread torchtitan/models/llama3/__init__.py Outdated
rope_theta=500000,
attn_type="flex",
attn_mask_type="block_causal",
flex_attention_kernel_options={"BACKEND": "FLASH"},

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 have two questions:

  1. what gpus can it run on? can it run on H100 / A100?
  2. if so, is it the most efficient kernel on all hardware?

Basically, I'd like to understand: as a user, when should I use what.

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.

yeah here is my current world model:
On B200 it is the fastest when its supported. The primary things that aren't supported and being worked on
-> Dynamic shapes (its on my list)
-> Learnable bias ( I dont think this applies for any titan models)
-> Head dim constraints (deepseek mla is not but can/should be)

For hopper it is generally faster but I have been mostly focusing on blackwell so I cant tell you definitively. And the backward needs to be implemented - I will do this. There is an A100 kernel but I would expect triton to be fine and maybe better since there is much more robust benchmarking.

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.

The other main requirement is that users need to have fa4 installed for this to work. it is very easy to install but still.

So in the future I might roll this into auto which is the current behavior, we make not promises if we lower to a triton impl or fa4. But I am mostly using this PR for testing right now

@Aneureka

Aneureka commented Dec 23, 2025 •

Copy link
Copy Markdown

Hi @drisspg, it looks like the slowdown in 2D tensor indexing within mask_mod is primarily due to the fact that we are re-computing the 2D index in a column-major order to make CuTe happy, e.g., (b, s) -> (b + s * B), which can lead to additional significant integer calculation instructions and increase register pressure.

However, CuTe DSL by design accepts hierarchical coordinates (e.g., __getitem__ of Tensor), so this re-computation is unnecessary. In fact, when passing the re-computed scalar index, CuTe DSL will need to convert it back to the hierarchical form to compute the offset (see the implementation of crd2idx).

In this fix, I changed _fixed_indexer_cute to return the index directly and tweaked ssa_to_indexable to accept a sequence of TensorSSA, after which I observed that 2D indexing performance roughly matched (~1.08x slower) 1D indexing. Could you apply the fix and try again? Note that this fix has not been thoroughly tested and may not be robust for all cases.

Thank you!

@drisspg

drisspg commented Dec 24, 2025

Copy link
Copy Markdown
Contributor Author

@Aneureka Thanks again for the tip, I put up: pytorch/pytorch#171222 and good tip on crd2idx My intuition was that under the hood things would need to be flattened, but I guess I was already thinking strided so this makes sense.

pytorchmergebot pushed a commit to pytorch/pytorch that referenced this pull request Dec 24, 2025
Running the old reproer, here: pytorch/torchtitan#2171

Before this PR

```Py
❯ python issue_repro_2d_indexing.py
Config: B=8, S=8192, H=2, D=128
Documents per sequence: [7, 11, 8, 7, 6, 7, 6, 11]

Block mask sparsity: 86.19%
kv_num_blocks equal: True
kv_indices equal: True
Attention output max diff: 0.00e+00

Benchmark results:
  2D [b, idx]     FLASH :  1468.33 μs
  2D [b, idx]     TRITON:   386.17 μs
  1D [b*S+idx]    FLASH :   467.82 μs
  1D [b*S+idx]    TRITON:   388.35 μs

```

After this PR
``` Py

Config: B=8, S=8192, H=2, D=128
Documents per sequence: [7, 11, 8, 7, 6, 7, 6, 11]

Block mask sparsity: 86.19%
kv_num_blocks equal: True
kv_indices equal: True
Attention output max diff: 0.00e+00

Benchmark results:
  2D [b, idx]     FLASH :   440.89 μs
  2D [b, idx]     TRITON:   386.76 μs
  1D [b*S+idx]    FLASH :   441.16 μs
  1D [b*S+idx]    TRITON:   390.21 μs

```

Thanks for the advice @Aneureka

Pull Request resolved: #171222
Approved by: https://github.com/henrylhtsang
@drisspg

drisspg commented Dec 29, 2025

Copy link
Copy Markdown
Contributor Author

Other perf issue with update: pytorch/pytorch#171267

krastogi-in pushed a commit to krastogi-in/pytorch that referenced this pull request Jan 9, 2026
Running the old reproer, here: pytorch/torchtitan#2171

Before this PR

```Py
❯ python issue_repro_2d_indexing.py
Config: B=8, S=8192, H=2, D=128
Documents per sequence: [7, 11, 8, 7, 6, 7, 6, 11]

Block mask sparsity: 86.19%
kv_num_blocks equal: True
kv_indices equal: True
Attention output max diff: 0.00e+00

Benchmark results:
  2D [b, idx]     FLASH :  1468.33 μs
  2D [b, idx]     TRITON:   386.17 μs
  1D [b*S+idx]    FLASH :   467.82 μs
  1D [b*S+idx]    TRITON:   388.35 μs

```

After this PR
``` Py

Config: B=8, S=8192, H=2, D=128
Documents per sequence: [7, 11, 8, 7, 6, 7, 6, 11]

Block mask sparsity: 86.19%
kv_num_blocks equal: True
kv_indices equal: True
Attention output max diff: 0.00e+00

Benchmark results:
  2D [b, idx]     FLASH :   440.89 μs
  2D [b, idx]     TRITON:   386.76 μs
  1D [b*S+idx]    FLASH :   441.16 μs
  1D [b*S+idx]    TRITON:   390.21 μs

```

Thanks for the advice @Aneureka

Pull Request resolved: pytorch#171222
Approved by: https://github.com/henrylhtsang
@drisspg

drisspg commented Jan 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Now that 4.3.5 is out and we updated it:

fwd:
image

BWD
image

Triton:
fwd
image

image

TODO:
Extra contiguous calls - this is expansion of blocksparse tensors since I needed this to work around a bug in the past, fwd perf is a lil low. Perhaps CLC will help here

drisspg added a commit that referenced this pull request Jan 12, 2026
stack-info: PR: #2171, branch: drisspg/stack/4
drisspg added a commit that referenced this pull request Jan 15, 2026
stack-info: PR: #2171, branch: drisspg/stack/4
drisspg added a commit that referenced this pull request Jan 20, 2026
stack-info: PR: #2171, branch: drisspg/stack/4
drisspg added a commit that referenced this pull request Mar 26, 2026
stack-info: PR: #2171, branch: drisspg/stack/4
Made-with: Cursor
@drisspg
drisspg marked this pull request as ready for review March 26, 2026 21:57
@drisspg
drisspg marked this pull request as draft March 27, 2026 01:01
@drisspg drisspg mentioned this pull request Mar 27, 2026
@drisspg
drisspg marked this pull request as ready for review March 27, 2026 01:01
@drisspg
drisspg marked this pull request as draft March 27, 2026 02:00
@drisspg
drisspg marked this pull request as ready for review March 27, 2026 02:00
attn_backend="flex",
attn_mask_type="block_causal",
rope_backend="complex",
flex_attention_kernel_options={"BACKEND": "FLASH"},

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.

when should we use Flash backend?

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.

should user config anything other than BACKEND?

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.

the currently supported backends, Literal["AUTO", "TRITON", "FLASH", "TRITON_DECODE"]
For training workloads auto is default and should be used. IN the future we might Allow for Auto to dispatch to FLASH but not yet since it does require changes to block mask sizes on blackwell

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.

@drisspg When should we use which? Depending on the answer we can provide the most reasonable UX in titan.

attn_mask_type="block_causal",
rope_backend="complex",
flex_attention_kernel_options={"BACKEND": "FLASH"},
flex_attention_block_size=(256, 128),

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.

should this be configured by user at all? what's the guidance?

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.

Yeah it should be, FWIW @liangel-02 will want something like this for the rl stuff.

In blackwell to use FLASH you will need at least* (256, 128) due to how the kernel works. But this in general is not a bitwise matching change. So for now making it very explicit

Comment thread torchtitan/models/common/attention.py Outdated
Comment on lines +555 to +556
flex_attention_kernel_options: dict | None = None
flex_attention_block_size: int | tuple[int, int] | None = 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.

This is violating encapsulation. Instead of hardcoding flex related fields in general GQAttention module, we should make inner_attention configurable.

@drisspg drisspg Mar 27, 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.

Sounds good, in general being able to impl specific options feels desirable

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 33s —— View job


Review: Add Flex flash backend to flex attention module

  • Read changed files and understand the diff
  • Review torchtitan/models/common/attention.py changes
  • Review torchtitan/models/common/decoder.py changes
  • Review torchtitan/models/llama3/__init__.py changes
  • Review torchtitan/models/llama3/config_registry.py changes
  • Check existing review comments and concerns
  • Post comprehensive review

Overview

This PR adds support for the FLASH backend in the flex attention module by threading kernel_options and BLOCK_SIZE through the config system to FlexAttentionWrapper and create_block_mask. It also adds a new debugmodel_flex_flash flavor for testing. There are several design and correctness issues to address.


Issue 1: Encapsulation violation in Decoder — cast to GQAttention.Config

File: torchtitan/models/common/decoder.py:181

I agree with @tianyu-l's existing review comment. The Decoder base class is used by Llama3, Llama4, Qwen3, DeepSeek-V3, and GPT-OSS. The _get_flex_attention_masks method now does:

attn_config = cast(GQAttention.Config, self.attn_config)
if attn_config.flex_attention_block_size is not None:
    kwargs["BLOCK_SIZE"] = attn_config.flex_attention_block_size

This is unsafe — self.attn_config is typed as BaseAttention.Config, and DeepSeek-V3 and GPT-OSS use their own Attention.Config subclasses that inherit from BaseAttention.Config directly, not from GQAttention.Config. If those models ever use flex backend, this cast would silently produce wrong behavior or AttributeError.

Recommendation: Either:

  1. Add flex_attention_block_size to BaseAttention.Config (since it's a general flex attention concern, not GQA-specific), or
  2. Use getattr(self.attn_config, 'flex_attention_block_size', None) for a safe duck-type check, or
  3. Make FlexAttentionWrapper own the block_size parameter (keeping it out of the attention config entirely), similar to how kernel_options is already passed to FlexAttentionWrapper.__init__.

Option 3 seems cleanest — BLOCK_SIZE is an implementation detail of block mask creation, and passing it through two layers of config to get to create_attention_mask is indirect.


Issue 2: flex_attention_kernel_options and flex_attention_block_size on GQAttention.Config — leaky abstraction

File: torchtitan/models/common/attention.py:555-556

These two fields are flex-backend-specific but live on GQAttention.Config, which also supports varlen and sdpa backends. There's no validation that these fields are only set when attn_backend="flex". A user could set flex_attention_kernel_options={"BACKEND": "FLASH"} with attn_backend="sdpa" and it would silently be ignored.

Per the project rules: "When a code path silently skips user configuration, emit a warning."

Recommendation: Add validation in __post_init__ — either error or warn when these flex-specific fields are set but attn_backend != "flex".

Fix this →


Issue 3: Unintentional change to debugmodel_flex_attn

File: torchtitan/models/llama3/__init__.py:73-81

The existing debugmodel_flex_attn config was changed from n_heads=16 to n_heads=2 and correspondingly dim=256 // 16 to dim=256 // 2 for RoPE. This is a significant behavioral change to an existing config that is used in CI integration tests. The PR description doesn't mention or justify this change.

On origin/main, debugmodel_flex_attn uses n_heads=16, rope.dim=256//16. This PR changes it to n_heads=2, rope.dim=256//2. This breaks the existing test config and changes what it validates.

Recommendation: Revert the debugmodel_flex_attn changes. If n_heads=2 is needed for FLASH backend testing, it's already in the new debugmodel_flex_flash config.

Fix this →


Issue 4: BLACKWELL_FLASH_BLOCK_SIZE exported but unused

File: torchtitan/models/common/attention.py:56,60

BLACKWELL_FLASH_BLOCK_SIZE is added to __all__ and defined as a module-level constant, but it's never referenced anywhere in the codebase. The debugmodel_flex_flash config hardcodes (256, 128) directly instead of using this constant.

Recommendation: Either use this constant in the config (e.g., flex_attention_block_size=BLACKWELL_FLASH_BLOCK_SIZE) or remove it. Dead code shouldn't be merged.


Issue 5: dict type for config field is not serialization-friendly

File: torchtitan/models/common/attention.py:555

flex_attention_kernel_options: dict | None = None

Using a bare dict as a dataclass field type is problematic for config serialization/deserialization (TOML, JSON) and for dataclasses.replace() (shallow copy — the dict is shared by reference, per project rules). Consider whether this should be a frozen dataclass or at minimum documented that mutation is unsafe.


Issue 6: Import ordering

File: torchtitan/models/common/decoder.py:14

from torchtitan.components.tokenizer import BaseTokenizer
from typing import cast

The typing import should come before third-party/local imports per standard Python convention (stdlib first). pre-commit may or may not catch this depending on isort config, but it's worth fixing.


Issue 7: Missing head_dim constraint documentation/validation for FLASH backend

The PR description and review comments mention that FLASH backend has head_dim constraints (64+ supported, DeepSeek MLA not yet supported). There's no validation that head_dim meets FLASH backend requirements. A user could configure flex_attention_kernel_options={"BACKEND": "FLASH"} with an unsupported head_dim and get a cryptic error at runtime.

Recommendation: Consider adding a validation check or at minimum a docstring on the config fields documenting the FLASH backend constraints.


Summary

The core functionality (threading kernel_options through to flex_attention and BLOCK_SIZE through to create_block_mask) is sound and straightforward. The main concerns are:

  1. The cast in decoder.py breaks the abstraction boundary of the Decoder base class (high severity)
  2. Unintentional change to debugmodel_flex_attn modifies existing CI test config without justification (high severity)
  3. No validation of flex-specific config fields when using non-flex backends (medium severity)
  4. BLACKWELL_FLASH_BLOCK_SIZE is dead code (low severity)
  5. dict config field needs care around shallow copy semantics (low severity)

stack-info: PR: #2171, branch: drisspg/stack/4
Made-with: Cursor
@drisspg
drisspg marked this pull request as draft March 27, 2026 02:34
@drisspg
drisspg marked this pull request as ready for review March 27, 2026 02:35
@wwwjn

wwwjn commented Mar 27, 2026

Copy link
Copy Markdown
Contributor

@drisspg Add an instruction for users , document when to use which

@drisspg

drisspg commented Mar 27, 2026

Copy link
Copy Markdown
Contributor Author

good question:

flash attention wheel

  • we dont require users to have flash_attn installed. if you try to use the FLASH backend without it, we error with a clear message telling you whats missing
  • its currently an optional runtime dep. theres a possibility we make it a full runtime dep of pytorch in the future but we're not doing that yet
  • It is however a pure python package that can be installed here: https://pypi.org/project/flash-attn-4/. Currently releasing beta wheels ever wednesday

when to use FLASH backend

  • if you're on Hopper or Blackwell, i'd recommend installing the wheel and using the FLASH backend. its basically always faster for training workloads, which are typically compute bound for almost every mask mod i've tested on both architectures
  • that said, its opt-in right now bc the newer code requires newer pytorch versions and is still very actively developed

block sizes

  • on Blackwell with BlockMask, we require larger block sizes (the (256, 128) you see in the config). this is bc the min tile size is dictated by what the flash attention kernel needs, so we're constrained there
  • being able to configure block sizes is useful regardless of which backend you're on tbh. people often autotune offline to find optimal block sizes and then bake those in so they skip runtime autotuning and get deterministic behavior

@tianyu-l

Copy link
Copy Markdown
Contributor

Thanks @drisspg ! If you don't mind, I'll take over and prepare a PR for this.

@drisspg drisspg closed this Mar 28, 2026
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Mar 28, 2026
tianyu-l added a commit that referenced this pull request Mar 31, 2026
for several things:
- Save a pair of transpose for varlen attention, by moving the transpose
for sdpa / flex inside their own module. I had to change
`_ContextParallel(seq_dim=2, ...)` to `seq_dim=1` -> I also had to
change flux model impl to adapt.
- The above change follows
#2709 which is only for the
generator. With this PR I'm able to remove `VLLMGQAttention` module
added in that PR.
- Make `inner_attention` a python config, instead of string
`attn_backend` which is now used in qwen3 `model_registry` as a
convenient way to switch config.
- Thanks to that, we can support FlexAttention with configurable
options, including `block_size` and `kernel_options` to enable Flash
attention backend #2171. Added
a config `qwen3_debugmodel_flex_flash` to the registry.
- Move `annotate_flex_attention_for_regional_inductor` from general
attention file to `graph_trainer` where it's used.
- remove outdated artificial restrictions on CP / CP + TP
- some naming improvement

NOTE:
- GraphTrainer tests fail on main as well
- Model test on Llama4+PP+compile fails on main as well
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
for several things:
- Save a pair of transpose for varlen attention, by moving the transpose
for sdpa / flex inside their own module. I had to change
`_ContextParallel(seq_dim=2, ...)` to `seq_dim=1` -> I also had to
change flux model impl to adapt.
- The above change follows
pytorch#2709 which is only for the
generator. With this PR I'm able to remove `VLLMGQAttention` module
added in that PR.
- Make `inner_attention` a python config, instead of string
`attn_backend` which is now used in qwen3 `model_registry` as a
convenient way to switch config.
- Thanks to that, we can support FlexAttention with configurable
options, including `block_size` and `kernel_options` to enable Flash
attention backend pytorch#2171. Added
a config `qwen3_debugmodel_flex_flash` to the registry.
- Move `annotate_flex_attention_for_regional_inductor` from general
attention file to `graph_trainer` where it's used.
- remove outdated artificial restrictions on CP / CP + TP
- some naming improvement

NOTE:
- GraphTrainer tests fail on main as well
- Model test on Llama4+PP+compile fails on main as well
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
for several things:
- Save a pair of transpose for varlen attention, by moving the transpose
for sdpa / flex inside their own module. I had to change
`_ContextParallel(seq_dim=2, ...)` to `seq_dim=1` -> I also had to
change flux model impl to adapt.
- The above change follows
pytorch#2709 which is only for the
generator. With this PR I'm able to remove `VLLMGQAttention` module
added in that PR.
- Make `inner_attention` a python config, instead of string
`attn_backend` which is now used in qwen3 `model_registry` as a
convenient way to switch config.
- Thanks to that, we can support FlexAttention with configurable
options, including `block_size` and `kernel_options` to enable Flash
attention backend pytorch#2171. Added
a config `qwen3_debugmodel_flex_flash` to the registry.
- Move `annotate_flex_attention_for_regional_inductor` from general
attention file to `graph_trainer` where it's used.
- remove outdated artificial restrictions on CP / CP + TP
- some naming improvement

NOTE:
- GraphTrainer tests fail on main as well
- Model test on Llama4+PP+compile fails on main as well
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

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants