Repository: pytorch
Issue: Backwards pass through Beta distribution rsample gives inf for 4 < alpha - 2**16 < 1040, beta = 3/2
Labels: module: distributions,triaged

### 🐛 Describe the bug

I am encountering an inf when backpropagating through the rsample method of the `torch.distributions.beta.Beta` distribution.

```python
import torch

size = 16384
alpha = torch.as_tensor([2 ** 16 + 1039.]) # fails for 4 < alpha - 2**16 < 1040
beta = torch.as_tensor([1.5])

alpha.requires_grad_()
z = torch.distributions.beta.Beta(alpha, beta).rsample((size,))
loss = z.mean()
loss.backward()
print(alpha.grad) # returns tensor([inf])
```

Some datapoints:
- I can reproduce this with `device='cpu'` and `device='cuda'`.
- The bug does not happen if I make alpha a `torch.float64`.
- With `beta = 1.5`, the bug only happens if `4 < alpha - 2**16 < 1040`.
- The bug is stochastic and depends on the rsample drawing a sample that is sufficiently close to 1. With `size=16384` the bug almost always happens.
- Following the rabbit hole, I am fairly sure that the error occurs inside [_beta_grad_beta_small](https://github.com/pytorch/pytorch/blob/03005bb655d033f33979dda3f7ef4e3d5bde109e/aten/src/ATen/native/Distributions.h#L397), because the error only occurs for samples that meet the criteria `if (x >= 0.5f && boundary < 0.75f)` in [dirichlet_grad_one](https://github.com/pytorch/pytorch/blob/03005bb655d033f33979dda3f7ef4e3d5bde109e/aten/src/ATen/native/Distributions.h#L455).

### Versions

PyTorch version: 2.3.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Rocky Linux release 8.9 (Green Obsidian) (x86_64)
GCC version: (GCC) 8.5.0 20210514 (Red Hat 8.5.0-20)
Clang version: Could not collect
CMake version: version 3.29.3
Libc version: glibc-2.28

Python version: 3.10.14 | packaged by conda-forge | (main, Mar 20 2024, 12:45:18) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-4.18.0-513.11.1.el8_9.x86_64-x86_64-with-glibc2.28
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A100 80GB PCIe
GPU 1: NVIDIA A100 80GB PCIe
GPU 2: NVIDIA A100 80GB PCIe
GPU 3: NVIDIA A100 80GB PCIe

Nvidia driver version: 545.23.08
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
Byte Order:          Little Endian
CPU(s):              32
On-line CPU(s) list: 0-31
Thread(s) per core:  1
Core(s) per socket:  16
Socket(s):           2
NUMA node(s):        2
Vendor ID:           GenuineIntel
CPU family:          6
Model:               85
Model name:          Intel(R) Xeon(R) Silver 4216 CPU @ 2.10GHz
Stepping:            7
CPU MHz:             3200.000
CPU max MHz:         3200.0000
CPU min MHz:         800.0000
BogoMIPS:            4200.00
Virtualization:      VT-x
L1d cache:           32K
L1i cache:           32K
L2 cache:            1024K
L3 cache:            22528K
NUMA node0 CPU(s):   0-15
NUMA node1 CPU(s):   16-31
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 smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts pku ospke avx512_vnni md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] gpytorch==1.11
[pip3] numpy==1.25.2
[pip3] torch==2.3.0
[pip3] torch_geometric==2.3.1
[pip3] torchmetrics==0.11.4
[pip3] torchvision==0.15.2
[pip3] triton==2.3.0
[conda] gpytorch                  1.11                     pypi_0    pypi
[conda] numpy                     1.25.2                   pypi_0    pypi
[conda] torch                     2.3.0                    pypi_0    pypi
[conda] torch-geometric           2.3.1                    pypi_0    pypi
[conda] torchmetrics              0.11.4                   pypi_0    pypi
[conda] torchvision               0.15.2                   pypi_0    pypi
[conda] triton                    2.3.0                    pypi_0    pypi

cc @fritzo @neerajprad @alicanb @nikitaved