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,1810 @@
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ from collections.abc import Iterable
6
+ import ctypes as ct
7
+ import itertools
8
+ from math import prod
9
+ from typing import Any, Optional
10
+
11
+ import numpy as np
12
+ import torch
13
+ from torch import Tensor
14
+ from typing_extensions import deprecated
15
+
16
+ from bitsandbytes.utils import pack_dict_to_tensor, unpack_tensor_to_dict
17
+
18
+ from .cextension import lib
19
+
20
+ name2qmap = {}
21
+
22
+ """C FUNCTIONS FOR OPTIMIZERS"""
23
+
24
+
25
+ class GlobalPageManager:
26
+ _instance = None
27
+
28
+ def __init__(self):
29
+ raise RuntimeError("Call get_instance() instead")
30
+
31
+ def initialize(self):
32
+ self.paged_tensors = []
33
+
34
+ @classmethod
35
+ def get_instance(cls):
36
+ if cls._instance is None:
37
+ cls._instance = cls.__new__(cls)
38
+ cls._instance.initialize()
39
+ return cls._instance
40
+
41
+ def prefetch_all(self, to_cpu=False):
42
+ # assume the first added, will be the
43
+ # ones that are used first, so swap them in last
44
+ # in the case they are evicted again
45
+ for t in self.paged_tensors[::-1]:
46
+ prefetch_tensor(t, to_cpu)
47
+
48
+
49
+ class CUBLAS_Context:
50
+ _instance = None
51
+
52
+ def __init__(self):
53
+ raise RuntimeError("Call get_instance() instead")
54
+
55
+ def initialize(self):
56
+ self.context = {}
57
+
58
+ @classmethod
59
+ def get_instance(cls):
60
+ if cls._instance is None:
61
+ cls._instance = cls.__new__(cls)
62
+ cls._instance.initialize()
63
+ return cls._instance
64
+
65
+ def get_context(self, device):
66
+ if device.index not in self.context:
67
+ prev_device = torch.cuda.current_device()
68
+ torch.cuda.set_device(device)
69
+ self.context[device.index] = ct.c_void_p(lib.get_context())
70
+ torch.cuda.set_device(prev_device)
71
+ return self.context[device.index]
72
+
73
+
74
+ FIRST_CUDA_DEVICE = torch.device("cuda", index=0)
75
+
76
+ # When multiple GPUs are present, we use a context manager to
77
+ # switch to the correct device of a tensor before invoking our CUDA
78
+ # kernels in the C++ library. However, when there's only one device
79
+ # there is no need to incur the overhead of cudaGetDevice/cudaSetDevice.
80
+ if torch.cuda.device_count() > 1:
81
+
82
+ def _cuda_device_of(a: torch.Tensor):
83
+ return torch.cuda.device_of(a)
84
+ else:
85
+ import contextlib
86
+
87
+ def _cuda_device_of(a: torch.Tensor):
88
+ return contextlib.nullcontext()
89
+
90
+
91
+ def get_paged(*shape, dtype=torch.float32, device=FIRST_CUDA_DEVICE):
92
+ num_bytes = dtype.itemsize * prod(shape)
93
+ managed_ptr = lib.cget_managed_ptr(ct.c_size_t(num_bytes))
94
+ c_ptr = ct.cast(managed_ptr, ct.POINTER(ct.c_int))
95
+ new_array = np.ctypeslib.as_array(c_ptr, shape=shape)
96
+ out = torch.frombuffer(new_array, dtype=dtype, count=prod(shape)).view(shape)
97
+ out.is_paged = True
98
+ out.page_deviceid = device.index
99
+ return out
100
+
101
+
102
+ def prefetch_tensor(A: torch.Tensor, to_cpu=False):
103
+ assert A.is_paged, "Only paged tensors can be prefetched!"
104
+ if to_cpu:
105
+ deviceid = -1
106
+ else:
107
+ deviceid = A.page_deviceid
108
+
109
+ lib.cprefetch(get_ptr(A), ct.c_size_t(A.nbytes), ct.c_int32(deviceid))
110
+
111
+
112
+ def elementwise_func(func_name, A, B, value, prefetch=True):
113
+ func = None
114
+ if A.dtype == torch.float32:
115
+ func = getattr(lib, f"c{func_name}_fp32", None)
116
+ cvalue = ct.c_float(value)
117
+ elif A.dtype == torch.uint8:
118
+ func = getattr(lib, f"c{func_name}_uint8", None)
119
+ cvalue = ct.c_uint8(value)
120
+
121
+ if func is None:
122
+ raise NotImplementedError(f"Function not implemented: {func_name}")
123
+
124
+ is_managed = getattr(A, "is_managed", False)
125
+ if is_managed and prefetch:
126
+ prefetch_tensor(A)
127
+ if B is not None:
128
+ prefetch_tensor(B)
129
+
130
+ func(get_ptr(A), get_ptr(B), cvalue, ct.c_int64(A.numel()))
131
+ if A.is_paged or B.is_paged:
132
+ # paged function are fully asynchronous
133
+ # if we return from this function, we want to the tensor
134
+ # to be in the correct state, that is the final state after the
135
+ # operation occurred. So we synchronize.
136
+ if torch.cuda.is_available():
137
+ torch.cuda.synchronize()
138
+ elif hasattr(torch, "xpu") and torch.xpu.is_available():
139
+ torch.xpu.synchronize()
140
+
141
+
142
+ def fill(A, value, device=None, prefetch=True):
143
+ elementwise_func("fill", A, None, value)
144
+
145
+
146
+ def _mul(A, B, device=None):
147
+ elementwise_func("_mul", A, B, 0)
148
+
149
+
150
+ def create_linear_map(signed=True, total_bits=8, add_zero=True):
151
+ sign = -1.0 if signed else 0.0
152
+ total_values = 2**total_bits
153
+ if add_zero or total_bits < 8:
154
+ # add a zero
155
+ # since we simulate less bits by having zeros in the data type, we
156
+ # we need to center the quantization around zero and as such lose
157
+ # a single value
158
+ total_values = 2**total_bits if not signed else 2**total_bits - 1
159
+
160
+ values = torch.linspace(sign, 1.0, total_values)
161
+ gap = 256 - values.numel()
162
+ if gap == 0:
163
+ return values
164
+ else:
165
+ l = values.numel() // 2 # noqa: E741
166
+ return torch.Tensor(values[:l].tolist() + [0] * gap + values[l:].tolist())
167
+
168
+
169
+ def create_normal_map(offset=0.9677083, use_extra_value=True):
170
+ """Create the NormalFloat (NF4) quantization map.
171
+
172
+ Constructs a lookup table of 16 quantization values (stored in a 256-element tensor for
173
+ indexing convenience) derived from quantiles of the standard normal distribution N(0, 1).
174
+ Each bin has approximately equal probability mass under the normal distribution, which is
175
+ optimal for normally-distributed data like neural network weights.
176
+
177
+ Unlike floating-point types (FP4, FP8), NF4 is NOT a float encoding — the 4-bit index is
178
+ simply a lookup into this table. There is no sign/exponent/mantissa decomposition.
179
+
180
+ The values are generated by computing ``scipy.stats.norm.ppf()`` (inverse CDF) at evenly
181
+ spaced quantile points, then normalizing to [-1, 1].
182
+
183
+ For more details, see: QLoRA: Efficient Finetuning of Quantized LLMs
184
+ (https://arxiv.org/abs/2305.14314)
185
+
186
+ Args:
187
+ offset: The outermost quantile boundary, controlling the range of the normal distribution
188
+ that is covered. ``norm.ppf(offset)`` gives the largest bin edge in standard deviations.
189
+ The default (0.9677083) covers up to ~1.845 standard deviations and was empirically
190
+ optimized to minimize quantization error for typical neural network weight distributions.
191
+ use_extra_value: If True, creates an asymmetric type with 8 negative and 9 positive values
192
+ (including zero), for 15 non-zero values total. If False, creates a symmetric type
193
+ with 7 negative and 7 positive values (14 non-zero values total).
194
+
195
+ Returns:
196
+ A 256-element tensor where the first 16 values are the sorted NF4 quantization levels
197
+ normalized to [-1, 1], and the remaining values are zero (padding for 8-bit indexing).
198
+ """
199
+ try:
200
+ from scipy.stats import norm
201
+ except ImportError as ie:
202
+ raise ImportError(
203
+ "Scipy is required for `create_normal_map`. Install `bitsandbytes` with the `[test]` extra.",
204
+ ) from ie
205
+
206
+ if use_extra_value:
207
+ # one more positive value, this is an asymmetric type
208
+ v1 = norm.ppf(torch.linspace(offset, 0.5, 9)[:-1]).tolist()
209
+ v2 = [0] * (256 - 15) ## we have 15 non-zero values in this data type
210
+ v3 = (-norm.ppf(torch.linspace(offset, 0.5, 8)[:-1])).tolist()
211
+ else:
212
+ v1 = norm.ppf(torch.linspace(offset, 0.5, 8)[:-1]).tolist()
213
+ v2 = [0] * (256 - 14) ## we have 14 non-zero values in this data type
214
+ v3 = (-norm.ppf(torch.linspace(offset, 0.5, 8)[:-1])).tolist()
215
+
216
+ v = v1 + v2 + v3
217
+
218
+ values = torch.Tensor(v)
219
+ values = values.sort().values
220
+ values /= values.max()
221
+
222
+ assert values.numel() == 256
223
+
224
+ return values
225
+
226
+
227
+ def create_fp8_map(signed=True, exponent_bits=5, precision_bits=2, total_bits=8):
228
+ """Create a floating-point quantization map with configurable bit layout.
229
+
230
+ Generates a lookup table for a custom floating-point format following IEEE 754-like encoding
231
+ with configurable exponent and mantissa (precision) bits. Despite the name, this function
232
+ handles any total bit width (including FP4 when called with ``total_bits=4``).
233
+
234
+ The encoding uses:
235
+ - Exponent bias: ``2^(exponent_bits - 1)``
236
+ - Normal values: ``(1 + mantissa) * 2^(exponent - bias - 1)``
237
+ - Subnormal values (exponent field = 0): ``mantissa * 2^(-bias)``
238
+
239
+ Note: The values in the returned tensor are normalized by dividing by the maximum value,
240
+ so the actual represented range is [-1, 1].
241
+
242
+ For the FP4 type used in bitsandbytes (2 exponent bits, 1 mantissa bit, signed):
243
+ ``create_fp8_map(signed=True, exponent_bits=2, precision_bits=1, total_bits=4)``
244
+
245
+ Args:
246
+ signed: Whether the format includes a sign bit.
247
+ exponent_bits: Number of bits for the exponent field.
248
+ precision_bits: Number of bits for the mantissa (precision/fraction) field.
249
+ total_bits: Total number of bits per value (must equal sign + exponent + precision).
250
+
251
+ Returns:
252
+ A 256-element tensor of sorted quantization levels normalized to [-1, 1].
253
+ For types with fewer than 8 bits, the remaining entries are zero-padded.
254
+ """
255
+ e = exponent_bits
256
+ p = precision_bits
257
+ has_sign = 1 if signed else 0
258
+ assert e + p == total_bits - has_sign
259
+ # the exponent is biased to 2^(e-1) -1 == 0
260
+ evalues = []
261
+ for i, val in enumerate(range(-(2 ** (exponent_bits - has_sign)), 2 ** (exponent_bits - has_sign), 1)):
262
+ evalues.append(2**val)
263
+
264
+ values = []
265
+ lst = list(itertools.product([0, 1], repeat=precision_bits))
266
+ # for ev in evalues:
267
+ bias = 2 ** (exponent_bits - 1)
268
+ for evalue in range(2 ** (exponent_bits)):
269
+ for bit_pattern in lst:
270
+ value = 1 if evalue != 0 else 0
271
+ for i, pval in enumerate(list(bit_pattern)):
272
+ value += pval * (2 ** -(i + 1))
273
+ if evalue == 0:
274
+ # subnormals
275
+ value = value * 2**-(bias)
276
+ else:
277
+ # normals
278
+ value = value * 2 ** -(evalue - bias - 1)
279
+ values.append(value)
280
+ if signed:
281
+ values.append(-value)
282
+
283
+ assert len(values) == 2**total_bits
284
+ values.sort()
285
+ if total_bits < 8:
286
+ gap = 256 - len(values)
287
+ for i in range(gap):
288
+ values.append(0)
289
+ values.sort()
290
+ code = torch.tensor(values)
291
+ code /= code.max()
292
+
293
+ return code
294
+
295
+
296
+ def create_dynamic_map(signed=True, max_exponent_bits=7, total_bits=8):
297
+ """
298
+ Creates the dynamic quantiztion map.
299
+
300
+ The dynamic data type is made up of a dynamic exponent and
301
+ fraction. As the exponent increase from 0 to -7 the number
302
+ of bits available for the fraction shrinks.
303
+
304
+ This is a generalization of the dynamic type where a certain
305
+ number of the bits and be reserved for the linear quantization
306
+ region (the fraction). n determines the maximum number of
307
+ exponent bits.
308
+
309
+ For more details see
310
+ (8-Bit Approximations for Parallelism in Deep Learning)[https://arxiv.org/abs/1511.04561]
311
+ """
312
+
313
+ data = []
314
+ # these are additional items that come from the case
315
+ # where all the exponent bits are zero and no
316
+ # indicator bit is present
317
+ non_sign_bits = total_bits - 1
318
+ additional_items = 2 ** (non_sign_bits - max_exponent_bits) - 1
319
+ for i in range(max_exponent_bits):
320
+ fraction_items = int(
321
+ 2 ** (i + non_sign_bits - max_exponent_bits) + 1
322
+ if signed
323
+ else 2 ** (i + non_sign_bits - max_exponent_bits + 1) + 1,
324
+ )
325
+ boundaries = torch.linspace(0.1, 1, fraction_items, dtype=torch.float32)
326
+ means = (boundaries[:-1] + boundaries[1:]) / 2.0
327
+ data += ((10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
328
+ if signed:
329
+ data += (-(10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
330
+
331
+ if additional_items > 0:
332
+ boundaries = torch.linspace(0.1, 1, additional_items + 1, dtype=torch.float32)
333
+ means = (boundaries[:-1] + boundaries[1:]) / 2.0
334
+ data += ((10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
335
+ if signed:
336
+ data += (-(10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
337
+
338
+ data.append(0)
339
+ data.append(1.0)
340
+
341
+ assert len(data) == 2**total_bits
342
+
343
+ gap = 256 - len(data)
344
+ for i in range(gap):
345
+ data.append(0)
346
+
347
+ data.sort()
348
+ return torch.tensor(data, dtype=torch.float32)
349
+
350
+
351
+ def is_on_gpu(tensors: Iterable[Optional[torch.Tensor]]):
352
+ """Verifies that the input tensors are all on the same device.
353
+
354
+ An input tensor may also be marked as `paged`, in which case the device placement is ignored.
355
+ CPU tensors are allowed and checked for consistency among themselves.
356
+
357
+ Args:
358
+ tensors (`Iterable[Optional[torch.Tensor]]`): A list of tensors to verify.
359
+
360
+ Raises:
361
+ `RuntimeError`: Raised when the verification fails.
362
+
363
+ Returns:
364
+ `Literal[True]`
365
+ """
366
+
367
+ devices = set()
368
+
369
+ for t in tensors:
370
+ # NULL pointers and paged tensors are OK.
371
+ if t is not None and not getattr(t, "is_paged", False):
372
+ devices.add((t.device.type, t.device.index))
373
+
374
+ # All tensors on CPU is valid
375
+ if devices == {("cpu", None)}:
376
+ return True
377
+
378
+ # Check that no CPU tensors are mixed with GPU tensors
379
+ has_cpu = ("cpu", None) in devices
380
+ if has_cpu and len(devices) > 1:
381
+ raise RuntimeError(
382
+ f"Input tensors need to be on the same device, but found the following tensor and device combinations:\n {[(t.shape, t.device) for t in tensors if t is not None]}",
383
+ )
384
+
385
+ # GPU path: all tensors must be on the same single GPU
386
+ if len(devices) > 1:
387
+ raise RuntimeError(
388
+ f"Input tensors need to be on the same GPU, but found the following tensor and device combinations:\n {[(t.shape, t.device) for t in tensors if t is not None]}",
389
+ )
390
+ return True
391
+
392
+
393
+ def _get_tensor_stream(tensor: Tensor) -> ct.c_void_p:
394
+ # We use the raw stream for performance reasons.
395
+ if tensor.device.type == "cuda":
396
+ return ct.c_void_p(torch._C._cuda_getCurrentRawStream(tensor.device.index))
397
+ if tensor.device.type == "xpu":
398
+ return ct.c_void_p(torch._C._xpu_getCurrentRawStream(tensor.device.index))
399
+ # For CPU tensors (e.g. paged optimizer states), use current device's stream.
400
+ if hasattr(torch, "xpu") and torch.xpu.is_available():
401
+ return ct.c_void_p(torch._C._xpu_getCurrentRawStream(torch.xpu.current_device()))
402
+ return ct.c_void_p(torch._C._cuda_getCurrentRawStream(torch.cuda.current_device()))
403
+
404
+
405
+ def get_ptr(A: Optional[Tensor]) -> Optional[ct.c_void_p]:
406
+ """Gets the memory address of the first element of a tenso
407
+
408
+ Args:
409
+ A (`Optional[Tensor]`): A PyTorch tensor.
410
+
411
+ Returns:
412
+ `Optional[ct.c_void_p]`: A pointer to the underlying tensor data.
413
+ """
414
+ if A is None:
415
+ return None
416
+
417
+ return ct.c_void_p(A.data_ptr())
418
+
419
+
420
+ class QuantState:
421
+ """container for quantization state components to work with Params4bit and similar classes"""
422
+
423
+ valid_quant_types = ("fp4", "nf4")
424
+ valid_qs_type_keys = [f"bitsandbytes__{x}" for x in valid_quant_types]
425
+ valid_qs_keys = [
426
+ "absmax",
427
+ "quant_map",
428
+ "nested_absmax",
429
+ "nested_quant_map",
430
+ "quant_state",
431
+ "quant_type",
432
+ "blocksize",
433
+ "dtype",
434
+ "shape",
435
+ "nested_blocksize",
436
+ "nested_dtype",
437
+ "nested_offset",
438
+ ]
439
+
440
+ def __init__(
441
+ self,
442
+ absmax,
443
+ shape=None,
444
+ code=None,
445
+ blocksize=None,
446
+ quant_type=None,
447
+ dtype=None,
448
+ offset=None,
449
+ state2=None,
450
+ ):
451
+ self.absmax = absmax
452
+ self.shape = shape
453
+ self.code = code
454
+ self.dtype = dtype
455
+ self.blocksize = blocksize
456
+ self.quant_type = quant_type
457
+ self.offset = offset
458
+ self.state2 = state2
459
+ self.nested = state2 is not None
460
+
461
+ def __getattr__(self, name):
462
+ # Support attribute access for packed state_dict keys like "bitsandbytes__nf4".
463
+ # PyTorch's FSDP state_dict traversal (_get_fqns) resolves dotted FQN paths via
464
+ # getattr. The packed key "quant_state.bitsandbytes__nf4" causes it to call
465
+ # getattr(quant_state_obj, "bitsandbytes__nf4"), which we handle here.
466
+ if name.startswith("bitsandbytes__"):
467
+ qs_dict = self.as_dict(packed=True)
468
+ packed_key = "quant_state." + name
469
+ if packed_key in qs_dict:
470
+ return qs_dict[packed_key]
471
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
472
+
473
+ def __getitem__(self, idx):
474
+ """
475
+ ensures compatibility with older quant state scheme with nested lists.
476
+ assumes the following layout:
477
+ state = [qabsmax, input_shape, A.dtype, blocksize, [offset, state2], quant_type]
478
+ state2 = [absmax, input_shape, A.dtype, blocksize, None, quant_type]
479
+ """
480
+ if self.nested:
481
+ list_repr = [
482
+ self.absmax,
483
+ self.shape,
484
+ self.dtype,
485
+ self.blocksize,
486
+ [self.offset, self.state2],
487
+ self.quant_type,
488
+ ]
489
+ else:
490
+ list_repr = [self.absmax, self.shape, self.dtype, self.blocksize, None, self.quant_type]
491
+ return list_repr[idx]
492
+
493
+ @classmethod
494
+ def from_dict(cls, qs_dict: dict[str, Any], device: torch.device) -> "QuantState":
495
+ """
496
+ unpacks components of state_dict into QuantState
497
+ where necessary, convert into strings, torch.dtype, ints, etc.
498
+
499
+ qs_dict: based on state_dict, with only relevant keys, striped of prefixes.
500
+
501
+ item with key `quant_state.bitsandbytes__[nf4/fp4]` may contain minor and non-tensor quant state items.
502
+ """
503
+
504
+ # unpacking tensor with non-tensor components
505
+ qs_key = [k for k, v in qs_dict.items() if "quant_state" in k and isinstance(v, torch.Tensor)]
506
+ if "quant_type" not in qs_dict:
507
+ if not qs_key:
508
+ raise ValueError("Expected packed or unpacked quant_state items, found neither")
509
+ elif len(qs_key) != 1 or qs_key[0].split(".")[-1] not in cls.valid_qs_type_keys:
510
+ raise ValueError(
511
+ f"There should be exactly one `quant_state` item with ending from {cls.valid_qs_type_keys}.\nDetected {qs_key}.",
512
+ )
513
+
514
+ # unpacking minor and non-tensor quant state items if necessary
515
+ if len(qs_key) == 1:
516
+ first_qs_key = qs_key[0]
517
+ qs_dict.update(unpack_tensor_to_dict(qs_dict.pop(first_qs_key)))
518
+
519
+ qs_dict = {k.split(".")[-1]: v for k, v in qs_dict.items()} # strip prefixes
520
+ assert set(qs_dict.keys()).issubset(cls.valid_qs_keys)
521
+
522
+ if "nested_absmax" in qs_dict:
523
+ offset = torch.tensor(float(qs_dict["nested_offset"])).to(device)
524
+ state2 = cls(
525
+ absmax=qs_dict["nested_absmax"].to(device),
526
+ blocksize=qs_dict["nested_blocksize"],
527
+ code=qs_dict["nested_quant_map"].to(device),
528
+ dtype=getattr(torch, qs_dict["nested_dtype"]),
529
+ )
530
+ else:
531
+ offset, state2 = None, None
532
+
533
+ quant_state = cls(
534
+ quant_type=qs_dict["quant_type"],
535
+ absmax=qs_dict["absmax"].to(device),
536
+ blocksize=qs_dict["blocksize"],
537
+ code=qs_dict["quant_map"].to(device),
538
+ dtype=getattr(torch, qs_dict["dtype"]),
539
+ shape=torch.Size(qs_dict["shape"]) if qs_dict["shape"] is not None else None,
540
+ offset=offset,
541
+ state2=state2,
542
+ )
543
+ return quant_state
544
+
545
+ def as_dict(self, packed: bool = False) -> dict[str, Any]:
546
+ """
547
+ returns dict of tensors and strings to use in serialization via _save_to_state_dict()
548
+ param: packed -- returns dict[str, torch.Tensor] for state_dict fit for safetensors saving
549
+ """
550
+ qs_dict = {
551
+ "quant_type": self.quant_type,
552
+ "absmax": self.absmax,
553
+ "blocksize": self.blocksize,
554
+ "quant_map": self.code,
555
+ "dtype": str(self.dtype).strip("torch."),
556
+ "shape": tuple(self.shape) if self.shape is not None else None,
557
+ }
558
+ if self.nested:
559
+ qs_dict.update(
560
+ {
561
+ "nested_absmax": self.state2.absmax,
562
+ "nested_blocksize": self.state2.blocksize,
563
+ "nested_quant_map": self.state2.code.clone(), # un-shared to avoid restoring it after shared tensors are removed by safetensors
564
+ "nested_dtype": str(self.state2.dtype).strip("torch."),
565
+ "nested_offset": self.offset.item(),
566
+ },
567
+ )
568
+ if not packed or self.quant_type is None:
569
+ return qs_dict
570
+
571
+ # packed format allows serialization of non-tensor components, critical for saving in safetensors format
572
+ qs_packed_dict = {k: v for k, v in qs_dict.items() if isinstance(v, torch.Tensor)}
573
+ non_tensor_dict = {k: v for k, v in qs_dict.items() if not isinstance(v, torch.Tensor)}
574
+ key = "quant_state.bitsandbytes__"
575
+ if self.quant_type is not None:
576
+ key += self.quant_type
577
+ qs_packed_dict[key] = pack_dict_to_tensor(non_tensor_dict)
578
+ return qs_packed_dict
579
+
580
+ def to(self, device):
581
+ # make sure the quantization state is on the right device
582
+ self.code = self.code.to(device)
583
+ self.absmax = self.absmax.to(device)
584
+ if self.nested:
585
+ self.offset = self.offset.to(device)
586
+ self.state2.absmax = self.state2.absmax.to(device)
587
+ self.state2.code = self.state2.code.to(device)
588
+
589
+ def __eq__(self, other):
590
+ if not isinstance(other, QuantState):
591
+ return False
592
+
593
+ return (
594
+ torch.allclose(self.absmax, other.absmax, atol=1e-6)
595
+ and self.shape == other.shape
596
+ and torch.allclose(self.code, other.code, atol=1e-6)
597
+ and self.dtype == other.dtype
598
+ and self.blocksize == other.blocksize
599
+ and self.quant_type == other.quant_type
600
+ and (
601
+ self.offset == other.offset
602
+ if self.offset is not None and other.offset is not None
603
+ else self.offset is other.offset
604
+ )
605
+ and (
606
+ self.state2 == other.state2
607
+ if self.state2 is not None and other.state2 is not None
608
+ else self.state2 is other.state2
609
+ )
610
+ )
611
+
612
+
613
+ def quantize_blockwise(
614
+ A: torch.Tensor,
615
+ code: Optional[torch.Tensor] = None,
616
+ absmax: Optional[torch.Tensor] = None,
617
+ out: Optional[torch.Tensor] = None,
618
+ blocksize=4096,
619
+ nested=False,
620
+ ) -> tuple[torch.Tensor, QuantState]:
621
+ """Quantize a tensor in blocks of values.
622
+
623
+ The input tensor is quantized by dividing it into blocks of `blocksize` values.
624
+ The the absolute maximum value within these blocks is calculated for scaling
625
+ the non-linear quantization.
626
+
627
+ Args:
628
+ A (`torch.Tensor`): The input tensor. Supports `float16`, `bfloat16`, or `float32` datatypes.
629
+ code (`torch.Tensor`, *optional*):
630
+ A mapping describing the low-bit data type. Defaults to a signed 8-bit dynamic type.
631
+ For more details, see (8-Bit Approximations for Parallelism in Deep Learning)[https://arxiv.org/abs/1511.04561].
632
+ absmax (`torch.Tensor`, *optional*): A tensor to use to store the absmax values.
633
+ out (`torch.Tensor`, *optional*): A tensor to use to store the result.
634
+ blocksize (`int`, *optional*):
635
+ The size of the blocks. Defaults to 4096.
636
+ Valid values are 64, 128, 256, 512, 1024, 2048, and 4096.
637
+ nested (`bool`, *optional*): Whether to additionally quantize the absmax values. Defaults to False.
638
+
639
+ Raises:
640
+ ValueError: Raised when the input data type is not supported.
641
+
642
+ Returns:
643
+ `Tuple[torch.Tensor, QuantState]`: A tuple containing the quantization results.
644
+ - `torch.Tensor`: The quantized tensor.
645
+ - [`QuantState`]: The state object used to undo the quantization.
646
+ """
647
+
648
+ if blocksize <= 0:
649
+ raise ValueError(f"blocksize must be positive, got {blocksize}")
650
+ if A.dtype not in (torch.float32, torch.float16, torch.bfloat16):
651
+ raise ValueError(f"Blockwise quantization only supports 16/32-bit floats, but got {A.dtype}")
652
+
653
+ if code is None:
654
+ if "dynamic" not in name2qmap:
655
+ name2qmap["dynamic"] = create_dynamic_map().to(A.device)
656
+ code = name2qmap["dynamic"]
657
+
658
+ _out, _absmax = torch.ops.bitsandbytes.quantize_blockwise.default(
659
+ A,
660
+ code.to(A.device),
661
+ blocksize,
662
+ )
663
+
664
+ if nested:
665
+ offset = _absmax.mean()
666
+ _absmax -= offset
667
+ qabsmax, state2 = quantize_blockwise(_absmax, blocksize=blocksize, nested=False)
668
+ quant_state = QuantState(
669
+ absmax=qabsmax,
670
+ code=code.to(A.device, copy=True),
671
+ blocksize=blocksize,
672
+ dtype=A.dtype,
673
+ offset=offset,
674
+ state2=state2,
675
+ )
676
+ else:
677
+ quant_state = QuantState(absmax=_absmax, code=code.to(A.device, copy=True), blocksize=blocksize, dtype=A.dtype)
678
+
679
+ # TODO(matthewdouglas): Deprecate out kwarg
680
+ out = out.copy_(_out) if out is not None else _out
681
+
682
+ # TODO(matthewdouglas): Deprecate absmax kwarg
683
+ if absmax is not None:
684
+ quant_state.absmax = absmax.copy_(quant_state.absmax)
685
+
686
+ return out, quant_state
687
+
688
+
689
+ def dequantize_blockwise(
690
+ A: torch.Tensor,
691
+ quant_state: Optional[QuantState] = None,
692
+ absmax: Optional[torch.Tensor] = None,
693
+ code: Optional[torch.Tensor] = None,
694
+ out: Optional[torch.Tensor] = None,
695
+ blocksize: int = 4096,
696
+ nested=False,
697
+ ) -> torch.Tensor:
698
+ """Dequantize a tensor in blocks of values.
699
+
700
+ The input tensor is dequantized by dividing it into blocks of `blocksize` values.
701
+ The the absolute maximum value within these blocks is used for scaling
702
+ the non-linear dequantization.
703
+
704
+ Args:
705
+ A (`torch.Tensor`): The quantized input tensor.
706
+ quant_state ([`QuantState`], *optional*):
707
+ The quantization state as returned by [`quantize_blockwise`].
708
+ Required if `absmax` is not provided.
709
+ absmax (`torch.Tensor`, *optional*):
710
+ A tensor containing the scaling values.
711
+ Required if `quant_state` is not provided and ignored otherwise.
712
+ code (`torch.Tensor`, *optional*):
713
+ A mapping describing the low-bit data type. Defaults to a signed 8-bit dynamic type.
714
+ For more details, see (8-Bit Approximations for Parallelism in Deep Learning)[https://arxiv.org/abs/1511.04561].
715
+ Ignored when `quant_state` is provided.
716
+ out (`torch.Tensor`, *optional*): A tensor to use to store the result.
717
+ blocksize (`int`, *optional*):
718
+ The size of the blocks. Defaults to 4096.
719
+ Valid values are 64, 128, 256, 512, 1024, 2048, and 4096.
720
+ Ignored when `quant_state` is provided.
721
+
722
+ Raises:
723
+ ValueError: Raised when the input data type is not supported.
724
+
725
+ Returns:
726
+ `torch.Tensor`:
727
+ The dequantized tensor. The datatype is indicated by `quant_state.dtype` and defaults to `torch.float32`.
728
+ """
729
+
730
+ if quant_state is None and absmax is None:
731
+ raise ValueError("dequantize_blockwise requires either quant_state or absmax")
732
+ if A.dtype != torch.uint8:
733
+ raise ValueError(f"A must be uint8, got {A.dtype}")
734
+ if code is None and quant_state is None:
735
+ if "dynamic" not in name2qmap:
736
+ name2qmap["dynamic"] = create_dynamic_map().to(A.device)
737
+ code = name2qmap["dynamic"]
738
+
739
+ if quant_state is None:
740
+ quant_state = QuantState(absmax=absmax, code=code, blocksize=blocksize, dtype=torch.float32)
741
+
742
+ if quant_state.blocksize <= 0:
743
+ raise ValueError(f"blocksize must be positive, got {quant_state.blocksize}")
744
+
745
+ absmax = quant_state.absmax
746
+ if quant_state.nested:
747
+ absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
748
+ absmax += quant_state.offset
749
+ if absmax.dtype != torch.float32:
750
+ absmax = absmax.float()
751
+
752
+ if out is not None:
753
+ torch.ops.bitsandbytes.dequantize_blockwise.out(
754
+ A,
755
+ absmax,
756
+ quant_state.code.to(A.device),
757
+ quant_state.blocksize,
758
+ quant_state.dtype,
759
+ out=out,
760
+ )
761
+ return out
762
+
763
+ return torch.ops.bitsandbytes.dequantize_blockwise.default(
764
+ A,
765
+ absmax,
766
+ quant_state.code.to(A.device),
767
+ quant_state.blocksize,
768
+ quant_state.dtype,
769
+ )
770
+
771
+
772
+ def get_4bit_type(typename, device=None, blocksize=64):
773
+ if device is None:
774
+ device = "cuda"
775
+ data = None
776
+ if typename == "nf4":
777
+ # NF4 (NormalFloat4) quantization type.
778
+ #
779
+ # These 16 values are a lookup table derived from quantiles of the standard normal
780
+ # distribution N(0, 1), where each bin has equal probability mass. The 4-bit index
781
+ # is just a position in this table — NF4 is NOT a floating-point encoding (no
782
+ # sign/exponent/mantissa decomposition). This is fundamentally different from FP4.
783
+ #
784
+ # Generated by: create_normal_map(offset=0.9677083, use_extra_value=True)
785
+ # Values are hardcoded to avoid a scipy dependency at runtime.
786
+ #
787
+ # For details see: QLoRA (https://arxiv.org/abs/2305.14314)
788
+ data = [
789
+ -1.0,
790
+ -0.6961928009986877,
791
+ -0.5250730514526367,
792
+ -0.39491748809814453,
793
+ -0.28444138169288635,
794
+ -0.18477343022823334,
795
+ -0.09105003625154495,
796
+ 0.0,
797
+ 0.07958029955625534,
798
+ 0.16093020141124725,
799
+ 0.24611230194568634,
800
+ 0.33791524171829224,
801
+ 0.44070982933044434,
802
+ 0.5626170039176941,
803
+ 0.7229568362236023,
804
+ 1.0,
805
+ ]
806
+ elif typename == "fp4":
807
+ # FP4 (4-bit floating point) quantization type.
808
+ #
809
+ # Unlike NF4, FP4 is an actual floating-point encoding with 1 sign bit, 2 exponent
810
+ # bits, and 1 mantissa bit. Values below are listed in bit-pattern order (not value
811
+ # order), where only the 3 non-sign bits are shown:
812
+ #
813
+ # 0b000 = 0 (subnormal: zero)
814
+ # 0b001 = 0.0625 (subnormal: 0.5 * 2^-2)
815
+ # 0b010 = 8 0b011 = 12 0b100 = 4
816
+ # 0b101 = 6 0b110 = 2 0b111 = 3
817
+ #
818
+ # The exponent bias is 2^(e-1) = 2, which differs from IEEE 754's convention.
819
+ # These can be regenerated with:
820
+ # create_fp8_map(signed=True, exponent_bits=2, precision_bits=1, total_bits=4)
821
+ #
822
+ # All values are normalized to [-1, 1] after construction (see end of function).
823
+ data = [0, 0.0625, 8.0, 12.0, 4.0, 6.0, 2.0, 3.0, -0, -0.0625, -8.0, -12.0, -4.0, -6.0, -2.0, -3.0]
824
+ elif typename == "int4":
825
+ data = [7, 6, 5, 4, 3, 2, 1, 0, -0, -1, -2, -3, -4, -5, -6, -7]
826
+ elif typename == "af4":
827
+ # Taken from: NF4 Isn't Information Theoretically Optimal (and that's Good)
828
+ # https://arxiv.org/abs/2306.06965
829
+ if blocksize == 64:
830
+ data = [
831
+ -1.0,
832
+ -0.69441008,
833
+ -0.51243739,
834
+ -0.3736951,
835
+ -0.25607552,
836
+ -0.14982478,
837
+ -0.04934812,
838
+ 0.0,
839
+ 0.04273164,
840
+ 0.12934483,
841
+ 0.21961274,
842
+ 0.31675666,
843
+ 0.42563882,
844
+ 0.55496234,
845
+ 0.72424863,
846
+ 1.0,
847
+ ][::-1]
848
+ else:
849
+ raise NotImplementedError("4-bit AbnormalFloats currently only support blocksize 64.")
850
+
851
+ if data is None:
852
+ raise NotImplementedError(f"Typename {typename} not supported")
853
+
854
+ data = torch.tensor(data, device=device)
855
+ data.div_(data.abs().max())
856
+
857
+ assert data.numel() == 16
858
+
859
+ return data
860
+
861
+
862
+ def quantize_fp4(
863
+ A: torch.Tensor,
864
+ absmax: Optional[torch.Tensor] = None,
865
+ out: Optional[torch.Tensor] = None,
866
+ blocksize=None,
867
+ compress_statistics=False,
868
+ quant_storage=torch.uint8,
869
+ ):
870
+ return quantize_4bit(A, absmax, out, blocksize, compress_statistics, "fp4", quant_storage)
871
+
872
+
873
+ def quantize_nf4(
874
+ A: torch.Tensor,
875
+ absmax: Optional[torch.Tensor] = None,
876
+ out: Optional[torch.Tensor] = None,
877
+ blocksize=None,
878
+ compress_statistics=False,
879
+ quant_storage=torch.uint8,
880
+ ):
881
+ return quantize_4bit(A, absmax, out, blocksize, compress_statistics, "nf4", quant_storage)
882
+
883
+
884
+ def quantize_4bit(
885
+ A: torch.Tensor,
886
+ absmax: Optional[torch.Tensor] = None,
887
+ out: Optional[torch.Tensor] = None,
888
+ blocksize=None,
889
+ compress_statistics=False,
890
+ quant_type="fp4",
891
+ quant_storage=torch.uint8,
892
+ ) -> tuple[torch.Tensor, QuantState]:
893
+ """Quantize tensor A in blocks of 4-bit values.
894
+
895
+ Quantizes tensor A by dividing it into blocks which are independently quantized.
896
+
897
+ Args:
898
+ A (`torch.Tensor`): The input tensor. Supports `float16`, `bfloat16`, or `float32` datatypes.
899
+ absmax (`torch.Tensor`, *optional*): A tensor to use to store the absmax values.
900
+ out (`torch.Tensor`, *optional*): A tensor to use to store the result.
901
+ blocksize (`int`, *optional*):
902
+ The size of the blocks. Defaults to 64.
903
+ Valid values are 32, 64, 128, 256, 512, 1024, 2048, and 4096.
904
+ compress_statistics (`bool`, *optional*): Whether to additionally quantize the absmax values. Defaults to False.
905
+ quant_type (`str`, *optional*): The data type to use: `nf4` or `fp4`. Defaults to `fp4`.
906
+ quant_storage (`torch.dtype`, *optional*): The dtype of the tensor used to store the result. Defaults to `torch.uint8`.
907
+
908
+ Raises:
909
+ ValueError: Raised when the input data type is not supported.
910
+
911
+ Returns:
912
+ Tuple[`torch.Tensor`, `QuantState`]: A tuple containing the quantization results.
913
+ - `torch.Tensor`: The quantized tensor with packed 4-bit values.
914
+ - [`QuantState`]: The state object used to undo the quantization.
915
+ """
916
+
917
+ if blocksize is None:
918
+ blocksize = 64
919
+
920
+ if blocksize not in (32, 64, 128, 256, 512, 1024, 2048, 4096):
921
+ raise ValueError(f"invalid blocksize {blocksize}")
922
+ if quant_type not in ("nf4", "fp4"):
923
+ raise ValueError(f"quant_type must be 'nf4' or 'fp4', got {quant_type!r}")
924
+ if A.dtype not in (torch.bfloat16, torch.float16, torch.float32):
925
+ raise ValueError(f"Blockwise 4bit quantization only supports 16/32-bit floats, but got {A.dtype}")
926
+
927
+ input_shape = A.shape
928
+
929
+ _out, _absmax = torch.ops.bitsandbytes.quantize_4bit.default(
930
+ A,
931
+ blocksize,
932
+ quant_type,
933
+ quant_storage,
934
+ )
935
+
936
+ code = get_4bit_type(quant_type, device=A.device)
937
+
938
+ if compress_statistics:
939
+ offset = _absmax.mean()
940
+ qabsmax, state2 = quantize_blockwise(_absmax - offset, blocksize=256)
941
+ del _absmax
942
+ state = QuantState(
943
+ absmax=qabsmax,
944
+ shape=input_shape,
945
+ dtype=A.dtype,
946
+ blocksize=blocksize,
947
+ code=code,
948
+ quant_type=quant_type,
949
+ offset=offset,
950
+ state2=state2,
951
+ )
952
+ else:
953
+ state = QuantState(
954
+ absmax=_absmax,
955
+ shape=input_shape,
956
+ dtype=A.dtype,
957
+ blocksize=blocksize,
958
+ code=code,
959
+ quant_type=quant_type,
960
+ )
961
+
962
+ # TODO(matthewdouglas): Deprecate out kwarg
963
+ out = out.copy_(_out) if out is not None else _out
964
+
965
+ # TODO(matthewdouglas): Deprecate absmax kwarg
966
+ if absmax is not None:
967
+ state.absmax = absmax.copy_(state.absmax)
968
+
969
+ return out, state
970
+
971
+
972
+ def dequantize_fp4(
973
+ A: torch.Tensor,
974
+ quant_state: Optional[QuantState] = None,
975
+ absmax: Optional[torch.Tensor] = None,
976
+ out: Optional[torch.Tensor] = None,
977
+ blocksize: Optional[int] = None,
978
+ ) -> torch.Tensor:
979
+ return dequantize_4bit(A, quant_state, absmax, out, blocksize, "fp4")
980
+
981
+
982
+ def dequantize_nf4(
983
+ A: torch.Tensor,
984
+ quant_state: Optional[QuantState] = None,
985
+ absmax: Optional[torch.Tensor] = None,
986
+ out: Optional[torch.Tensor] = None,
987
+ blocksize: Optional[int] = None,
988
+ ) -> torch.Tensor:
989
+ return dequantize_4bit(A, quant_state, absmax, out, blocksize, "nf4")
990
+
991
+
992
+ def dequantize_4bit(
993
+ A: torch.Tensor,
994
+ quant_state: Optional[QuantState] = None,
995
+ absmax: Optional[torch.Tensor] = None,
996
+ out: Optional[torch.Tensor] = None,
997
+ blocksize: Optional[int] = None,
998
+ quant_type="fp4",
999
+ ) -> torch.Tensor:
1000
+ """Dequantizes a packed 4-bit quantized tensor.
1001
+
1002
+ The input tensor is dequantized by dividing it into blocks of `blocksize` values.
1003
+ The absolute maximum value within these blocks is used for scaling
1004
+ the non-linear dequantization.
1005
+
1006
+ Args:
1007
+ A (`torch.Tensor`): The quantized input tensor.
1008
+ quant_state ([`QuantState`], *optional*):
1009
+ The quantization state as returned by [`quantize_4bit`].
1010
+ Required if `absmax` is not provided.
1011
+ absmax (`torch.Tensor`, *optional*):
1012
+ A tensor containing the scaling values.
1013
+ Required if `quant_state` is not provided and ignored otherwise.
1014
+ out (`torch.Tensor`, *optional*): A tensor to use to store the result.
1015
+ blocksize (`int`, *optional*):
1016
+ The size of the blocks. Defaults to 64.
1017
+ Valid values are 32, 64, 128, 256, 512, 1024, 2048, and 4096.
1018
+ quant_type (`str`, *optional*): The data type to use: `nf4` or `fp4`. Defaults to `fp4`.
1019
+
1020
+ Raises:
1021
+ ValueError: Raised when the input data type or blocksize is not supported.
1022
+
1023
+ Returns:
1024
+ `torch.Tensor`: The dequantized tensor.
1025
+ """
1026
+
1027
+ if blocksize is None:
1028
+ blocksize = 64
1029
+
1030
+ if quant_state is None:
1031
+ if absmax is None or out is None:
1032
+ raise ValueError("dequantize_4bit requires both absmax and out when quant_state is not provided")
1033
+
1034
+ quant_state = QuantState(
1035
+ absmax=absmax,
1036
+ shape=out.shape,
1037
+ dtype=out.dtype,
1038
+ blocksize=blocksize,
1039
+ quant_type=quant_type,
1040
+ )
1041
+
1042
+ else:
1043
+ absmax = quant_state.absmax
1044
+
1045
+ if quant_state.blocksize not in (32, 64, 128, 256, 512, 1024, 2048, 4096):
1046
+ raise ValueError(f"invalid blocksize {quant_state.blocksize}")
1047
+ if quant_state.quant_type not in ("nf4", "fp4"):
1048
+ raise ValueError(f"quant_type must be 'nf4' or 'fp4', got {quant_state.quant_type!r}")
1049
+ if quant_state.dtype not in (torch.bfloat16, torch.float16, torch.float32):
1050
+ raise ValueError(f"Blockwise 4bit dequantization only supports 16/32-bit floats, but got {quant_state.dtype}")
1051
+
1052
+ if quant_state.nested:
1053
+ absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
1054
+ absmax += quant_state.offset
1055
+ if absmax.dtype != torch.float32:
1056
+ absmax = absmax.float()
1057
+
1058
+ if out is not None:
1059
+ torch.ops.bitsandbytes.dequantize_4bit.out(
1060
+ A, absmax, quant_state.blocksize, quant_state.quant_type, quant_state.shape, quant_state.dtype, out=out
1061
+ )
1062
+ else:
1063
+ out = torch.ops.bitsandbytes.dequantize_4bit.default(
1064
+ A,
1065
+ absmax,
1066
+ quant_state.blocksize,
1067
+ quant_state.quant_type,
1068
+ quant_state.shape,
1069
+ quant_state.dtype,
1070
+ )
1071
+
1072
+ # BC shim: callers that pass the packed weight in transposed [1, (N*K+1)//2] form
1073
+ # receive the output transposed back to [K, N]. bnb's own paths no longer trigger
1074
+ # this since B is normalized to [(N*K+1)//2, 1] at the matmul_4bit entry point.
1075
+ if A.shape[0] == 1:
1076
+ return out.t()
1077
+ return out
1078
+
1079
+
1080
+ def optimizer_update_32bit(
1081
+ optimizer_name: str,
1082
+ g: Tensor,
1083
+ p: Tensor,
1084
+ state1: Tensor,
1085
+ beta1: float,
1086
+ eps: float,
1087
+ step: int,
1088
+ lr: float,
1089
+ state2: Optional[torch.Tensor] = None,
1090
+ beta2: float = 0.0,
1091
+ beta3: float = 0.0,
1092
+ alpha: float = 0.0,
1093
+ weight_decay: float = 0.0,
1094
+ gnorm_scale: float = 1.0,
1095
+ unorm_vec: Optional[torch.Tensor] = None,
1096
+ max_unorm: float = 0.0,
1097
+ skip_zeros=False,
1098
+ ) -> None:
1099
+ """
1100
+ Performs an inplace optimizer update with one or two optimizer states.
1101
+
1102
+ Universal optimizer update for 32-bit state and 32/16-bit gradients/weights.
1103
+
1104
+ Parameters
1105
+ ----------
1106
+ optimizer_name : str
1107
+ The name of the optimizer: {adam}.
1108
+ g : torch.Tensor
1109
+ Gradient tensor.
1110
+ p : torch.Tensor
1111
+ Parameter tensor.
1112
+ state1 : torch.Tensor
1113
+ Optimizer state 1.
1114
+ beta1 : float
1115
+ Optimizer beta1.
1116
+ eps : float
1117
+ Optimizer epsilon.
1118
+ weight_decay : float
1119
+ Weight decay.
1120
+ step : int
1121
+ Current optimizer step.
1122
+ lr : float
1123
+ The learning rate.
1124
+ state2 : torch.Tensor
1125
+ Optimizer state 2.
1126
+ beta2 : float
1127
+ Optimizer beta2.
1128
+ beta3 : float
1129
+ Optimizer beta3.
1130
+ alpha : float
1131
+ Optimizer alpha.
1132
+ gnorm_scale : float
1133
+ The factor to rescale the gradient to the max clip value.
1134
+ unorm_vec : torch.Tensor
1135
+ The tensor for the update norm.
1136
+ max_unorm : float
1137
+ The maximum update norm relative to the weight norm.
1138
+ skip_zeros : bool
1139
+ Whether to skip zero-valued gradients or not (default: False).
1140
+ """
1141
+
1142
+ param_norm = 0.0
1143
+ if max_unorm > 0.0:
1144
+ param_norm = torch.norm(p.data.float())
1145
+
1146
+ is_on_gpu([g, p, state1, state2, unorm_vec])
1147
+ torch.ops.bitsandbytes.optimizer_update_32bit(
1148
+ optimizer_name,
1149
+ g,
1150
+ p,
1151
+ state1,
1152
+ state2,
1153
+ unorm_vec,
1154
+ max_unorm,
1155
+ param_norm,
1156
+ beta1,
1157
+ beta2,
1158
+ beta3,
1159
+ alpha,
1160
+ eps,
1161
+ weight_decay,
1162
+ step,
1163
+ lr,
1164
+ gnorm_scale,
1165
+ skip_zeros,
1166
+ )
1167
+
1168
+
1169
+ def optimizer_update_8bit_blockwise(
1170
+ optimizer_name: str,
1171
+ g: Tensor,
1172
+ p: Tensor,
1173
+ state1: Tensor,
1174
+ state2: Optional[torch.Tensor],
1175
+ beta1: float,
1176
+ beta2: float,
1177
+ beta3: float,
1178
+ alpha: float,
1179
+ eps: float,
1180
+ step: int,
1181
+ lr: float,
1182
+ qmap1: Tensor,
1183
+ qmap2: Optional[torch.Tensor],
1184
+ absmax1: Tensor,
1185
+ absmax2: Optional[torch.Tensor],
1186
+ weight_decay: float = 0.0,
1187
+ gnorm_scale: float = 1.0,
1188
+ skip_zeros=False,
1189
+ ) -> None:
1190
+ is_on_gpu([p, g, state1, state2, qmap1, qmap2, absmax1, absmax2])
1191
+
1192
+ torch.ops.bitsandbytes.optimizer_update_8bit_blockwise(
1193
+ optimizer_name,
1194
+ g,
1195
+ p,
1196
+ state1,
1197
+ state2,
1198
+ beta1,
1199
+ beta2,
1200
+ beta3,
1201
+ alpha,
1202
+ eps,
1203
+ step,
1204
+ lr,
1205
+ qmap1,
1206
+ qmap2,
1207
+ absmax1,
1208
+ absmax2,
1209
+ weight_decay,
1210
+ gnorm_scale,
1211
+ skip_zeros,
1212
+ )
1213
+
1214
+
1215
+ @deprecated("This function is deprecated and will be removed in a future release.", category=FutureWarning)
1216
+ def check_matmul(A, B, out, transposed_A, transposed_B, expected_type=torch.int8):
1217
+ if not torch.cuda.is_initialized():
1218
+ torch.cuda.init()
1219
+ if A.dtype != expected_type or B.dtype != expected_type:
1220
+ raise TypeError(f"Expected torch.int8 input tensors A and B, but got {A.dtype} and {B.dtype}")
1221
+
1222
+ sA = A.shape
1223
+ sB = B.shape
1224
+ tA = transposed_A
1225
+ tB = transposed_B
1226
+
1227
+ correct = True
1228
+
1229
+ if len(sA) == 2 and len(sB) == 2:
1230
+ if not tA and not tB and A.shape[1] != B.shape[0]:
1231
+ correct = False
1232
+ elif tA and not tB and A.shape[0] != B.shape[0]:
1233
+ correct = False
1234
+ elif tA and tB and A.shape[0] != B.shape[1]:
1235
+ correct = False
1236
+ elif not tA and tB and A.shape[1] != B.shape[1]:
1237
+ correct = False
1238
+ elif len(sA) == 3 and len(sB) == 2:
1239
+ if not tA and not tB and A.shape[2] != B.shape[0]:
1240
+ correct = False
1241
+ elif tA and not tB and A.shape[1] != B.shape[0]:
1242
+ correct = False
1243
+ elif tA and tB and A.shape[1] != B.shape[1]:
1244
+ correct = False
1245
+ elif not tA and tB and A.shape[2] != B.shape[1]:
1246
+ correct = False
1247
+ elif len(sA) == 3 and len(sB) == 3:
1248
+ if not tA and not tB and A.shape[2] != B.shape[1]:
1249
+ correct = False
1250
+ elif tA and not tB and A.shape[1] != B.shape[1]:
1251
+ correct = False
1252
+ elif tA and tB and A.shape[1] != B.shape[2]:
1253
+ correct = False
1254
+ elif not tA and tB and A.shape[2] != B.shape[2]:
1255
+ correct = False
1256
+
1257
+ if out is not None:
1258
+ sout = out.shape
1259
+ # special case common in backprop
1260
+ if not correct and len(sA) == 3 and len(sB) == 3:
1261
+ if sout[0] == sA[2] and sout[1] == sB[2] and sA[0] == sB[0] and sA[1] == sB[1]:
1262
+ correct = True
1263
+ else:
1264
+ if len(sA) == 2 and len(sB) == 2:
1265
+ if not tA and not tB:
1266
+ sout = (sA[0], sB[1])
1267
+ elif tA and tB:
1268
+ sout = (sA[1], sB[0])
1269
+ elif tA and not tB:
1270
+ sout = (sA[1], sB[1])
1271
+ elif not tA and tB:
1272
+ sout = (sA[0], sB[0])
1273
+ elif len(sA) == 3 and len(sB) == 2:
1274
+ if not tA and not tB:
1275
+ sout = (sA[0], sA[1], sB[1])
1276
+ elif tA and tB:
1277
+ sout = (sA[0], sA[2], sB[0])
1278
+ elif tA and not tB:
1279
+ sout = (sA[0], sA[2], sB[1])
1280
+ elif not tA and tB:
1281
+ sout = (sA[0], sA[1], sB[0])
1282
+ elif len(sA) == 3 and len(sB) == 3:
1283
+ if not tA and not tB:
1284
+ sout = (sA[0], sA[1], sB[2])
1285
+ elif tA and tB:
1286
+ sout = (sA[0], sA[2], sB[1])
1287
+ elif tA and not tB:
1288
+ sout = (sA[0], sA[2], sB[2])
1289
+ elif not tA and tB:
1290
+ sout = (sA[0], sA[1], sB[1])
1291
+
1292
+ if not correct:
1293
+ raise ValueError(
1294
+ f"Tensor dimensions incorrect for matrix mulitiplication: A x B: {sA} x {sB} with transpose for A x B: {tA} x {tB}.",
1295
+ )
1296
+
1297
+ return sout
1298
+
1299
+
1300
+ def gemv_4bit(
1301
+ A: Tensor,
1302
+ B: Tensor,
1303
+ out: Optional[torch.Tensor] = None,
1304
+ transposed_A=False,
1305
+ transposed_B=False,
1306
+ state=None,
1307
+ ):
1308
+ if state is None:
1309
+ raise ValueError("state cannot be None. gemv_4bit() requires the state from quantize_4bit()")
1310
+
1311
+ absmax = state.absmax
1312
+ if state.nested:
1313
+ absmax = dequantize_blockwise(absmax, state.state2) + state.offset
1314
+
1315
+ if out is not None:
1316
+ torch.ops.bitsandbytes.gemv_4bit.out(
1317
+ A,
1318
+ B,
1319
+ state.shape,
1320
+ absmax,
1321
+ state.code,
1322
+ state.blocksize,
1323
+ out=out,
1324
+ )
1325
+ return out
1326
+
1327
+ return torch.ops.bitsandbytes.gemv_4bit.default(
1328
+ A,
1329
+ B,
1330
+ state.shape,
1331
+ absmax,
1332
+ state.code,
1333
+ state.blocksize,
1334
+ )
1335
+
1336
+
1337
+ @deprecated("This function is deprecated and will be removed in a future release.", category=FutureWarning)
1338
+ def igemm(
1339
+ A: Tensor,
1340
+ B: Tensor,
1341
+ out: Optional[torch.Tensor] = None,
1342
+ transposed_A=False,
1343
+ transposed_B=False,
1344
+ ):
1345
+ sout = check_matmul(A, B, out, transposed_A, transposed_B)
1346
+ if out is None:
1347
+ out = torch.zeros(size=sout, dtype=torch.int32, device=A.device)
1348
+ if len(A.shape) == 3 and len(B.shape) == 3:
1349
+ if A.shape[0] == B.shape[0] and A.shape[2] == B.shape[1]:
1350
+ return batched_igemm(A, B, out)
1351
+
1352
+ sA = A.shape
1353
+ sB = B.shape
1354
+ if transposed_A and len(sA) == 2:
1355
+ sA = (sA[1], sA[0])
1356
+ elif transposed_A and len(sA) == 3:
1357
+ sA = (sA[0], sA[2], sA[0])
1358
+ if transposed_B and len(sB) == 2:
1359
+ sB = (sB[1], sB[0])
1360
+ elif transposed_B and len(sB) == 3:
1361
+ sB = (sB[0], sB[2], sB[0])
1362
+ # this is a mess: cuBLAS expect column major, but PyTorch is row major.
1363
+ # So to perform the matrix multiplication, we have to treat A, B, and C matrices
1364
+ # (transpose of row major is column major)
1365
+ # This means we compute B^T A^T = C^T and we explicitly switch the dimensions of each of these
1366
+
1367
+ # matrices in the input arguments for cuBLAS
1368
+ # column major: A @ B = C: [m, k] @ [k, n] = [m, n]
1369
+ # row major: B^T @ A^T = C^T: [m, k] @ [k, n] = [m, n]
1370
+ # column major with row major layout: B^T @ A^T = C^T: [k, m] @ [n, k] = [n, m]
1371
+ if len(sB) == 2:
1372
+ if B.stride()[0] == B.shape[1]:
1373
+ transposed_B = False
1374
+ elif B.stride()[1] == B.shape[0]:
1375
+ transposed_B = True
1376
+ if len(A.shape) == 2:
1377
+ if A.stride()[0] == A.shape[1]:
1378
+ transposed_A = False
1379
+ elif A.stride()[1] == A.shape[0]:
1380
+ transposed_A = True
1381
+ else:
1382
+ if A.stride()[1] == A.shape[2]:
1383
+ transposed_A = False
1384
+ elif A.stride()[2] == A.shape[1]:
1385
+ transposed_A = True
1386
+
1387
+ if len(sA) == 2:
1388
+ n = sA[0]
1389
+ ldb = A.stride()[1 if transposed_A else 0]
1390
+ elif len(sA) == 3 and len(sB) == 2:
1391
+ n = sA[0] * sA[1]
1392
+ ldb = sA[2]
1393
+
1394
+ m = sB[1]
1395
+ k = sB[0]
1396
+ lda = B.stride()[(1 if transposed_B else 0)]
1397
+ ldc = sB[1]
1398
+ elif len(sB) == 3:
1399
+ # special case
1400
+ assert len(sA) == 3
1401
+ if not (sA[0] == sB[0] and sA[1] == sB[1]):
1402
+ raise ValueError(
1403
+ f"Only bsi,bso->io supported for tensor contractions, but dims for A x B were: {sA} x {sB}",
1404
+ )
1405
+
1406
+ transposed_A = True
1407
+ transposed_B = False
1408
+
1409
+ m = sB[2]
1410
+ n = sA[2]
1411
+ k = sB[0] * sB[1]
1412
+
1413
+ lda = m
1414
+ ldb = sA[2]
1415
+ ldc = m
1416
+
1417
+ ptr = CUBLAS_Context.get_instance().get_context(A.device)
1418
+
1419
+ # B^T @ A^T = C^T
1420
+ # [km, nk -> mn]
1421
+ is_on_gpu([B, A, out])
1422
+ lib.cigemm(
1423
+ ptr,
1424
+ ct.c_bool(transposed_B),
1425
+ ct.c_bool(transposed_A),
1426
+ ct.c_int32(m),
1427
+ ct.c_int32(n),
1428
+ ct.c_int32(k),
1429
+ get_ptr(B),
1430
+ get_ptr(A),
1431
+ get_ptr(out),
1432
+ ct.c_int32(lda),
1433
+ ct.c_int32(ldb),
1434
+ ct.c_int32(ldc),
1435
+ )
1436
+ return out
1437
+
1438
+
1439
+ @deprecated("This function is deprecated and will be removed in a future release.", category=FutureWarning)
1440
+ def batched_igemm(
1441
+ A: Tensor,
1442
+ B: Tensor,
1443
+ out: Optional[torch.Tensor] = None,
1444
+ transposed_A=False,
1445
+ transposed_B=False,
1446
+ ):
1447
+ if not len(A.shape) == 3 or not len(B.shape) == 3:
1448
+ raise ValueError(f"Expected 3-dimensional tensors for bmm, but got shapes A and B: {A.shape} and {B.shape}")
1449
+ sout = check_matmul(A, B, out, transposed_A, transposed_B)
1450
+ if out is None:
1451
+ out = torch.zeros(size=sout, dtype=torch.int32, device=A.device)
1452
+
1453
+ if B.is_contiguous():
1454
+ lda = B.stride()[1]
1455
+ transposed_A = False
1456
+ else:
1457
+ s = B.stride()
1458
+ if s[0] != B.shape[0]:
1459
+ B = B.contiguous()
1460
+ lda = B.stride()[1]
1461
+ elif s[2] == B.shape[1]:
1462
+ transposed_A = True
1463
+ lda = B.stride()[2]
1464
+ else:
1465
+ if s[2] == 1:
1466
+ B = B.contiguous()
1467
+ lda = B.stride()[1]
1468
+ elif s[1] == 1:
1469
+ B = B.contiguous()
1470
+ lda = B.stride()[1]
1471
+ else:
1472
+ B = B.contiguous()
1473
+ lda = B.stride()[1]
1474
+
1475
+ if A.is_contiguous():
1476
+ ldb = A.stride()[1]
1477
+ transposed_B = False
1478
+ else:
1479
+ s = A.stride()
1480
+ if s[0] != A.shape[0]:
1481
+ A = A.contiguous()
1482
+ ldb = A.stride()[1]
1483
+ transposed_B = False
1484
+ elif s[2] == A.shape[1]:
1485
+ ldb = A.stride()[2]
1486
+ transposed_B = True
1487
+ else:
1488
+ A = A.contiguous()
1489
+ ldb = A.stride()[1]
1490
+ transposed_B = False
1491
+
1492
+ # this is a mess: cuBLAS expect column major, but PyTorch is row major.
1493
+ # So to perform the matrix multiplication, we have to treat A, B, and C matrices
1494
+ # (transpose of row major is column major)
1495
+ # This means we compute B^T A^T = C^T and we explicitly switch the dimensions of each of these
1496
+ # matrices in the input arguments for cuBLAS
1497
+
1498
+ # column major: A @ B = C: [batch, m, k] @ [batch, k, n] = [batch, m, n]
1499
+ # row major: B^T @ A^T = C^T: [batch, m, k] @ [batch, k, n] = [batch, m, n]
1500
+ # column major with row major layout: B^T @ A^T = C^T: [batch, k, m] @ [batch, n, k] = [batch, n, m]
1501
+ num_batch = A.shape[0]
1502
+ n = A.shape[1]
1503
+ m = B.shape[2]
1504
+ k = B.shape[1]
1505
+
1506
+ ldc = m
1507
+
1508
+ strideA = B.shape[1] * B.shape[2]
1509
+ strideB = A.shape[1] * A.shape[2]
1510
+ strideC = A.shape[1] * B.shape[2]
1511
+
1512
+ ptr = CUBLAS_Context.get_instance().get_context(A.device)
1513
+
1514
+ is_on_gpu([B, A, out])
1515
+ lib.cbatched_igemm(
1516
+ ptr,
1517
+ ct.c_bool(transposed_B),
1518
+ ct.c_bool(transposed_A),
1519
+ ct.c_int32(m),
1520
+ ct.c_int32(n),
1521
+ ct.c_int32(k),
1522
+ get_ptr(B),
1523
+ get_ptr(A),
1524
+ get_ptr(out),
1525
+ ct.c_int32(lda),
1526
+ ct.c_int32(ldb),
1527
+ ct.c_int32(ldc),
1528
+ ct.c_long(strideA),
1529
+ ct.c_long(strideB),
1530
+ ct.c_long(strideC),
1531
+ ct.c_uint32(num_batch),
1532
+ )
1533
+ return out
1534
+
1535
+
1536
+ def int8_linear_matmul(A: torch.Tensor, B: torch.Tensor, out: Optional[torch.Tensor] = None, dtype=torch.int32):
1537
+ """Performs an 8-bit integer matrix multiplication.
1538
+
1539
+ A linear transformation is applied such that `out = A @ B.T`. When possible, integer tensor core hardware is
1540
+ utilized to accelerate the operation.
1541
+
1542
+ Args:
1543
+ A (`torch.Tensor`): The first matrix operand with the data type `torch.int8`.
1544
+ B (`torch.Tensor`): The second matrix operand with the data type `torch.int8`.
1545
+ out (`torch.Tensor`, *optional*): A pre-allocated tensor used to store the result.
1546
+ dtype (`torch.dtype`, *optional*): The expected data type of the output. Defaults to `torch.int32`.
1547
+
1548
+ Raises:
1549
+ `NotImplementedError`: The operation is not supported in the current environment.
1550
+ `RuntimeError`: Raised when the cannot be completed for any other reason.
1551
+
1552
+ Returns:
1553
+ `torch.Tensor`: The result of the operation.
1554
+ """
1555
+ if out is not None:
1556
+ torch.ops.bitsandbytes.int8_linear_matmul.out(A, B, out)
1557
+ return out
1558
+
1559
+ return torch.ops.bitsandbytes.int8_linear_matmul.default(A, B)
1560
+
1561
+
1562
+ def int8_mm_dequant(
1563
+ A: torch.Tensor,
1564
+ row_stats: torch.Tensor,
1565
+ col_stats: torch.Tensor,
1566
+ out: Optional[torch.Tensor] = None,
1567
+ bias: Optional[torch.Tensor] = None,
1568
+ ):
1569
+ """Performs dequantization on the result of a quantized int8 matrix multiplication.
1570
+
1571
+ Args:
1572
+ A (`torch.Tensor` with dtype `torch.int32`): The result of a quantized int8 matrix multiplication.
1573
+ row_stats (`torch.Tensor`): The row-wise quantization statistics for the lhs operand of the matrix multiplication.
1574
+ col_stats (`torch.Tensor`): The column-wise quantization statistics for the rhs operand of the matrix multiplication.
1575
+ out (`torch.Tensor`, *optional*): A pre-allocated tensor to store the output of the operation.
1576
+ bias (`torch.Tensor`, *optional*): An optional bias vector to add to the result.
1577
+
1578
+ Returns:
1579
+ `torch.Tensor`: The dequantized result with an optional bias, with dtype `torch.float16`.
1580
+ """
1581
+ result = torch.ops.bitsandbytes.int8_mm_dequant.default(A, row_stats, col_stats, dtype=torch.float16, bias=bias)
1582
+
1583
+ # TODO(matthewdouglas): Deprecate out kwarg
1584
+ if out is not None:
1585
+ return out.copy_(result)
1586
+
1587
+ return result
1588
+
1589
+
1590
+ def int8_double_quant(
1591
+ A: torch.Tensor,
1592
+ col_stats: Optional[torch.Tensor] = None,
1593
+ row_stats: Optional[torch.Tensor] = None,
1594
+ out_col: Optional[torch.Tensor] = None,
1595
+ out_row: Optional[torch.Tensor] = None,
1596
+ threshold=0.0,
1597
+ ):
1598
+ """Determine the quantization statistics for input matrix `A` in accordance to the `LLM.int8()` algorithm.
1599
+
1600
+ The statistics are determined both row-wise and column-wise (transposed).
1601
+
1602
+ For more information, see the [LLM.int8() paper](https://arxiv.org/abs/2208.07339).
1603
+
1604
+ <Tip>
1605
+ This function is useful for training, but for inference it is advised to use [`int8_vectorwise_quant`] instead.
1606
+ This implementation performs additional column-wise transposed calculations which are not optimized.
1607
+ </Tip>
1608
+
1609
+ Args:
1610
+ A (`torch.Tensor` with dtype `torch.float16`): The input matrix.
1611
+ col_stats (`torch.Tensor`, *optional*): A pre-allocated tensor to hold the column-wise quantization scales.
1612
+ row_stats (`torch.Tensor`, *optional*): A pre-allocated tensor to hold the row-wise quantization scales.
1613
+ out_col (`torch.Tensor`, *optional*): A pre-allocated tensor to hold the column-wise quantized data.
1614
+ out_row (`torch.Tensor`, *optional*): A pre-allocated tensor to hold the row-wise quantized data.
1615
+ threshold (`float`, *optional*):
1616
+ An optional threshold for sparse decomposition of outlier features.
1617
+
1618
+ No outliers are held back when 0.0. Defaults to 0.0.
1619
+
1620
+ Returns:
1621
+ `Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor]]`: A tuple containing the quantized tensor and relevant statistics.
1622
+ - `torch.Tensor` with dtype `torch.int8`: The row-wise quantized data.
1623
+ - `torch.Tensor` with dtype `torch.int8`: The column-wise quantized data.
1624
+ - `torch.Tensor` with dtype `torch.float32`: The row-wise quantization scales.
1625
+ - `torch.Tensor` with dtype `torch.float32`: The column-wise quantization scales.
1626
+ - `torch.Tensor` with dtype `torch.int32`, *optional*: A list of column indices which contain outlier features.
1627
+ """
1628
+
1629
+ if row_stats is not None:
1630
+ raise ValueError("row_stats must be None. int8_double_quant() does not support pre-allocated row_stats.")
1631
+ if col_stats is not None:
1632
+ raise ValueError("col_stats must be None. int8_double_quant() does not support pre-allocated col_stats.")
1633
+ if out_col is not None:
1634
+ raise ValueError("out_col must be None. int8_double_quant() does not support pre-allocated out_col.")
1635
+ if out_row is not None:
1636
+ raise ValueError("out_row must be None. int8_double_quant() does not support pre-allocated out_row.")
1637
+
1638
+ return torch.ops.bitsandbytes.int8_double_quant.default(A, threshold=threshold)
1639
+
1640
+
1641
+ def int8_vectorwise_dequant(A: torch.Tensor, stats: torch.Tensor):
1642
+ """Dequantizes a tensor with dtype `torch.int8` to `torch.float32`.
1643
+
1644
+ Args:
1645
+ A (`torch.Tensor` with dtype `torch.int8`): The quantized int8 tensor.
1646
+ stats (`torch.Tensor` with dtype `torch.float32`): The row-wise quantization statistics.
1647
+
1648
+ Returns:
1649
+ `torch.Tensor` with dtype `torch.float32`: The dequantized tensor.
1650
+ """
1651
+ # To dequantize we divide by 127, or multiply by the reciprocal.
1652
+ return torch.ops.bitsandbytes.int8_vectorwise_dequant.default(A, stats)
1653
+
1654
+
1655
+ def int8_vectorwise_quant(A: torch.Tensor, threshold=0.0):
1656
+ """Quantizes a tensor with dtype `torch.float16` to `torch.int8` in accordance to the `LLM.int8()` algorithm.
1657
+
1658
+ For more information, see the [LLM.int8() paper](https://arxiv.org/abs/2208.07339).
1659
+
1660
+ Args:
1661
+ A (`torch.Tensor` with dtype `torch.float16`): The input tensor.
1662
+ threshold (`float`, *optional*):
1663
+ An optional threshold for sparse decomposition of outlier features.
1664
+
1665
+ No outliers are held back when 0.0. Defaults to 0.0.
1666
+
1667
+ Returns:
1668
+ `Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]`: A tuple containing the quantized tensor and relevant statistics.
1669
+ - `torch.Tensor` with dtype `torch.int8`: The quantized data.
1670
+ - `torch.Tensor` with dtype `torch.float32`: The quantization scales.
1671
+ - `torch.Tensor` with dtype `torch.int32`, *optional*: A list of column indices which contain outlier features.
1672
+ """
1673
+ return torch.ops.bitsandbytes.int8_vectorwise_quant.default(A, threshold)
1674
+
1675
+
1676
+ def _convert_weight_packed_for_cpu(qweight: torch.Tensor, quant_state: QuantState, block_n: int = 32):
1677
+ """
1678
+ qweight: (K * N / 2) uint8
1679
+ return: packed_weight
1680
+ """
1681
+ if qweight.dtype != torch.uint8:
1682
+ quant_state.original_storage_type = qweight.dtype
1683
+ qweight = qweight.view(torch.uint8)
1684
+ quant_state.original_dtype = quant_state.dtype
1685
+ quant_state.original_nested = quant_state.nested
1686
+ quant_state.original_qshape = qweight.shape
1687
+
1688
+ qweight = qweight.reshape(-1)
1689
+ unpacked_w = torch.empty(qweight.shape[0] * 2, dtype=torch.int32, device=qweight.device)
1690
+ unpacked_w[1::2] = qweight & 0xF
1691
+ unpacked_w[::2] = qweight >> 4
1692
+ qweight_final = unpacked_w.reshape(quant_state.shape).to(torch.uint8) # (*, N, K)
1693
+ # pack weight: [*, N, K] -> [*, N, K/2] combine low and high bit
1694
+ assert len(qweight_final.shape) == 2
1695
+ N, K = qweight_final.shape[0], qweight_final.shape[1]
1696
+ assert N % block_n == 0, "N must be divisible by block_n"
1697
+ assert K % 2 == 0, "K must be even"
1698
+ BLOCK_N = block_n
1699
+ BIT_COUNT = 32 # (=32 low +32 high)
1700
+ new_shape = [N // BLOCK_N, BLOCK_N, K // 2, 2]
1701
+ out_shape = [N, K // 2]
1702
+ qw = qweight_final.reshape(new_shape) # (..., N/B, B, K/2, 2)
1703
+ qw = qw.transpose(-3, -2).contiguous() # (..., N/B, K/2, B, 2)
1704
+ qw = qw.reshape(-1, BIT_COUNT * 2) # [-1, 64]
1705
+ high = qw[:, BIT_COUNT:] # high 32
1706
+ low = qw[:, :BIT_COUNT] # low 32
1707
+ packed = ((high << 4) | low).to(torch.uint8) # combine
1708
+ final_qweight = packed.reshape(out_shape)
1709
+ if quant_state.nested:
1710
+ absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
1711
+ absmax += quant_state.offset
1712
+ if absmax.dtype != torch.float32:
1713
+ absmax = absmax.float()
1714
+
1715
+ quant_state.absmax = absmax
1716
+ quant_state.nested = False
1717
+ delattr(quant_state, "state2")
1718
+
1719
+ quant_state.absmax = (
1720
+ quant_state.absmax.reshape(quant_state.shape[0], quant_state.shape[1] // quant_state.blocksize)
1721
+ .T.to(torch.bfloat16)
1722
+ .contiguous()
1723
+ )
1724
+
1725
+ quant_state.dtype = torch.bfloat16
1726
+ quant_state.packing_format_for_cpu = True
1727
+ return final_qweight, quant_state
1728
+
1729
+
1730
+ def _convert_weight_packed_for_cpu_inverse(
1731
+ packed_weight: torch.Tensor,
1732
+ quant_state: QuantState,
1733
+ block_n: int = 32,
1734
+ ) -> tuple[torch.Tensor, QuantState]:
1735
+ """
1736
+ packed_weight: [N, K/2] uint8, output of `_convert_weight_packed_for_cpu` (final_qweight)
1737
+ quant_state: QuantState that was modified by `_convert_weight_packed_for_cpu`
1738
+ Returns:
1739
+ qweight: [*, N, K] uint8, original qweight shape (quant_state.shape)
1740
+ recovered_state: QuantState with partially restored fields (best-effort inverse)
1741
+ """
1742
+ assert quant_state.packing_format_for_cpu, "only for packing format"
1743
+ assert packed_weight.dtype == torch.uint8
1744
+ assert len(packed_weight.shape) == 2, "packed_weight should be [N, K/2]"
1745
+ N, K_half = packed_weight.shape
1746
+ K = K_half * 2
1747
+
1748
+ # 1) packed [N, K/2] -> [N//BLOCK_N, BLOCK_N, K/2, 2]
1749
+ BLOCK_N = block_n
1750
+ BIT_COUNT = 32 # (=32 low + 32 high)
1751
+
1752
+ assert N % BLOCK_N == 0, "N must be divisible by block_n"
1753
+ assert K % 2 == 0, "K must be even"
1754
+
1755
+ # [N, K/2] -> [-1, 64] (32 low + 32 high)
1756
+ packed = packed_weight.reshape(-1, BIT_COUNT) # [-1, 64]
1757
+ # split high/low nibbles
1758
+ high = (packed >> 4) & 0xF
1759
+ low = packed & 0xF
1760
+ # concatenate to [..., 64], first 32 are low, last 32 are high
1761
+ qw = torch.cat([low, high], dim=-1).to(torch.uint8) # [..., 64]
1762
+
1763
+ # -> [N/BLOCK_N, K/2, BLOCK_N, 2] -> [N, K]
1764
+ qw = qw.reshape(N // BLOCK_N, K_half, BLOCK_N, 2) # [N/B, K/2, B, 2]
1765
+ qw = qw.transpose(-3, -2).contiguous() # [N/B, B, K/2, 2]
1766
+ qw = qw.reshape(N, K) # [N, K]
1767
+
1768
+ qweight = qw # [N, K]
1769
+
1770
+ unpacked_w = qweight.reshape(-1).to(torch.int32) # [K*N]
1771
+ high4 = (unpacked_w[::2] & 0xF).to(torch.uint8)
1772
+ low4 = (unpacked_w[1::2] & 0xF).to(torch.uint8)
1773
+ qweight = (high4 << 4) | low4 # [K*N/2]
1774
+
1775
+ # 2) Best-effort restore of quant_state fields (absmax / dtype / nested flags, etc.)
1776
+ recovered_state = quant_state
1777
+ qweight = qweight.to(torch.uint8).reshape(recovered_state.original_qshape)
1778
+
1779
+ # quantize absmax
1780
+ if recovered_state.original_nested:
1781
+ absmax = recovered_state.absmax.T.reshape(-1).to(recovered_state.original_dtype)
1782
+ offset = absmax.mean()
1783
+ qabsmax, state2 = quantize_blockwise(absmax - offset, blocksize=256)
1784
+ recovered_state.absmax = qabsmax
1785
+ recovered_state.offset = offset
1786
+ recovered_state.state2 = state2
1787
+ recovered_state.nested = True
1788
+
1789
+ recovered_state.dtype = recovered_state.original_dtype
1790
+ recovered_state.packing_format_for_cpu = False
1791
+
1792
+ if getattr(recovered_state, "original_storage_type", None):
1793
+ qweight = qweight.view(recovered_state.original_storage_type)
1794
+
1795
+ return qweight, recovered_state
1796
+
1797
+
1798
+ def has_avx512bf16():
1799
+ """
1800
+ Try calling native lib.has_avx512bf16_cpu().
1801
+ Return False explicitly if symbol missing or call fails.
1802
+ """
1803
+ try:
1804
+ support_avx_bf16 = lib.has_avx512bf16_cpu()
1805
+ except (AttributeError, RuntimeError, OSError):
1806
+ support_avx_bf16 = False
1807
+ return support_avx_bf16
1808
+
1809
+
1810
+ C = 127.0