Repository: pytorch
Issue: Consider relaxing torch.cond's requirement that the outputs of each branch have matching requires_grad metadata
Labels: triaged,oncall: pt2,module: higher order operators,module: pt2-dispatcher

### 🐛 Describe the bug

Here is a surprising behavior I found while working on https://github.com/pytorch/pytorch/pull/140979

```python
import torch

torch.set_default_device("cuda")

def cond_relu(x):
    return torch.cond(x > 0, lambda x: x, lambda _: torch.zeros_like(x), [x])

def imperative_relu(x):
    if x > 0:
        return x
    else:
        return torch.zeros_like(x)

x = -torch.ones((), requires_grad=False)
# Works 
y1 = torch.nn.functional.relu(x)
# Works 
y2 = imperative_relu(x)
# Works 
y3 = cond_relu(x)


x = -torch.ones((), requires_grad=True)
# Works 
y1 = torch.nn.functional.relu(x)
# Works 
y2 = imperative_relu(x)
# Does not work 
y3 = cond_relu(x)
```

When the input of cond_relu has requires_grad=True, we get the following error:

```
Traceback (most recent call last):
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/variables/higher_order_ops.py", line 54, in graph_break_as_hard_error
    return fn(*args, **kwargs)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/variables/higher_order_ops.py", line 872, in call_function
    unimplemented(
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/exc.py", line 313, in unimplemented
    raise Unsupported(msg, case_name=case_name)
torch._dynamo.exc.Unsupported: Expected branches to return tensors with same metadata. [(tensor_pair, difference)...]:[('pair0:', TensorMetadata(shape=torch.Size([]), dtype=torch.float32, requires_grad=True, stride=(), memory_format=None, is_quantized=False, qparams={}), TensorMetadata(shape=torch.Size([]), dtype=torch.float32, requires_grad=False, stride=(), memory_format=None, is_quantized=False, qparams={}))]

The above exception was the direct cause of the following exception: 

Traceback (most recent call last):
  File "/home/dgalvez/scratch/code/asr/pytorch/repros/cond_quirks2.py", line 29, in <module>
    y2 = cond_relu(x)
  File "/home/dgalvez/scratch/code/asr/pytorch/repros/cond_quirks2.py", line 6, in cond_relu
    return torch.cond(x > 0, lambda x: x, lambda _: torch.zeros_like(x), [x])
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_higher_order_ops/cond.py", line 207, in cond
    return torch.compile(_cond_op_wrapper, backend=backend, fullgraph=True)(
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/eval_frame.py", line 556, in _fn
    return fn(*args, **kwargs)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/convert_frame.py", line 1419, in __call__
    return self._torchdynamo_orig_callable(
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/convert_frame.py", line 567, in __call__
    return _compile(
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/convert_frame.py", line 1000, in _compile
    guarded_code = compile_inner(code, one_graph, hooks, transform)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/convert_frame.py", line 730, in compile_inner
    return _compile_inner(code, one_graph, hooks, transform)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_utils_internal.py", line 95, in wrapper_function
    return function(*args, **kwargs)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/convert_frame.py", line 765, in _compile_inner
    out_code = transform_code_object(code, transform)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/bytecode_transformation.py", line 1348, in transform_code_object
    transformations(instructions, code_options)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/convert_frame.py", line 248, in _fn
    return fn(*args, **kwargs)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/convert_frame.py", line 682, in transform
    tracer.run()
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/symbolic_convert.py", line 2841, in run
    super().run()
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/symbolic_convert.py", line 1032, in run
    while self.step():
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/symbolic_convert.py", line 944, in step
    self.dispatch_table[inst.opcode](self, inst)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/symbolic_convert.py", line 641, in wrapper
    return inner_fn(self, inst)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/symbolic_convert.py", line 1714, in CALL_FUNCTION_EX
    self.call_function(fn, argsvars.items, kwargsvars)
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/symbolic_convert.py", line 879, in call_function
    self.push(fn.call_function(self, args, kwargs))  # type: ignore[arg-type]
  File "/home/dgalvez/scratch/code/asr/pytorch/torch/_dynamo/variables/higher_order_ops.py", line 57, in graph_break_as_hard_error
    raise UncapturedHigherOrderOpError(reason + msg) from e
torch._dynamo.exc.UncapturedHigherOrderOpError: Cond doesn't work unless it is captured completely with torch.compile. Scroll up to find out what causes the graph break.

from user code:
   File "/home/dgalvez/scratch/code/asr/pytorch/torch/_higher_order_ops/cond.py", line 197, in _cond_op_wrapper
    return cond_op(*args, **kwargs)

Set TORCH_LOGS="+dynamo" and TORCHDYNAMO_VERBOSE=1 for more information


You can suppress this exception and fall back to eager by setting:   
    import torch._dynamo
    torch._dynamo.config.suppress_errors = True
```

The important part is this:

```
torch._dynamo.exc.Unsupported: Expected branches to return tensors with same metadata. [(tensor_pair, difference)...]:[('pair0:', TensorMetadata(shape=torch.Size([]), dtype=torch.float32, requires_grad=True, stride=(), memory_format=None, is_quantized=False, qparams={}), TensorMetadata(shape=torch.Size([]), dtype=torch.float32, requires_grad=False, stride=(), memory_format=None, is_quantized=False, qparams={}))]
```

You can see that the only difference between the branches is that one output has requires_grad=True, while the other has requires_grad=False.

This is a little bit unfortunate since it doesn't match some other existing behaviors.

I don't think that simply promoting a tensor with requires_grad=False to have requires_grad=True if the corresponding output from the other branch has requires_grad=True will be problematic. At the very least, this would not affect the ability to run the backward pass via conditional nodes in cuda graphs. This would match the behavior of existing code, where sometimes a gradient is not backpropagated based on runtime values. What do you think?

@bohnstingl @ydwu4 @eellison 

### Versions

```
Collecting environment information...
PyTorch version: 2.6.0a0+git13535e2
Is debug build: True
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64)
GCC version: (Ubuntu 13.2.0-23ubuntu4) 13.2.0
Clang version: 18.1.3 (1ubuntu1)
CMake version: version 3.27.7
Libc version: glibc-2.39

Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-47-generic-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 12.4.99
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA A100 80GB PCIe
Nvidia driver version: 560.35.03
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: False

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        45 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               16
On-line CPU(s) list:                  0-15
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Platinum 8160 CPU @ 2.10GHz
CPU family:                           6
Model:                                85
Thread(s) per core:                   1
Core(s) per socket:                   1
Socket(s):                            16
Stepping:                             4
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 syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault pti ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat pku ospke md_clear flush_l1d arch_capabilities
Hypervisor vendor:                    VMware
Virtualization type:                  full
L1d cache:                            512 KiB (16 instances)
L1i cache:                            512 KiB (16 instances)
L2 cache:                             16 MiB (16 instances)
L3 cache:                             528 MiB (16 instances)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-15
Vulnerability Gather data sampling:   Unknown: Dependent on hypervisor status
Vulnerability Itlb multihit:          KVM: Mitigation: VMX unsupported
Vulnerability L1tf:                   Mitigation; PTE Inversion
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
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] cudnn==1.1.0
[pip3] flake8==6.1.0
[pip3] flake8-bugbear==23.3.23
[pip3] flake8-comprehensions==3.15.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.11.2
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.22.4
[pip3] nvidia-cublas-cu12==12.1.3.1
[pip3] nvidia-cuda-cupti-cu12==12.1.105
[pip3] nvidia-cuda-nvrtc-cu12==12.1.105
[pip3] nvidia-cuda-runtime-cu12==12.1.105
[pip3] nvidia-cudnn-cu12==8.9.2.26
[pip3] nvidia-cufft-cu12==11.0.2.54
[pip3] nvidia-curand-cu12==10.3.2.106
[pip3] nvidia-cusolver-cu12==11.4.5.107
[pip3] nvidia-cusparse-cu12==12.1.0.106
[pip3] nvidia-nccl-cu12==2.20.5
[pip3] nvidia-nvjitlink-cu12==12.3.101
[pip3] nvidia-nvtx-cu12==12.1.105
[pip3] nvidia-pytriton==0.5.3
[pip3] nvtx==0.2.10
[pip3] onnx==1.17.0
[pip3] onnx-graphsurgeon==0.3.27
[pip3] onnxruntime==1.16.3
[pip3] onnxruntime-gpu==1.16.3
[pip3] onnxscript==0.1.0.dev20240817
[pip3] open-clip-torch==2.24.0
[pip3] optree==0.13.0
[pip3] pytorch-lightning==2.2.1
[pip3] pytorch-triton==3.0.0+901819d2b6
[pip3] torch==2.6.0a0+git13535e2
[pip3] torchdiffeq==0.2.3
[pip3] torchmetrics==1.2.0
[pip3] torchsde==0.2.6
[pip3] triton==3.1.0
[pip3] triton-model-navigator==0.7.5
[pip3] tritonclient==2.43.0
[conda] blas                      1.0                         mkl
[conda] cudnn                     1.1.0                    pypi_0    pypi
[conda] mkl                       2023.1.0         h213fc3f_46344
[conda] mkl-service               2.4.0           py310h5eee18b_1
[conda] mkl_fft                   1.3.10          py310h5eee18b_0
[conda] mkl_random                1.2.7           py310h1128e8f_0
[conda] numpy                     1.24.4                   pypi_0    pypi
[conda] nvidia-cublas-cu12        12.1.3.1                 pypi_0    pypi
[conda] nvidia-cuda-cupti-cu12    12.1.105                 pypi_0    pypi
[conda] nvidia-cuda-nvrtc-cu12    12.1.105                 pypi_0    pypi
[conda] nvidia-cuda-runtime-cu12  12.1.105                 pypi_0    pypi
[conda] nvidia-cudnn-cu12         8.9.2.26                 pypi_0    pypi
[conda] nvidia-cufft-cu12         11.0.2.54                pypi_0    pypi
[conda] nvidia-curand-cu12        10.3.2.106               pypi_0    pypi
[conda] nvidia-cusolver-cu12      11.4.5.107               pypi_0    pypi
[conda] nvidia-cusparse-cu12      12.1.0.106               pypi_0    pypi
[conda] nvidia-nccl-cu12          2.20.5                   pypi_0    pypi
[conda] nvidia-nvjitlink-cu12     12.3.101                 pypi_0    pypi
[conda] nvidia-nvtx-cu12          12.1.105                 pypi_0    pypi
[conda] nvidia-pytriton           0.5.3                    pypi_0    pypi
[conda] nvtx                      0.2.10                   pypi_0    pypi
[conda] open-clip-torch           2.24.0                   pypi_0    pypi
[conda] optree                    0.13.0                   pypi_0    pypi
[conda] pytorch-lightning         2.2.1                    pypi_0    pypi
[conda] pytorch-triton            3.0.0+901819d2b6          pypi_0    pypi
[conda] torch                     2.6.0a0+git13535e2           dev_0    <develop>
[conda] torchdiffeq               0.2.3                    pypi_0    pypi
[conda] torchfix                  0.4.0                    pypi_0    pypi
[conda] torchmetrics              1.2.0                    pypi_0    pypi
[conda] torchsde                  0.2.6                    pypi_0    pypi
[conda] triton                    3.1.0                    pypi_0    pypi
[conda] triton-model-navigator    0.7.5                    pypi_0    pypi
[conda] tritonclient              2.43.0                   pypi_0    pypi
```

cc @ezyang @gchanan @zou3519 @kadeng @msaroufim @chauhang @penguinwu @ydwu4 @bdhirsh @yf225