torch.compile does not respect branching in forward()
Labels: triaged, oncall: pt2, module: guards

### 🐛 Describe the bug

Hey all,
I have a Module that has an if statement in its `forward()` function. When using torch.compile, the model is frozen in the first branching it encountered. I have created a minimal repro script that recreates this problem without all the other fuzz.

```python
import torch
from torch import nn
from torch.optim import Adam


class SimpleNetwork(nn.Module):
    def __init__(self):
        super().__init__()

        self.layers = nn.Sequential(nn.Conv2d(3, 16, 3, 2, 1),
                                     nn.ReLU(),
                                     nn.Conv2d(16, 32, 3, 2, 1),
                                     nn.AdaptiveAvgPool2d(1))

        self.return_input = True

    def forward(self, x):
        ret = self.layers(x)[0, 0]

        if self.return_input:
            return ret, x
        else:
            return ret


if __name__ == '__main__':
    loss = nn.CrossEntropyLoss()
    net = SimpleNetwork().to('cuda')
    net_optim = torch.compile(net)
    optim = Adam(net_optim.parameters(), lr=1e-4)

    for i in range(10):
        optim.zero_grad()
        dummy_input = torch.rand((1, 3, 32, 32), device=torch.device('cuda', 0))
        dummy_target = torch.randint(0, 32, (1, ), device=torch.device('cuda', 0))
        # here the output is a tuple of (result, input)
        out = net_optim(dummy_input)
        l = loss(out[0], dummy_target)
        l.backward()
        optim.step()

    net_optim.return_input = False
    dummy_input = torch.rand((1, 3, 32, 32), device=torch.device('cuda', 0))
    # the expected output here is just the result. This should NOT be a tuple because we set return_orig to False
    out = net_optim(dummy_input)
    print(type(out))
```

At the very end the module still returns a tuple of (result, input) even though it should return the result only.

It can of course be that this is intended behavior (after all, how could torch.compile know about the other branch at compile time?). If that is the case, I would very much appreciate a hint as to how to reset the model compilation upon changing `return_input`. 
Why not simply create a new compiled model by calling torch.compile again? Because that is not as straightforward as it seems. IIRC the correct order is `initialize model` -> `torch.compile` -> `initialize optimizers` -> `initialize DDP` (which is what I am using). Redoing the compile step would require me to redo the other steps as well which is just ugly.

Best,
Fabian


### Error logs

_No response_

### Minified repro

_No response_

### Versions

Collecting environment information...
PyTorch version: 2.1.0.dev20230724
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Jul  5 2023, 18:54:27) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.19.0-46-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4090
Nvidia driver version: 530.30.02
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
Address sizes:                   48 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          16
On-line CPU(s) list:             0-15
Vendor ID:                       AuthenticAMD
Model name:                      AMD Ryzen 7 5800X 8-Core Processor
CPU family:                      25
Model:                           33
Thread(s) per core:              2
Core(s) per socket:              8
Socket(s):                       1
Stepping:                        0
Frequency boost:                 enabled
CPU max MHz:                     5083,9839
CPU min MHz:                     2200,0000
BogoMIPS:                        7600.15
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm
Virtualization:                  AMD-V
L1d cache:                       256 KiB (8 instances)
L1i cache:                       256 KiB (8 instances)
L2 cache:                        4 MiB (8 instances)
L3 cache:                        32 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-15
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Not affected
Vulnerability Retbleed:          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; Retpolines, IBPB conditional, IBRS_FW, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] torch==2.1.0.dev20230724
[pip3] torchaudio==2.1.0.dev20230724
[pip3] torchvision==0.16.0.dev20230724
[pip3] triton==2.1.0
[conda] Could not collect


cc @ezyang @msaroufim @wconstab @bdhirsh @anijain2305