Repository: pytorch
Issue: Inconsistent gradients in torch script function
Labels: oncall: jit

### 🐛 Describe the bug

This code reproduce the bug:

```python
import torch


@torch.jit.script
def log_diff(s: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
    loss = s.log() - t.log()
    return loss.real


def log_diff_ref(s: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
    loss = s.log() - t.log()
    return loss.real


for i in range(2):
    print()
    print(f"#### {i=} ####")
    torch.manual_seed(23333)
    s = torch.rand([], dtype=torch.complex64)
    t = torch.rand([], dtype=torch.complex64)
    print(f"{s=}")
    print(f"{t=}")
    s = s.requires_grad_()

    loss = log_diff(s, t)
    loss_ref = log_diff_ref(s, t)
    print(f"{loss=}")
    print(f"{loss_ref=}")

    grad, = torch.autograd.grad(loss, s, retain_graph=True)
    grad_ref, = torch.autograd.grad(loss_ref, s, retain_graph=True)
    print(f"{grad=}")
    print(f"{grad_ref=}")

    diff = grad - grad_ref
    print(f"{diff=}")
```

The result is something like:
```

#### i=0 ####
s=tensor(0.9137+0.6452j)
t=tensor(0.6840+0.0498j)
loss=tensor(0.4892, grad_fn=<SelectBackward0>)
loss_ref=tensor(0.4892, grad_fn=<SelectBackward0>)
grad=tensor(0.7303+0.5157j)
grad_ref=tensor(0.7303+0.5157j)
diff=tensor(0.+0.j)

#### i=1 ####
s=tensor(0.9137+0.6452j)
t=tensor(0.6840+0.0498j)
loss=tensor(0.4892, grad_fn=<SelectBackward0>)
loss_ref=tensor(0.4892, grad_fn=<SelectBackward0>)
grad=tensor(0.7303-0.5157j)
grad_ref=tensor(0.7303+0.5157j)
diff=tensor(0.-1.0314j)
```

As we can see, invoking the same function multiple times yield different gradient results (diff != 0 when i = 1 while diff = 0 when i = 0)

### Versions

Collecting environment information...
PyTorch version: 2.5.1+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Arch Linux (x86_64)
GCC version: (GCC) 14.2.1 20240910
Clang version: 18.1.8
CMake version: version 3.31.0
Libc version: glibc-2.40

Python version: 3.12.7 (main, Oct  1 2024, 11:15:50) [GCC 14.2.1 20240910] (64-bit runtime)
Python platform: Linux-6.6.59-1-lts-x86_64-with-glibc2.40
Is CUDA available: True
CUDA runtime version: 12.6.77
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3060
Nvidia driver version: 565.57.01
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:                        39 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               12
On-line CPU(s) list:                  0-11
Vendor ID:                            GenuineIntel
Model name:                           12th Gen Intel(R) Core(TM) i5-12400F
CPU family:                           6
Model:                                151
Thread(s) per core:                   2
Core(s) per socket:                   6
Socket(s):                            1
Stepping:                             5
CPU(s) scaling MHz:                   49%
CPU max MHz:                          4400.0000
CPU min MHz:                          800.0000
BogoMIPS:                             4993.00
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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            288 KiB (6 instances)
L1i cache:                            192 KiB (6 instances)
L2 cache:                             7.5 MiB (6 instances)
L3 cache:                             18 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-11
Vulnerability Gather data sampling:   Not affected
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
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; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] mypy==1.13.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] nvidia-cublas-cu12==12.4.5.8
[pip3] nvidia-cuda-cupti-cu12==12.4.127
[pip3] nvidia-cuda-nvrtc-cu12==12.4.127
[pip3] nvidia-cuda-runtime-cu12==12.4.127
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.2.1.3
[pip3] nvidia-curand-cu12==10.3.5.147
[pip3] nvidia-cusolver-cu12==11.6.1.9
[pip3] nvidia-cusparse-cu12==12.3.1.170
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.4.127
[pip3] torch==2.5.1
[pip3] triton==3.1.0
[conda] Could not collect

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel