bitsandbytes 0.50.0__py3-none-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. bitsandbytes/__init__.py +78 -0
  2. bitsandbytes/__main__.py +4 -0
  3. bitsandbytes/_ops.py +510 -0
  4. bitsandbytes/autograd/__init__.py +0 -0
  5. bitsandbytes/autograd/_functions.py +491 -0
  6. bitsandbytes/backends/__init__.py +0 -0
  7. bitsandbytes/backends/cpu/__init__.py +0 -0
  8. bitsandbytes/backends/cpu/ops.py +580 -0
  9. bitsandbytes/backends/cuda/__init__.py +0 -0
  10. bitsandbytes/backends/cuda/ops.py +1199 -0
  11. bitsandbytes/backends/default/__init__.py +0 -0
  12. bitsandbytes/backends/default/ops.py +632 -0
  13. bitsandbytes/backends/hpu/__init__.py +0 -0
  14. bitsandbytes/backends/hpu/ops.py +53 -0
  15. bitsandbytes/backends/mps/__init__.py +0 -0
  16. bitsandbytes/backends/mps/ops.py +277 -0
  17. bitsandbytes/backends/triton/__init__.py +0 -0
  18. bitsandbytes/backends/triton/kernels_4bit.py +577 -0
  19. bitsandbytes/backends/triton/kernels_8bit_quant.py +195 -0
  20. bitsandbytes/backends/triton/kernels_optim.py +1177 -0
  21. bitsandbytes/backends/triton/ops.py +304 -0
  22. bitsandbytes/backends/utils.py +94 -0
  23. bitsandbytes/backends/xpu/__init__.py +0 -0
  24. bitsandbytes/backends/xpu/ops.py +305 -0
  25. bitsandbytes/cextension.py +405 -0
  26. bitsandbytes/consts.py +12 -0
  27. bitsandbytes/cuda_specs.py +111 -0
  28. bitsandbytes/diagnostics/__init__.py +0 -0
  29. bitsandbytes/diagnostics/cuda.py +193 -0
  30. bitsandbytes/diagnostics/main.py +134 -0
  31. bitsandbytes/diagnostics/utils.py +12 -0
  32. bitsandbytes/functional.py +1810 -0
  33. bitsandbytes/libbitsandbytes_cpu.dll +0 -0
  34. bitsandbytes/nn/__init__.py +19 -0
  35. bitsandbytes/nn/modules.py +1220 -0
  36. bitsandbytes/nn/parametrize.py +206 -0
  37. bitsandbytes/optim/__init__.py +22 -0
  38. bitsandbytes/optim/adagrad.py +187 -0
  39. bitsandbytes/optim/adam.py +346 -0
  40. bitsandbytes/optim/adamw.py +337 -0
  41. bitsandbytes/optim/ademamix.py +410 -0
  42. bitsandbytes/optim/lamb.py +190 -0
  43. bitsandbytes/optim/lars.py +259 -0
  44. bitsandbytes/optim/lion.py +266 -0
  45. bitsandbytes/optim/optimizer.py +756 -0
  46. bitsandbytes/optim/rmsprop.py +170 -0
  47. bitsandbytes/optim/sgd.py +152 -0
  48. bitsandbytes/py.typed +0 -0
  49. bitsandbytes/utils.py +208 -0
  50. bitsandbytes-0.50.0.dist-info/METADATA +288 -0
  51. bitsandbytes-0.50.0.dist-info/RECORD +54 -0
  52. bitsandbytes-0.50.0.dist-info/WHEEL +5 -0
  53. bitsandbytes-0.50.0.dist-info/licenses/LICENSE +21 -0
  54. bitsandbytes-0.50.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,405 @@
1
+ import ctypes as ct
2
+ import functools
3
+ import logging
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ from typing import Optional
8
+
9
+ import torch
10
+
11
+ from bitsandbytes.consts import DYNAMIC_LIBRARY_SUFFIX, PACKAGE_DIR
12
+ from bitsandbytes.cuda_specs import (
13
+ CUDASpecs,
14
+ get_cuda_specs,
15
+ get_cuda_version_tuple,
16
+ get_rocm_gpu_arch,
17
+ )
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def get_cuda_bnb_library_path(cuda_specs: CUDASpecs) -> Path:
23
+ """
24
+ Get the path to the best matching CUDA/ROCm BNB native library for the given specs.
25
+
26
+ When no override is set, selects from packaged libraries using the following priority:
27
+ 1. Exact version match.
28
+ 2. Highest packaged version <= runtime version, same major (e.g. runtime 12.9, ship 12.8).
29
+ 3. Lowest packaged version > runtime version, same major (e.g. runtime 12.0, ship 12.1).
30
+ No cross-major fallback: if no same-major library exists, returns the exact non-existent
31
+ path so the caller raises a clear "not found" error.
32
+ A warning is logged when falling back. Override env vars bypass selection entirely
33
+ and load the named version with no fallback. The returned path is not guaranteed to
34
+ exist when no packaged libs are found, or when an override names an absent version.
35
+ """
36
+ is_hip = bool(torch.version.hip)
37
+ prefix = "rocm" if is_hip else "cuda"
38
+ override_var = "BNB_ROCM_VERSION" if is_hip else "BNB_CUDA_VERSION"
39
+
40
+ override_value = os.environ.get(override_var)
41
+
42
+ if override_value is not None:
43
+ if not override_value.isdigit():
44
+ raise RuntimeError(f"{override_var}={override_value!r}: value must be digits only (e.g. '124' for 12.4).")
45
+ library_name = f"libbitsandbytes_{prefix}{override_value}{DYNAMIC_LIBRARY_SUFFIX}"
46
+ logger.warning(
47
+ f"WARNING: {override_var}={override_value} environment variable detected; loading {library_name}.\n"
48
+ f"This overrides automatic {'ROCm' if is_hip else 'CUDA'} version selection.\n"
49
+ f"If this was unintended clear the variable and retry: unset {override_var}\n",
50
+ )
51
+ return PACKAGE_DIR / library_name
52
+
53
+ available = _find_cuda_libs(prefix, is_hip)
54
+ runtime_version = cuda_specs.cuda_version_tuple
55
+
56
+ if not available:
57
+ return PACKAGE_DIR / f"libbitsandbytes_{prefix}{cuda_specs.cuda_version_string}{DYNAMIC_LIBRARY_SUFFIX}"
58
+
59
+ if runtime_version in available:
60
+ return available[runtime_version]
61
+
62
+ lower = [v for v in available if v[0] == runtime_version[0] and v < runtime_version]
63
+ if lower:
64
+ selected = max(lower)
65
+ else:
66
+ higher_same = [v for v in available if v[0] == runtime_version[0] and v > runtime_version]
67
+ if higher_same:
68
+ selected = min(higher_same)
69
+ else:
70
+ # No same-major library available. Return the non-existent exact path so
71
+ # get_native_library() raises a clear "not found" error.
72
+ return PACKAGE_DIR / f"libbitsandbytes_{prefix}{cuda_specs.cuda_version_string}{DYNAMIC_LIBRARY_SUFFIX}"
73
+
74
+ logger.warning(
75
+ f"No prebuilt binary for {'ROCm' if is_hip else 'CUDA'} "
76
+ f"{runtime_version[0]}.{runtime_version[1]}, loading "
77
+ f"{'ROCm' if is_hip else 'CUDA'} {selected[0]}.{selected[1]} instead. "
78
+ f"Set {override_var} to override."
79
+ )
80
+ return available[selected]
81
+
82
+
83
+ class BNBNativeLibrary:
84
+ _lib: ct.CDLL
85
+ compiled_with_cuda = False
86
+
87
+ def __init__(self, lib: ct.CDLL):
88
+ self._lib = lib
89
+
90
+ @functools.cache # noqa: B019
91
+ def __getattr__(self, name):
92
+ fn = getattr(self._lib, name, None)
93
+
94
+ if fn is not None:
95
+ return fn
96
+
97
+ def throw_on_call(*args, **kwargs):
98
+ raise RuntimeError(
99
+ f"Method '{name}' not available in CPU-only version of bitsandbytes.\n"
100
+ "Reinstall with GPU support or use CUDA-enabled hardware."
101
+ )
102
+
103
+ return throw_on_call
104
+
105
+ def __getitem__(self, item):
106
+ return self.__getattr__(item)
107
+
108
+
109
+ class CudaBNBNativeLibrary(BNBNativeLibrary):
110
+ compiled_with_cuda = True
111
+
112
+ def __init__(self, lib: ct.CDLL):
113
+ super().__init__(lib)
114
+ lib.get_context.restype = ct.c_void_p
115
+ lib.cget_managed_ptr.restype = ct.c_void_p
116
+
117
+
118
+ class XpuBNBNativeLibrary(BNBNativeLibrary):
119
+ """XPU native library with SYCL USM paged memory support."""
120
+
121
+ def __init__(self, lib: ct.CDLL):
122
+ super().__init__(lib)
123
+ if hasattr(lib, "cget_managed_ptr"):
124
+ lib.cget_managed_ptr.restype = ct.c_void_p
125
+
126
+
127
+ def _split_cuda_version(compact: str, is_hip: bool) -> tuple[int, int]:
128
+ """Split a compact CUDA/ROCm version string from a library filename into (major, minor).
129
+
130
+ CUDA: major is always 2 digits (11, 12, 13...), e.g. '118' -> (11, 8), '132' -> (13, 2).
131
+ ROCm: major is always 1 digit for now (6, 7...), e.g. '72' -> (7, 2), '713' -> (7, 13).
132
+ Note: revisit if ROCm major reaches 10.
133
+ """
134
+ if is_hip:
135
+ return int(compact[:1]), int(compact[1:])
136
+ return int(compact[:2]), int(compact[2:])
137
+
138
+
139
+ def _find_cuda_libs(prefix: str, is_hip: bool) -> dict[tuple[int, int], Path]:
140
+ """Return a {(major, minor): Path} mapping for all packaged CUDA/ROCm library files."""
141
+ result = {}
142
+ for lib in PACKAGE_DIR.glob(f"libbitsandbytes_{prefix}*{DYNAMIC_LIBRARY_SUFFIX}"):
143
+ match = re.search(rf"{prefix}(\d+)", lib.name)
144
+ if match:
145
+ try:
146
+ result[_split_cuda_version(match.group(1), is_hip)] = lib
147
+ except (ValueError, IndexError):
148
+ continue
149
+ return result
150
+
151
+
152
+ def get_available_cuda_binary_versions() -> list[str]:
153
+ """Get formatted CUDA/ROCm versions from existing library files."""
154
+ is_hip = bool(torch.version.hip)
155
+ prefix = "rocm" if is_hip else "cuda"
156
+ return sorted(f"{major}.{minor}" for major, minor in _find_cuda_libs(prefix, is_hip))
157
+
158
+
159
+ def parse_cuda_version(version_str: str) -> str:
160
+ """Convert a raw version code string (e.g. '118', '713') to a dotted version (e.g. '11.8', '7.13')."""
161
+ if version_str.isdigit():
162
+ is_hip = bool(torch.version.hip)
163
+ try:
164
+ major, minor = _split_cuda_version(version_str, is_hip)
165
+ return f"{major}.{minor}"
166
+ except (ValueError, IndexError):
167
+ pass
168
+ return version_str
169
+
170
+
171
+ class ErrorHandlerMockBNBNativeLibrary(BNBNativeLibrary):
172
+ """
173
+ Mock library handler that defers errors until native methods are called.
174
+
175
+ This class serves as a fallback when the native bitsandbytes library fails to load.
176
+ It captures the original error and generates detailed troubleshooting guidance.
177
+
178
+ Key behaviors:
179
+ - Allows attribute access and method assignment without immediate errors
180
+ - Throws a RuntimeError with diagnostic information only when a native method is called, as otherwise it would error out on import, breaking backward compatibility
181
+ - Handles both missing CUDA dependencies and version mismatch scenarios
182
+
183
+ Error scenarios covered:
184
+ 1. Missing shared library dependencies (e.g., libcudart.so not in LD_LIBRARY_PATH or through PyTorch CUDA installation)
185
+ 2. CUDA version mismatch between PyTorch and available pre-compiled binaries
186
+ 3. Completely missing pre-compiled binaries when CUDA is detected
187
+ 4. Custom BNB_CUDA_VERSION or BNB_ROCM_VERSION override but mismatch
188
+ 5. CPU-only installation attempts when GPU functionality is requested
189
+
190
+ """
191
+
192
+ def __init__(self, error_msg: str):
193
+ self.error_msg = error_msg
194
+ self.available_versions = get_available_cuda_binary_versions()
195
+ override_value = os.environ.get("BNB_ROCM_VERSION") if HIP_ENVIRONMENT else os.environ.get("BNB_CUDA_VERSION")
196
+ user_version = get_cuda_version_tuple()
197
+ user_version_str = f"{user_version[0]}.{user_version[1]}" if user_version else "unknown"
198
+ self.requested_version = parse_cuda_version(override_value) if override_value else user_version_str
199
+
200
+ # Pre-generate the error message based on error type
201
+ if "cannot open shared object file" in error_msg:
202
+ self.formatted_error = self._format_dependency_error()
203
+ else: # lib loading errors
204
+ self.formatted_error = self._format_lib_error_message(
205
+ available_versions=self.available_versions,
206
+ user_cuda_version=user_version_str,
207
+ original_error=f"Original error: {self.error_msg}\n" if self.error_msg else "",
208
+ requested_version=self.requested_version,
209
+ )
210
+
211
+ def _format_lib_error_message(
212
+ self,
213
+ available_versions: list[str],
214
+ user_cuda_version: str,
215
+ original_error: str = "",
216
+ requested_version: Optional[str] = None,
217
+ ) -> str:
218
+ """Format detailed error message for library loading failures"""
219
+ analysis = ""
220
+ no_cpu_lib_found = "libbitsandbytes_cpu.so: cannot open" in original_error
221
+ no_cuda_lib_found = f"{BNB_BACKEND} binary not found" in original_error
222
+
223
+ if no_cpu_lib_found:
224
+ analysis = "\n🚨 Failed to load CPU-only bitsandbytes library 🚨\n\n"
225
+
226
+ elif no_cuda_lib_found:
227
+ version_list_str = "\n - " + "\n - ".join(available_versions) if available_versions else "NONE"
228
+ analysis = (
229
+ (
230
+ f"\n🚨 {BNB_BACKEND} VERSION MISMATCH 🚨\n"
231
+ f"Requested {BNB_BACKEND} version: {requested_version}\n"
232
+ f"Detected PyTorch {BNB_BACKEND} version: {user_cuda_version}\n"
233
+ f"Available pre-compiled versions: {version_list_str}\n\n"
234
+ "This means:\n"
235
+ "The version you're trying to use is NOT distributed with this package\n\n"
236
+ )
237
+ if available_versions
238
+ else "\n🚨 Forgot to compile the bitsandbytes library? 🚨\n"
239
+ "1. You're not using the package but checked-out the source code\n"
240
+ "2. You MUST compile from source\n\n"
241
+ )
242
+
243
+ base_msg = "Attempted to use bitsandbytes native library functionality but it's not available.\n\n"
244
+
245
+ troubleshooting = (
246
+ (
247
+ f"This typically happens when:\n"
248
+ f"1. bitsandbytes doesn't ship with a pre-compiled binary for your {BNB_BACKEND} version\n"
249
+ f"2. The library wasn't compiled properly during installation from source\n\n"
250
+ )
251
+ if no_cuda_lib_found
252
+ else f"This typically happens when you checked the code out from source and your torch installation doesn't detect {BNB_BACKEND} on your machine.\n\n"
253
+ )
254
+
255
+ note = (
256
+ (
257
+ f"bitsandbytes tried to find a compatible {BNB_BACKEND} binary but none could be loaded.\n"
258
+ f"If your {BNB_BACKEND} version isn't among the available pre-compiled versions above, you must compile from source.\n\n"
259
+ )
260
+ if no_cuda_lib_found
261
+ else ""
262
+ )
263
+
264
+ compile_instructions = (
265
+ ("COMPILE FROM SOURCE for CPU-only:\n `cmake -DCOMPUTE_BACKEND=cpu -S . && make`\n\n")
266
+ if not no_cuda_lib_found
267
+ else (
268
+ "You have two options:\n"
269
+ "1. COMPILE FROM SOURCE (required if no binary exists):\n"
270
+ " https://huggingface.co/docs/bitsandbytes/main/en/installation#cuda-compile\n"
271
+ "2. Use BNB_CUDA_VERSION to specify a DIFFERENT CUDA version from the detected one, which is installed on your machine and matching an available pre-compiled version listed above\n\n"
272
+ )
273
+ if not HIP_ENVIRONMENT
274
+ else (
275
+ "You have two options:\n"
276
+ "1. COMPILE FROM SOURCE as mentioned here:\n"
277
+ " https://huggingface.co/docs/bitsandbytes/main/en/installation?backend=AMD+ROCm#amd-gpu\n"
278
+ "2. Use BNB_ROCM_VERSION to specify a DIFFERENT ROCm version from the detected one, matching the version the library was built with.\n\n"
279
+ )
280
+ )
281
+
282
+ diagnostics = (
283
+ f"🔍 Run this command for detailed diagnostics:\n"
284
+ f"python -m bitsandbytes\n\n"
285
+ f"If you've tried everything and still have issues:\n"
286
+ f"1. Include ALL version info (operating system, bitsandbytes, pytorch, {BNB_BACKEND.lower()}, python)\n"
287
+ f"2. Describe what you've tried in detail\n"
288
+ f"3. Open an issue with this information:\n"
289
+ f" https://github.com/bitsandbytes-foundation/bitsandbytes/issues\n\n"
290
+ )
291
+
292
+ return f"{analysis}{base_msg}{troubleshooting}{note}{compile_instructions}{original_error}\n{diagnostics}"
293
+
294
+ def _format_dependency_error(self) -> str:
295
+ """Format error message for missing shared libraries"""
296
+ # Extract missing library name from error
297
+ error_parts = self.error_msg.split(":")
298
+ missing_lib = error_parts[0].strip() if len(error_parts) > 0 else "unknown library"
299
+ cuda_major_version = (
300
+ self.requested_version.split(".")[0] if "." in self.requested_version else self.requested_version
301
+ )
302
+
303
+ return (
304
+ f"\n🚨 {BNB_BACKEND} SETUP ERROR: Missing dependency: {missing_lib} 🚨\n\n"
305
+ f"{BNB_BACKEND} {cuda_major_version}.x runtime libraries were not found in the LD_LIBRARY_PATH.\n\n"
306
+ f"To fix this, make sure that:\n"
307
+ f"1. You have installed {BNB_BACKEND} {cuda_major_version}.x toolkit on your system\n"
308
+ f"2. The {BNB_BACKEND} runtime libraries are in your LD_LIBRARY_PATH\n\n"
309
+ f"You can add them with (and persist the change by adding the line to your .bashrc):\n"
310
+ f" export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/{BNB_BACKEND.lower()}-{cuda_major_version}.x/"
311
+ f"{'lib64' if not HIP_ENVIRONMENT else 'lib'}\n\n"
312
+ f"Original error: {self.error_msg}\n\n"
313
+ f"🔍 Run this command for detailed diagnostics:\n"
314
+ f"python -m bitsandbytes\n\n"
315
+ f"If you've tried everything and still have issues:\n"
316
+ f"1. Include ALL version info (operating system, bitsandbytes, pytorch, {BNB_BACKEND.lower()}, python)\n"
317
+ f"2. Describe what you've tried in detail\n"
318
+ f"3. Open an issue with this information:\n"
319
+ f" https://github.com/bitsandbytes-foundation/bitsandbytes/issues\n\n"
320
+ )
321
+
322
+ def __getattr__(self, name):
323
+ """Return a dummy function that throws when called, rather than on attribute access"""
324
+
325
+ def throw_on_call(*args, **kwargs):
326
+ raise RuntimeError(f"{self.formatted_error}Native code method attempted to call: lib.{name}()")
327
+
328
+ return throw_on_call
329
+
330
+ def __getitem__(self, name):
331
+ return self.__getattr__(name)
332
+
333
+
334
+ def get_xpu_bnb_library_path() -> Path:
335
+ """Get the path to the XPU native library matching the oneAPI toolchain.
336
+
337
+ Prefers the versioned library (e.g. libbitsandbytes_xpu2026) matching the first
338
+ 4 digits of torch.version.xpu, falling back to an unversioned libbitsandbytes_xpu.
339
+ """
340
+ xpu_version = getattr(torch.version, "xpu", None)
341
+ if xpu_version:
342
+ versioned = PACKAGE_DIR / f"libbitsandbytes_xpu{xpu_version[:4]}{DYNAMIC_LIBRARY_SUFFIX}"
343
+ if versioned.exists():
344
+ return versioned
345
+ return PACKAGE_DIR / f"libbitsandbytes_xpu{DYNAMIC_LIBRARY_SUFFIX}"
346
+
347
+
348
+ def get_native_library() -> BNBNativeLibrary:
349
+ """
350
+ Load CUDA library XOR CPU, as the latter contains a subset of symbols of the former.
351
+ """
352
+ cuda_specs = get_cuda_specs()
353
+ binary_path = PACKAGE_DIR / f"libbitsandbytes_cpu{DYNAMIC_LIBRARY_SUFFIX}"
354
+
355
+ if cuda_specs:
356
+ cuda_binary_path = get_cuda_bnb_library_path(cuda_specs)
357
+
358
+ if not cuda_binary_path.exists():
359
+ raise RuntimeError(f"No compatible {BNB_BACKEND} binary found at {cuda_binary_path}")
360
+
361
+ binary_path = cuda_binary_path
362
+
363
+ if torch._C._has_xpu:
364
+ binary_path = get_xpu_bnb_library_path()
365
+
366
+ logger.debug(f"Loading bitsandbytes native library from: {binary_path}")
367
+
368
+ # Try to load the library - any errors will propagate up
369
+ dll = ct.cdll.LoadLibrary(str(binary_path))
370
+
371
+ if hasattr(dll, "get_context"): # only a CUDA-built library exposes this
372
+ return CudaBNBNativeLibrary(dll)
373
+
374
+ if torch._C._has_xpu:
375
+ return XpuBNBNativeLibrary(dll)
376
+
377
+ return BNBNativeLibrary(dll)
378
+
379
+
380
+ ROCM_GPU_ARCH = get_rocm_gpu_arch()
381
+
382
+ HIP_ENVIRONMENT = False
383
+ BNB_BACKEND = "CPU"
384
+ if torch.version.hip:
385
+ HIP_ENVIRONMENT = True
386
+ BNB_BACKEND = "ROCm"
387
+ elif torch.cuda.is_available():
388
+ BNB_BACKEND = "CUDA"
389
+ elif torch._C._has_xpu:
390
+ BNB_BACKEND = "XPU"
391
+
392
+ try:
393
+ lib = get_native_library()
394
+ except Exception as e:
395
+ if BNB_BACKEND in ("CPU", "XPU"):
396
+ lib = ErrorHandlerMockBNBNativeLibrary("XPU/CPU can run without native library.")
397
+ else:
398
+ error_msg = str(e)
399
+ logger.error(
400
+ f"bitsandbytes library load error: {error_msg}",
401
+ exc_info=True,
402
+ )
403
+
404
+ # create a mock with error messaging as fallback
405
+ lib = ErrorHandlerMockBNBNativeLibrary(error_msg)
bitsandbytes/consts.py ADDED
@@ -0,0 +1,12 @@
1
+ from pathlib import Path
2
+ import platform
3
+
4
+ DYNAMIC_LIBRARY_SUFFIX = {
5
+ "Darwin": ".dylib",
6
+ "Linux": ".so",
7
+ "Windows": ".dll",
8
+ }.get(platform.system(), ".so")
9
+
10
+ PACKAGE_DIR = Path(__file__).parent
11
+ PACKAGE_GITHUB_URL = "https://github.com/TimDettmers/bitsandbytes"
12
+ NONPYTORCH_DOC_URL = "https://github.com/TimDettmers/bitsandbytes/blob/main/docs/source/nonpytorchcuda.mdx"
@@ -0,0 +1,111 @@
1
+ import dataclasses
2
+ from functools import lru_cache
3
+ import logging
4
+ import platform
5
+ import re
6
+ import subprocess
7
+ from typing import Optional
8
+
9
+ import torch
10
+
11
+
12
+ @dataclasses.dataclass(frozen=True)
13
+ class CUDASpecs:
14
+ highest_compute_capability: tuple[int, int]
15
+ cuda_version_string: str
16
+ cuda_version_tuple: tuple[int, int]
17
+
18
+ @property
19
+ def has_imma(self) -> bool:
20
+ return torch.version.hip or self.highest_compute_capability >= (7, 5)
21
+
22
+
23
+ def get_compute_capabilities() -> list[tuple[int, int]]:
24
+ return sorted(torch.cuda.get_device_capability(torch.cuda.device(i)) for i in range(torch.cuda.device_count()))
25
+
26
+
27
+ @lru_cache(None)
28
+ def get_cuda_version_tuple() -> Optional[tuple[int, int]]:
29
+ """Get CUDA/HIP version as a tuple of (major, minor)."""
30
+ try:
31
+ if torch.version.cuda:
32
+ version_str = torch.version.cuda
33
+ elif torch.version.hip:
34
+ version_str = torch.version.hip
35
+ else:
36
+ return None
37
+
38
+ parts = version_str.split(".")
39
+ if len(parts) >= 2:
40
+ return tuple(map(int, parts[:2]))
41
+ return None
42
+ except (AttributeError, ValueError, IndexError):
43
+ return None
44
+
45
+
46
+ def get_cuda_version_string() -> Optional[str]:
47
+ """Get CUDA/HIP version as a string."""
48
+ version_tuple = get_cuda_version_tuple()
49
+ if version_tuple is None:
50
+ return None
51
+ major, minor = version_tuple
52
+ return f"{major}{minor}"
53
+
54
+
55
+ def get_cuda_specs() -> Optional[CUDASpecs]:
56
+ """Get CUDA/HIP specifications."""
57
+ if not torch.cuda.is_available():
58
+ return None
59
+
60
+ try:
61
+ compute_capabilities = get_compute_capabilities()
62
+ if not compute_capabilities:
63
+ return None
64
+
65
+ version_tuple = get_cuda_version_tuple()
66
+ if version_tuple is None:
67
+ return None
68
+
69
+ version_string = get_cuda_version_string()
70
+ if version_string is None:
71
+ return None
72
+
73
+ return CUDASpecs(
74
+ highest_compute_capability=compute_capabilities[-1],
75
+ cuda_version_string=version_string,
76
+ cuda_version_tuple=version_tuple,
77
+ )
78
+ except Exception:
79
+ return None
80
+
81
+
82
+ def get_rocm_gpu_arch() -> str:
83
+ """Get ROCm GPU architecture."""
84
+ logger = logging.getLogger(__name__)
85
+ try:
86
+ if torch.version.hip:
87
+ # On Windows, use hipinfo.exe; on Linux, use rocminfo
88
+ if platform.system() == "Windows":
89
+ cmd = ["hipinfo.exe"]
90
+ arch_pattern = r"gcnArchName:\s+gfx([a-zA-Z\d]+)"
91
+ else:
92
+ cmd = ["rocminfo"]
93
+ arch_pattern = r"Name:\s+gfx([a-zA-Z\d]+)"
94
+
95
+ result = subprocess.run(cmd, capture_output=True, text=True)
96
+ match = re.search(arch_pattern, result.stdout)
97
+ if match:
98
+ return "gfx" + match.group(1)
99
+ else:
100
+ return "unknown"
101
+ else:
102
+ return "unknown"
103
+ except Exception as e:
104
+ logger.error(f"Could not detect ROCm GPU architecture: {e}")
105
+ if torch.cuda.is_available():
106
+ logger.warning(
107
+ """
108
+ ROCm GPU architecture detection failed despite ROCm being available.
109
+ """,
110
+ )
111
+ return "unknown"
File without changes