Repository: pytorch
Issue: arctan2 fp16 error when optimising
Labels: module: autograd,module: optimizer,triaged,module: half

### 🐛 Describe the bug

I can't narrow it down further, but torch.arctan2 seemingly calculates the correct gradients and optimises correctly for fp32,fp64 and bfloat16, but for some reason, the version for fp16 raises NaNs after a single optimisation iteration (whether using SGD or Adam or AdamW, didn't bother checking other optimisers after confirming the issue for 3 optimisers). Importantly, it looks like the NaN's occur after optimisation, but never beforehand, ie making the random tensors bigger never results in NaN in the loss for the zeroth iteration.
 
``` 
import torch
torch.manual_seed(2)
from functools import partial
def test_arctan2_grads(dtype:torch.dtype,optim:torch.optim.Optimizer):
    C,H,W = 2,384,384
    inp,target = torch.randn((C,H,W),requires_grad=True,dtype=dtype,device='cuda'),torch.randn((1,H,W),requires_grad=False,dtype=dtype,device='cuda')
    start_inp = inp.clone().detach()
    optim = optim(params=[inp],lr=1e-5)

    for i in range(100):
        optim.zero_grad()
        numerator,denominator = inp[0,:,:],inp[1,:,:]
        denom_nonzero = torch.where(denominator!=0, denominator,torch.finfo(denominator.dtype).eps)
        b = torch.arctan2(numerator,denominator).unsqueeze(0)
        # b = torch.arctan2(numerator,denom_nonzero).unsqueeze(0)
        loss_unreduced = b-target
        isnan = torch.isnan(loss_unreduced)
        if torch.sum(isnan)>0:
            nan_index = torch.nonzero(isnan)[0].squeeze()
            print(f"Dtype = {dtype} had NaN at {nan_index.cpu().numpy()} after {i} iterations")
            print(f"start values at index = {start_inp[:,nan_index[1],nan_index[2]]}")
            print(f"after {i} iterations of optimisation: {inp[:,nan_index[1],nan_index[2]]}")
            return None
        loss = (loss_unreduced).mean()
        loss.backward()
        optim.step()
test_arctan2_grads_sgd = partial(test_arctan2_grads,optim=torch.optim.SGD)
test_arctan2_grads_adam = partial(test_arctan2_grads,optim=torch.optim.Adam)
test_arctan2_grads_adamw = partial(test_arctan2_grads,optim=partial(torch.optim.AdamW,weight_decay=1e-2))

test_arctan2_grads_sgd(torch.float32)
test_arctan2_grads_sgd(torch.float64)
test_arctan2_grads_sgd(torch.bfloat16)

test_arctan2_grads_adam(torch.float32)
test_arctan2_grads_adam(torch.float64)
test_arctan2_grads_adam(torch.bfloat16)

test_arctan2_grads_adamw(torch.float32)
test_arctan2_grads_adamw(torch.float64)
test_arctan2_grads_adamw(torch.bfloat16)


test_arctan2_grads_sgd(torch.float16)
test_arctan2_grads_adam(torch.float16)
test_arctan2_grads_adamw(torch.float16)
```
This (for me) prints to the console: 
![image](https://github.com/pytorch/pytorch/assets/94324854/0e3b218e-eff9-4fed-ad86-89ed9c3e2614)


### Versions


Collecting environment information...
PyTorch version: 2.1.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.2.0-37-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.1.66
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 5700X 8-Core Processor
CPU family:                         25
Model:                              33
Thread(s) per core:                 2
Core(s) per socket:                 8
Socket(s):                          1
Stepping:                           2
Frequency boost:                    enabled
CPU max MHz:                        4661.7178
CPU min MHz:                        2200.0000
BogoMIPS:                           6800.37
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 x2apic 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
Virtualisation:                     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 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 Retbleed:             Not affected
Vulnerability Spec rstack overflow: Mitigation; safe RET, no microcode
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] mypy-extensions==1.0.0
[pip3] numpy==1.23.2
[pip3] torch==2.1.0+cu121
[pip3] torch-tb-profiler==0.4.1
[pip3] torchmetrics==0.9.3
[pip3] torchvision==0.16.0+cu121
[pip3] triton==2.1.0
[conda] Could not collect

cc @ezyang @albanD @zou3519 @gqchen @pearu @nikitaved @soulitzer @Lezcano @Varal7 @vincentqb @jbschlosser @janeyx99 @crcrpar