pytorch - 💡(How to fix) Fix Flex Attention produces NaN with `torch.compile(flex_attention, dynamic=True)` and batch-dependent mask closures

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…

Error Message

Error logs

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 52 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 192 On-line CPU(s) list: 0-191 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Platinum 8469C CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 48 Socket(s): 2 Stepping: 8 CPU(s) scaling MHz: 82% CPU max MHz: 3800.0000 CPU min MHz: 800.0000 BogoMIPS: 5200.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 intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm 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 hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm uintr md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 4.5 MiB (96 instances) L1i cache: 3 MiB (96 instances) L2 cache: 192 MiB (96 instances) L3 cache: 195 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-47,96-143 NUMA node1 CPU(s): 48-95,144-191 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 store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Code Example

MOD_VISUAL = 0   # visual token
MOD_TEXT   = 1   # question text token
MOD_ANSWER = 2   # answer text token

def create_mf_mask(sample_id_map, modality_map):
    def mask_mod(b, h, q_idx, kv_idx):
        same_sample = sample_id_map[q_idx] == sample_id_map[kv_idx]
        q_is_visual = modality_map[q_idx] == MOD_VISUAL
        kv_is_visual = modality_map[kv_idx] == MOD_VISUAL
        kv_is_question = modality_map[kv_idx] == MOD_TEXT

        past_causal = q_idx >= kv_idx
        future_v2v = (q_idx < kv_idx) & q_is_visual & kv_is_visual
        future_v2q = (q_idx < kv_idx) & q_is_visual & kv_is_question

        return same_sample & (past_causal | future_v2v | future_v2q)
    return mask_mod

---

B, L, H, D = query_states.shape

q = query_states.transpose(1, 2)  # [B, H, L, D]
k = key_states.transpose(1, 2)
v = value_states.transpose(1, 2)

mask_mod = create_mf_mask(sample_id_map, modality_map)

block_mask = create_block_mask(
    mask_mod,
    B=B,
    H=None,
    Q_LEN=L,    # L is varying per batch
    KV_LEN=L,
    BLOCK_SIZE=128,
    _compile=False,
)

compiled_flex_attn = torch.compile(
    flex_attention,
    fullgraph=True,
    dynamic=True,
)

attn_output = compiled_flex_attn(q, k, v, block_mask=block_mask)

---

2026-06-09 15:23:50,521 - pytorch_lightning.utilities.rank_zero - INFO - lightning_net_alignment.py:184 - Step [790/73000]: lr: 0.00005000, 0.00003675, 0.00003491, 0.00003317, 0.00003151, 0.00002994, 0.00002844, 0.00002702, 0.00002438, 0.00002438, 0.00002567, 0.00002438 Text_CrossEntropyLoss: 1.26553, total_loss: 1.26553, iter_time: 6.243, batch_size: 1
2026-06-09 15:24:33,887 - pytorch_lightning.utilities.rank_zero - INFO - lightning_net_alignment.py:184 - Step [800/73000]: lr: 0.00005000, 0.00003675, 0.00003491, 0.00003317, 0.00003151, 0.00002993, 0.00002844, 0.00002702, 0.00002438, 0.00002438, 0.00002567, 0.00002438 Text_CrossEntropyLoss: nan, total_loss: nan, iter_time: 5.099, batch_size: 1
2026-06-09 15:25:16,058 - pytorch_lightning.utilities.rank_zero - INFO - lightning_net_alignment.py:184 - Step [810/73000]: lr: 0.00005000, 0.00003675, 0.00003491, 0.00003317, 0.00003151, 0.00002993, 0.00002844, 0.00002702, 0.00002438, 0.00002438, 0.00002567, 0.00002438 Text_CrossEntropyLoss: nan, total_loss: nan, iter_time: 4.122, batch_size: 2
2026-06-09 15:25:59,638 - pytorch_lightning.utilities.rank_zero - INFO - lightning_net_alignment.py:184 - Step [820/73000]: lr: 0.00005000, 0.00003675, 0.00003491, 0.00003317, 0.00003151, 0.00002993, 0.00002844, 0.00002702, 0.00002438, 0.00002438, 0.00002567, 0.00002438 Text_CrossEntropyLoss: nan, total_loss: nan, iter_time: 4.033, batch_size: 2
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

When wrapping flex_attention with torch.compile(dynamic=True, fullgraph=True), we observe NaN in attention output during training with create_block_mask(_compile=False)

This suggests the compiled Triton kernel for flex_attention introduces a numerical bug ? when combined with:

  • dynamic=True (symbolic shapes)
  • fullgraph=True
  • Batch-dependent BlockMask (varying sparsity pattern per iteration)

Key Code

Mask (batch-dependent)

mf mask allows visual tokens to see future tokens (but not answer tokens):

MOD_VISUAL = 0   # visual token
MOD_TEXT   = 1   # question text token
MOD_ANSWER = 2   # answer text token

def create_mf_mask(sample_id_map, modality_map):
    def mask_mod(b, h, q_idx, kv_idx):
        same_sample = sample_id_map[q_idx] == sample_id_map[kv_idx]
        q_is_visual = modality_map[q_idx] == MOD_VISUAL
        kv_is_visual = modality_map[kv_idx] == MOD_VISUAL
        kv_is_question = modality_map[kv_idx] == MOD_TEXT

        past_causal = q_idx >= kv_idx
        future_v2v = (q_idx < kv_idx) & q_is_visual & kv_is_visual
        future_v2q = (q_idx < kv_idx) & q_is_visual & kv_is_question

        return same_sample & (past_causal | future_v2v | future_v2q)
    return mask_mod

BlockMask creation + compiled flex_attention

B, L, H, D = query_states.shape

q = query_states.transpose(1, 2)  # [B, H, L, D]
k = key_states.transpose(1, 2)
v = value_states.transpose(1, 2)

mask_mod = create_mf_mask(sample_id_map, modality_map)

block_mask = create_block_mask(
    mask_mod,
    B=B,
    H=None,
    Q_LEN=L,    # L is varying per batch
    KV_LEN=L,
    BLOCK_SIZE=128,
    _compile=False,
)

compiled_flex_attn = torch.compile(
    flex_attention,
    fullgraph=True,
    dynamic=True,
)

attn_output = compiled_flex_attn(q, k, v, block_mask=block_mask)

Error logs

2026-06-09 15:23:50,521 - pytorch_lightning.utilities.rank_zero - INFO - lightning_net_alignment.py:184 - Step [790/73000]: lr: 0.00005000, 0.00003675, 0.00003491, 0.00003317, 0.00003151, 0.00002994, 0.00002844, 0.00002702, 0.00002438, 0.00002438, 0.00002567, 0.00002438 Text_CrossEntropyLoss: 1.26553, total_loss: 1.26553, iter_time: 6.243, batch_size: 1
2026-06-09 15:24:33,887 - pytorch_lightning.utilities.rank_zero - INFO - lightning_net_alignment.py:184 - Step [800/73000]: lr: 0.00005000, 0.00003675, 0.00003491, 0.00003317, 0.00003151, 0.00002993, 0.00002844, 0.00002702, 0.00002438, 0.00002438, 0.00002567, 0.00002438 Text_CrossEntropyLoss: nan, total_loss: nan, iter_time: 5.099, batch_size: 1
2026-06-09 15:25:16,058 - pytorch_lightning.utilities.rank_zero - INFO - lightning_net_alignment.py:184 - Step [810/73000]: lr: 0.00005000, 0.00003675, 0.00003491, 0.00003317, 0.00003151, 0.00002993, 0.00002844, 0.00002702, 0.00002438, 0.00002438, 0.00002567, 0.00002438 Text_CrossEntropyLoss: nan, total_loss: nan, iter_time: 4.122, batch_size: 2
2026-06-09 15:25:59,638 - pytorch_lightning.utilities.rank_zero - INFO - lightning_net_alignment.py:184 - Step [820/73000]: lr: 0.00005000, 0.00003675, 0.00003491, 0.00003317, 0.00003151, 0.00002993, 0.00002844, 0.00002702, 0.00002438, 0.00002438, 0.00002567, 0.00002438 Text_CrossEntropyLoss: nan, total_loss: nan, iter_time: 4.033, batch_size: 2

Versions

PyTorch version: 2.8.0a0+5228986c39.nv25.06 Is debug build: False CUDA used to build PyTorch: 12.9 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.2 LTS (x86_64) GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0 Clang version: 18.1.3 (1ubuntu1) CMake version: version 3.31.6 Libc version: glibc-2.39

Python version: 3.12.3 (main, Feb 4 2025, 14:48:35) [GCC 13.3.0] (64-bit runtime) Python platform: Linux-5.10.134-16.3.al8.x86_64-x86_64-with-glibc2.39 Is CUDA available: True CUDA runtime version: 12.9.86 CUDA_MODULE_LOADING set to: LAZY GPU models and configuration: GPU 0: NVIDIA H800 GPU 1: NVIDIA H800 GPU 2: NVIDIA H800 GPU 3: NVIDIA H800 GPU 4: NVIDIA H800 GPU 5: NVIDIA H800 GPU 6: NVIDIA H800 GPU 7: NVIDIA H800

Nvidia driver version: 550.127.08 cuDNN version: Probably one of the following: /usr/lib/x86_64-linux-gnu/libcudnn.so.9.10.2 /usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.10.2 /usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.10.2 /usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.10.2 /usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.10.2 /usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.10.2 /usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.10.2 /usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.10.2 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: 52 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 192 On-line CPU(s) list: 0-191 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Platinum 8469C CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 48 Socket(s): 2 Stepping: 8 CPU(s) scaling MHz: 82% CPU max MHz: 3800.0000 CPU min MHz: 800.0000 BogoMIPS: 5200.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 intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm 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 hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm uintr md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 4.5 MiB (96 instances) L1i cache: 3 MiB (96 instances) L2 cache: 192 MiB (96 instances) L3 cache: 195 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-47,96-143 NUMA node1 CPU(s): 48-95,144-191 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 store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] intel-openmp==2021.4.0 [pip3] mkl==2021.1.1 [pip3] mkl-devel==2021.1.1 [pip3] mkl-include==2021.1.1 [pip3] mypy_extensions==1.1.0 [pip3] numpy==1.26.4 [pip3] nvidia-cuda-nvrtc-cu12==12.9.86 [pip3] nvidia-cudnn-frontend==1.12.0 [pip3] nvidia-nccl-cu12==2.27.7 [pip3] nvtx==0.2.11 [pip3] onnx==1.17.0 [pip3] onnx_graphsurgeon==0.5.8 [pip3] onnxruntime==1.17.0 [pip3] optree==0.16.0 [pip3] pynvjitlink==0.3.0 [pip3] pytorch-e2e-entry-point==0.0.1 [pip3] pytorch-lightning==2.3.0 [pip3] pytorch-triton==3.3.0+git96316ce52.nvinternal [pip3] tbb==2021.13.1 [pip3] torch==2.8.0a0+5228986c39.nv25.6 [pip3] torch_tensorrt==2.8.0a0 [pip3] torchao==0.11.0+git [pip3] torchdata==0.11.0 [pip3] torchmetrics==1.8.1 [pip3] torchprofile==0.0.4 [pip3] torchvision==0.22.0a0+95f10a4e [pip3] triton==3.2.0 [conda] Could not collect

cc @chauhang @penguinwu @ezyang @bobrenjc93 @aditvenk @laithsakka @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @aakhundov @coconutruben @jataylo @Chillee @drisspg @yanboliang @BoyuanFeng @liangel-02 @howardzhang-cv

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