Repository: pytorch
Issue: torch.compile 100x slower than eager mode for torch.cumprod backward pass
Labels: module: autograd,triaged,actionable,oncall: pt2,module: inductor,module: pt2-dispatcher

### 🐛 Describe the bug


When using torch.compile on a model that includes the backward pass of torch.cumprod, the compiled version is significantly slower than the eager execution, especially for large input dimensions. The performance degradation appears to scale with the size of the dimension over which cumprod is computed.

## To Reproduce
```python
#!/usr/bin/env python3

# the dimention over which we compute cumprod
# larger number results in much slower compilation and execution
N_DIM = 8
print(f"Running with N_DIM={N_DIM}")

import torch
import torch.nn as nn
import time

if torch.cuda.is_available():
    torch.set_default_device('cuda')
    device = torch.device('cuda')
else:
    torch.set_default_device('cpu')
    device = torch.device('cpu')

N_REPEAT = 10
N_WARMUP = 2

class CumProdModule(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        a = torch.cumprod(x, dim=1)
        y = a.sum()
        return y

# e.g. (batch_size, sequence_length, features)
x = torch.rand(8, N_DIM, 5000, requires_grad=True)

model = CumProdModule()

def benchmark(model, x, n_repeat, n_warmup):
    # Warmup iterations
    for _ in range(n_warmup):
        y = model(x)
        y.backward()
    if torch.cuda.is_available():
        torch.cuda.synchronize()

    start_time = time.time()
    for _ in range(n_repeat):
        y = model(x)
        y.backward()
        if torch.cuda.is_available():
            torch.cuda.synchronize()
    end_time = time.time()

    return (end_time - start_time) / n_repeat

print(f"Running on {device}")
eager_time = benchmark(model, x, N_REPEAT, N_WARMUP)
print(f"Eager average time: {eager_time:.6f} seconds")

compiled_model = torch.compile(model, fullgraph=True)

compiled_time = benchmark(compiled_model, x, N_REPEAT, N_WARMUP)
print(f"Compiled average time: {compiled_time:.6f} seconds")
print(f"Compiled is {compiled_time / eager_time :.2f}x slower than eager")
```

Output:
```
Running with N_DIMS=2048
Running on cuda
Eager average time: 0.032862 seconds
Compiled average time: 1.431347 seconds
Compiled is 43.56x slower than eager
```
## Details

The issue seems to be due to decomposition of `cumprod_backward`.
for example a snippet of inductor post_grad graph looks like this
```python
class GraphModule(torch.nn.Module):
    def forward(self, primals_1: "f32[8, 32, 5000][160000, 5000, 1]cuda:0", tangents_1: "f32[][]cuda:0"):
        # File: /home/pi/usr/dev/python/tmp/torch_tests/slow_cumprod/./time_cumprod.py:26 in forward, code: y = a.sum()
        expand: "f32[8, 32, 5000][0, 0, 0]cuda:0" = torch.ops.aten.expand.default(tangents_1, [8, 32, 5000]);  tangents_1 = None

        # File: /home/pi/usr/dev/python/tmp/torch_tests/slow_cumprod/./time_cumprod.py:25 in forward, code: a = torch.cumprod(x, dim=1)
        full: "f32[1][1]cuda:0" = torch.ops.aten.full.default([1], 1, dtype = torch.float32, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)
        expand_1: "f32[8, 1, 5000][0, 1, 0]cuda:0" = torch.ops.aten.expand.default(full, [8, 1, 5000]);  full = None
        slice_1: "f32[8, 31, 5000][160000, 5000, 1]cuda:0" = torch.ops.aten.slice.Tensor(primals_1, 1, 1)
        cumprod_1: "f32[8, 31, 5000][155000, 5000, 1]cuda:0" = torch.ops.aten.cumprod.default(slice_1, 1);  slice_1 = None

        cat: "f32[8, 32, 5000][160000, 5000, 1]cuda:0" = torch.ops.aten.cat.default([expand_1, cumprod_1], 1);  expand_1 = cumprod_1 = None
        slice_2: "f32[8, 32, 5000][0, 0, 0]cuda:0" = torch.ops.aten.slice.Tensor(expand, 1, 0)
        mul_1: "f32[8, 32, 5000][160000, 5000, 1]cuda:0" = torch.ops.aten.mul.Tensor(slice_2, cat);  slice_2 = cat = None
        sum_2: "f32[8, 5000][5000, 1]cuda:0" = torch.ops.aten.sum.dim_IntList(mul_1, [1]);  mul_1 = None
        slice_3: "f32[8, 1, 5000][160000, 5000, 1]cuda:0" = torch.ops.aten.slice.Tensor(primals_1, 1, 0, 1)
        prod: "f32[8, 1, 5000][5000, 5000, 1]cuda:0" = torch.ops.aten.prod.dim_int(slice_3, 1, True);  slice_3 = None
        slice_4: "f32[8, 30, 5000][160000, 5000, 1]cuda:0" = torch.ops.aten.slice.Tensor(primals_1, 1, 2)
        cumprod_2: "f32[8, 30, 5000][150000, 5000, 1]cuda:0" = torch.ops.aten.cumprod.default(slice_4, 1);  slice_4 = None

        expand_2: "f32[8, 30, 5000][5000, 0, 1]cuda:0" = torch.ops.aten.expand.default(prod, [8, 30, 5000])
        mul_2: "f32[8, 30, 5000][150000, 5000, 1]cuda:0" = torch.ops.aten.mul.Tensor(expand_2, cumprod_2);  expand_2 = cumprod_2 = None
        cat_1: "f32[8, 31, 5000][155000, 5000, 1]cuda:0" = torch.ops.aten.cat.default([prod, mul_2], 1);  prod = mul_2 = None
        slice_5: "f32[8, 31, 5000][0, 0, 0]cuda:0" = torch.ops.aten.slice.Tensor(expand, 1, 1)
        mul_3: "f32[8, 31, 5000][155000, 5000, 1]cuda:0" = torch.ops.aten.mul.Tensor(slice_5, cat_1);  slice_5 = cat_1 = None
        sum_3: "f32[8, 5000][5000, 1]cuda:0" = torch.ops.aten.sum.dim_IntList(mul_3, [1]);  mul_3 = None
        slice_6: "f32[8, 2, 5000][160000, 5000, 1]cuda:0" = torch.ops.aten.slice.Tensor(primals_1, 1, 0, 2)
        prod_1: "f32[8, 1, 5000][5000, 5000, 1]cuda:0" = torch.ops.aten.prod.dim_int(slice_6, 1, True);  slice_6 = None
        slice_7: "f32[8, 29, 5000][160000, 5000, 1]cuda:0" = torch.ops.aten.slice.Tensor(primals_1, 1, 3)
        cumprod_3: "f32[8, 29, 5000][145000, 5000, 1]cuda:0" = torch.ops.aten.cumprod.default(slice_7, 1);  slice_7 = None

        expand_3: "f32[8, 29, 5000][5000, 0, 1]cuda:0" = torch.ops.aten.expand.default(prod_1, [8, 29, 5000])
        mul_4: "f32[8, 29, 5000][145000, 5000, 1]cuda:0" = torch.ops.aten.mul.Tensor(expand_3, cumprod_3);  expand_3 = cumprod_3 = None
        cat_2: "f32[8, 30, 5000][150000, 5000, 1]cuda:0" = torch.ops.aten.cat.default([prod_1, mul_4], 1);  prod_1 = mul_4 = None
        slice_8: "f32[8, 30, 5000][0, 0, 0]cuda:0" = torch.ops.aten.slice.Tensor(expand, 1, 2)
        mul_5: "f32[8, 30, 5000][150000, 5000, 1]cuda:0" = torch.ops.aten.mul.Tensor(slice_8, cat_2);  slice_8 = cat_2 = None
        sum_4: "f32[8, 5000][5000, 1]cuda:0" = torch.ops.aten.sum.dim_IntList(mul_5, [1]);  mul_5 = None
        slice_9: "f32[8, 3, 5000][160000, 5000, 1]cuda:0" = torch.ops.aten.slice.Tensor(primals_1, 1, 0, 3)
        prod_2: "f32[8, 1, 5000][5000, 5000, 1]cuda:0" = torch.ops.aten.prod.dim_int(slice_9, 1, True);  slice_9 = None
        slice_10: "f32[8, 28, 5000][160000, 5000, 1]cuda:0" = torch.ops.aten.slice.Tensor(primals_1, 1, 4)
        cumprod_4: "f32[8, 28, 5000][140000, 5000, 1]cuda:0" = torch.ops.aten.cumprod.default(slice_10, 1);  slice_10 = None
        
       # The pattern repeats, generating a block for each step in the cumprod.
```

- The generated graph seems to create a block for each element along the cumprod dimension (dim=1 in this case)

- This unrolling leads to increased compilation times and slower execution in the compiled model.

- One way to work around this is to introduce a graph break with torch._dynamo.disable. This works but of course not ideal for performance. Any other workaround ideas would be much appreciated.



## Request
Is there a way to prevent the decomposition of cumprod_backward during compilation so that the backward pass can remain efficient in the compiled model? Is it possible for torch.compile to automatically (or heuristically) decide on whether to decompose or not?

Attachments: [torch_trace_slow_cumprod.log](https://github.com/user-attachments/files/17045003/dedicated_log_torch_trace_twzmnd3p.log)

### Versions

```
Collecting environment information...
PyTorch version: 2.4.0
Is debug build: False
CUDA used to build PyTorch: 12.2
ROCM used to build PyTorch: N/A

OS: Gentoo Linux (x86_64)
GCC version: (GCC) 13.3.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.39

Python version: 3.11.9 (main, Apr  2 2024, 08:25:04) [GCC 13.3.0] (64-bit runtime)
Python platform: Linux-6.6.50-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4090
Nvidia driver version: 550.78
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, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               32
On-line CPU(s) list:                  0-31
Vendor ID:                            AuthenticAMD
Model name:                           AMD Ryzen 9 7950X3D 16-Core Processor
CPU family:                           25
Model:                                97
Thread(s) per core:                   2
Core(s) per socket:                   16
Socket(s):                            1
Stepping:                             2
CPU(s) scaling MHz:                   28%
CPU max MHz:                          5714.0000
CPU min MHz:                          400.0000
BogoMIPS:                             8399.91
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid overflow_recov succor smca fsrm flush_l1d amd_lbr_pmc_freeze
Virtualization:                       AMD-V
L1d cache:                            512 KiB (16 instances)
L1i cache:                            512 KiB (16 instances)
L2 cache:                             16 MiB (16 instances)
L3 cache:                             128 MiB (2 instances)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-31
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 Reg file data sampling: Not affected
Vulnerability Retbleed:               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; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] torch==2.4.0
[pip3] triton==3.0.0.post1
[conda] Could not collect
```


cc @ezyang @albanD @gqchen @pearu @nikitaved @soulitzer @Varal7 @xmfan @chauhang @penguinwu @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @yf225 @chenyang78 @kadeng @muchulee8 @ColinPeppler @amjames @desertfire @zou3519 @bdhirsh