Repository: pytorch
Issue: tracing does not work when torch.distributions is involved
Labels: oncall: jit

### 🐛 Describe the bug

Basically the title, i am working on a reinforcement learning model and wanted to trace it to a scriptmodel to use it in C++, but it wont trace when torch.distributions, specifically the MultivariateNormal distribution (i have not tried the others).

I define a module that uses the distribution like this
```python
class ActorModel(torch.nn.Module):
    def __init__(self, actor):
        super().__init__()
        self.actor = actor
    def forward(self, x):
        logits = self.actor(x)[0]
        batch_size = logits.shape[0]
        action_dim = 3
        
        # Split the logits into the mean and Cholesky factor
        tril_flat = logits[:, action_dim:]
        mean = logits[:, :action_dim]
        tril_flat = torch.where(tril_flat == 0, 1e-8, tril_flat).detach()
        tril = torch.zeros(batch_size, action_dim, action_dim, device=logits.device)
        tril[:, torch.tril(torch.ones(action_dim, action_dim, device=logits.device)).bool()] = tril_flat
        
        # Construct the multivariate normal distribution
        dist = MultivariateNormal(mean, scale_tril=tril)    
        return dist.sample()
```

and I then (try to) trace it like this
```python
actor.load_state_dict(policy.actor.state_dict())
actor = actor.to(torch.device('cpu'))
actor_module = ActorModel(actor)
actor_module.eval()
for param in actor_module.parameters():
    param.requires_grad = False

with torch.no_grad():
    example_input = torch.rand((1, 2, 290))
    traced_script_last_model = torch.jit.script(actor_module, example_input)
```
The result is a fail in the sanity check, along with a warning about non-deterministic nodes
```
/home/bigbaduser/.local/lib/python3.11/site-packages/torch/jit/_trace.py:1084: TracerWarning: Trace had nondeterministic nodes. Did you forget call .eval() on your model? Nodes:
        %bvec : Float(1, 3, strides=[3, 1], requires_grad=0, device=cpu) = aten::normal(%588, %596, %597) # /home/bigbaduser/.local/lib/python3.11/site-packages/torch/distributions/u
tils.py:48:0
This may cause errors in trace checking. To disable trace checking, pass check_trace=False to torch.jit.trace()
  _check_trace(
/home/bigbaduser/.local/lib/python3.11/site-packages/torch/jit/_trace.py:1084: TracerWarning: Output nr 1. of the traced function does not match the corresponding output of the Pytho
n function. Detailed error:
Tensor-likes are not close!

Mismatched elements: 3 / 3 (100.0%)
Greatest absolute difference: 6.103819370269775 at index (0, 2) (up to 1e-05 allowed)
Greatest relative difference: 9.780014123811462 at index (0, 1) (up to 1e-05 allowed)
  _check_trace(
```
And I know that the issue is in the distributions because when I try to trace the model itself with
```python
with torch.no_grad():
    example_input = torch.rand((1, 2, 290))
    traced_script_last_model = torch.jit.script(lambda x: actor(x)[0], example_input)
```
it works without issue. I thought it could be the `torch.where` since that is (at least in my head, i dont know how it is implemented) a control flow operation, but i tried deleting that line and it didn't matter, same error

### Versions

```
Collecting environment information...
PyTorch version: 2.0.0+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Arch Linux (x86_64)
GCC version: (GCC) 13.1.1 20230429
Clang version: 15.0.7
CMake version: version 3.26.3
Libc version: glibc-2.37

Python version: 3.11.3 (main, Apr  5 2023, 15:52:25) [GCC 12.2.1 20230201] (64-bit runtime)
Python platform: Linux-6.3.1-arch1-1-x86_64-with-glibc2.37
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 3080 Ti
Nvidia driver version: 530.41.03
cuDNN version: Probably one of the following:
/usr/lib/libcudnn.so.8.8.0
/usr/lib/libcudnn_adv_infer.so.8.8.0
/usr/lib/libcudnn_adv_train.so.8.8.0
/usr/lib/libcudnn_cnn_infer.so.8.8.0
/usr/lib/libcudnn_cnn_train.so.8.8.0
/usr/lib/libcudnn_ops_infer.so.8.8.0
/usr/lib/libcudnn_ops_train.so.8.8.0
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:                   39 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          6
On-line CPU(s) list:             0-5
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Core(TM) i5-8400 CPU @ 2.80GHz
CPU family:                      6
Model:                           158
Thread(s) per core:              1
Core(s) per socket:              6
Socket(s):                       1
Stepping:                        10
CPU(s) scaling MHz:              95%
CPU max MHz:                     4000.0000
CPU min MHz:                     800.0000
BogoMIPS:                        5602.18
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 pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single pti ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp
Virtualization:                  VT-x
L1d cache:                       192 KiB (6 instances)
L1i cache:                       192 KiB (6 instances)
L2 cache:                        1.5 MiB (6 instances)
L3 cache:                        9 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-5
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Mitigation; PTE Inversion; VMX conditional cache flushes, SMT disabled
Vulnerability Mds:               Vulnerable: Clear CPU buffers attempted, no microcode; SMT disabled
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Vulnerable: Clear CPU buffers attempted, no microcode; SMT disabled
Vulnerability Retbleed:          Mitigation; IBRS
Vulnerability Spec store bypass: Vulnerable
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
Vulnerability Srbds:             Vulnerable: No microcode
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] torch==2.0.0
[pip3] triton==2.0.0
[conda] Could not collect
```

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel