Repository: pytorch
Issue: Compile error for custom op with optional mutable tensor list argument
Labels: triaged,module: custom-operators,module: functionalization,oncall: pt2,module: aotdispatch,module: pt2-dispatcher

### 🐛 Describe the bug

It showed that the Torch auto functionalization doesn't support custom op with optional mutable tensor list argument.

The following code shows this problem. "Tensor(a!)[]? out_list" argument of the op is not supported for auto functionalization:

```
import torch

@torch.library.custom_op("mylib::mysin", mutates_args=["out_list"], schema="(Tensor x, Tensor(a!)[]? out_list) -> (Tensor)")
def mysin(x: torch.Tensor, out_list: list[torch.Tensor] = None) -> torch.Tensor:
    r = x.sin()
    return r

@torch.library.register_fake("mylib::mysin")
def mysin_fake(x, out_list: list[torch.Tensor] = None) -> torch.Tensor:
    return torch.empty_like(x)


def fn(x):
    x = x * 3
    s = [torch.empty_like(x)]
    x= mysin(x, out_list=s)
    x =  x / 3
    return x

fn = torch.compile(fn)

x = torch.randn(3, requires_grad=False)
y= fn(x)
print(y)
```

When executing the above code, the following exception happens:

```
  File "/home/haifchen/working/envs/env_test_nightly/lib/python3.10/site-packages/torch/_subclasses/functional_tensor.py", line 535, in __torch_dispatch__
    outs_unwrapped = func._op_dk(
torch._dynamo.exc.BackendCompilerFailed: backend='inductor' raised:
RuntimeError: Found a custom (non-ATen) operator whose output has alias annotations: mylib::mysin(Tensor x, Tensor(a!)[]? out_list) -> Tensor. We only support functionalizing operators whose outputs do not have alias annotations (e.g. 'Tensor(a)' is a Tensor with an alias annotation whereas 'Tensor' is a Tensor without. The '(a)' is the alias annotation). The alias annotation specifies that the output Tensor shares storage with an input that has the same annotation. Please check if (1) the output needs to be an output (if not, don't return it), (2) if the output doesn't share storage with any inputs, then delete the alias annotation. (3) if the output indeed shares storage with an input, then add a .clone() before returning it to prevent storage sharing and then delete the alias annotation. Otherwise, please file an issue on GitHub.

While executing %x_1 : [num_users=1] = call_function[target=torch.ops.mylib.mysin.default](args = (%x,), kwargs = {out_list: [%empty_like]})
Original traceback:
  File "/home/haifchen/working/test/test-custom-op-alias.py", line 136, in fn
    x= mysin(x, out_list=s)
  File "/home/haifchen/working/envs/env_test_nightly/lib/python3.10/site-packages/torch/_library/custom_ops.py", line 669, in __call__
    return self._opoverload(*args, **kwargs)
```

If we change the custom op schema to "(Tensor x, Tensor(a!)[] out_list) -> (Tensor)", it works.

Is there any fundamental difficulties to support optional mutable tensor list argument?



### Versions

Collecting environment information...
PyTorch version: 2.6.0.dev20240914+cpu
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04 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.22.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Sep 11 2024, 15:47:36) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-122-generic-x86_64-with-glibc2.35
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
Address sizes:                        43 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               12
On-line CPU(s) list:                  0-11
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz
CPU family:                           6
Model:                                85
Thread(s) per core:                   1
Core(s) per socket:                   6
Socket(s):                            2
Stepping:                             0
BogoMIPS:                             4190.15
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 nopl xtopology tsc_reliable nonstop_tsc cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xsaves arat pku ospke md_clear flush_l1d arch_capabilities
Virtualization:                       VT-x
Hypervisor vendor:                    VMware
Virtualization type:                  full
L1d cache:                            384 KiB (12 instances)
L1i cache:                            384 KiB (12 instances)
L2 cache:                             12 MiB (12 instances)
L3 cache:                             55 MiB (2 instances)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-11
Vulnerability Gather data sampling:   Unknown: Dependent on hypervisor status
Vulnerability Itlb multihit:          KVM: Mitigation: VMX disabled
Vulnerability L1tf:                   Mitigation; PTE Inversion; VMX flush not necessary, SMT disabled
Vulnerability Mds:                    Mitigation; Clear CPU buffers; SMT Host state unknown
Vulnerability Meltdown:               Mitigation; PTI
Vulnerability Mmio stale data:        Mitigation; Clear CPU buffers; SMT Host state unknown
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; 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; IBRS; IBPB conditional; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==2.1.1
[pip3] torch==2.6.0.dev20240914+cpu
[conda] Could not collect


cc @bdhirsh @ezyang @chauhang @penguinwu @zou3519 @yf225