_utils.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import ctypes
  2. import sys
  3. from typing import Any, Optional, Union
  4. import torch
  5. # The _get_device_index has been moved to torch.utils._get_device_index
  6. from torch._utils import _get_device_index as _torch_get_device_index
  7. def _get_hip_runtime_library() -> ctypes.CDLL:
  8. if sys.platform == "win32":
  9. lib = ctypes.CDLL(f"amdhip64_{torch.version.hip[0]}.dll")
  10. else: # Unix-based systems
  11. lib = ctypes.CDLL("libamdhip64.so")
  12. lib.cuGetErrorString = lib.hipGetErrorString # type: ignore[attr-defined]
  13. lib.cuModuleLoadData = lib.hipModuleLoadData # type: ignore[attr-defined]
  14. lib.cuModuleGetFunction = lib.hipModuleGetFunction # type: ignore[attr-defined]
  15. lib.cuLaunchKernel = lib.hipModuleLaunchKernel # type: ignore[attr-defined]
  16. lib.cuFuncSetAttribute = lib.hipFuncSetAttribute # type: ignore[attr-defined]
  17. return lib
  18. def _get_cuda_library() -> ctypes.CDLL:
  19. if sys.platform == "win32":
  20. return ctypes.CDLL("nvcuda.dll")
  21. else: # Unix-based systems
  22. return ctypes.CDLL("libcuda.so.1")
  23. # Load GPU driver runtime
  24. def _get_gpu_runtime_library() -> ctypes.CDLL:
  25. if torch.version.hip:
  26. return _get_hip_runtime_library()
  27. else:
  28. return _get_cuda_library()
  29. # Helper: check CUDA errors
  30. def _check_cuda(result: int) -> None:
  31. if result == 0:
  32. return
  33. err_str = ctypes.c_char_p()
  34. libcuda = _get_gpu_runtime_library() # Get reference to CUDA library
  35. libcuda.cuGetErrorString(result, ctypes.byref(err_str))
  36. error_message = (
  37. err_str.value.decode() if err_str.value is not None else "Unknown CUDA error"
  38. )
  39. raise RuntimeError(f"CUDA error: {error_message}")
  40. def _get_hiprtc_library() -> ctypes.CDLL:
  41. if sys.platform == "win32":
  42. version_str = "".join(["0", torch.version.hip[0], "0", torch.version.hip[2]])
  43. lib = ctypes.CDLL(f"hiprtc{version_str}.dll")
  44. else:
  45. lib = ctypes.CDLL("libhiprtc.so")
  46. # Provide aliases for HIP RTC functions to match NVRTC API
  47. lib.nvrtcGetErrorString = lib.hiprtcGetErrorString # type: ignore[attr-defined]
  48. lib.nvrtcCreateProgram = lib.hiprtcCreateProgram # type: ignore[attr-defined]
  49. lib.nvrtcDestroyProgram = lib.hiprtcDestroyProgram # type: ignore[attr-defined]
  50. lib.nvrtcCompileProgram = lib.hiprtcCompileProgram # type: ignore[attr-defined]
  51. lib.nvrtcGetPTXSize = lib.hiprtcGetCodeSize # type: ignore[attr-defined]
  52. lib.nvrtcGetPTX = lib.hiprtcGetCode # type: ignore[attr-defined]
  53. lib.nvrtcGetProgramLogSize = lib.hiprtcGetProgramLogSize # type: ignore[attr-defined]
  54. lib.nvrtcGetProgramLog = lib.hiprtcGetProgramLog # type: ignore[attr-defined]
  55. lib.nvrtcAddNameExpression = lib.hiprtcAddNameExpression # type: ignore[attr-defined]
  56. lib.nvrtcGetLoweredName = lib.hiprtcGetLoweredName # type: ignore[attr-defined]
  57. return lib
  58. def _get_nvrtc_library() -> ctypes.CDLL:
  59. major_version = int(torch.version.cuda.split(".")[0]) # type: ignore[union-attr]
  60. if sys.platform == "win32":
  61. nvrtc_libs = [
  62. f"nvrtc64_{major_version}0_0.dll",
  63. ]
  64. else:
  65. nvrtc_libs = [
  66. f"libnvrtc.so.{major_version}",
  67. "libnvrtc.so", # Fallback to unversioned
  68. ]
  69. for lib_name in nvrtc_libs:
  70. try:
  71. return ctypes.CDLL(lib_name)
  72. except OSError:
  73. continue
  74. raise OSError("Could not find any NVRTC library")
  75. def _get_gpu_rtc_library() -> ctypes.CDLL:
  76. # Since PyTorch already loads the GPU RTC library, we can use the system library
  77. # which should be compatible with PyTorch's version
  78. if torch.version.hip:
  79. return _get_hiprtc_library()
  80. else:
  81. return _get_nvrtc_library()
  82. def _get_gpu_rtc_compatible_flags() -> list[str]:
  83. """
  84. Get HIPCC/NVCC flags that are compatible with NVRTC compilation.
  85. Returns:
  86. List of HIPCC/NVCC flags that can be safely used with NVRTC.
  87. """
  88. from torch.utils.cpp_extension import COMMON_HIPCC_FLAGS, COMMON_NVCC_FLAGS
  89. nvrtc_unsupported_flags = {
  90. "--expt-relaxed-constexpr",
  91. }
  92. # Filter out unsupported flags
  93. compatible_flags = [
  94. flag for flag in COMMON_NVCC_FLAGS if flag not in nvrtc_unsupported_flags
  95. ]
  96. if torch.version.hip:
  97. compatible_flags.extend(COMMON_HIPCC_FLAGS)
  98. return compatible_flags
  99. def _nvrtc_compile(
  100. kernel_source: str,
  101. kernel_name: str,
  102. compute_capability: Optional[str] = None,
  103. cuda_include_dirs: Optional[list] = None,
  104. nvcc_options: Optional[list] = None,
  105. auto_pch: bool = False,
  106. ) -> tuple[bytes, str]:
  107. """
  108. Compiles a CUDA kernel using NVRTC and returns the PTX code.
  109. Args:
  110. kernel_source (str): The CUDA kernel source code as a string
  111. kernel_name (str): The name of the kernel function to compile
  112. compute_capability (str, None): The compute capability to target (e.g., "86").
  113. If None, will detect from current device.
  114. cuda_include_dirs (list, None): List of directories containing CUDA headers
  115. nvcc_options (list, None): Additional options to pass to NVRTC
  116. auto_pch (bool): Enable automatic precompiled headers (CUDA 12.8+)
  117. Returns:
  118. Tuple[bytes, str]: The compiled PTX code and mangled kernel name
  119. """
  120. # Ensure CUDA is initialized
  121. import torch.cuda
  122. # Load NVRTC library
  123. libnvrtc = _get_gpu_rtc_library()
  124. # NVRTC constants
  125. NVRTC_SUCCESS = 0
  126. # Helper: check NVRTC errors
  127. def check_nvrtc(result: int) -> None:
  128. if result != NVRTC_SUCCESS:
  129. err_str = ctypes.c_char_p()
  130. libnvrtc.nvrtcGetErrorString(result, ctypes.byref(err_str))
  131. error_message = (
  132. err_str.value.decode()
  133. if err_str.value is not None
  134. else "Unknown CUDA error"
  135. )
  136. raise RuntimeError(f"CUDA error: {error_message}")
  137. # Convert source to bytes
  138. source_bytes = kernel_source.encode("utf-8")
  139. # Get compute capability if not provided
  140. if compute_capability is None:
  141. props = torch.cuda.get_device_properties(torch.cuda.current_device())
  142. if torch.version.hip:
  143. compute_capability = f"{props.gcnArchName}"
  144. else:
  145. compute_capability = f"{props.major}{props.minor}"
  146. # Prepare compilation options
  147. options = []
  148. if torch.version.hip:
  149. options.append(f"--offload-arch={compute_capability}".encode())
  150. else:
  151. options.append(f"--gpu-architecture=sm_{compute_capability}".encode())
  152. # Auto-detect and add CUDA include paths
  153. from torch.utils.cpp_extension import include_paths
  154. cuda_include_paths = include_paths("cuda")
  155. for cuda_path in cuda_include_paths:
  156. options.append(f"-I{cuda_path}".encode())
  157. # Add custom include directories
  158. if cuda_include_dirs:
  159. for directory in cuda_include_dirs:
  160. options.append(f"-I{directory}".encode())
  161. # Enable automatic precompiled headers (CUDA 12.8+)
  162. if auto_pch:
  163. assert str(torch.version.cuda) >= "12.8", "PCH requires CUDA 12.8+"
  164. if nvcc_options is None:
  165. nvcc_options = []
  166. nvcc_options.append("--pch")
  167. # Add custom NVCC options
  168. if nvcc_options:
  169. for option in nvcc_options:
  170. options.append(option.encode("utf-8"))
  171. nvrtc_compatible_flags = _get_gpu_rtc_compatible_flags()
  172. options.extend([flag.encode("utf-8") for flag in nvrtc_compatible_flags])
  173. # Convert options to C array
  174. num_options = len(options)
  175. options_array = (ctypes.c_char_p * num_options)(*options)
  176. # Create program
  177. prog = ctypes.c_void_p()
  178. check_nvrtc(
  179. libnvrtc.nvrtcCreateProgram(
  180. ctypes.byref(prog),
  181. source_bytes,
  182. f"{kernel_name}.cu".encode(),
  183. 0,
  184. None,
  185. None,
  186. )
  187. )
  188. # Add kernel name, which can be a template expression
  189. c_kernel_name = kernel_name.encode("utf-8")
  190. check_nvrtc(libnvrtc.nvrtcAddNameExpression(prog, c_kernel_name))
  191. # Compile program
  192. res = libnvrtc.nvrtcCompileProgram(prog, num_options, options_array)
  193. # Handle compilation errors
  194. if res != NVRTC_SUCCESS:
  195. # Get log
  196. log_size = ctypes.c_size_t()
  197. libnvrtc.nvrtcGetProgramLogSize(prog, ctypes.byref(log_size))
  198. log = ctypes.create_string_buffer(log_size.value)
  199. libnvrtc.nvrtcGetProgramLog(prog, log)
  200. raise RuntimeError(f"Kernel compilation failed:\n{log.value.decode()}")
  201. # Get PTX
  202. ptx_size = ctypes.c_size_t()
  203. check_nvrtc(libnvrtc.nvrtcGetPTXSize(prog, ctypes.byref(ptx_size)))
  204. ptx = ctypes.create_string_buffer(ptx_size.value)
  205. check_nvrtc(libnvrtc.nvrtcGetPTX(prog, ptx))
  206. # Get mangled name
  207. c_mangled_name = ctypes.c_char_p()
  208. check_nvrtc(
  209. libnvrtc.nvrtcGetLoweredName(prog, c_kernel_name, ctypes.byref(c_mangled_name))
  210. )
  211. if c_mangled_name.value is not None:
  212. mangled_name = c_mangled_name.value.decode() # make a copy
  213. else:
  214. mangled_name = ""
  215. libnvrtc.nvrtcDestroyProgram(ctypes.byref(prog))
  216. # For HIP, hipRTC generates raw CO binaries instead of PTX,
  217. # and for some reason, ".value" causes the string to be truncated,
  218. # likely due to the presence of '\0' in the string. So we use .raw instead.
  219. ptx_bytes = ptx.raw if torch.version.hip else ptx.value
  220. return ptx_bytes, mangled_name
  221. class _CudaModule:
  222. def __init__(self, module: ctypes.c_void_p) -> None:
  223. self._module = module
  224. self._kernels: dict[str, _CudaKernel] = {}
  225. def __getattr__(self, name: str) -> "_CudaKernel":
  226. if name in self._kernels:
  227. return self._kernels[name]
  228. # Import the CUDA library inside the method
  229. # pyrefly: ignore [missing-module-attribute]
  230. from torch.cuda._utils import _get_gpu_runtime_library
  231. libcuda = _get_gpu_runtime_library()
  232. func = ctypes.c_void_p()
  233. try:
  234. _check_cuda(
  235. libcuda.cuModuleGetFunction(
  236. ctypes.byref(func), self._module, name.encode("utf-8")
  237. )
  238. )
  239. kernel = _CudaKernel(func, self._module)
  240. self._kernels[name] = kernel
  241. return kernel
  242. except RuntimeError as err:
  243. raise AttributeError(f"No kernel named '{name}' in this module") from err
  244. class _CudaKernel:
  245. """
  246. Represents a compiled CUDA kernel that can be called with PyTorch tensors.
  247. """
  248. def __init__(self, func: ctypes.c_void_p, module: ctypes.c_void_p) -> None:
  249. self.func = func
  250. self.module = module
  251. self._max_shared_mem_bytes = 0
  252. def __call__(
  253. self,
  254. grid: tuple[int, int, int] = (1, 1, 1),
  255. block: tuple[int, int, int] = (1, 1, 1),
  256. args: Optional[list] = None,
  257. shared_mem: int = 0,
  258. stream: Optional[Any] = None,
  259. ) -> None:
  260. """
  261. Call the compiled CUDA kernel
  262. Args:
  263. grid (tuple): Grid dimensions (grid_x, grid_y, grid_z)
  264. block (tuple): Block dimensions (block_x, block_y, block_z)
  265. args (list): List of arguments to pass to the kernel.
  266. PyTorch tensor arguments will be automatically converted to pointers.
  267. shared_mem (int): Shared memory size in bytes
  268. stream (torch.cuda.Stream): CUDA stream to use. If None, uses current stream.
  269. """
  270. import torch
  271. libcuda = torch.cuda._utils._get_gpu_runtime_library()
  272. if not args:
  273. args = []
  274. # Process arguments and convert tensors to pointers
  275. processed_args: list[ctypes.c_void_p] = []
  276. c_args = []
  277. for arg in args:
  278. if isinstance(arg, torch.Tensor):
  279. if not arg.is_cuda and not (arg.is_cpu and arg.is_pinned()):
  280. raise ValueError(
  281. "All tensor arguments must be CUDA tensors or pinned CPU tensors"
  282. )
  283. # Get pointer to tensor data
  284. ptr = ctypes.c_void_p(arg.data_ptr())
  285. processed_args.append(ptr)
  286. c_args.append(ctypes.byref(ptr))
  287. elif isinstance(arg, int):
  288. # Convert integers to C int
  289. c_int = ctypes.c_int(arg)
  290. # Store the C int for reference keeping, not in processed_args
  291. c_args.append(ctypes.byref(c_int))
  292. elif isinstance(arg, float):
  293. # Python floats are doubles - use double by default
  294. c_double = ctypes.c_double(arg)
  295. # Store the C double for reference keeping, not in processed_args
  296. c_args.append(ctypes.byref(c_double))
  297. else:
  298. raise TypeError(f"Unsupported argument type: {type(arg)}")
  299. # Convert to array of void pointers
  300. c_args_array = (ctypes.c_void_p * len(c_args))()
  301. for i, arg in enumerate(c_args):
  302. c_args_array[i] = ctypes.cast(arg, ctypes.c_void_p)
  303. # Get the stream
  304. if stream is None:
  305. # Defer import to avoid circular imports
  306. import torch.cuda
  307. stream = torch.cuda.current_stream()
  308. # Check if kernel requires large shared memory but hasn't been configured
  309. if shared_mem >= 48 * 1024 and (
  310. self._max_shared_mem_bytes == 0 or shared_mem > self._max_shared_mem_bytes
  311. ):
  312. configured_msg = (
  313. "not configured"
  314. if self._max_shared_mem_bytes == 0
  315. else f"only {self._max_shared_mem_bytes} bytes configured"
  316. )
  317. raise RuntimeError(
  318. f"Kernel requires {shared_mem} bytes of shared memory (>= 48KB), "
  319. f"but {configured_msg}. "
  320. "Call kernel.set_shared_memory_config(shared_mem) after compilation "
  321. "and before launching the kernel."
  322. )
  323. _check_cuda(
  324. libcuda.cuLaunchKernel(
  325. self.func,
  326. grid[0],
  327. grid[1],
  328. grid[2],
  329. block[0],
  330. block[1],
  331. block[2],
  332. shared_mem,
  333. stream._as_parameter_,
  334. c_args_array,
  335. None,
  336. )
  337. )
  338. def set_shared_memory_config(self, shared_mem_bytes: int) -> None:
  339. if shared_mem_bytes < 48 * 1024:
  340. # No configuration needed for <= 48KB, just update the value
  341. self._max_shared_mem_bytes = shared_mem_bytes
  342. return
  343. libcuda = _get_gpu_runtime_library()
  344. # Get device properties to validate against limits
  345. device_props = torch.cuda.get_device_properties()
  346. # HIP doesn't have shared_memory_per_block_optin in device properties, so we hard-code it here
  347. if torch.version.hip:
  348. # navi, CDNA1-CDNA3 allows a max of 64KB shared memory
  349. # CDNA4 allows a max of 160KB shared memory
  350. max_shared_mem = (
  351. 65536 if device_props.gcnArchName != "gfx950" else 160 * 1024
  352. )
  353. else:
  354. max_shared_mem = getattr(
  355. device_props, "shared_memory_per_block_optin", 49152
  356. )
  357. if shared_mem_bytes > max_shared_mem:
  358. raise RuntimeError(
  359. f"Requested shared memory ({shared_mem_bytes} bytes) exceeds "
  360. f"device limit ({max_shared_mem} bytes). "
  361. "Consider reducing block size or shared memory usage."
  362. )
  363. # Set the function attribute once
  364. # https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TYPES.html
  365. cudaFuncAttributeMaxDynamicSharedMemorySize = 8
  366. _check_cuda(
  367. libcuda.cuFuncSetAttribute(
  368. self.func,
  369. cudaFuncAttributeMaxDynamicSharedMemorySize,
  370. shared_mem_bytes,
  371. )
  372. )
  373. self._max_shared_mem_bytes = shared_mem_bytes
  374. def _cuda_load_module(
  375. ptx: Union[str, bytes], kernel_names: Optional[list[str]] = None
  376. ) -> Union[_CudaModule, dict[str, "_CudaKernel"]]:
  377. """
  378. Loads a CUDA module from PTX code and returns a module object that can access kernels.
  379. Args:
  380. ptx (bytes or str): The PTX code to load
  381. kernel_names (list, optional): List of kernel names to extract from the module.
  382. If None, will return a module object with __getattr__.
  383. Returns:
  384. object: If kernel_names is None, returns a module object with __getattr__ to access kernels.
  385. If kernel_names is provided, returns a dict mapping kernel names to _CudaKernel objects.
  386. """
  387. # Ensure CUDA is initialized
  388. import torch.cuda
  389. # Load CUDA driver library
  390. libcuda = _get_gpu_runtime_library()
  391. # Convert PTX to bytes if it's a string
  392. if isinstance(ptx, str):
  393. ptx = ptx.encode("utf-8")
  394. # Load PTX module
  395. module = ctypes.c_void_p()
  396. # Get the current stream without directly importing torch.cuda at module level
  397. stream = torch.cuda.current_stream()
  398. with stream:
  399. _check_cuda(libcuda.cuModuleLoadData(ctypes.byref(module), ptx))
  400. if not kernel_names:
  401. return _CudaModule(module)
  402. # Return specific kernels
  403. kernels = {}
  404. for name in kernel_names:
  405. func = ctypes.c_void_p()
  406. _check_cuda(
  407. libcuda.cuModuleGetFunction(
  408. ctypes.byref(func), module, name.encode("utf-8")
  409. )
  410. )
  411. kernels[name] = _CudaKernel(func, module)
  412. return kernels
  413. def _get_device_index(
  414. device: Any, optional: bool = False, allow_cpu: bool = False
  415. ) -> int:
  416. r"""Get the device index from :attr:`device`, which can be a torch.device object, a Python integer, or ``None``.
  417. If :attr:`device` is a torch.device object, returns the device index if it
  418. is a CUDA device. Note that for a CUDA device without a specified index,
  419. i.e., ``torch.device('cuda')``, this will return the current default CUDA
  420. device if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``,
  421. CPU devices will be accepted and ``-1`` will be returned in this case.
  422. If :attr:`device` is a Python integer, it is returned as is.
  423. If :attr:`device` is ``None``, this will return the current default CUDA
  424. device if :attr:`optional` is ``True``.
  425. """
  426. if isinstance(device, int):
  427. return device
  428. if isinstance(device, str):
  429. device = torch.device(device)
  430. if isinstance(device, torch.device):
  431. if allow_cpu:
  432. if device.type not in ["cuda", "cpu"]:
  433. raise ValueError(f"Expected a cuda or cpu device, but got: {device}")
  434. elif device.type != "cuda":
  435. raise ValueError(f"Expected a cuda device, but got: {device}")
  436. if not torch.jit.is_scripting():
  437. if isinstance(device, torch.cuda.device):
  438. return device.idx
  439. return _torch_get_device_index(device, optional, allow_cpu)