Repository: pytorch
Issue: torch.accelerator.is_available() raise RuntimeError if no available CUDA/XPU devices
Labels: high priority,triaged,module: regression,bug,module: accelerator

### 🐛 Describe the bug

```python
>>> import torch
>>> torch.accelerator.is_available()
/home/guangyey/repos/stock-pytorch/torch/xpu/__init__.py:120: UserWarning: XPU device count is zero! (Triggered internally at /home/guangyey/repos/stock-pytorch/c10/xpu/XPUFunctions.cpp:117.)
  torch._C._xpu_init()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/guangyey/repos/stock-pytorch/torch/accelerator/__init__.py", line 46, in is_available
    return device_count() > 0
  File "/home/guangyey/repos/stock-pytorch/torch/accelerator/__init__.py", line 33, in device_count
    return torch._C._accelerator_deviceCount()
  File "/home/guangyey/repos/stock-pytorch/torch/xpu/__init__.py", line 120, in _lazy_init
    torch._C._xpu_init()
RuntimeError: No XPU devices are available.
```

The root cause is that https://github.com/pytorch/pytorch/pull/144368 changed the current accelerator detection from runtime to compile time. The call stack now follows this flow `torch.accelerator.device_count` -> [device_lazy_init](https://github.com/pytorch/pytorch/blob/7a93a58b3c9bd528b86d76aaa924d7ad43be0864/torch/csrc/DeviceAccelerator.cpp#L16) -> [lazyInitDevice](https://github.com/pytorch/pytorch/blob/7a93a58b3c9bd528b86d76aaa924d7ad43be0864/torch/csrc/xpu/Module.cpp#L412) -> [device_count_ensure_non_zero](https://github.com/pytorch/pytorch/blob/7a93a58b3c9bd528b86d76aaa924d7ad43be0864/aten/src/ATen/xpu/detail/XPUHooks.cpp#L14)

As a result, a RuntimeError is raised if a user runs a PyTorch wheel built with XPU on a machine without any available XPU devices. The same issue applies to CUDA as well.

### Versions

Collecting environment information...
PyTorch version: 2.7.0a0+gitcfd08f8
Is debug build: False
CUDA used to build PyTorch: None
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.31.1
Libc version: glibc-2.35

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-5.19.0-32-generic-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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:                   42 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          24
On-line CPU(s) list:             0-23
Vendor ID:                       GenuineIntel
Model name:                      12th Gen Intel(R) Core(TM) i9-12900
CPU family:                      6
Model:                           151
Thread(s) per core:              2
Core(s) per socket:              16
Socket(s):                       1
Stepping:                        2
CPU max MHz:                     5100.0000
CPU min MHz:                     800.0000
BogoMIPS:                        4838.40
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 smx 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 epb invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi 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 avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi umip pku ospke waitpkg gfni vaes vpclmulqdq tme rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       640 KiB (16 instances)
L1i cache:                       768 KiB (16 instances)
L2 cache:                        14 MiB (10 instances)
L3 cache:                        30 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-23
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; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] flake8==6.1.0
[pip3] flake8-bugbear==23.3.23
[pip3] flake8-comprehensions==3.15.0
[pip3] flake8-executable==2.1.3
[pip3] flake8-logging-format==0.9.0
[pip3] flake8-pyi==23.3.1
[pip3] flake8-simplify==0.19.3
[pip3] mypy==1.13.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] optree==0.13.0
[pip3] torch==2.7.0a0+gitcfd08f8
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] optree                    0.13.0                   pypi_0    pypi
[conda] torch                     2.7.0a0+gitcfd08f8           dev_0    <develop>
[conda] torchfix                  0.4.0                    pypi_0    pypi

cc @ezyang @gchanan @zou3519 @kadeng @msaroufim @albanD @EikanWang