Repository: pytorch
Issue: [AOTI] timm_nfnet performs worse than Inductor due to less constant folding optimization
Labels: triaged,oncall: pt2,module: inductor

### 🐛 Describe the bug

We found that `timm_nfnet` (in the torchbench suite) using AOTI performs worse than Inductor and noticed that AOTI has less constant folding optimization. In this model, in the computation [here](https://github.com/huggingface/pytorch-image-models/blob/v1.0.3/timm/layers/std_conv.py#L69-L73), there's a BN computation on the weight of the Convolution. Since all the inputs to this BN operation are constant during inference when we have turned on freezing, the BN computation has been folded into a Constant when using Inductor. However with AOTI, the BN computation is not folded and will still be executed during runtime.

**Reproducer**:
On the bottom is the reproducer code `test.py`.
We disabled mkldnn to make it easier to compare the graph using AOTI and Inductor (AOTI can't hit mkldnn fusion for now due to the current issue while Inductor can hit the mkldnn fusion).

By running with `TORCH_LOGS="+inductor,+output_code" python -u test/my-repro-conv-bn-folding.py -c`, we can get the post grad graph of Inductor. The weight of the convolution `_frozen_param4` is already a Constant.
```
TRACED GRAPH
 ===== AFTER POST GRAD =====
 /home/user/inductor/pytorch/torch/fx/_lazy_graph_module.py class <lambda>(torch.nn.Module):
    def forward(self, arg3_1: "f32[128, 3, 192, 192]"):
        # No stacktrace found for following nodes
        _frozen_param2: "f32[16]" = self._frozen_param2
        _frozen_param4: "f32[16, 3, 3, 3]" = self._frozen_param4
        
        # File: /home/user/inductor/pytorch/torch/nn/functional.py:4539 in pad, code: return torch._C._nn.pad(input, pad, mode, value)
        constant_pad_nd: "f32[128, 3, 193, 193]" = torch.ops.aten.constant_pad_nd.default(arg3_1, [0, 1, 0, 1], 0.0);  arg3_1 = None
        
        # File: /home/user/inductor/pytorch/test/my-repro-conv-bn-folding.py:159 in forward, code: return F.conv2d(x, weight, self.bias, self.stride, self.padding, self.dilation, self.groups)
        convolution: "f32[128, 16, 96, 96]" = torch.ops.aten.convolution.default(constant_pad_nd, _frozen_param4, _frozen_param2, [2, 2], [0, 0], [1, 1], False, [0, 0], 1);  constant_pad_nd = _frozen_param4 = _frozen_param2 = None
        
        # No stacktrace found for following nodes
        inductor_force_stride_order_default: "f32[128, 16, 96, 96]" = torch.ops.prims.inductor_force_stride_order.default(convolution, (147456, 9216, 96, 1));  convolution = None
        return (inductor_force_stride_order_default,)
        

```


Using `TORCH_LOGS="+inductor,+output_code" python -u test/my-repro-conv-bn-folding.py`, below is the post grad graph of AOTI, the weight of Convolution `clone_default` is not folded into a Constant:
```
TRACED GRAPH
 ===== AFTER POST GRAD =====
 /home/user/inductor/pytorch/torch/fx/_lazy_graph_module.py class <lambda>(torch.nn.Module):
    def forward(self, arg3_1: "f32[128, 3, 192, 192]"):
        # No stacktrace found for following nodes
        bias: "f32[16]" = self.bias
        
        # File: /home/user/inductor/pytorch/test/my-repro-conv-bn-folding.py:155 in forward, code: weight = F.batch_norm(
        _frozen_param2: "f32[1, 16, 27]" = self._frozen_param2
        
        # File: /home/user/inductor/pytorch/torch/nn/functional.py:4539 in pad, code: return torch._C._nn.pad(input, pad, mode, value)
        constant_pad_nd: "f32[128, 3, 193, 193]" = torch.ops.aten.constant_pad_nd.default(arg3_1, [0, 1, 0, 1], 0.0);  arg3_1 = None
        
        # File: /home/user/inductor/pytorch/test/my-repro-conv-bn-folding.py:155 in forward, code: weight = F.batch_norm(
        full_default: "f32[16, 1]" = torch.ops.aten.full.default([16, 1], 0.19245009124279022, dtype = torch.float32, layout = torch.strided, device = device(type='cpu'), pin_memory = False)
        mul_2: "f32[1, 16, 27]" = torch.ops.aten.mul.Tensor(_frozen_param2, full_default);  _frozen_param2 = full_default = None
        view_2: "f32[16, 3, 3, 3]" = torch.ops.aten.reshape.default(mul_2, [16, 3, 3, 3]);  mul_2 = None
        
        # No stacktrace found for following nodes
        clone_default: "f32[16, 3, 3, 3]" = torch.ops.aten.clone.default(view_2, memory_format = torch.channels_last);  view_2 = None
        
        # File: /home/user/inductor/pytorch/test/my-repro-conv-bn-folding.py:159 in forward, code: return F.conv2d(x, weight, self.bias, self.stride, self.padding, self.dilation, self.groups)
        convolution: "f32[128, 16, 96, 96]" = torch.ops.aten.convolution.default(constant_pad_nd, clone_default, bias, [2, 2], [0, 0], [1, 1], False, [0, 0], 1);  constant_pad_nd = clone_default = bias = None
        
        # No stacktrace found for following nodes
        inductor_force_stride_order_default: "f32[128, 16, 96, 96]" = torch.ops.prims.inductor_force_stride_order.default(convolution, (147456, 9216, 96, 1));  convolution = None
        return (inductor_force_stride_order_default,)
```


```py
# test.py
import math
from typing import List, Tuple
import argparse
import torch
import torch._inductor.config as config
import torch.nn.functional as F

from typing import (
    Any,
    Mapping,
    Tuple,
)
import copy
import dataclasses
import functools
import weakref
from torch.utils import _pytree as pytree

def main(use_api_after_the_change, compile):

    def _normalize_bench_inputs(example_inputs) -> Tuple[Tuple[Any], Mapping[str, Any]]:
        # NOTE(bowbao): For huggingface benchmark, example_inputs are formatted as dictionary,
        # and consumed like `model(**example_inputs)`.
        # For other benchmarks, example_inputs are formatted as tuple and consumed
        # like `model(*example_inputs)`.
        if isinstance(example_inputs, dict):
            return (), example_inputs
        else:
            return tuple(example_inputs), {}

    def _register_dataclass_output_as_pytree(example_outputs) -> None:
        # NOTE(angelayi): For huggingface benchmark, some example outputs are
        # formatted as a dataclass which pytree cannot consume. So we want
        # to register the pytree implementation here
        example_outputs_flat = pytree.tree_leaves(example_outputs)
        output_dataclass_types = [
            type(out) for out in example_outputs_flat if dataclasses.is_dataclass(type(out))
        ]
        for output_type in output_dataclass_types:
            from torch._export.utils import register_dataclass_as_pytree_node

            register_dataclass_as_pytree_node(
                output_type,
                serialized_type_name=f"{output_type.__module__}.{output_type.__name__}",
            )

    class AOTInductorModelCache:
        cache = dict()

        @classmethod
        def load(cls, model, example_inputs, device):
            import torch._inductor
            import torch.export._trace

            key = weakref.ref(model)
            if key not in cls.cache:
                # Register the output dataclass to pytree
                example_args, example_kwargs = _normalize_bench_inputs(example_inputs)
                with torch.no_grad():
                    # copy.deepcopy is required to prevent any surprising side-effect,
                    # see https://github.com/pytorch/pytorch/issues/113029
                    example_outputs = copy.deepcopy(model)(*example_args, **example_kwargs)

                if pytree._is_namedtuple_instance(example_outputs):
                    typ = type(example_outputs)
                    pytree._register_namedtuple(
                        typ,
                        serialized_type_name=f"{typ.__module__}.{typ.__name__}",
                    )
                else:
                    _register_dataclass_output_as_pytree(example_outputs)

                
                if use_api_after_the_change:
                    gm = torch.export._trace._export(
                        model,
                        example_args,
                        example_kwargs,
                        pre_dispatch=True,
                    ).module()
                else:
                    gm = torch.export._trace._export_to_torch_ir(
                        model,
                        example_args,
                        example_kwargs,
                    )
                
                with torch.no_grad():
                    so_path = torch._inductor.aot_compile(
                        gm, example_args, example_kwargs
                    )  # type: ignore[arg-type]

                cls.cache[key] = torch._export.aot_load(so_path, device)

            return cls.cache[key]

    def export_aot_inductor(model, example_inputs, device):
        optimized = AOTInductorModelCache.load(model, example_inputs, device)

        def opt_aot_inductor(_, example_inputs, collect_outputs=False):
            example_args, example_kwargs = _normalize_bench_inputs(example_inputs)
            return optimized(*example_args, **example_kwargs)

        return opt_aot_inductor

    # Calculate asymmetric TensorFlow-like 'SAME' padding for a convolution
    def get_same_padding(x: int, kernel_size: int, stride: int, dilation: int):
        if isinstance(x, torch.Tensor):
            return torch.clamp(((x / stride).ceil() - 1) * stride + (kernel_size - 1) * dilation + 1 - x, min=0)
        else:
            return max((math.ceil(x / stride) - 1) * stride + (kernel_size - 1) * dilation + 1 - x, 0)

    # Dynamically pad input x with 'SAME' padding for conv with specified args
    def pad_same(
            x,
            kernel_size: List[int],
            stride: List[int],
            dilation: List[int] = (1, 1),
            value: float = 0,
    ):
        ih, iw = x.size()[-2:]
        pad_h = get_same_padding(ih, kernel_size[0], stride[0], dilation[0])
        pad_w = get_same_padding(iw, kernel_size[1], stride[1], dilation[1])
        x = F.pad(x, (pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2), value=value)
        return x


    class ReproModel(torch.nn.Conv2d):
        def __init__(
                self, in_channels, out_channels, kernel_size, stride=1, padding='SAME',
                dilation=1, groups=1, bias=True, gamma=1.0, eps=1e-6, gain_init=1.0):
            padding, is_dynamic = 0, True
            super().__init__(
                in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation,
                groups=groups, bias=bias)
            self.gain = torch.nn.Parameter(torch.full((self.out_channels, 1, 1, 1), gain_init))
            self.scale = gamma * self.weight[0].numel() ** -0.5
            self.same_pad = is_dynamic
            self.eps = eps

        def forward(self, x):
            if self.same_pad:
                x = pad_same(x, self.kernel_size, self.stride, self.dilation)
            weight = F.batch_norm(
                self.weight.reshape(1, self.out_channels, -1), None, None,
                weight=(self.gain * self.scale).view(-1),
                training=True, momentum=0., eps=self.eps).reshape_as(self.weight)
            return F.conv2d(x, weight, self.bias, self.stride, self.padding, self.dilation, self.groups)


    config.profiler_mark_wrapper_call = True
    config.cpp.enable_kernel_profile = True

    if compile:
        optimize_ctx = functools.partial(
            torch.compile,
            backend="inductor",
        )
        optimized_model_iter_fn = optimize_ctx(lambda mod, inputs: mod(*inputs))
    else:
        optimize_ctx = functools.partial(
            export_aot_inductor, device="cpu"
        )
        optimized_model_iter_fn = optimize_ctx
    
    in_channels = 3
    out_channels = 16
    kernel_size = 3
    stride = 2
    bias = True
    eps = 1e-05
    
    example_inputs = (torch.randn(128, in_channels, 192, 192),)
    model = ReproModel(in_channels, out_channels, kernel_size, stride, bias=bias, eps=eps)
    model.eval()
    with torch.no_grad(), config.patch({"freezing": True}):
        for _ in range(3):
            optimized_model_iter_fn(model, example_inputs)
        
        with torch.autograd.profiler.profile(True) as prof:
            optimized_model_iter_fn(model, example_inputs)
        print(prof.key_averages().table(sort_by="self_cpu_time_total"))
    
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--after", "-a", action="store_true", help="use the api after the regression"
    )
    parser.add_argument(
        "--compile", "-c", action="store_true", help="use the api after the regression"
    )    
    args = parser.parse_args()
    
    with torch.backends.mkldnn.flags(enabled=False):
        main(args.after, args.compile)
    print("done")
```

### Versions

Collecting environment information...
PyTorch version: 2.4.0a0+git669560d
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: CentOS Stream 8 (x86_64)
GCC version: (GCC) 11.2.1 20220127 (Red Hat 11.2.1-9)
Clang version: Could not collect
CMake version: version 3.26.4
Libc version: glibc-2.28

Python version: 3.9.18 (main, Sep 11 2023, 13:41:44) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.16.0-x86_64-with-glibc2.28
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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): 240
On-line CPU(s) list: 0-239
Thread(s) per core: 2
Core(s) per socket: 60
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 143
Model name: Intel(R) Xeon(R) Platinum 8490H
Stepping: 8
CPU MHz: 1900.000
CPU max MHz: 3500.0000
CPU min MHz: 800.0000
BogoMIPS: 3800.00
Virtualization: VT-x
L1d cache: 48K
L1i cache: 32K
L2 cache: 2048K
L3 cache: 115200K
NUMA node0 CPU(s): 0-59,120-179
NUMA node1 CPU(s): 60-119,180-239
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 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 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 avx512_fp16 amx_tile flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] flake8==6.1.0
[pip3] flake8-bugbear==23.3.23
[pip3] flake8-comprehensions==3.12.0
[pip3] flake8-executable==2.1.3
[pip3] flake8-logging-format==0.9.0
[pip3] flake8-pyi==23.3.1
[pip3] flake8-simplify==0.19.3
[pip3] mypy==1.9.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.0
[pip3] optree==0.11.0
[pip3] torch==2.4.0a0+git669560d
[pip3] torchvision==0.19.0a0+f0c94cd
[pip3] vit-pytorch==0.40.2
[conda] blas 1.0 mkl
[conda] mkl 2023.1.0 h213fc3f_46343
[conda] mkl-include 2023.2.0 pypi_0 pypi
[conda] mkl-service 2.4.0 py39h5eee18b_1
[conda] mkl-static 2023.2.0 pypi_0 pypi
[conda] mkl_fft 1.3.8 py39h5eee18b_0
[conda] mkl_random 1.2.4 py39hdb19cb5_0
[conda] numpy 1.26.0 pypi_0 pypi
[conda] numpy-base 1.26.4 py39hb5e798b_0
[conda] optree 0.11.0 pypi_0 pypi
[conda] torch 2.4.0a0+git669560d dev_0
[conda] torchfix 0.4.0 pypi_0 pypi
[conda] torchvision 0.19.0a0+f0c94cd dev_0
[conda] vit-pytorch 0.40.2 dev_0

cc @ezyang @msaroufim @bdhirsh @anijain2305 @chauhang @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @peterbell10 @ipiszy @yf225 @chenyang78 @kadeng @muchulee8 @ColinPeppler @amjames @desertfire