Skip to content

Compile fails on Flex attention + FSDP #134739

@platers

Description

@platers

🐛 Describe the bug

Flex attention on FSDP works without compile, but not with compile. The key error seems to be ValueError: Pointer argument (at 2) cannot be accessed from Triton (cpu tensor?). It also works without a block_mask.

Error logs

-> % torchrun  --nproc_per_node=2 flex_fsdp.py
W0829 00:56:14.552000 680552 torch/distributed/run.py:793] 
W0829 00:56:14.552000 680552 torch/distributed/run.py:793] *****************************************
W0829 00:56:14.552000 680552 torch/distributed/run.py:793] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. 
W0829 00:56:14.552000 680552 torch/distributed/run.py:793] *****************************************
skipping cudagraphs due to skipping cudagraphs due to multiple devices: device(type='cuda', index=1), device(type='cuda', index=0)
[rank1]: Traceback (most recent call last):
[rank1]:   File "[REDACTED]/flex_fsdp.py", line 56, in <module>
[rank1]:     
[rank1]:   File "[REDACTED]/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
[rank1]:     return self._call_impl(*args, **kwargs)
[rank1]:   File "[REDACTED]/torch/nn/modules/module.py", line 1747, in _call_impl
[rank1]:     return forward_call(*args, **kwargs)
[rank1]:   File "[REDACTED]/torch/distributed/fsdp/fully_sharded_data_parallel.py", line 864, in forward
[rank1]:     output = self._fsdp_wrapped_module(*args, **kwargs)
[rank1]:   File "[REDACTED]/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
[rank1]:     return self._call_impl(*args, **kwargs)
[rank1]:   File "[REDACTED]/torch/nn/modules/module.py", line 1747, in _call_impl
[rank1]:     return forward_call(*args, **kwargs)
[rank1]:   File "[REDACTED]/torch/_dynamo/eval_frame.py", line 465, in _fn
[rank1]:     return fn(*args, **kwargs)
[rank1]:   File "[REDACTED]/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
[rank1]:     return self._call_impl(*args, **kwargs)
[rank1]:   File "[REDACTED]/torch/nn/modules/module.py", line 1747, in _call_impl
[rank1]:     return forward_call(*args, **kwargs)
[rank1]:   File "[REDACTED]/flex_fsdp.py", line 23, in forward
[rank1]:     def forward(self, x):
[rank1]:   File "[REDACTED]/torch/_dynamo/eval_frame.py", line 632, in _fn
[rank1]:     return fn(*args, **kwargs)
[rank1]:   File "[REDACTED]/torch/_functorch/aot_autograd.py", line 1100, in forward
[rank1]:     return compiled_fn(full_args)
[rank1]:   File "[REDACTED]/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 308, in runtime_wrapper
[rank1]:     all_outs = call_func_at_runtime_with_args(
[rank1]:   File "[REDACTED]/torch/_functorch/_aot_autograd/utils.py", line 124, in call_func_at_runtime_with_args
[rank1]:     out = normalize_as_list(f(args))
[rank1]:   File "[REDACTED]/torch/_functorch/_aot_autograd/utils.py", line 98, in g
[rank1]:     return f(*args)
[rank1]:   File "[REDACTED]/torch/autograd/function.py", line 575, in apply
[rank1]:     return super().apply(*args, **kwargs)  # type: ignore[misc]
[rank1]:   File "[REDACTED]/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 1525, in forward
[rank1]:     fw_outs = call_func_at_runtime_with_args(
[rank1]:   File "[REDACTED]/torch/_functorch/_aot_autograd/utils.py", line 124, in call_func_at_runtime_with_args
[rank1]:     out = normalize_as_list(f(args))
[rank1]:   File "[REDACTED]/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 488, in wrapper
[rank1]:     return compiled_fn(runtime_args)
[rank1]:   File "[REDACTED]/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 667, in inner_fn
[rank1]:     outs = compiled_fn(args)
[rank1]:   File "[REDACTED]/torch/_inductor/codecache.py", line 1464, in __call__
[rank1]:     return self.current_callable(inputs)
[rank1]:   File "[REDACTED]/torch/_inductor/utils.py", line 1954, in run
[rank1]:     return model(new_inputs)
[rank1]:   File "[REDACTED]/torchinductor_victor/wj/cwjdqvgoke23vff3px7gsasmyalyiwh5hxpqyks5gmydiuy4z45h.py", line 624, in call
[rank1]:     triton_tem_fused_0.run(primals_1, buf0, primals_2, primals_3, primals_4, primals_5, buf1, grid=torch._inductor.kernel.flex_attention.flex_attention_grid(1, 2, 256, 64, meta0), stream=stream1)
[rank1]:   File "[REDACTED]/torch/_inductor/runtime/triton_heuristics.py", line 884, in run
[rank1]:     return launcher(
[rank1]:   File "<string>", line 13, in launcher
[rank1]:   File "[REDACTED]/triton/backends/nvidia/driver.py", line 365, in __call__
[rank1]:     self.launch(*args, **kwargs)
[rank1]: ValueError: Pointer argument (at 2) cannot be accessed from Triton (cpu tensor?)
W0829 00:56:24.984000 680552 torch/distributed/elastic/multiprocessing/api.py:890] Sending process 681845 closing signal SIGTERM
E0829 00:56:25.150000 680552 torch/distributed/elastic/multiprocessing/api.py:862] failed (exitcode: 1) local_rank: 1 (pid: 681849) of binary: [REDACTED]/python
Traceback (most recent call last):
  File "[REDACTED]/torchrun", line 8, in <module>
    sys.exit(main())
  File "[REDACTED]/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 355, in wrapper
    return f(*args, **kwargs)
  File "[REDACTED]/torch/distributed/run.py", line 919, in main
    run(args)
  File "[REDACTED]/torch/distributed/run.py", line 910, in run
    elastic_launch(
  File "[REDACTED]/torch/distributed/launcher/api.py", line 138, in __call__
    return launch_agent(self._config, self._entrypoint, list(args))
  File "[REDACTED]/torch/distributed/launcher/api.py", line 269, in launch_agent
    raise ChildFailedError(
torch.distributed.elastic.multiprocessing.errors.ChildFailedError: 
============================================================
flex_fsdp.py FAILED
------------------------------------------------------------
Failures:
  <NO_OTHER_FAILURES>
------------------------------------------------------------
Root Cause (first observed failure):
[0]:
  time      : 2024-08-29_00:56:24
  host      : compute-h100-ord-node-13.local.vcn
  rank      : 1 (local_rank: 1)
  exitcode  : 1 (pid: 681849)
  error_file: <N/A>
  traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html
============================================================

Minified repro

import torch
import torch.nn as nn
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.nn.attention.flex_attention import flex_attention, create_block_mask

torch.set_default_device("cuda")


def sliding_window(b, h, q_idx, kv_idx):
    return q_idx - kv_idx <= 128


B, S, H, D = 1, 256, 2, 64
d_model = H * D  # Total model dimension
block_mask = create_block_mask(sliding_window, B=None, H=None, Q_LEN=S, KV_LEN=S)


class TransformerBlock(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        # Self-attention
        B, S, _ = x.shape
        x_reshaped = x.view(B, S, H, D).transpose(1, 2)
        attn_output = flex_attention(
            x_reshaped, x_reshaped, x_reshaped, block_mask=block_mask
        )
        x = x + attn_output.sum()

        return x


# Initialize distributed environment
torch.distributed.init_process_group(backend="nccl")
torch.cuda.set_device(torch.distributed.get_rank())

# Create and wrap the model with FSDP
model = TransformerBlock()

model = torch.compile(model, mode="reduce-overhead", dynamic=False)

fsdp_model = FSDP(
    model,
    use_orig_params=True,
    mixed_precision=torch.distributed.fsdp.MixedPrecision(
        param_dtype=torch.float16,
        reduce_dtype=torch.float16,
        buffer_dtype=torch.float16,
    ),
)

# Create input tensor
x = torch.randn(B, S, d_model, device="cuda", dtype=torch.float16, requires_grad=True)

# Forward pass with FSDP
output = fsdp_model(x)

# Backward pass
output.sum().backward()

# Check gradients
print("Gradients computed:")
print(f"x.grad is not None: {x.grad is not None}")

# Print model parameters
for name, param in fsdp_model.named_parameters():
    if param.grad is not None:
        print(f"{name} has gradients")
    else:
        print(f"{name} has no gradients")

# Clean up
torch.distributed.destroy_process_group()

Run with torchrun --nproc_per_node=2 flex_fsdp.py

Versions

python3 collect_env.py
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 23357  100 23357    0     0   105k      0 --:--:-- --:--:-- --:--:--  106k
/home/victor/anaconda3/envs/flex/lib/python3.10/site-packages/torch/_subclasses/functional_tensor.py:271: UserWarning: Failed to initialize NumPy: No module named 'numpy' (Triggered internally at ../torch/csrc/utils/tensor_numpy.cpp:84.)
  cpu = _conversion_method_template(device=torch.device("cpu"))
Collecting environment information...
PyTorch version: 2.5.0.dev20240827+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
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.10.14 (main, May  6 2024, 19:42:50) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.5.0-1018-oracle-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.5.119
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.161.07
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.7
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:                      46 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             224
On-line CPU(s) list:                0-111
Off-line CPU(s) list:               112-223
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Platinum 8480+
CPU family:                         6
Model:                              143
Thread(s) per core:                 1
Core(s) per socket:                 56
Socket(s):                          2
Stepping:                           8
CPU max MHz:                        3800.0000
CPU min MHz:                        0.0000
BogoMIPS:                           4000.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 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 hwp hwp_act_window hwp_epp hwp_pkg_req 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:                          5.3 MiB (112 instances)
L1i cache:                          3.5 MiB (112 instances)
L2 cache:                           224 MiB (112 instances)
L3 cache:                           210 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-55
NUMA node1 CPU(s):                  56-111
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:    Vulnerable
Vulnerability Spectre v1:           Vulnerable: __user pointer sanitization and usercopy barriers only; no swapgs barriers
Vulnerability Spectre v2:           Vulnerable, IBPB: disabled, STIBP: disabled, PBRSB-eIBRS: Vulnerable
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] pytorch-triton==3.0.0+dedb7bdf33
[pip3] torch==2.5.0.dev20240827+cu121
[conda] pytorch-triton            3.0.0+dedb7bdf33          pypi_0    pypi
[conda] torch                     2.5.0.dev20240827+cu121          pypi_0    pypi

cc @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o @zhaojuanmao @mrshenli @rohan-varma @chauhang @penguinwu @zou3519 @ydwu4 @bdhirsh @yf225 @Chillee @drisspg @yanboliang @BoyuanFeng @XilunWu @ezyang

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions