device_interface.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. """
  2. Device abstraction layer for TorchDynamo and Inductor backends.
  3. This module provides a unified interface for different hardware backends (CUDA, XPU,
  4. CPU, MPS, MTIA) through a common device interface. Key components include:
  5. - DeviceInterface: Base class defining the common API for all device types
  6. - Device-specific implementations: CudaInterface, XpuInterface, CpuInterface, MpsInterface, MtiaInterface
  7. - Device registration system for managing available backends
  8. - Worker APIs for multi-processing scenarios
  9. - Stream and event management across different devices
  10. - Device property caching for worker processes
  11. The abstraction layer enables device-agnostic code in TorchDynamo while allowing
  12. specialized implementations for each hardware backend's unique features.
  13. """
  14. import inspect
  15. import time
  16. from collections import namedtuple
  17. from collections.abc import Iterable
  18. from dataclasses import dataclass
  19. from typing import Any, Callable, Literal, Optional, Union
  20. import torch
  21. get_cuda_stream: Optional[Callable[[int], int]]
  22. if torch.cuda._is_compiled():
  23. from torch._C import _cuda_getCurrentRawStream as get_cuda_stream
  24. else:
  25. get_cuda_stream = None
  26. # Recording the device properties in the main process but used in worker process.
  27. caching_worker_device_properties: dict[str, Any] = {}
  28. caching_worker_current_devices: dict[str, int] = {}
  29. class DeviceInterface:
  30. """
  31. This is a simple device runtime interface for Inductor. It enables custom
  32. backends to be integrated with Inductor in a device-agnostic semantic.
  33. """
  34. class device:
  35. def __new__(cls, device: torch.types.Device) -> Any:
  36. raise NotImplementedError
  37. class Event:
  38. def __new__(cls, *args: Any, **kwargs: Any) -> Any:
  39. raise NotImplementedError(
  40. "Event should be inherited from torch.Event, otherwise, it couldn't be captured by dynamo."
  41. )
  42. class Stream:
  43. def __new__(cls, *args: Any, **kwargs: Any) -> Any:
  44. raise NotImplementedError(
  45. "Stream should be inherited from torch.Stream, otherwise, it couldn't be captured by dynamo."
  46. )
  47. class Worker:
  48. """
  49. Worker API to query device properties that will work in multi processing
  50. workers that cannot use the GPU APIs (due to processing fork() and
  51. initialization time issues). Properties are recorded in the main process
  52. before we fork the workers.
  53. """
  54. @staticmethod
  55. def set_device(device: int) -> None:
  56. raise NotImplementedError
  57. @staticmethod
  58. def current_device() -> int:
  59. raise NotImplementedError
  60. @staticmethod
  61. def get_device_properties(device: torch.types.Device = None) -> Any:
  62. raise NotImplementedError
  63. @staticmethod
  64. def current_device() -> int:
  65. raise NotImplementedError
  66. @staticmethod
  67. def set_device(device: torch.types.Device) -> None:
  68. raise NotImplementedError
  69. @staticmethod
  70. def maybe_exchange_device(device: int) -> int:
  71. raise NotImplementedError
  72. @staticmethod
  73. def exchange_device(device: int) -> int:
  74. raise NotImplementedError
  75. @staticmethod
  76. def device_count() -> int:
  77. raise NotImplementedError
  78. @staticmethod
  79. def is_available() -> bool:
  80. raise NotImplementedError
  81. @staticmethod
  82. def stream(stream: torch.Stream) -> Any:
  83. raise NotImplementedError
  84. @staticmethod
  85. def current_stream() -> torch.Stream:
  86. raise NotImplementedError
  87. @staticmethod
  88. def set_stream(stream: torch.Stream) -> None:
  89. raise NotImplementedError
  90. @staticmethod
  91. def _set_stream_by_id(stream_id: int, device_index: int, device_type: int) -> None:
  92. raise NotImplementedError
  93. @staticmethod
  94. def get_raw_stream(device_idx: int) -> int:
  95. raise NotImplementedError
  96. @staticmethod
  97. def synchronize(device: torch.types.Device = None) -> None:
  98. raise NotImplementedError
  99. @classmethod
  100. def get_device_properties(cls, device: torch.types.Device = None) -> Any:
  101. return cls.Worker.get_device_properties(device)
  102. @staticmethod
  103. def get_compute_capability(device: torch.types.Device = None) -> Any:
  104. raise NotImplementedError
  105. @staticmethod
  106. def is_bf16_supported(including_emulation: bool = False) -> bool:
  107. raise NotImplementedError
  108. @classmethod
  109. def is_dtype_supported(
  110. cls, dtype: torch.dtype, including_emulation: bool = False
  111. ) -> bool:
  112. return dtype != torch.bfloat16 or cls.is_bf16_supported(including_emulation)
  113. @staticmethod
  114. def memory_allocated(device: torch.types.Device = None) -> int:
  115. raise NotImplementedError
  116. @staticmethod
  117. def is_triton_capable(device: torch.types.Device = None) -> bool:
  118. """
  119. Returns True if the device has Triton support, False otherwise, even if
  120. the appropriate Triton backend is not available.
  121. """
  122. return False
  123. @classmethod
  124. def raise_if_triton_unavailable(cls, device: torch.types.Device = None) -> None:
  125. """
  126. Raises a `RuntimeError` with the appropriate human-readable instructions
  127. to resolve the issue if Triton is not available for the given device, or
  128. the default device if `device` is `None`.
  129. The caller should ensure the presence of the 'triton' package before
  130. calling this method.
  131. """
  132. if not cls.is_triton_capable():
  133. raise RuntimeError("This device is not capable of supporting Triton")
  134. class DeviceGuard:
  135. """
  136. This class provides a context manager for device switching. This is a stripped
  137. down version of torch.{device_name}.device.
  138. The context manager changes the current device to the given device index
  139. on entering the context and restores the original device on exiting.
  140. The device is switched using the provided device interface.
  141. """
  142. def __init__(
  143. self, device_interface: type[DeviceInterface], index: Optional[int]
  144. ) -> None:
  145. self.device_interface = device_interface
  146. self.idx = index
  147. self.prev_idx = -1
  148. def __enter__(self) -> None:
  149. if self.idx is not None:
  150. self.prev_idx = self.device_interface.exchange_device(self.idx)
  151. def __exit__(self, type: Any, value: Any, traceback: Any) -> Literal[False]:
  152. if self.idx is not None:
  153. self.idx = self.device_interface.maybe_exchange_device(self.prev_idx)
  154. return False
  155. class CudaInterface(DeviceInterface):
  156. device = torch.cuda.device # type: ignore[assignment]
  157. # register Event and Stream class into the backend interface
  158. # make sure Event and Stream are implemented and inherited from the torch.Event and torch.Stream
  159. Event = torch.cuda.Event # type: ignore[assignment]
  160. Stream = torch.cuda.Stream # type: ignore[assignment]
  161. class Worker:
  162. @staticmethod
  163. def set_device(device: int) -> None:
  164. caching_worker_current_devices["cuda"] = device
  165. @staticmethod
  166. def current_device() -> int:
  167. if "cuda" in caching_worker_current_devices:
  168. return caching_worker_current_devices["cuda"]
  169. return torch.cuda.current_device()
  170. @staticmethod
  171. def get_device_properties(device: torch.types.Device = None) -> Any:
  172. if device is not None:
  173. if isinstance(device, str):
  174. device = torch.device(device)
  175. assert device.type == "cuda"
  176. if isinstance(device, torch.device):
  177. device = device.index
  178. if device is None:
  179. device = CudaInterface.Worker.current_device()
  180. if "cuda" not in caching_worker_device_properties:
  181. device_prop = [
  182. torch.cuda.get_device_properties(i)
  183. for i in range(torch.cuda.device_count())
  184. ]
  185. caching_worker_device_properties["cuda"] = device_prop
  186. return caching_worker_device_properties["cuda"][device]
  187. current_device = staticmethod(torch.cuda.current_device)
  188. set_device = staticmethod(torch.cuda.set_device)
  189. device_count = staticmethod(torch.cuda.device_count)
  190. stream = staticmethod(torch.cuda.stream) # type: ignore[assignment]
  191. current_stream = staticmethod(torch.cuda.current_stream)
  192. set_stream = staticmethod(torch.cuda.set_stream) # type: ignore[assignment]
  193. _set_stream_by_id = staticmethod(torch.cuda._set_stream_by_id) # type: ignore[assignment]
  194. synchronize = staticmethod(torch.cuda.synchronize)
  195. get_device_properties = staticmethod(torch.cuda.get_device_properties) # type: ignore[assignment]
  196. get_raw_stream = staticmethod(get_cuda_stream) # type: ignore[assignment, arg-type]
  197. exchange_device = staticmethod(torch.cuda._exchange_device) # type: ignore[arg-type, has-type]
  198. maybe_exchange_device = staticmethod(torch.cuda._maybe_exchange_device) # type: ignore[arg-type, has-type]
  199. memory_allocated = staticmethod(torch.cuda.memory_allocated)
  200. is_bf16_supported = staticmethod(torch.cuda.is_bf16_supported) # type: ignore[arg-type]
  201. # Can be mock patched by @patch decorator.
  202. @staticmethod
  203. def is_available() -> bool:
  204. return torch.cuda.is_available()
  205. @staticmethod
  206. def get_compute_capability(device: torch.types.Device = None) -> Union[int, str]:
  207. if torch.version.hip is None:
  208. major, min = torch.cuda.get_device_capability(device)
  209. return major * 10 + min
  210. else:
  211. return torch.cuda.get_device_properties(device).gcnArchName.split(":", 1)[0]
  212. @staticmethod
  213. def is_triton_capable(device: torch.types.Device = None) -> bool:
  214. return (
  215. torch.version.hip is not None
  216. or torch.cuda.get_device_properties(device).major >= 7
  217. )
  218. @staticmethod
  219. def raise_if_triton_unavailable(device: torch.types.Device = None) -> None:
  220. from torch._inductor.exc import GPUTooOldForTriton
  221. if not CudaInterface.is_triton_capable(device):
  222. device_props = torch.cuda.get_device_properties(device)
  223. raise GPUTooOldForTriton(device_props, inspect.currentframe())
  224. import triton.backends
  225. if torch.version.hip is not None:
  226. if "amd" not in triton.backends.backends:
  227. raise RuntimeError("triton not built with the 'amd' backend")
  228. elif "nvidia" not in triton.backends.backends:
  229. raise RuntimeError("triton not built with the 'nvidia' backend")
  230. get_mtia_stream: Optional[Callable[[int], int]]
  231. if torch.mtia._is_compiled():
  232. from torch._C import _mtia_getCurrentRawStream as get_mtia_stream
  233. else:
  234. get_mtia_stream = None
  235. class MtiaInterface(DeviceInterface):
  236. device = torch.mtia.device # type: ignore[assignment]
  237. Event = torch.mtia.Event # type: ignore[assignment]
  238. Stream = torch.mtia.Stream # type: ignore[assignment]
  239. class Worker:
  240. @staticmethod
  241. def set_device(device: int) -> None:
  242. caching_worker_current_devices["mtia"] = device
  243. @staticmethod
  244. def current_device() -> int:
  245. if "mtia" in caching_worker_current_devices:
  246. return caching_worker_current_devices["mtia"]
  247. return torch.mtia.current_device()
  248. @staticmethod
  249. def get_device_properties(device: torch.types.Device = None) -> Any:
  250. if device is not None:
  251. if isinstance(device, str):
  252. device = torch.device(device)
  253. assert device.type == "mtia"
  254. if isinstance(device, torch.device):
  255. device = device.index
  256. if device is None:
  257. device = MtiaInterface.Worker.current_device()
  258. if "mtia" not in caching_worker_device_properties:
  259. device_prop = [
  260. torch.mtia.get_device_properties(i)
  261. for i in range(torch.mtia.device_count())
  262. ]
  263. caching_worker_device_properties["mtia"] = device_prop
  264. return caching_worker_device_properties["mtia"][device]
  265. current_device = staticmethod(torch.mtia.current_device)
  266. set_device = staticmethod(torch.mtia.set_device) # type: ignore[assignment]
  267. device_count = staticmethod(torch.mtia.device_count)
  268. stream = staticmethod(torch.mtia.stream) # type: ignore[assignment]
  269. current_stream = staticmethod(torch.mtia.current_stream)
  270. set_stream = staticmethod(torch.mtia.set_stream) # type: ignore[assignment]
  271. _set_stream_by_id = staticmethod(torch.mtia._set_stream_by_id) # type: ignore[assignment]
  272. synchronize = staticmethod(torch.mtia.synchronize)
  273. get_device_properties = staticmethod(torch.mtia.get_device_properties) # type: ignore[assignment]
  274. get_raw_stream = staticmethod(get_mtia_stream) # type: ignore[assignment, arg-type]
  275. exchange_device = staticmethod(torch.mtia._exchange_device) # type: ignore[arg-type]
  276. maybe_exchange_device = staticmethod(torch.mtia._maybe_exchange_device) # type: ignore[arg-type]
  277. memory_allocated = staticmethod(torch.mtia.memory_allocated) # type: ignore[assignment]
  278. is_bf16_supported = staticmethod(torch.mtia.is_bf16_supported) # type: ignore[arg-type]
  279. # Can be mock patched by @patch decorator.
  280. @staticmethod
  281. def is_available() -> bool:
  282. ret = torch.mtia.is_available()
  283. return ret
  284. @staticmethod
  285. def get_compute_capability(device: torch.types.Device = None) -> Any:
  286. cc = torch.mtia.get_device_capability(device)
  287. return cc
  288. @staticmethod
  289. def is_triton_capable(device: torch.types.Device = None) -> bool:
  290. return True
  291. @staticmethod
  292. def raise_if_triton_unavailable(evice: torch.types.Device = None) -> None:
  293. import triton.backends
  294. if "mtia" not in triton.backends.backends:
  295. raise RuntimeError("triton not built with the 'mtia' backend")
  296. get_xpu_stream: Optional[Callable[[int], int]]
  297. if torch.xpu._is_compiled():
  298. from torch._C import _xpu_getCurrentRawStream as get_xpu_stream
  299. else:
  300. get_xpu_stream = None
  301. class XpuInterface(DeviceInterface):
  302. device = torch.xpu.device # type: ignore[assignment]
  303. Event = torch.xpu.Event # type: ignore[assignment]
  304. Stream = torch.xpu.Stream # type: ignore[assignment]
  305. class Worker:
  306. @staticmethod
  307. def set_device(device: int) -> None:
  308. caching_worker_current_devices["xpu"] = device
  309. @staticmethod
  310. def current_device() -> int:
  311. if "xpu" in caching_worker_current_devices:
  312. return caching_worker_current_devices["xpu"]
  313. return torch.xpu.current_device()
  314. @staticmethod
  315. def get_device_properties(device: torch.types.Device = None) -> Any:
  316. if device is not None:
  317. if isinstance(device, str):
  318. device = torch.device(device)
  319. assert device.type == "xpu"
  320. if isinstance(device, torch.device):
  321. device = device.index
  322. if device is None:
  323. device = XpuInterface.Worker.current_device()
  324. if "xpu" not in caching_worker_device_properties:
  325. device_prop = [
  326. torch.xpu.get_device_properties(i)
  327. for i in range(torch.xpu.device_count())
  328. ]
  329. caching_worker_device_properties["xpu"] = device_prop
  330. return caching_worker_device_properties["xpu"][device]
  331. current_device = staticmethod(torch.xpu.current_device)
  332. set_device = staticmethod(torch.xpu.set_device)
  333. device_count = staticmethod(torch.xpu.device_count)
  334. stream = staticmethod(torch.xpu.stream) # type: ignore[assignment]
  335. current_stream = staticmethod(torch.xpu.current_stream)
  336. set_stream = staticmethod(torch.xpu.set_stream) # type: ignore[assignment]
  337. _set_stream_by_id = staticmethod(torch.xpu._set_stream_by_id) # type: ignore[assignment]
  338. synchronize = staticmethod(torch.xpu.synchronize)
  339. get_device_properties = staticmethod(torch.xpu.get_device_properties) # type: ignore[assignment]
  340. get_raw_stream = staticmethod(get_xpu_stream) # type: ignore[assignment, arg-type]
  341. exchange_device = staticmethod(torch.xpu._exchange_device) # type: ignore[arg-type]
  342. maybe_exchange_device = staticmethod(torch.xpu._maybe_exchange_device) # type: ignore[arg-type]
  343. memory_allocated = staticmethod(torch.xpu.memory_allocated)
  344. # Can be mock patched by @patch decorator.
  345. @staticmethod
  346. def is_available() -> bool:
  347. return torch.xpu.is_available()
  348. @staticmethod
  349. def get_compute_capability(device: torch.types.Device = None) -> Any:
  350. cc = torch.xpu.get_device_capability(device)
  351. return cc
  352. @staticmethod
  353. def is_bf16_supported(including_emulation: bool = False) -> bool:
  354. return torch.xpu.is_bf16_supported()
  355. @staticmethod
  356. def is_triton_capable(device: torch.types.Device = None) -> bool:
  357. return True
  358. @staticmethod
  359. def raise_if_triton_unavailable(device: torch.types.Device = None) -> None:
  360. import triton.backends
  361. if "intel" not in triton.backends.backends:
  362. raise RuntimeError("triton not built with the 'intel' backend")
  363. @dataclass
  364. class CpuDeviceProperties:
  365. multi_processor_count: int
  366. class CpuInterface(DeviceInterface):
  367. class Event(torch.Event):
  368. def __init__(self, enable_timing: bool = True) -> None:
  369. self.time = 0.0
  370. def elapsed_time(self, end_event: Any) -> float:
  371. return (end_event.time - self.time) * 1000
  372. def record(self, stream: Any = None) -> None:
  373. self.time = time.perf_counter()
  374. class Worker:
  375. @staticmethod
  376. def get_device_properties(
  377. device: torch.types.Device = None,
  378. ) -> CpuDeviceProperties:
  379. import multiprocessing
  380. cpu_count = multiprocessing.cpu_count()
  381. return CpuDeviceProperties(cpu_count)
  382. @staticmethod
  383. def is_available() -> bool:
  384. return True
  385. @staticmethod
  386. def is_bf16_supported(including_emulation: bool = False) -> bool:
  387. return True
  388. @staticmethod
  389. def get_compute_capability(device: torch.types.Device = None) -> str:
  390. return ""
  391. @staticmethod
  392. def get_raw_stream(device_idx: Any) -> int:
  393. return 0
  394. @staticmethod
  395. def current_device() -> int:
  396. return 0
  397. @staticmethod
  398. def synchronize(device: torch.types.Device = None) -> None:
  399. pass
  400. @staticmethod
  401. def is_triton_capable(device: torch.types.Device = None) -> bool:
  402. return True
  403. @staticmethod
  404. def raise_if_triton_unavailable(device: torch.types.Device = None) -> None:
  405. import triton.backends
  406. if "cpu" not in triton.backends.backends:
  407. raise RuntimeError("triton not built with the 'cpu' backend")
  408. class MpsInterface(DeviceInterface):
  409. @staticmethod
  410. def is_bf16_supported(including_emulation: bool = False) -> bool:
  411. return torch.backends.mps.is_macos_or_newer(14, 0)
  412. @classmethod
  413. def is_dtype_supported(
  414. cls, dtype: torch.dtype, including_emulation: bool = False
  415. ) -> bool:
  416. if dtype in [torch.float64, torch.complex128]:
  417. return False
  418. return dtype != torch.bfloat16 or cls.is_bf16_supported(including_emulation)
  419. @staticmethod
  420. def is_available() -> bool:
  421. return torch.backends.mps.is_available()
  422. @staticmethod
  423. def current_device() -> int:
  424. return 0
  425. @staticmethod
  426. def get_compute_capability(device: torch.types.Device = None) -> str:
  427. return ""
  428. @staticmethod
  429. def synchronize(device: torch.types.Device = None) -> None:
  430. torch.mps.synchronize()
  431. class Worker:
  432. @staticmethod
  433. def get_device_properties(device: torch.types.Device = None) -> Any:
  434. return namedtuple("MPSProperties", ["multi_processor_count"])(
  435. torch.backends.mps.get_core_count() # type: ignore[arg-type]
  436. )
  437. @staticmethod
  438. def current_device() -> int:
  439. return 0
  440. device_interfaces: dict[str, type[DeviceInterface]] = {}
  441. _device_initialized = False
  442. def register_interface_for_device(
  443. device: Union[str, torch.device], device_interface: type[DeviceInterface]
  444. ) -> None:
  445. if isinstance(device, torch.device):
  446. device = device.type
  447. device_interfaces[device] = device_interface
  448. def get_interface_for_device(device: Union[str, torch.device]) -> type[DeviceInterface]:
  449. if isinstance(device, torch.device):
  450. device = device.type
  451. if not _device_initialized:
  452. init_device_reg()
  453. if device in device_interfaces:
  454. return device_interfaces[device]
  455. raise NotImplementedError(f"No interface for device {device}")
  456. def get_registered_device_interfaces() -> Iterable[tuple[str, type[DeviceInterface]]]:
  457. if not _device_initialized:
  458. init_device_reg()
  459. return device_interfaces.items()
  460. def init_device_reg() -> None:
  461. global _device_initialized
  462. register_interface_for_device("cuda", CudaInterface)
  463. for i in range(torch.cuda.device_count()):
  464. register_interface_for_device(f"cuda:{i}", CudaInterface)
  465. register_interface_for_device("xpu", XpuInterface)
  466. for i in range(torch.xpu.device_count()):
  467. register_interface_for_device(f"xpu:{i}", XpuInterface)
  468. register_interface_for_device("mtia", MtiaInterface)
  469. for i in range(torch.mtia.device_count()):
  470. register_interface_for_device(f"mtia:{i}", MtiaInterface)
  471. register_interface_for_device("cpu", CpuInterface)
  472. register_interface_for_device("mps", MpsInterface)
  473. _device_initialized = True