Repository: pytorch
Issue: Behavior Difference with Flex Attention + Sequence Packing
Labels: oncall: pt2,module: higher order operators,module: pt2-dispatcher,module: flex attention

### 🐛 Describe the bug

### Issue:
I'm observing odd attention map patterns in my flex attention sequence packing runs that aren't there on (what should be) identical F.SDPA runs:
  
F.SDPA maps at step 24k
![Image](https://github.com/user-attachments/assets/cb6cc80a-d73a-44c9-a9f0-b38b98814a3f)

Flex Attention maps a step 24K
 ![Image](https://github.com/user-attachments/assets/b979ef22-1b0d-4f2e-9634-953437e55288)

I created these maps with this function: https://gist.github.com/zaptrem/932adb082755574409e0084e8647757c

It calculates attention manually (so we can see the attention maps), compares the final result to that of Flex Attention to verify the maps are accurate, then plots them.

Here is the image it outputs while running it on my model:

![Image](https://github.com/user-attachments/assets/719b35bc-4683-48dd-9c10-26a51eac5324)

And here is the text it prints:
https://gist.github.com/zaptrem/cd8147ae21b569287dfa841eba519148


### Background:
- I'm training a causal transformer. In order to enable efficient training on variable sequence lengths I decided to add sequence packing with flex attention + BlockMasks.

- I trained two models for comparison: F.SDPA with batch size 44 where each sequence is 512 long, and Flex Attention batch size 22 where each sequence is length 1024 (two 512-long sequences packed together). Causal+document based BlockMasks are applied as specified here: https://gist.github.com/zaptrem/ddf6fb358104dda3866597ba1c34fa40
 
The losses are similar (flex attention is consistently slightly lower), but the attention masks are not and though it's hard to tell so early in training I believe the outputs are worse from the flex attention model.



### Versions

poetry run python collect_env.py 
Collecting environment information...
PyTorch version: 2.7.0.dev20250127+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

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

Python version: 3.11.11 (main, Dec  4 2024, 08:55:07) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.0-1023-aws-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA H100 80GB HBM3
GPU 1: NVIDIA H100 80GB HBM3
GPU 2: NVIDIA H100 80GB HBM3
GPU 3: NVIDIA H100 80GB HBM3
GPU 4: NVIDIA H100 80GB HBM3
GPU 5: NVIDIA H100 80GB HBM3
GPU 6: NVIDIA H100 80GB HBM3
GPU 7: NVIDIA H100 80GB HBM3

Nvidia driver version: 535.183.01
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      48 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             104
On-line CPU(s) list:                0-103
Vendor ID:                          GenuineIntel
Model name:                         Intel Xeon Processor (SapphireRapids)
CPU family:                         6
Model:                              143
Thread(s) per core:                 1
Core(s) per socket:                 104
Socket(s):                          1
Stepping:                           4
BogoMIPS:                           5600.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves avx_vnni avx512_bf16 wbnoinvd arat vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b fsrm md_clear serialize tsxldtrk avx512_fp16 arch_capabilities
Virtualization:                     VT-x
Hypervisor vendor:                  KVM
Virtualization type:                full
L1d cache:                          3.3 MiB (104 instances)
L1i cache:                          3.3 MiB (104 instances)
L2 cache:                           416 MiB (104 instances)
L3 cache:                           16 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-103
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:      Unknown: No mitigations
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 Syscall hardening, KVM SW loop
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] audio-diffusion-pytorch==0.1.3
[pip3] ema-pytorch==0.6.5
[pip3] numpy==1.26.4
[pip3] nvidia-cublas-cu12==12.4.5.8
[pip3] nvidia-cuda-cupti-cu12==12.4.127
[pip3] nvidia-cuda-nvrtc-cu12==12.4.127
[pip3] nvidia-cuda-runtime-cu12==12.4.127
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.2.1.3
[pip3] nvidia-curand-cu12==10.3.5.147
[pip3] nvidia-cusolver-cu12==11.6.1.9
[pip3] nvidia-cusparse-cu12==12.3.1.170
[pip3] nvidia-cusparselt-cu12==0.6.2
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.4.127
[pip3] onnxruntime==1.18.1
[pip3] pytorch-lightning==2.4.0
[pip3] pytorch-metric-learning==2.5.0
[pip3] pytorch-triton==3.2.0+gitb2684bf3
[pip3] torch==2.7.0.dev20250127+cu124
[pip3] torch-audiomentations==0.11.1
[pip3] torch-optimi==0.2.1
[pip3] torch-pitch-shift==1.2.4
[pip3] torch-stoi==0.2.3
[pip3] torchaudio==2.6.0.dev20250127+cu124
[pip3] torchcde==0.2.5
[pip3] torchcfm==1.0.5
[pip3] torchdiffeq==0.2.4
[pip3] torchdyn==1.0.6
[pip3] torchmetrics==1.4.0.post0
[pip3] torchsde==0.2.6
[pip3] torchvision==0.22.0.dev20250127+cu124
[pip3] triton==3.1.0
[conda] Could not collect

cc @chauhang @penguinwu @zou3519 @ydwu4 @bdhirsh @yf225 @Chillee @drisspg @yanboliang @BoyuanFeng