Repository: pytorch
Issue: [PT2] torch.compile doesn't perform horizontal fusion
Labels: feature,triaged,oncall: pt2,module: inductor

### 🐛 Describe the bug

I wrote a program to test if PT2 will perform horizontal fusion for the split-cat horizontal fusion described in this [blog post](https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/).

Looking at the Kineto trace, I see that there was some vertical fusion of point-wise kernels, but no horizontal fusion.

### Error logs

_No response_

### Minified repro

```
import random
import sys

import torch
import torch._dynamo
import torch.nn as nn

from torch._inductor import config
from torch.profiler import ProfilerActivity
from torch._inductor import config as torchinductor_config


def trace_handler(prof):
    s_trace_link = ( "horizontal_issue_raw.json")
    prof.export_chrome_trace(s_trace_link)
    print("Trace link {}".format(s_trace_link))


def unfused(input_data, batch_size, input_dim, layer_norm, linear_layer):

    split_input_data = torch.split(input_data, batch_size * input_dim )
    norm_features = []
    for i in range(len(split_input_data)):
        # This conditional is enough to completely kill PT2's ability to fuse:
        # if i == 0:
        #     print(f"shape split_input_data[0] = {split_input_data[0].shape}")
        f = split_input_data[i]
        f_view = f.view([batch_size, input_dim])
        norm_f = layer_norm(f_view)
        tanh_norm_f = torch.tanh(norm_f)
        norm_features.append(tanh_norm_f)

    linear_input = torch.stack(norm_features)
    linear_output = linear_layer(linear_input)
    result = nn.functional.relu(linear_output)

    return result


def get_compiled_model(num_inputs, batch_size, input_dim, layer_norm, linear_layer):

    torchinductor_config.aggressive_fusion = True

    inputs = torch.rand(num_inputs * batch_size * input_dim, device='cuda:0') 
    compiled_unfused = torch.compile(unfused) 

    # Run warmup iterations.
    for _ in range(10):
        compiled_unfused(inputs, batch_size, input_dim, layer_norm, linear_layer)
    torch.cuda.synchronize()

    return compiled_unfused


def run_example_pt2():
    
    num_inputs = 16
    batch_size = 2**16
    input_dim = 128

    layer_norm = torch.nn.LayerNorm(input_dim, eps=0.0, elementwise_affine=False, device='cuda:0')
    linear_layer = nn.Linear(input_dim, 1, device='cuda:0')

    config.triton.unique_kernel_names = True
    config.triton.descriptive_names = "torch"

    compiled_unfused = get_compiled_model(num_inputs, batch_size, input_dim, layer_norm, linear_layer)

    inputs = torch.rand(num_inputs * batch_size * input_dim, device='cuda:0')

    # Use PyTorch profiler to collect a trace.
    with torch.profiler.profile(
        with_stack=True,
        record_shapes=True,
        activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
        on_trace_ready=trace_handler,
    ):
        # Run the model without horizontally fused layer norm.
        pred1 = unfused(inputs, batch_size, input_dim, layer_norm, linear_layer)
        torch.cuda.synchronize()

        # Run the compiled version of the unfused function.
        pred3 = compiled_unfused(inputs, batch_size, input_dim, layer_norm, linear_layer)
        torch.cuda.synchronize()


def main(argv):
    # Run multiple times to get more warmups (trace will be from last call).
    run_example_pt2()
    run_example_pt2()
    run_example_pt2()
    run_example_pt2()


if __name__ == "__main__":
    main(sys.argv[1:])
```
![hf](https://github.com/pytorch/pytorch/assets/3028629/4aa72bd4-0f3f-42d8-bba3-26dbb14ffdaf)


### Versions

Collecting environment information...
PyTorch version: 2.1.0.dev20230504
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: CentOS Stream 8 (x86_64)
GCC version: (GCC) 8.5.0 20210514 (Red Hat 8.5.0-18)
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.28

Python version: 3.11.3 (main, Apr 19 2023, 23:54:32) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.12.0-0_fbk13_zion_7455_gb24de3bdb045-x86_64-with-glibc2.28
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA PG509-210
GPU 1: NVIDIA PG509-210
GPU 2: NVIDIA PG509-210
GPU 3: NVIDIA PG509-210
GPU 4: NVIDIA PG509-210
GPU 5: NVIDIA PG509-210
GPU 6: NVIDIA PG509-210
GPU 7: NVIDIA PG509-210

Nvidia driver version: 525.105.17
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
Byte Order:          Little Endian
CPU(s):              192
On-line CPU(s) list: 0-191
Thread(s) per core:  2
Core(s) per socket:  24
Socket(s):           4
NUMA node(s):        4
Vendor ID:           GenuineIntel
CPU family:          6
Model:               85
Model name:          Intel(R) Xeon(R) Platinum 8339HC CPU @ 1.80GHz
Stepping:            11
CPU MHz:             2499.998
CPU max MHz:         1801.0000
CPU min MHz:         800.0000
BogoMIPS:            3600.00
Virtualization:      VT-x
L1d cache:           32K
L1i cache:           32K
L2 cache:            1024K
L3 cache:            33792K
NUMA node0 CPU(s):   0-23,96-119
NUMA node1 CPU(s):   24-47,120-143
NUMA node2 CPU(s):   48-71,144-167
NUMA node3 CPU(s):   72-95,168-191
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 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 cdp_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke avx512_vnni md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] torch==2.1.0.dev20230504
[pip3] torchaudio==2.1.0.dev20230504
[pip3] torchvision==0.16.0.dev20230504
[pip3] triton==2.1.0
[conda] blas                      1.0                         mkl  
[conda] brotlipy                  0.7.0           py311h9bf148f_1002    pytorch-nightly
[conda] cffi                      1.15.1          py311h9bf148f_3    pytorch-nightly
[conda] cryptography              38.0.4          py311h46ebde7_0    pytorch-nightly
[conda] filelock                  3.9.0                   py311_0    pytorch-nightly
[conda] mkl                       2021.4.0           h06a4308_640  
[conda] mkl-service               2.4.0           py311h9bf148f_0    pytorch-nightly
[conda] mkl_fft                   1.3.1           py311hc796f24_0    pytorch-nightly
[conda] mkl_random                1.2.2           py311hbba84a0_0    pytorch-nightly
[conda] mpmath                    1.2.1                   py311_0    pytorch-nightly
[conda] numpy                     1.24.3          py311hc206e33_0  
[conda] numpy-base                1.24.3          py311hfd5febd_0  
[conda] pillow                    9.3.0           py311h3fd9d12_2    pytorch-nightly
[conda] pysocks                   1.7.1                   py311_0    pytorch-nightly
[conda] pytorch                   2.1.0.dev20230504 py3.11_cuda11.8_cudnn8.7.0_0    pytorch-nightly
[conda] pytorch-cuda              11.8                 h7e8668a_5    pytorch-nightly
[conda] pytorch-mutex             1.0                        cuda    pytorch-nightly
[conda] requests                  2.28.1                  py311_0    pytorch-nightly
[conda] torchaudio                2.1.0.dev20230504     py311_cu118    pytorch-nightly
[conda] torchtriton               2.1.0+7d1a95b046           py311    pytorch-nightly
[conda] torchvision               0.16.0.dev20230504     py311_cu118    pytorch-nightly
[conda] urllib3                   1.26.14                 py311_0    pytorch-nightly


cc @ezyang @msaroufim @wconstab @bdhirsh @anijain2305 @zou3519 @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @peterbell10 @ipiszy @yf225 @chenyang78 @kadeng @muchulee8 @aakhundov @ColinPeppler @ngimel @Xia-Weiwen @soumith