pytorch - 💡(How to fix) Fix [2.10] [repro] torch.ops.aten._flash_attention_forward FlopCounterMode uses wrong permute, gets count wrong [9 comments, 3 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#178064Fetched 2026-04-08 01:12:21
View on GitHub
Comments
9
Participants
3
Timeline
21
Reactions
1
Author
Timeline (top)
commented ×9labeled ×4mentioned ×4subscribed ×4

Root Cause

if you're wondering "why would anybody use _flash_attention_forward", it's because it's a drop-in replacement for FA3 that supports varlen and participates in torch dispatch. it's how I access flop-counting.

Fix Action

Fix / Workaround

if you're wondering "why would anybody use _flash_attention_forward", it's because it's a drop-in replacement for FA3 that supports varlen and participates in torch dispatch. it's how I access flop-counting.

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 128 On-line CPU(s) list: 0-127 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Platinum 8462Y+ CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 32 Socket(s): 2 Stepping: 8 CPU max MHz: 4100.0000 CPU min MHz: 800.0000 BogoMIPS: 5600.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hfi vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 3 MiB (64 instances) L1i cache: 2 MiB (64 instances) L2 cache: 128 MiB (64 instances) L3 cache: 120 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126 NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127 Vulnerability Gather data sampling: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Code Example

from abc import ABC, abstractmethod
from typing import Optional

import torch
from torch import Tensor, nn, no_grad
from torch.nn.attention import SDPBackend, sdpa_kernel
from torch.nn.functional import mse_loss, scaled_dot_product_attention
from torch.testing import assert_close
from torch.utils.flop_counter import FlopCounterMode
from typing_extensions import override


class Attention(nn.Module, ABC):
    def __init__(
        self,
        in_dim: int,
        out_dim: int,
        heads: int,
        head_dim: int,
        device: Optional[torch.device | int | str] = None,
        dtype: Optional[torch.dtype] = None,
    ):
        self.call_super_init = True
        super().__init__()

        self.heads = heads
        self.head_dim = head_dim

        factory_kwargs = {"device": device, "dtype": dtype}
        self.qkv_proj = nn.Linear(in_features=in_dim, out_features=3 * heads * head_dim, bias=False, **factory_kwargs)
        self.o_proj = nn.Linear(in_features=heads * head_dim, out_features=out_dim, bias=False, **factory_kwargs)

    @abstractmethod
    def forward(self, x: Tensor) -> Tensor: ...


class SDPA(Attention):
    @override
    def forward(self, x: Tensor) -> Tensor:
        qkv: Tensor = self.qkv_proj(x)
        q, k, v = qkv.unflatten(-1, (3, self.heads, self.head_dim)).movedim(-4, -2).unbind(-4)
        attn = scaled_dot_product_attention(q, k, v)
        attn = attn.movedim(-2, -3).flatten(start_dim=-2)
        out = self.o_proj(attn)
        return out


class FA2(Attention):
    @override
    def forward(self, x: Tensor) -> Tensor:
        qkv: Tensor = self.qkv_proj(x)
        q, k, v = qkv.unflatten(-1, (3, self.heads, -1)).unbind(-3)
        attn: Tensor
        attn, _, _, _, _ = torch.ops.aten._flash_attention_forward(
            q,
            k,
            v,
            cum_seq_q=None,
            cum_seq_k=None,
            max_q=q.size(-2),
            max_k=k.size(-2),
            dropout_p=0.0,
            is_causal=False,
            return_debug_mask=False,
            scale=None,
            window_size_left=-1,
            window_size_right=-1,
        )
        attn = attn.flatten(start_dim=-2)
        out = self.o_proj(attn)
        return out


device = torch.device("cuda")
meta = torch.device("meta")
dtype = torch.float16
gen = torch.Generator(device)

head_dim = 128
heads = 8
model_dim = 320

sdpa = SDPA(
    in_dim=model_dim,
    out_dim=model_dim,
    heads=heads,
    head_dim=head_dim,
    device=meta,
    dtype=dtype,
)
fa2 = FA2(
    in_dim=model_dim,
    out_dim=model_dim,
    heads=heads,
    head_dim=head_dim,
    device=meta,
    dtype=dtype,
)
sdpa.to_empty(device=device)
fa2.to_empty(device=device)

with no_grad():
    for attn in (sdpa, fa2):
        for proj in (attn.qkv_proj, attn.o_proj):
            nn.init.normal_(proj.weight, std=proj.in_features**-0.5, generator=gen.manual_seed(42))


input = torch.randn((2, 1024, model_dim), device=device, dtype=dtype, generator=gen.manual_seed(42))
target = torch.randn((2, 1024, model_dim), device=device, dtype=dtype, generator=gen.manual_seed(41))

sdpa_fwd_flop_counter = FlopCounterMode(display=False)
with sdpa_fwd_flop_counter, sdpa_kernel(SDPBackend.FLASH_ATTENTION):
    sdpa_out: Tensor = sdpa(input)
sdpa_fwd_flops: int = sdpa_fwd_flop_counter.get_total_flops()

fa2_fwd_flop_counter = FlopCounterMode(display=False)
with fa2_fwd_flop_counter:
    fa2_out: Tensor = fa2(input)
fa2_fwd_flops: int = fa2_fwd_flop_counter.get_total_flops()

print("==testing fwd parity:==")

print(f"""SDPA fwd BFLOP: {sdpa_fwd_flops / 1000_000_000:.1f}
FA2  fwd BFLOP: {fa2_fwd_flops / 1000_000_000:.1f}""")
print(f"SDPA and FA2 fwd flop match: {fa2_fwd_flops == sdpa_fwd_flops}")

assert_close(sdpa_out, fa2_out)
print("SDPA and FA2 projections outputs are allclose")

print("==testing bwd parity:==")

sdpa_bwd_flop_counter = FlopCounterMode(display=False)
sdpa_loss: Tensor = mse_loss(sdpa_out, target)
with sdpa_bwd_flop_counter:
    sdpa_loss.backward()
sdpa_bwd_flops: int = sdpa_bwd_flop_counter.get_total_flops()

fa2_bwd_flop_counter = FlopCounterMode(display=False)
fa2_loss: Tensor = mse_loss(fa2_out, target)
with fa2_bwd_flop_counter:
    fa2_loss.backward()
fa2_bwd_flops: int = fa2_bwd_flop_counter.get_total_flops()

print(f"""SDPA bwd BFLOP: {sdpa_bwd_flops / 1000_000_000:.1f}
FA2  bwd BFLOP: {fa2_bwd_flops / 1000_000_000:.1f}""")
print(f"SDPA and FA2 bwd flop match: {fa2_bwd_flops == sdpa_bwd_flops}")

assert_close(sdpa.qkv_proj.weight.grad, fa2.qkv_proj.weight.grad)
assert_close(sdpa.o_proj.weight.grad, fa2.o_proj.weight.grad)
print("SDPA and FA2 grads are allclose")

---

==testing fwd parity:==
SDPA fwd BFLOP: 14.0
FA2  fwd BFLOP: 5.4
SDPA and FA2 fwd flop match: False
SDPA and FA2 projections outputs are allclose
==testing bwd parity:==
SDPA bwd BFLOP: 28.2
FA2  bwd BFLOP: 6.9
SDPA and FA2 bwd flop match: False
SDPA and FA2 grads are allclose

---

Collecting environment information...
PyTorch version: 2.10.0+cu128
Is debug build: False
CUDA used to build PyTorch: 12.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.5 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Mar  3 2026, 11:56:32) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.13-65-650-4141-22041-coreweave-amd64-85c45edc-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: 
GPU models and configuration: 
GPU 0: NVIDIA H100 80GB HBM3
GPU 1: NVIDIA H100 80GB HBM3

Nvidia driver version: 570.172.08
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.18.1
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Caching allocator config: N/A

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      46 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             128
On-line CPU(s) list:                0-127
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Platinum 8462Y+
CPU family:                         6
Model:                              143
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          2
Stepping:                           8
CPU max MHz:                        4100.0000
CPU min MHz:                        800.0000
BogoMIPS:                           5600.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hfi vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          3 MiB (64 instances)
L1i cache:                          2 MiB (64 instances)
L2 cache:                           128 MiB (64 instances)
L3 cache:                           120 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126
NUMA node1 CPU(s):                  1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] clip-anytorch==2.6.0
[pip3] dctorch==0.1.2
[pip3] DISTS_pytorch==0.1
[pip3] lovely-numpy==0.2.20
[pip3] mypy_extensions==1.1.0
[pip3] numpy==1.26.4
[pip3] nvidia-cublas-cu12==12.8.4.1
[pip3] nvidia-cuda-cupti-cu12==12.8.90
[pip3] nvidia-cuda-nvrtc-cu12==12.8.93
[pip3] nvidia-cuda-runtime-cu12==12.8.90
[pip3] nvidia-cudnn-cu12==9.10.2.21
[pip3] nvidia-cufft-cu12==11.3.3.83
[pip3] nvidia-curand-cu12==10.3.9.90
[pip3] nvidia-cusolver-cu12==11.7.3.90
[pip3] nvidia-cusparse-cu12==12.5.8.93
[pip3] nvidia-cusparselt-cu12==0.7.1
[pip3] nvidia-nccl-cu12==2.27.5
[pip3] nvidia-nvjitlink-cu12==12.8.93
[pip3] nvidia-nvtx-cu12==12.8.90
[pip3] open_clip_torch==3.3.0
[pip3] optree==0.19.0
[pip3] torch==2.10.0
[pip3] torch_c_dlpack_ext==0.1.5
[pip3] torchaudio==2.10.0
[pip3] torchdata==0.11.0
[pip3] torchdiffeq==0.2.5
[pip3] torchsde==0.2.6
[pip3] torchtitan==0.2.2
[pip3] torchvision==0.25.0
[pip3] triton==3.6.0
[pip3] welford-torch==0.2.5
[conda] Could not collect
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

torch.ops.aten._flash_attention_forward counts flops incorrectly.
its flop counter assumes that the dimensions will be supplied in (batch, heads, seq, dim) order like SDPA, but _flash_attention_forward actually requires (batch, seq, heads, dim) order.

this repro shows that SDPA (FA2 backend) and _flash_attention_forward can get allclose the same result and grads, but totally different flop counts:

from abc import ABC, abstractmethod
from typing import Optional

import torch
from torch import Tensor, nn, no_grad
from torch.nn.attention import SDPBackend, sdpa_kernel
from torch.nn.functional import mse_loss, scaled_dot_product_attention
from torch.testing import assert_close
from torch.utils.flop_counter import FlopCounterMode
from typing_extensions import override


class Attention(nn.Module, ABC):
    def __init__(
        self,
        in_dim: int,
        out_dim: int,
        heads: int,
        head_dim: int,
        device: Optional[torch.device | int | str] = None,
        dtype: Optional[torch.dtype] = None,
    ):
        self.call_super_init = True
        super().__init__()

        self.heads = heads
        self.head_dim = head_dim

        factory_kwargs = {"device": device, "dtype": dtype}
        self.qkv_proj = nn.Linear(in_features=in_dim, out_features=3 * heads * head_dim, bias=False, **factory_kwargs)
        self.o_proj = nn.Linear(in_features=heads * head_dim, out_features=out_dim, bias=False, **factory_kwargs)

    @abstractmethod
    def forward(self, x: Tensor) -> Tensor: ...


class SDPA(Attention):
    @override
    def forward(self, x: Tensor) -> Tensor:
        qkv: Tensor = self.qkv_proj(x)
        q, k, v = qkv.unflatten(-1, (3, self.heads, self.head_dim)).movedim(-4, -2).unbind(-4)
        attn = scaled_dot_product_attention(q, k, v)
        attn = attn.movedim(-2, -3).flatten(start_dim=-2)
        out = self.o_proj(attn)
        return out


class FA2(Attention):
    @override
    def forward(self, x: Tensor) -> Tensor:
        qkv: Tensor = self.qkv_proj(x)
        q, k, v = qkv.unflatten(-1, (3, self.heads, -1)).unbind(-3)
        attn: Tensor
        attn, _, _, _, _ = torch.ops.aten._flash_attention_forward(
            q,
            k,
            v,
            cum_seq_q=None,
            cum_seq_k=None,
            max_q=q.size(-2),
            max_k=k.size(-2),
            dropout_p=0.0,
            is_causal=False,
            return_debug_mask=False,
            scale=None,
            window_size_left=-1,
            window_size_right=-1,
        )
        attn = attn.flatten(start_dim=-2)
        out = self.o_proj(attn)
        return out


device = torch.device("cuda")
meta = torch.device("meta")
dtype = torch.float16
gen = torch.Generator(device)

head_dim = 128
heads = 8
model_dim = 320

sdpa = SDPA(
    in_dim=model_dim,
    out_dim=model_dim,
    heads=heads,
    head_dim=head_dim,
    device=meta,
    dtype=dtype,
)
fa2 = FA2(
    in_dim=model_dim,
    out_dim=model_dim,
    heads=heads,
    head_dim=head_dim,
    device=meta,
    dtype=dtype,
)
sdpa.to_empty(device=device)
fa2.to_empty(device=device)

with no_grad():
    for attn in (sdpa, fa2):
        for proj in (attn.qkv_proj, attn.o_proj):
            nn.init.normal_(proj.weight, std=proj.in_features**-0.5, generator=gen.manual_seed(42))


input = torch.randn((2, 1024, model_dim), device=device, dtype=dtype, generator=gen.manual_seed(42))
target = torch.randn((2, 1024, model_dim), device=device, dtype=dtype, generator=gen.manual_seed(41))

sdpa_fwd_flop_counter = FlopCounterMode(display=False)
with sdpa_fwd_flop_counter, sdpa_kernel(SDPBackend.FLASH_ATTENTION):
    sdpa_out: Tensor = sdpa(input)
sdpa_fwd_flops: int = sdpa_fwd_flop_counter.get_total_flops()

fa2_fwd_flop_counter = FlopCounterMode(display=False)
with fa2_fwd_flop_counter:
    fa2_out: Tensor = fa2(input)
fa2_fwd_flops: int = fa2_fwd_flop_counter.get_total_flops()

print("==testing fwd parity:==")

print(f"""SDPA fwd BFLOP: {sdpa_fwd_flops / 1000_000_000:.1f}
FA2  fwd BFLOP: {fa2_fwd_flops / 1000_000_000:.1f}""")
print(f"SDPA and FA2 fwd flop match: {fa2_fwd_flops == sdpa_fwd_flops}")

assert_close(sdpa_out, fa2_out)
print("SDPA and FA2 projections outputs are allclose")

print("==testing bwd parity:==")

sdpa_bwd_flop_counter = FlopCounterMode(display=False)
sdpa_loss: Tensor = mse_loss(sdpa_out, target)
with sdpa_bwd_flop_counter:
    sdpa_loss.backward()
sdpa_bwd_flops: int = sdpa_bwd_flop_counter.get_total_flops()

fa2_bwd_flop_counter = FlopCounterMode(display=False)
fa2_loss: Tensor = mse_loss(fa2_out, target)
with fa2_bwd_flop_counter:
    fa2_loss.backward()
fa2_bwd_flops: int = fa2_bwd_flop_counter.get_total_flops()

print(f"""SDPA bwd BFLOP: {sdpa_bwd_flops / 1000_000_000:.1f}
FA2  bwd BFLOP: {fa2_bwd_flops / 1000_000_000:.1f}""")
print(f"SDPA and FA2 bwd flop match: {fa2_bwd_flops == sdpa_bwd_flops}")

assert_close(sdpa.qkv_proj.weight.grad, fa2.qkv_proj.weight.grad)
assert_close(sdpa.o_proj.weight.grad, fa2.o_proj.weight.grad)
print("SDPA and FA2 grads are allclose")
==testing fwd parity:==
SDPA fwd BFLOP: 14.0
FA2  fwd BFLOP: 5.4
SDPA and FA2 fwd flop match: False
SDPA and FA2 projections outputs are allclose
==testing bwd parity:==
SDPA bwd BFLOP: 28.2
FA2  bwd BFLOP: 6.9
SDPA and FA2 bwd flop match: False
SDPA and FA2 grads are allclose

note that the FA2's bwd flop count isn't double its forward flop count, which to a first-order approximation might've been a reasonable expectation. whereas SDPA's is.

SDPA flop count reads its arguments correctly:
<img width="832" height="425" alt="Image" src="https://github.com/user-attachments/assets/927e0d93-2366-44e5-b87c-6a8a64b31a02" />

_flash_attention_forward flop count reads its arguments incorrectly:
<img width="780" height="440" alt="Image" src="https://github.com/user-attachments/assets/850f99c6-f69e-4221-bdea-f574c40c381d" />

if you're wondering "why would anybody use _flash_attention_forward", it's because it's a drop-in replacement for FA3 that supports varlen and participates in torch dispatch. it's how I access flop-counting.

so I can run a meta instance of my model under FlopCounterMode, which runs attention with exactly the same permutes as FA3 (minimizing how different I need to make my flop-count code to my real code).

Versions

Collecting environment information...
PyTorch version: 2.10.0+cu128
Is debug build: False
CUDA used to build PyTorch: 12.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.5 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Mar  3 2026, 11:56:32) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.13-65-650-4141-22041-coreweave-amd64-85c45edc-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: 
GPU models and configuration: 
GPU 0: NVIDIA H100 80GB HBM3
GPU 1: NVIDIA H100 80GB HBM3

Nvidia driver version: 570.172.08
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.18.1
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.18.1
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Caching allocator config: N/A

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      46 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             128
On-line CPU(s) list:                0-127
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Platinum 8462Y+
CPU family:                         6
Model:                              143
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          2
Stepping:                           8
CPU max MHz:                        4100.0000
CPU min MHz:                        800.0000
BogoMIPS:                           5600.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hfi vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          3 MiB (64 instances)
L1i cache:                          2 MiB (64 instances)
L2 cache:                           128 MiB (64 instances)
L3 cache:                           120 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126
NUMA node1 CPU(s):                  1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] clip-anytorch==2.6.0
[pip3] dctorch==0.1.2
[pip3] DISTS_pytorch==0.1
[pip3] lovely-numpy==0.2.20
[pip3] mypy_extensions==1.1.0
[pip3] numpy==1.26.4
[pip3] nvidia-cublas-cu12==12.8.4.1
[pip3] nvidia-cuda-cupti-cu12==12.8.90
[pip3] nvidia-cuda-nvrtc-cu12==12.8.93
[pip3] nvidia-cuda-runtime-cu12==12.8.90
[pip3] nvidia-cudnn-cu12==9.10.2.21
[pip3] nvidia-cufft-cu12==11.3.3.83
[pip3] nvidia-curand-cu12==10.3.9.90
[pip3] nvidia-cusolver-cu12==11.7.3.90
[pip3] nvidia-cusparse-cu12==12.5.8.93
[pip3] nvidia-cusparselt-cu12==0.7.1
[pip3] nvidia-nccl-cu12==2.27.5
[pip3] nvidia-nvjitlink-cu12==12.8.93
[pip3] nvidia-nvtx-cu12==12.8.90
[pip3] open_clip_torch==3.3.0
[pip3] optree==0.19.0
[pip3] torch==2.10.0
[pip3] torch_c_dlpack_ext==0.1.5
[pip3] torchaudio==2.10.0
[pip3] torchdata==0.11.0
[pip3] torchdiffeq==0.2.5
[pip3] torchsde==0.2.6
[pip3] torchtitan==0.2.2
[pip3] torchvision==0.25.0
[pip3] triton==3.6.0
[pip3] welford-torch==0.2.5
[conda] Could not collect

cc @drisspg @liangel-02 @howardzhang-cv

extent analysis

Fix Plan

To fix the incorrect flop count in _flash_attention_forward, we need to modify the function to correctly read its arguments.

The issue arises from the fact that _flash_attention_forward expects the dimensions in the order (batch, seq, heads, dim), but the flop counter assumes the order (batch, heads, seq, dim).

Here are the steps to fix the issue:

  • Modify the _flash_attention_forward function to correctly read its arguments.
  • Update the flop counter to match the correct order of dimensions.

Since the _flash_attention_forward function is a part of the PyTorch library, we cannot directly modify it. However, we can create a custom function that wraps around _flash_attention_forward and correctly reads its arguments.

Code Changes

import torch

def custom_flash_attention_forward(q, k, v, cum_seq_q=None, cum_seq_k=None, max_q=None, max_k=None, dropout_p=0.0, is_causal=False, return_debug_mask=False, scale=None, window_size_left=-1, window_size_right=-1):
    """
    Custom flash attention forward function that correctly reads its arguments.
    """
    # Transpose the input tensors to match the expected order
    q = q.transpose(1, 2)  # (batch, seq, heads, dim) -> (batch, heads, seq, dim)
    k = k.transpose(1, 2)  # (batch, seq, heads, dim) -> (batch, heads, seq, dim)
    v = v.transpose(1, 2)  # (batch, seq, heads, dim) -> (batch, heads, seq, dim)
    
    # Call the original _flash_attention_forward function
    attn, _, _, _, _ = torch.ops.aten._flash_attention_forward(
        q,
        k,
        v,
        cum_seq_q=cum_seq_q,
        cum_seq_k=cum_seq_k,
        max_q=max_q,
        max_k=max_k,
        dropout_p=dropout_p,
        is_causal=is_causal,
        return_debug_mask=return_debug_mask,
        scale=scale,
        window_size_left=window_size_left,
        window_size_right=window_size_right,
    )
    
    # Transpose the output tensor back to the original order
    attn = attn.transpose(1, 2)  # (batch, heads, seq, dim) -> (batch, seq, heads, dim)
    
    return attn

class FA2(Attention):
    @override
    def forward(self, x: Tensor) -> Tensor:
        qkv: Tensor = self.qkv_proj(x)
        q, k, v = qkv.unflatten(-1, (3, self.heads, -1)).unbind(-3)
        attn: Tensor
        attn = custom_flash_attention_forward(
            q,

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

pytorch - 💡(How to fix) Fix [2.10] [repro] torch.ops.aten._flash_attention_forward FlopCounterMode uses wrong permute, gets count wrong [9 comments, 3 participants]