Repository: pytorch
Issue: bmm, topk, cholesky, linalg.norm, max with out variants set causing recompilations in torch.compile
Labels: good first issue,triaged,oncall: pt2,module: dynamic shapes

### 🐛 Describe the bug

Out variants of following ops are causing extra recompilations (in 3rd iteration) in torch.compile when compared to not using out variant,
torch.bmm
torch.topk
torch.cholesky
torch.linalg.norm
torch.max

### Error logs

```
I0912 10:49:41.653000 29510 torch/_dynamo/logging.py:57] [0/0] Step 1: torchdynamo start tracing topk_func <ipython-input-11-cf34f6cf9be7>:9
I0912 10:49:41.684000 29510 torch/_dynamo/logging.py:57] [0/0] Step 1: torchdynamo done tracing topk_func (RETURN_VALUE)
I0912 10:49:41.692000 29510 torch/_dynamo/logging.py:57] [0/0] Step 2: calling compiler function inductor
I0912 10:49:41.787000 29510 torch/_dynamo/logging.py:57] [0/0] Step 2: done compiler function inductor
I0912 10:49:41.812000 29510 torch/fx/experimental/symbolic_shapes.py:3646] [0/0] produce_guards
I0912 10:49:41.833000 29510 torch/_dynamo/logging.py:57] [0/1] Step 1: torchdynamo start tracing topk_func <ipython-input-11-cf34f6cf9be7>:9
I0912 10:49:41.872000 29510 torch/fx/experimental/symbolic_shapes.py:3557] [0/1] create_symbol s0 = 7 for L['input'].size()[0] [2, int_oo] at <ipython-input-11-cf34f6cf9be7>:10 in topk_func (_dynamo/variables/builder.py:2711 in <lambda>), for more info run with TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL="s0"
I0912 10:49:41.895000 29510 torch/fx/experimental/symbolic_shapes.py:4857] [0/1] set_replacement s0 = 7 (range_refined_to_singleton) VR[7, 7]
I0912 10:49:41.902000 29510 torch/fx/experimental/symbolic_shapes.py:5106] [0/1] eval Eq(s0, 7) [guard added] at <ipython-input-11-cf34f6cf9be7>:10 in topk_func (utils/_stats.py:21 in wrapper), for more info run with TORCHDYNAMO_EXTENDED_DEBUG_GUARD_ADDED="Eq(s0, 7)"
I0912 10:49:41.908000 29510 torch/_dynamo/logging.py:57] [0/1] Step 1: torchdynamo done tracing topk_func (RETURN_VALUE)
I0912 10:49:41.915000 29510 torch/_dynamo/logging.py:57] [0/1] Step 2: calling compiler function inductor
Iter 1: No of recompiles: 0
I0912 10:49:42.168000 29510 torch/_dynamo/logging.py:57] [0/1] Step 2: done compiler function inductor
I0912 10:49:42.199000 29510 torch/fx/experimental/symbolic_shapes.py:3646] [0/1] produce_guards
I0912 10:49:42.234000 29510 torch/_dynamo/logging.py:57] [0/2] Step 1: torchdynamo start tracing topk_func <ipython-input-11-cf34f6cf9be7>:9
I0912 10:49:42.277000 29510 torch/fx/experimental/symbolic_shapes.py:3557] [0/2] create_symbol s0 = 9 for L['input'].size()[0] [2, int_oo] at <ipython-input-11-cf34f6cf9be7>:10 in topk_func (_dynamo/variables/builder.py:2711 in <lambda>), for more info run with TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL="s0"
I0912 10:49:42.295000 29510 torch/fx/experimental/symbolic_shapes.py:4857] [0/2] set_replacement s0 = 9 (range_refined_to_singleton) VR[9, 9]
I0912 10:49:42.297000 29510 torch/fx/experimental/symbolic_shapes.py:5106] [0/2] eval Eq(s0, 9) [guard added] at <ipython-input-11-cf34f6cf9be7>:10 in topk_func (utils/_stats.py:21 in wrapper), for more info run with TORCHDYNAMO_EXTENDED_DEBUG_GUARD_ADDED="Eq(s0, 9)"
I0912 10:49:42.308000 29510 torch/_dynamo/logging.py:57] [0/2] Step 1: torchdynamo done tracing topk_func (RETURN_VALUE)
I0912 10:49:42.328000 29510 torch/_dynamo/logging.py:57] [0/2] Step 2: calling compiler function inductor
Iter 2: No of recompiles: 1
I0912 10:49:42.508000 29510 torch/_dynamo/logging.py:57] [0/2] Step 2: done compiler function inductor
I0912 10:49:42.522000 29510 torch/fx/experimental/symbolic_shapes.py:3646] [0/2] produce_guards
Iter 3: No of recompiles: 2
```

### Minified repro

torch.topk
```
import torch

def get_num_torch_recompiles():
    guard_failures = torch._dynamo.utils.guard_failures
    num_recompiles = [len(guard_failures[code]) for code in guard_failures]
    return 0 if len(num_recompiles) == 0 else max(num_recompiles)

total_comps = 0
def topk_func(input, k, out):
  torch.topk(input, k, out=out)

torch._dynamo.reset()
opt_model = torch.compile(topk_func)

values = torch.empty(3)
indices = torch.empty(3, dtype=torch.long)
x = torch.arange(1., 6.)
opt_model(x, 3, out=(values, indices))
print(f"Iter 1: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()

x = torch.arange(1., 8.)
opt_model(x, 3, out=(values, indices))
print(f"Iter 2: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()

x = torch.arange(1., 10.)
opt_model(x, 3, out=(values, indices))
print(f"Iter 3: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()
```
torch.bmm
```
import torch

def get_num_torch_recompiles():
    guard_failures = torch._dynamo.utils.guard_failures
    num_recompiles = [len(guard_failures[code]) for code in guard_failures]
    return 0 if len(num_recompiles) == 0 else max(num_recompiles)

total_comps = 0
def bmm_func(input, mat, out):
  torch.bmm(input, mat, out=out)

torch._dynamo.reset()
opt_model = torch.compile(bmm_func)

input1 = torch.randn(10, 3, 4)
mat1 = torch.randn(10, 4, 5)
out1 = torch.empty(10, 3, 5)
opt_model(input1, mat1, out=out1)
print(f"Iter 1: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()

input2 = torch.randn(12, 5, 6)
mat2 = torch.randn(12, 6, 7)
out2 = torch.empty(12, 5, 7)
opt_model(input2, mat2, out=out2)
print(f"Iter 2: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()

input3 = torch.randn(14, 7, 8)
mat3 = torch.randn(14, 8, 9)
out3 = torch.empty(14, 7, 9)
opt_model(input3, mat3, out=out3)
print(f"Iter 3: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()
```
torch.cholesky
```
import torch

def get_num_torch_recompiles():
    guard_failures = torch._dynamo.utils.guard_failures
    num_recompiles = [len(guard_failures[code]) for code in guard_failures]
    return 0 if len(num_recompiles) == 0 else max(num_recompiles)

total_comps = 0

def cholesky_func(input, out):
    torch.linalg.cholesky(input, out=out)

torch._dynamo.reset()
opt_model = torch.compile(cholesky_func)

values = torch.randn(8, 32, 32)
ifm_positive_definite = values @ values.mT + torch.eye(values.shape[-1])
opt_model(ifm_positive_definite, out=ifm_positive_definite)
print(f"Iter 1: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()

values = torch.randn(9, 32, 32)
ifm_positive_definite = values @ values.mT + torch.eye(values.shape[-1])
opt_model(ifm_positive_definite, out=ifm_positive_definite)
print(f"Iter 2: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()

values = torch.randn(10, 32, 32)
ifm_positive_definite = values @ values.mT + torch.eye(values.shape[-1])
opt_model(ifm_positive_definite, out=ifm_positive_definite)
print(f"Iter 3: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()
```
torch.linalg.norm
```
import torch

def get_num_torch_recompiles():
    guard_failures = torch._dynamo.utils.guard_failures
    num_recompiles = [len(guard_failures[code]) for code in guard_failures]
    return 0 if len(num_recompiles) == 0 else max(num_recompiles)

total_comps = 0

def model_norm(inputs, out):
  return torch.linalg.norm(inputs, ord=-1, dim=(0, 1), out=out)

torch._dynamo.reset()
opt_model = torch.compile(model_norm)

a = torch.rand((16, 16, 550), dtype=torch.bfloat16)
out = torch.empty(550, dtype=torch.bfloat16)
opt_model(a, out)
print(f"Iter 1: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()

a = torch.rand((16, 16, 32), dtype=torch.bfloat16)
out = torch.empty(32, dtype=torch.bfloat16)
opt_model(a, out)
print(f"Iter 2: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()

a = torch.rand((16, 16, 341), dtype=torch.bfloat16)
out = torch.empty(341, dtype=torch.bfloat16)
opt_model(a, out)
print(f"Iter 3: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()

a = torch.rand((16, 16, 402), dtype=torch.bfloat16)
out = torch.empty(402, dtype=torch.bfloat16)
opt_model(a, out)
print(f"Iter 4: No of recompiles: {get_num_torch_recompiles() - total_comps}")
total_comps = get_num_torch_recompiles()
```
### Versions

```
Collecting environment information...
PyTorch version: 2.5.0.dev20240911+cpu
Is debug build: False
CUDA used to build PyTorch: Could not collect
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: 14.0.0-1ubuntu1.1
CMake version: version 3.30.3
Libc version: glibc-2.35

Python version: 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.1.85+-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: 12.2.140
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: Could not collect
Nvidia driver version: Could not collect
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.6
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, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               2
On-line CPU(s) list:                  0,1
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) CPU @ 2.20GHz
CPU family:                           6
Model:                                79
Thread(s) per core:                   2
Core(s) per socket:                   1
Socket(s):                            1
Stepping:                             0
BogoMIPS:                             4399.99
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 rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities
Hypervisor vendor:                    KVM
Virtualization type:                  full
L1d cache:                            32 KiB (1 instance)
L1i cache:                            32 KiB (1 instance)
L2 cache:                             256 KiB (1 instance)
L3 cache:                             55 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0,1
Vulnerability Gather data sampling:   Not affected
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Mitigation; PTE Inversion
Vulnerability Mds:                    Vulnerable; SMT Host state unknown
Vulnerability Meltdown:               Vulnerable
Vulnerability Mmio stale data:        Vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Vulnerable
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: Not affected; BHI: Vulnerable (Syscall hardening enabled)
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Vulnerable

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] optree==0.12.1
[pip3] torch==2.5.0.dev20240911+cpu
[pip3] torchaudio==2.4.0+cu121
[pip3] torchsummary==1.5.1
[pip3] torchvision==0.19.0+cu121
[conda] Could not collect
```

cc @ezyang @chauhang @penguinwu