Repository: pytorch
Issue: AoTInductor cumsum causes illegal memory access for large tensors
Labels: triaged,oncall: pt2,module: aotinductor

### 🐛 Describe the bug

Hello,
I found that when compiling torch.cumsum with AoTInductor a CUDA illegal memory access error gets thrown when the input tensor is large. This only happens with an AoT compiled model, and not with a JiT compiled model. 

This seems to happen with smaller tensors of double precision (works for length 1000, breaks for length 10000) than with float precision (works for length 100000, breaks for length 1000000).

The issue also seems to not only scale with the dimension along which the cumsum is taken. For example, taking the cumulative sum along dim 0 for a tensor of shape [100, 10000] and [1000, 100] works, but shape[1000, 1000] does not.

Code to reproduce:

```Python
import torch

class CumSum(torch.nn.Module):
    def __init__(self):
        super(CumSum, self).__init__()

    def forward(self, x):
        return torch.cumsum(x, dim=0)
    

def main():
    # illegal memory access for fp32
    inp_arr = torch.rand((1000000,)).cuda()
    # no issue for fp32
    # inp_arr = torch.rand((100000,)).cuda()
    
    # illegal memory access for fp64
    # inp_arr = torch.rand((10000,)).cuda().double()
    # no issue for fp64
    # inp_arr = torch.rand((1000,)).cuda().double()

    # illegal memory access, numel=1e6
    # inp_arr = torch.rand((100000, 10)).cuda()
    # illegal memory access, numel=1e6
    # inp_arr = torch.rand((1000, 1000)).cuda()
    # no issue, numel=1e6
    # inp_arr = torch.rand((100, 10000)).cuda()
    # no issue, numel=1e5
    # inp_arr = torch.rand((1000, 100)).cuda()

    cumsum_eager = CumSum()

    with torch.no_grad():
        so_path = torch._export.aot_compile(cumsum_eager, (inp_arr,))
    cumsum_aot_compiled = torch._export.aot_load(so_path, device="cuda")

    cumsum_jit_compiled = torch.compile(cumsum_eager)
    
    with torch.no_grad():
        for _ in range(100):
            out_eager = cumsum_eager(inp_arr)
            out_aot = cumsum_aot_compiled(inp_arr)
            out_jit = cumsum_jit_compiled(inp_arr)

            print(f"eager matches aot: {torch.allclose(out_eager, out_aot)}, max diff: {torch.abs(out_eager - out_aot).max()}")
            print(f"eager matches jit: {torch.allclose(out_eager, out_jit)}, max diff: {torch.abs(out_eager - out_jit).max()}")


if __name__ == "__main__":
    main()
```

Stacktrace when run with CUDA_LAUNCH_BLOCKING=1:
```
eager matches aot: True, max diff: 0.21875
eager matches jit: True, max diff: 0.34375
Error: CUDA driver error: an illegal memory access was encountered
Traceback (most recent call last):
  File "/.../test_cumsum.py", line 33, in <module>
    main()
  File "/.../test_cumsum.py", line 25, in main
    out_aot = cumsum_aot_compiled(inp_arr)
  File "/.../.local/lib/python3.10/site-packages/torch/_export/__init__.py", line 403, in optimized
    flat_outputs = runner.run(flat_inputs)  # type: ignore[attr-defined]
RuntimeError: run_func_( container_handle_, input_handles.data(), input_handles.size(), output_handles.data(), output_handles.size(), cuda_stream_handle, proxy_executor_handle_) API call failed at ../torch/csrc/inductor/aoti_runner/model_container_runner.cpp, line 75
Failed to destroy CUDA event in AOTInductor model: an illegal memory access was encountered
```

### Versions

PyTorch version: 2.3.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 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, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.15.153.1-microsoft-standard-WSL2-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.0.140
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA RTX A3000 Laptop GPU
Nvidia driver version: 537.79
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.8.0
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:                      39 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             16
On-line CPU(s) list:                0-15
Vendor ID:                          GenuineIntel
Model name:                         11th Gen Intel(R) Core(TM) i7-11850H @ 2.50GHz
CPU family:                         6
Model:                              141
Thread(s) per core:                 2
Core(s) per socket:                 8
Socket(s):                          1
Stepping:                           1
BogoMIPS:                           4992.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 arch_perfmon rep_good nopl xtopology tsc_reliable nonstop_tsc cpuid pni pclmulqdq ssse3 fma cx16 pdcm pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves avx512vbmi umip avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid fsrm avx512_vp2intersect md_clear flush_l1d arch_capabilities
Hypervisor vendor:                  Microsoft
Virtualization type:                full
L1d cache:                          384 KiB (8 instances)
L1i cache:                          256 KiB (8 instances)
L2 cache:                           10 MiB (8 instances)
L3 cache:                           24 MiB (1 instance)
Vulnerability Gather data sampling: Unknown: Dependent on hypervisor status
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:             Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow: 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] ament-flake8==0.12.11
[pip3] flake8==4.0.1
[pip3] numpy==1.26.4
[pip3] torch==2.3.1
[pip3] triton==2.3.1
[conda] Could not collect

cc @ezyang @anijain2305 @chauhang @penguinwu @desertfire @chenyang78