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,1220 @@
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
+ import copy
6
+ import logging
7
+ from typing import Any, Optional, TypeVar, Union, overload
8
+
9
+ import torch
10
+ from torch import Tensor, device, dtype, nn
11
+ import torch.nn.functional as F
12
+
13
+ import bitsandbytes as bnb
14
+ from bitsandbytes.functional import (
15
+ QuantState,
16
+ _convert_weight_packed_for_cpu,
17
+ _convert_weight_packed_for_cpu_inverse,
18
+ has_avx512bf16,
19
+ )
20
+ from bitsandbytes.optim import GlobalOptimManager
21
+ from bitsandbytes.utils import INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING, OutlierTracer
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ T = TypeVar("T", bound="torch.nn.Module")
26
+
27
+
28
+ class StableEmbedding(torch.nn.Embedding):
29
+ """
30
+ Custom embedding layer designed to improve stability during training for NLP tasks by using 32-bit optimizer states. It is designed to reduce gradient variations that can result from quantization. This embedding layer is initialized with Xavier uniform initialization followed by layer normalization.
31
+
32
+ Example:
33
+
34
+ ```
35
+ # Initialize StableEmbedding layer with vocabulary size 1000, embedding dimension 300
36
+ embedding_layer = StableEmbedding(num_embeddings=1000, embedding_dim=300)
37
+
38
+ # Reset embedding parameters
39
+ embedding_layer.reset_parameters()
40
+
41
+ # Perform a forward pass with input tensor
42
+ input_tensor = torch.tensor([1, 2, 3])
43
+ output_embedding = embedding_layer(input_tensor)
44
+ ```
45
+
46
+ Attributes:
47
+ norm (`torch.nn.LayerNorm`): Layer normalization applied after the embedding.
48
+
49
+ Methods:
50
+ reset_parameters(): Reset embedding parameters using Xavier uniform initialization.
51
+ forward(input: Tensor) -> Tensor: Forward pass through the stable embedding layer.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ num_embeddings: int,
57
+ embedding_dim: int,
58
+ padding_idx: Optional[int] = None,
59
+ max_norm: Optional[float] = None,
60
+ norm_type: float = 2.0,
61
+ scale_grad_by_freq: bool = False,
62
+ sparse: bool = False,
63
+ _weight: Optional[Tensor] = None,
64
+ device=None,
65
+ dtype=None,
66
+ ) -> None:
67
+ """
68
+ Args:
69
+ num_embeddings (`int`):
70
+ The number of unique embeddings (vocabulary size).
71
+ embedding_dim (`int`):
72
+ The dimensionality of the embedding.
73
+ padding_idx (`Optional[int]`):
74
+ Pads the output with zeros at the given index.
75
+ max_norm (`Optional[float]`):
76
+ Renormalizes embeddings to have a maximum L2 norm.
77
+ norm_type (`float`, defaults to `2.0`):
78
+ The p-norm to compute for the `max_norm` option.
79
+ scale_grad_by_freq (`bool`, defaults to `False`):
80
+ Scale gradient by frequency during backpropagation.
81
+ sparse (`bool`, defaults to `False`):
82
+ Computes dense gradients. Set to `True` to compute sparse gradients instead.
83
+ _weight (`Optional[Tensor]`):
84
+ Pretrained embeddings.
85
+ """
86
+ super().__init__(
87
+ num_embeddings,
88
+ embedding_dim,
89
+ padding_idx,
90
+ max_norm,
91
+ norm_type,
92
+ scale_grad_by_freq,
93
+ sparse,
94
+ _weight,
95
+ device,
96
+ dtype,
97
+ )
98
+ self.norm = torch.nn.LayerNorm(embedding_dim, device=device)
99
+ GlobalOptimManager.get_instance().register_module_override(self, "weight", {"optim_bits": 32})
100
+
101
+ def reset_parameters(self) -> None:
102
+ torch.nn.init.xavier_uniform_(self.weight)
103
+ self._fill_padding_idx_with_zero()
104
+
105
+ """ !!! This is a redefinition of _fill_padding_idx_with_zero in torch.nn.Embedding
106
+ to make the Layer compatible with Pytorch < 1.9.
107
+ This means that if this changes in future PyTorch releases this need to change too
108
+ which is cumbersome. However, with this we can ensure compatibility with previous
109
+ PyTorch releases.
110
+ """
111
+
112
+ def _fill_padding_idx_with_zero(self) -> None:
113
+ if self.padding_idx is not None:
114
+ with torch.no_grad():
115
+ self.weight[self.padding_idx].fill_(0)
116
+
117
+ def forward(self, input: Tensor) -> Tensor:
118
+ emb = F.embedding(
119
+ input,
120
+ self.weight,
121
+ self.padding_idx,
122
+ self.max_norm,
123
+ self.norm_type,
124
+ self.scale_grad_by_freq,
125
+ self.sparse,
126
+ )
127
+
128
+ # always apply layer norm in full precision
129
+ emb = emb.to(torch.get_default_dtype())
130
+
131
+ return self.norm(emb).to(self.weight.dtype)
132
+
133
+
134
+ class Embedding(torch.nn.Embedding):
135
+ """
136
+ Embedding class to store and retrieve word embeddings from their indices.
137
+ """
138
+
139
+ def __init__(
140
+ self,
141
+ num_embeddings: int,
142
+ embedding_dim: int,
143
+ padding_idx: Optional[int] = None,
144
+ max_norm: Optional[float] = None,
145
+ norm_type: float = 2.0,
146
+ scale_grad_by_freq: bool = False,
147
+ sparse: bool = False,
148
+ _weight: Optional[Tensor] = None,
149
+ device: Optional[device] = None,
150
+ ) -> None:
151
+ """
152
+ Args:
153
+ num_embeddings (`int`):
154
+ The number of unique embeddings (vocabulary size).
155
+ embedding_dim (`int`):
156
+ The dimensionality of the embedding.
157
+ padding_idx (`Optional[int]`):
158
+ Pads the output with zeros at the given index.
159
+ max_norm (`Optional[float]`):
160
+ Renormalizes embeddings to have a maximum L2 norm.
161
+ norm_type (`float`, defaults to `2.0`):
162
+ The p-norm to compute for the `max_norm` option.
163
+ scale_grad_by_freq (`bool`, defaults to `False`):
164
+ Scale gradient by frequency during backpropagation.
165
+ sparse (`bool`, defaults to `False`):
166
+ Computes dense gradients. Set to `True` to compute sparse gradients instead.
167
+ _weight (`Optional[Tensor]`):
168
+ Pretrained embeddings.
169
+ """
170
+ super().__init__(
171
+ num_embeddings,
172
+ embedding_dim,
173
+ padding_idx,
174
+ max_norm,
175
+ norm_type,
176
+ scale_grad_by_freq,
177
+ sparse,
178
+ _weight,
179
+ device=device,
180
+ )
181
+ GlobalOptimManager.get_instance().register_module_override(self, "weight", {"optim_bits": 32})
182
+
183
+ def reset_parameters(self) -> None:
184
+ torch.nn.init.xavier_uniform_(self.weight)
185
+ self._fill_padding_idx_with_zero()
186
+
187
+ """ !!! This is a redefinition of _fill_padding_idx_with_zero in torch.nn.Embedding
188
+ to make the Layer compatible with Pytorch < 1.9.
189
+ This means that if this changes in future PyTorch releases this need to change too
190
+ which is cumbersome. However, with this we can ensure compatibility with previous
191
+ PyTorch releases.
192
+ """
193
+
194
+ def _fill_padding_idx_with_zero(self) -> None:
195
+ if self.padding_idx is not None:
196
+ with torch.no_grad():
197
+ self.weight[self.padding_idx].fill_(0)
198
+
199
+ def forward(self, input: Tensor) -> Tensor:
200
+ emb = F.embedding(
201
+ input,
202
+ self.weight,
203
+ self.padding_idx,
204
+ self.max_norm,
205
+ self.norm_type,
206
+ self.scale_grad_by_freq,
207
+ self.sparse,
208
+ )
209
+
210
+ return emb
211
+
212
+
213
+ class Params4bit(torch.nn.Parameter):
214
+ def __new__(
215
+ cls,
216
+ data: Optional[torch.Tensor] = None,
217
+ requires_grad=False, # quantized weights should be frozen by default
218
+ quant_state: Optional[QuantState] = None,
219
+ blocksize: Optional[int] = None,
220
+ compress_statistics: bool = True,
221
+ quant_type: str = "fp4",
222
+ quant_storage: torch.dtype = torch.uint8,
223
+ module: Optional["Linear4bit"] = None,
224
+ bnb_quantized: bool = False,
225
+ **kwargs,
226
+ ) -> "Params4bit":
227
+ if data is None:
228
+ data = torch.empty(0)
229
+
230
+ if blocksize is None:
231
+ blocksize = 64
232
+
233
+ self = torch.Tensor._make_subclass(cls, data, requires_grad)
234
+ self.blocksize = blocksize
235
+ self.compress_statistics = compress_statistics
236
+ self.quant_type = quant_type
237
+ self.quant_state = quant_state
238
+ self.quant_storage = quant_storage
239
+ self.bnb_quantized = bnb_quantized
240
+ self.data = data
241
+ self.module = module
242
+ return self
243
+
244
+ def __getstate__(self):
245
+ state = self.__dict__.copy()
246
+ state["data"] = self.data
247
+ state["requires_grad"] = self.requires_grad
248
+ return state
249
+
250
+ def __setstate__(self, state):
251
+ self.requires_grad = state["requires_grad"]
252
+ self.blocksize = state["blocksize"]
253
+ self.compress_statistics = state["compress_statistics"]
254
+ self.quant_type = state["quant_type"]
255
+ self.quant_state = state["quant_state"]
256
+ self.data = state["data"]
257
+ self.quant_storage = state["quant_storage"]
258
+ self.bnb_quantized = state["bnb_quantized"]
259
+ self.module = state["module"]
260
+
261
+ # Properties that proxy QuantState attributes for FSDP state_dict traversal.
262
+ # FSDP's _get_fqns() resolves dotted FQN keys via getattr, e.g. "weight.absmax"
263
+ # becomes getattr(weight, "absmax"). Using @property instead of __getattr__
264
+ # avoids torch.compile graph breaks (see #1904), since Dynamo can trace
265
+ # descriptor protocol access but not __getattr__ on Tensor subclasses.
266
+ #
267
+ # Note: attributes that collide with Params4bit instance attrs (blocksize,
268
+ # quant_type) or Tensor attrs (dtype, shape) are intentionally omitted —
269
+ # they are packed into the bitsandbytes__* blob and not traversed by FSDP.
270
+
271
+ @property
272
+ def absmax(self):
273
+ qs = self.__dict__.get("quant_state")
274
+ if qs is not None:
275
+ return qs.absmax
276
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'absmax'")
277
+
278
+ @property
279
+ def code(self):
280
+ qs = self.__dict__.get("quant_state")
281
+ if qs is not None:
282
+ return qs.code
283
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'code'")
284
+
285
+ @property
286
+ def quant_map(self):
287
+ qs = self.__dict__.get("quant_state")
288
+ if qs is not None:
289
+ return qs.code
290
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'quant_map'")
291
+
292
+ @property
293
+ def offset(self):
294
+ qs = self.__dict__.get("quant_state")
295
+ if qs is not None:
296
+ return qs.offset
297
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'offset'")
298
+
299
+ @property
300
+ def state2(self):
301
+ qs = self.__dict__.get("quant_state")
302
+ if qs is not None:
303
+ return qs.state2
304
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'state2'")
305
+
306
+ @property
307
+ def nested_absmax(self):
308
+ qs = self.__dict__.get("quant_state")
309
+ if qs is not None and qs.state2 is not None:
310
+ return qs.state2.absmax
311
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'nested_absmax'")
312
+
313
+ @property
314
+ def nested_blocksize(self):
315
+ qs = self.__dict__.get("quant_state")
316
+ if qs is not None and qs.state2 is not None:
317
+ return qs.state2.blocksize
318
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'nested_blocksize'")
319
+
320
+ @property
321
+ def nested_quant_map(self):
322
+ qs = self.__dict__.get("quant_state")
323
+ if qs is not None and qs.state2 is not None:
324
+ return qs.state2.code
325
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'nested_quant_map'")
326
+
327
+ @property
328
+ def nested_dtype(self):
329
+ qs = self.__dict__.get("quant_state")
330
+ if qs is not None and qs.state2 is not None:
331
+ return qs.state2.dtype
332
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'nested_dtype'")
333
+
334
+ @property
335
+ def nested_offset(self):
336
+ qs = self.__dict__.get("quant_state")
337
+ if qs is not None:
338
+ return qs.offset
339
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'nested_offset'")
340
+
341
+ def __deepcopy__(self, memo):
342
+ new_instance = type(self).__new__(type(self))
343
+ state = self.__getstate__()
344
+ new_instance.__setstate__(state)
345
+ new_instance.quant_state = copy.deepcopy(state["quant_state"])
346
+ new_instance.data = copy.deepcopy(state["data"])
347
+ return new_instance
348
+
349
+ def __copy__(self):
350
+ new_instance = type(self).__new__(type(self))
351
+ state = self.__getstate__()
352
+ new_instance.__setstate__(state)
353
+ return new_instance
354
+
355
+ @classmethod
356
+ def from_prequantized(
357
+ cls,
358
+ data: torch.Tensor,
359
+ quantized_stats: dict[str, Any],
360
+ requires_grad: bool = False,
361
+ device="cuda",
362
+ module: Optional["Linear4bit"] = None,
363
+ **kwargs,
364
+ ) -> "Params4bit":
365
+ self = torch.Tensor._make_subclass(cls, data.to(device))
366
+ self.requires_grad = requires_grad
367
+ self.quant_state = QuantState.from_dict(qs_dict=quantized_stats, device=device)
368
+ self.blocksize = self.quant_state.blocksize
369
+ self.compress_statistics = self.quant_state.nested
370
+ self.quant_type = self.quant_state.quant_type
371
+ self.bnb_quantized = True
372
+
373
+ self.quant_storage = data.dtype
374
+ self.module = module
375
+
376
+ if self.module is not None:
377
+ self.module.quant_state = self.quant_state
378
+
379
+ return self
380
+
381
+ def _quantize(self, device):
382
+ w = self.data.contiguous().to(device)
383
+ w_4bit, quant_state = bnb.functional.quantize_4bit(
384
+ w,
385
+ blocksize=self.blocksize,
386
+ compress_statistics=self.compress_statistics,
387
+ quant_type=self.quant_type,
388
+ quant_storage=self.quant_storage,
389
+ )
390
+ self.data = w_4bit
391
+ self.quant_state = quant_state
392
+ if self.module is not None:
393
+ self.module.quant_state = quant_state
394
+ self.bnb_quantized = True
395
+ return self
396
+
397
+ def cpu(self):
398
+ return self.to(device="cpu")
399
+
400
+ def cuda(self, device: Optional[int | device | str] = None, non_blocking: bool = False):
401
+ if getattr(self.quant_state, "packing_format_for_cpu", False):
402
+ self.data, self.quant_state = _convert_weight_packed_for_cpu_inverse(self.data, self.quant_state)
403
+ return self.to(device="cuda" if device is None else device, non_blocking=non_blocking)
404
+
405
+ def xpu(self, device: Optional[int | device | str] = None, non_blocking: bool = False):
406
+ if getattr(self.quant_state, "packing_format_for_cpu", False):
407
+ self.data, self.quant_state = _convert_weight_packed_for_cpu_inverse(self.data, self.quant_state)
408
+ return self.to(device="xpu" if device is None else device, non_blocking=non_blocking)
409
+
410
+ @overload
411
+ def to(
412
+ self: T,
413
+ device: Optional[int | device] = ...,
414
+ dtype: Optional[dtype | str] = ...,
415
+ non_blocking: bool = ...,
416
+ ) -> T: ...
417
+
418
+ @overload
419
+ def to(self: T, dtype: dtype | str, non_blocking: bool = ...) -> T: ...
420
+
421
+ @overload
422
+ def to(self: T, tensor: Tensor, non_blocking: bool = ...) -> T: ...
423
+
424
+ def to(self, *args, **kwargs):
425
+ device, dtype, non_blocking, _ = torch._C._nn._parse_to(*args, **kwargs)
426
+
427
+ if device is not None and device.type != "meta" and not self.bnb_quantized:
428
+ return self._quantize(device)
429
+ else:
430
+ if self.quant_state is not None:
431
+ self.quant_state.to(device)
432
+
433
+ new_param = Params4bit(
434
+ super().to(device=device, dtype=dtype, non_blocking=non_blocking),
435
+ requires_grad=self.requires_grad,
436
+ quant_state=self.quant_state,
437
+ blocksize=self.blocksize,
438
+ compress_statistics=self.compress_statistics,
439
+ quant_type=self.quant_type,
440
+ quant_storage=self.quant_storage,
441
+ bnb_quantized=self.bnb_quantized,
442
+ )
443
+
444
+ return new_param
445
+
446
+ @classmethod
447
+ def __torch_function__(cls, func, types, args=(), kwargs=None):
448
+ if kwargs is None:
449
+ kwargs = {}
450
+
451
+ if func in [torch.chunk, torch.split]:
452
+ tensor = args[0]
453
+
454
+ result = super().__torch_function__(func, types, args, kwargs)
455
+
456
+ if isinstance(result, tuple):
457
+ return tuple(
458
+ cls(
459
+ data=chunk,
460
+ requires_grad=tensor.requires_grad,
461
+ quant_state=tensor.quant_state,
462
+ blocksize=tensor.blocksize,
463
+ compress_statistics=tensor.compress_statistics,
464
+ quant_type=tensor.quant_type,
465
+ quant_storage=tensor.quant_storage,
466
+ module=tensor.module,
467
+ bnb_quantized=tensor.bnb_quantized,
468
+ )
469
+ for chunk in result
470
+ )
471
+ else:
472
+ return cls(
473
+ data=result,
474
+ requires_grad=tensor.requires_grad,
475
+ quant_state=tensor.quant_state,
476
+ blocksize=tensor.blocksize,
477
+ compress_statistics=tensor.compress_statistics,
478
+ quant_type=tensor.quant_type,
479
+ quant_storage=tensor.quant_storage,
480
+ module=tensor.module,
481
+ bnb_quantized=tensor.bnb_quantized,
482
+ )
483
+
484
+ return super().__torch_function__(func, types, args, kwargs)
485
+
486
+
487
+ def fix_4bit_weight_quant_state_from_module(module: Union["Embedding4bit", "Linear4bit"]):
488
+ if getattr(module.weight, "quant_state", None) is not None:
489
+ return
490
+
491
+ if getattr(module, "quant_state", None) is None:
492
+ logger.warning(
493
+ "FP4 quantization state not initialized. Please call .cuda() or .to(device) on the LinearFP4 layer first.",
494
+ )
495
+
496
+ # the quant state got lost when the parameter got converted. This happens for example for fsdp
497
+ # since we registered the module, we can recover the state here
498
+ assert module.weight.shape[1] == 1
499
+ if not isinstance(module.weight, Params4bit):
500
+ module.weight = Params4bit(module.weight, quant_storage=module.quant_storage, bnb_quantized=True)
501
+ module.weight.quant_state = module.quant_state
502
+
503
+
504
+ class Linear4bit(nn.Linear):
505
+ """
506
+ This class is the base module for the 4-bit quantization algorithm presented in [QLoRA](https://arxiv.org/abs/2305.14314).
507
+ QLoRA 4-bit linear layers uses blockwise k-bit quantization under the hood, with the possibility of selecting various
508
+ compute datatypes such as FP4 and NF4.
509
+
510
+ In order to quantize a linear layer one should first load the original fp16 / bf16 weights into
511
+ the Linear4bit module, then call `quantized_module.to("cuda")` to quantize the fp16 / bf16 weights.
512
+
513
+ Example:
514
+
515
+ ```python
516
+ import torch
517
+ import torch.nn as nn
518
+
519
+ import bitsandbytes as bnb
520
+ from bitsandbytes.nn import Linear4bit
521
+
522
+ fp16_model = nn.Sequential(
523
+ nn.Linear(64, 64),
524
+ nn.Linear(64, 64)
525
+ )
526
+
527
+ quantized_model = nn.Sequential(
528
+ Linear4bit(64, 64),
529
+ Linear4bit(64, 64)
530
+ )
531
+
532
+ quantized_model.load_state_dict(fp16_model.state_dict())
533
+ quantized_model = quantized_model.to(0) # Quantization happens here
534
+ ```
535
+ """
536
+
537
+ def __init__(
538
+ self,
539
+ input_features,
540
+ output_features,
541
+ bias=True,
542
+ compute_dtype=None,
543
+ compress_statistics=True,
544
+ quant_type="fp4",
545
+ quant_storage=torch.uint8,
546
+ device=None,
547
+ ):
548
+ """
549
+ Initialize Linear4bit class.
550
+
551
+ Args:
552
+ input_features (`str`):
553
+ Number of input features of the linear layer.
554
+ output_features (`str`):
555
+ Number of output features of the linear layer.
556
+ bias (`bool`, defaults to `True`):
557
+ Whether the linear class uses the bias term as well.
558
+ """
559
+ super().__init__(input_features, output_features, bias, device)
560
+ self.weight = Params4bit(
561
+ self.weight.data,
562
+ requires_grad=False,
563
+ compress_statistics=compress_statistics,
564
+ quant_type=quant_type,
565
+ quant_storage=quant_storage,
566
+ module=self,
567
+ )
568
+ # self.persistent_buffers = [] # TODO consider as way to save quant state
569
+ self.compute_dtype = compute_dtype
570
+ self.compute_type_is_set = compute_dtype is not None
571
+ self.quant_state = None
572
+ self.quant_storage = quant_storage
573
+ self.support_avx512bf16_for_cpu = has_avx512bf16()
574
+
575
+ def set_compute_type(self, x):
576
+ if x.dtype in [torch.float32, torch.bfloat16]:
577
+ # the input is in a dtype that is safe to compute in, we switch
578
+ # to this type for speed and stability
579
+ self.compute_dtype = x.dtype
580
+ elif x.dtype == torch.float16:
581
+ # we take the compoute dtype passed into the layer
582
+ if self.compute_dtype in [None, torch.float32] and (x.numel() == x.shape[-1]):
583
+ # single batch inference with input torch.float16 and compute_dtype float32 -> slow inference when it could be fast
584
+ # warn the user about this
585
+ logger.warning(
586
+ "Input type into Linear4bit is torch.float16, but bnb_4bit_compute_dtype=torch.float32 (default). This will lead to slow inference.",
587
+ )
588
+ if self.compute_dtype in [None, torch.float32] and (x.numel() != x.shape[-1]):
589
+ logger.warning(
590
+ "Input type into Linear4bit is torch.float16, but bnb_4bit_compute_dtype=torch.float32 (default). This will lead to slow inference or training speed.",
591
+ )
592
+
593
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
594
+ """
595
+ save weight and bias,
596
+ then fill state_dict with components of quant_state
597
+ """
598
+ if getattr(self.weight, "quant_state", None) is not None and getattr(
599
+ self.weight.quant_state, "packing_format_for_cpu", False
600
+ ):
601
+ self.weight.data, self.weight.quant_state = _convert_weight_packed_for_cpu_inverse(
602
+ self.weight.data, self.weight.quant_state
603
+ )
604
+ super()._save_to_state_dict(destination, prefix, keep_vars) # saving weight and bias
605
+ if getattr(self.weight, "quant_state", None) is not None:
606
+ for k, v in self.weight.quant_state.as_dict(packed=True).items():
607
+ destination[prefix + "weight." + k] = v if keep_vars else v.detach()
608
+
609
+ def forward(self, x: torch.Tensor):
610
+ fix_4bit_weight_quant_state_from_module(self)
611
+ quant_state = self.weight.quant_state
612
+
613
+ if (
614
+ x.device.type == "cpu"
615
+ and self.support_avx512bf16_for_cpu
616
+ and not self.training
617
+ and x.requires_grad == False
618
+ and not getattr(quant_state, "packing_format_for_cpu", False)
619
+ ):
620
+ self.weight.data, quant_state = _convert_weight_packed_for_cpu(self.weight.data, quant_state)
621
+
622
+ if not self.compute_type_is_set:
623
+ self.set_compute_type(x)
624
+ self.compute_type_is_set = True
625
+
626
+ inp_dtype = x.dtype
627
+ if self.compute_dtype is not None:
628
+ x = x.to(self.compute_dtype)
629
+
630
+ bias = self.bias
631
+ if bias is not None:
632
+ if bias.dtype != x.dtype:
633
+ # TODO: do we need to cast bias like this?
634
+ bias.data = bias.data.to(x.dtype)
635
+ bias = bias.to(self.compute_dtype)
636
+
637
+ return bnb.matmul_4bit(x, self.weight, bias=bias, quant_state=quant_state).to(inp_dtype)
638
+
639
+
640
+ class LinearFP4(Linear4bit):
641
+ """
642
+ Implements the FP4 data type.
643
+ """
644
+
645
+ def __init__(
646
+ self,
647
+ input_features,
648
+ output_features,
649
+ bias=True,
650
+ compute_dtype=None,
651
+ compress_statistics=True,
652
+ quant_storage=torch.uint8,
653
+ device=None,
654
+ ):
655
+ """
656
+ Args:
657
+ input_features (`str`):
658
+ Number of input features of the linear layer.
659
+ output_features (`str`):
660
+ Number of output features of the linear layer.
661
+ bias (`bool`, defaults to `True`):
662
+ Whether the linear class uses the bias term as well.
663
+ """
664
+ super().__init__(
665
+ input_features,
666
+ output_features,
667
+ bias,
668
+ compute_dtype,
669
+ compress_statistics,
670
+ "fp4",
671
+ quant_storage,
672
+ device,
673
+ )
674
+
675
+
676
+ class LinearNF4(Linear4bit):
677
+ """Implements the NF4 data type.
678
+
679
+ Constructs a quantization data type where each bin has equal area under a standard normal distribution N(0, 1) that
680
+ is normalized into the range [-1, 1].
681
+
682
+ For more information read the paper: QLoRA: Efficient Finetuning of Quantized LLMs (https://arxiv.org/abs/2305.14314)
683
+
684
+ Implementation of the NF4 data type in bitsandbytes can be found in the `create_normal_map` function in
685
+ the `functional.py` file: https://github.com/TimDettmers/bitsandbytes/blob/main/bitsandbytes/functional.py#L236.
686
+ """
687
+
688
+ def __init__(
689
+ self,
690
+ input_features,
691
+ output_features,
692
+ bias=True,
693
+ compute_dtype=None,
694
+ compress_statistics=True,
695
+ quant_storage=torch.uint8,
696
+ device=None,
697
+ ):
698
+ """
699
+ Args:
700
+ input_features (`str`):
701
+ Number of input features of the linear layer.
702
+ output_features (`str`):
703
+ Number of output features of the linear layer.
704
+ bias (`bool`, defaults to `True`):
705
+ Whether the linear class uses the bias term as well.
706
+ """
707
+ super().__init__(
708
+ input_features,
709
+ output_features,
710
+ bias,
711
+ compute_dtype,
712
+ compress_statistics,
713
+ "nf4",
714
+ quant_storage,
715
+ device,
716
+ )
717
+
718
+
719
+ class Int8Params(torch.nn.Parameter):
720
+ def __new__(
721
+ cls,
722
+ data: Optional[torch.Tensor] = None,
723
+ requires_grad=True,
724
+ has_fp16_weights=False,
725
+ CB: Optional[torch.Tensor] = None,
726
+ SCB: Optional[torch.Tensor] = None,
727
+ **kwargs,
728
+ ):
729
+ if data is None:
730
+ data = torch.empty(0)
731
+ obj = torch.Tensor._make_subclass(cls, data, requires_grad)
732
+ obj.CB = CB
733
+ obj.SCB = SCB
734
+ obj.has_fp16_weights = has_fp16_weights
735
+ return obj
736
+
737
+ def _quantize(self, device):
738
+ if self.has_fp16_weights:
739
+ return super().to(device)
740
+
741
+ # We quantize the weight and store in 8bit row-major
742
+ B = self.data.contiguous().to(device=device, dtype=torch.float16)
743
+ CB, SCB, _ = bnb.functional.int8_vectorwise_quant(B)
744
+ self.data = CB
745
+ self.CB = CB
746
+ self.SCB = SCB
747
+
748
+ return self
749
+
750
+ def cpu(self):
751
+ return self.to(device="cpu")
752
+
753
+ def cuda(self, device: Optional[int | device | str] = None, non_blocking: bool = False):
754
+ return self.to(device="cuda" if device is None else device, non_blocking=non_blocking)
755
+
756
+ def xpu(self, device: Optional[int | device | str] = None, non_blocking: bool = False):
757
+ return self.to(device="xpu" if device is None else device, non_blocking=non_blocking)
758
+
759
+ def __deepcopy__(self, memo):
760
+ # adjust this if new arguments are added to the constructor
761
+ new_instance = type(self).__new__(
762
+ type(self),
763
+ data=copy.deepcopy(self.data, memo),
764
+ requires_grad=self.requires_grad,
765
+ has_fp16_weights=self.has_fp16_weights,
766
+ CB=copy.deepcopy(self.CB, memo),
767
+ SCB=copy.deepcopy(self.SCB, memo),
768
+ )
769
+ return new_instance
770
+
771
+ @overload
772
+ def to(
773
+ self: T,
774
+ device: Optional[int | device] = ...,
775
+ dtype: Optional[dtype | str] = ...,
776
+ non_blocking: bool = ...,
777
+ ) -> T: ...
778
+
779
+ @overload
780
+ def to(self: T, dtype: dtype | str, non_blocking: bool = ...) -> T: ...
781
+
782
+ @overload
783
+ def to(self: T, tensor: Tensor, non_blocking: bool = ...) -> T: ...
784
+
785
+ def to(self, *args, **kwargs):
786
+ device, dtype, non_blocking, _ = torch._C._nn._parse_to(*args, **kwargs)
787
+
788
+ is_quantized = self.data.dtype == torch.int8
789
+
790
+ if not is_quantized and device is not None and device.type != "meta" and self.data.device.type == "cpu":
791
+ # We're moving from a CPU device to a non-meta device.
792
+ # In this circumstance, we want to quantize if we haven't already.
793
+ return self._quantize(device)
794
+
795
+ # Create a new parameter on the target device.
796
+ new_param = Int8Params(
797
+ super().to(device=device, dtype=dtype, non_blocking=non_blocking),
798
+ requires_grad=self.requires_grad,
799
+ has_fp16_weights=self.has_fp16_weights,
800
+ )
801
+
802
+ # If we had already quantized, move the statistics appropriately.
803
+ if is_quantized:
804
+ new_param.CB = new_param.data
805
+
806
+ if device is not None and self.SCB is not None and self.SCB.device.type != "meta":
807
+ new_param.SCB = self.SCB.to(device)
808
+
809
+ return new_param
810
+
811
+
812
+ def maybe_rearrange_weight(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
813
+ weight = state_dict.get(f"{prefix}weight")
814
+ if weight is None:
815
+ # if the state dict has no weights for this layer (e.g., LoRA finetuning), do nothing
816
+ return
817
+ weight_format = state_dict.pop(f"{prefix}weight_format", "row")
818
+
819
+ if isinstance(weight_format, torch.Tensor):
820
+ weight_format = weight_format.item()
821
+
822
+ # For new weights format storage type, we explicitly check
823
+ # if weights_format is on the mapping
824
+ if isinstance(weight_format, int) and weight_format not in INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING:
825
+ raise ValueError(f"Expected supported weight format - got {weight_format}")
826
+ elif isinstance(weight_format, int) and weight_format in INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING:
827
+ weight_format = INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING[weight_format]
828
+
829
+ if weight_format != "row":
830
+ raise ValueError(f"Only 'row' weight format is supported, got {weight_format}")
831
+
832
+
833
+ class Embedding8bit(nn.Embedding):
834
+ """
835
+ This class implements [LLM.int8()](https://arxiv.org/abs/2208.07339) algorithm for embedding layer
836
+
837
+ Quantization API is similar to Linear8bitLt:
838
+ ```python
839
+ import torch
840
+ import torch.nn as nn
841
+
842
+ from bitsandbytes.nn import Embedding8bit
843
+
844
+ fp16_module = nn.Embedding(128, 64)
845
+ int8_module = Embedding8bit(128, 64)
846
+
847
+ int8_module.load_state_dict(fp16_module.state_dict())
848
+
849
+ int8_module = int8_module.to(0) # Quantization happens here
850
+ ```
851
+ """
852
+
853
+ def __init__(self, num_embeddings, embedding_dim, device=None, dtype=None):
854
+ super().__init__(num_embeddings, embedding_dim, device=device, dtype=dtype)
855
+ self.dtype = self.weight.data.dtype
856
+
857
+ self.weight = Int8Params(self.weight.data, has_fp16_weights=False, requires_grad=False)
858
+
859
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
860
+ raise NotImplementedError("Saving Embedding8bit module is not implemented")
861
+
862
+ def forward(self, input: Tensor) -> Tensor:
863
+ if not hasattr(self.weight, "SCB"):
864
+ raise RuntimeError("Embedding layer is not quantized. Please call .cuda() or .to(device) first.")
865
+
866
+ rows = self.weight.data
867
+ row_stats = self.weight.SCB
868
+
869
+ assert rows.shape == (self.num_embeddings, self.embedding_dim)
870
+ assert row_stats.shape == (self.num_embeddings,)
871
+
872
+ compressed_output = F.embedding(input, rows)
873
+ compressed_output_stats = F.embedding(input, row_stats.view(self.num_embeddings, 1))
874
+
875
+ output = compressed_output * (compressed_output_stats / 127.0)
876
+
877
+ return output.to(self.dtype)
878
+
879
+
880
+ class Embedding4bit(nn.Embedding):
881
+ """
882
+ This is the base class similar to Linear4bit. It implements the 4-bit quantization algorithm presented in
883
+ [QLoRA](https://arxiv.org/abs/2305.14314) for embeddings.
884
+
885
+ Quantization API is similar to Linear4bit:
886
+ ```python
887
+ import torch
888
+ import torch.nn as nn
889
+
890
+ from bitsandbytes.nn import Embedding4bit
891
+
892
+ fp16_module = nn.Embedding(128, 64)
893
+ quantized_module = Embedding4bit(128, 64)
894
+
895
+ quantized_module.load_state_dict(fp16_module.state_dict())
896
+
897
+ quantized_module = quantized_module.to(0) # Quantization happens here
898
+ ```
899
+ """
900
+
901
+ def __init__(
902
+ self,
903
+ num_embeddings,
904
+ embedding_dim,
905
+ dtype=None,
906
+ quant_type="fp4",
907
+ quant_storage=torch.uint8,
908
+ device=None,
909
+ ):
910
+ super().__init__(num_embeddings, embedding_dim, device=device, dtype=dtype)
911
+ self.dtype = self.weight.data.dtype
912
+
913
+ self.weight = Params4bit(
914
+ self.weight.data,
915
+ requires_grad=False,
916
+ compress_statistics=None,
917
+ quant_type=quant_type,
918
+ quant_storage=quant_storage,
919
+ module=self,
920
+ )
921
+
922
+ blocksize = self.weight.blocksize
923
+
924
+ if embedding_dim % blocksize != 0:
925
+ logger.warning(
926
+ f"Embedding size {embedding_dim} is not divisible by block size {blocksize}. "
927
+ "This will lead to slow inference.",
928
+ )
929
+
930
+ def _forward_with_partial_dequantize(self, input: Tensor):
931
+ assert self.embedding_dim % self.weight.quant_state.blocksize == 0
932
+
933
+ w_4bit_uint8 = self.weight.data.view(torch.uint8).view(self.num_embeddings * self.embedding_dim // 2, 1)
934
+
935
+ output_4bit = torch.nn.functional.embedding(
936
+ weight=w_4bit_uint8.view(self.num_embeddings, self.embedding_dim // 2),
937
+ input=input,
938
+ ).view(-1, 1)
939
+ assert output_4bit.shape == (input.numel() * self.embedding_dim // 2, 1)
940
+
941
+ blocks_per_emb = self.embedding_dim // self.weight.blocksize
942
+
943
+ absmax = self.weight.quant_state.absmax
944
+ assert absmax.shape == (self.num_embeddings * blocks_per_emb,)
945
+
946
+ output_absmax = torch.nn.functional.embedding(
947
+ weight=absmax.view(self.num_embeddings, blocks_per_emb),
948
+ input=input,
949
+ ).view(
950
+ -1,
951
+ )
952
+ assert output_absmax.shape == (input.numel() * blocks_per_emb,)
953
+
954
+ output_quant_state = copy.deepcopy(self.weight.quant_state)
955
+ output_quant_state.absmax = output_absmax
956
+ output_quant_state.shape = torch.Size((*input.shape, self.embedding_dim))
957
+
958
+ output = bnb.functional.dequantize_4bit(output_4bit, output_quant_state)
959
+ assert output.shape == (*input.shape, self.embedding_dim)
960
+
961
+ return output.to(self.dtype)
962
+
963
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
964
+ raise NotImplementedError("Saving Embedding4bit module is not implemented")
965
+
966
+ def forward(self, input: Tensor) -> Tensor:
967
+ fix_4bit_weight_quant_state_from_module(self)
968
+
969
+ if self.embedding_dim % self.weight.quant_state.blocksize == 0:
970
+ return self._forward_with_partial_dequantize(input)
971
+
972
+ dequantized_weight = bnb.functional.dequantize_4bit(self.weight.data, self.weight.quant_state)
973
+
974
+ return torch.nn.functional.embedding(
975
+ weight=dequantized_weight,
976
+ input=input,
977
+ ).to(self.dtype)
978
+
979
+
980
+ class EmbeddingFP4(Embedding4bit):
981
+ def __init__(
982
+ self,
983
+ num_embeddings,
984
+ embedding_dim,
985
+ dtype=None,
986
+ quant_storage=torch.uint8,
987
+ device=None,
988
+ ):
989
+ super().__init__(
990
+ num_embeddings,
991
+ embedding_dim,
992
+ dtype=dtype,
993
+ quant_type="fp4",
994
+ quant_storage=quant_storage,
995
+ device=device,
996
+ )
997
+
998
+
999
+ class EmbeddingNF4(Embedding4bit):
1000
+ def __init__(
1001
+ self,
1002
+ num_embeddings,
1003
+ embedding_dim,
1004
+ dtype=None,
1005
+ quant_storage=torch.uint8,
1006
+ device=None,
1007
+ ):
1008
+ super().__init__(
1009
+ num_embeddings,
1010
+ embedding_dim,
1011
+ dtype=dtype,
1012
+ quant_type="nf4",
1013
+ quant_storage=quant_storage,
1014
+ device=device,
1015
+ )
1016
+
1017
+
1018
+ class Linear8bitLt(nn.Linear):
1019
+ """
1020
+ This class is the base module for the [LLM.int8()](https://arxiv.org/abs/2208.07339) algorithm.
1021
+ To read more about it, have a look at the paper.
1022
+
1023
+ In order to quantize a linear layer one should first load the original fp16 / bf16 weights into
1024
+ the Linear8bitLt module, then call `int8_module.to("cuda")` to quantize the fp16 weights.
1025
+
1026
+ Example:
1027
+
1028
+ ```python
1029
+ import torch
1030
+ import torch.nn as nn
1031
+
1032
+ import bitsandbytes as bnb
1033
+ from bitsandbytes.nn import Linear8bitLt
1034
+
1035
+ fp16_model = nn.Sequential(
1036
+ nn.Linear(64, 64),
1037
+ nn.Linear(64, 64)
1038
+ )
1039
+
1040
+ int8_model = nn.Sequential(
1041
+ Linear8bitLt(64, 64, has_fp16_weights=False),
1042
+ Linear8bitLt(64, 64, has_fp16_weights=False)
1043
+ )
1044
+
1045
+ int8_model.load_state_dict(fp16_model.state_dict())
1046
+ int8_model = int8_model.to(0) # Quantization happens here
1047
+ ```
1048
+ """
1049
+
1050
+ def __init__(
1051
+ self,
1052
+ input_features: int,
1053
+ output_features: int,
1054
+ bias=True,
1055
+ has_fp16_weights=True,
1056
+ threshold=0.0,
1057
+ index=None,
1058
+ device=None,
1059
+ ):
1060
+ """
1061
+ Initialize Linear8bitLt class.
1062
+
1063
+ Args:
1064
+ input_features (`int`):
1065
+ Number of input features of the linear layer.
1066
+ output_features (`int`):
1067
+ Number of output features of the linear layer.
1068
+ bias (`bool`, defaults to `True`):
1069
+ Whether the linear class uses the bias term as well.
1070
+ has_fp16_weights (`bool`, defaults to `True`):
1071
+ If False, weights are quantized to int8 on ``.to(device)``. If True,
1072
+ weights remain in fp16 and are quantized on-the-fly during each forward pass.
1073
+ threshold (`float`, defaults to `0.0`):
1074
+ Outlier threshold for mixed-precision decomposition (LLM.int8()). During the
1075
+ forward pass, activation columns where any value exceeds this threshold are
1076
+ computed in fp16, while the remaining columns use int8. This operates on
1077
+ **activations** (inputs), not on weight values. Set to 0.0 to disable
1078
+ mixed-precision decomposition and quantize all columns to int8.
1079
+ index: Indices for weight reordering (used internally).
1080
+ device: Device to initialize the layer on.
1081
+ """
1082
+ super().__init__(input_features, output_features, bias, device)
1083
+ self.state = bnb.MatmulLtState()
1084
+ self.index = index
1085
+
1086
+ self.state.threshold = threshold
1087
+ self.state.has_fp16_weights = has_fp16_weights
1088
+
1089
+ if threshold > 0.0 and not has_fp16_weights:
1090
+ self.state.use_pool = True
1091
+
1092
+ self.weight = Int8Params(self.weight.data, has_fp16_weights=has_fp16_weights, requires_grad=has_fp16_weights)
1093
+ self._register_load_state_dict_pre_hook(maybe_rearrange_weight)
1094
+
1095
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
1096
+ super()._save_to_state_dict(destination, prefix, keep_vars)
1097
+
1098
+ # we only need to save SCB as extra data, because CB for quantized weights is already stored in weight.data
1099
+ scb_name = "SCB"
1100
+
1101
+ # case 1: .cuda was called, SCB is in self.weight
1102
+ param_from_weight = getattr(self.weight, scb_name, None)
1103
+ # case 2: self.init_8bit_state was called, SCB is in self.state
1104
+ param_from_state = getattr(self.state, scb_name)
1105
+
1106
+ key_name = prefix + f"{scb_name}"
1107
+
1108
+ # We now only save in row-major. This format information is stored for backwards compatibility.
1109
+ format_name = prefix + "weight_format"
1110
+
1111
+ if not self.state.has_fp16_weights:
1112
+ if param_from_weight is not None:
1113
+ destination[key_name] = param_from_weight if keep_vars else param_from_weight.detach()
1114
+ destination[format_name] = torch.tensor(0, dtype=torch.uint8)
1115
+ elif param_from_state is not None:
1116
+ destination[key_name] = param_from_state if keep_vars else param_from_state.detach()
1117
+ destination[format_name] = torch.tensor(0, dtype=torch.uint8)
1118
+
1119
+ def _load_from_state_dict(
1120
+ self,
1121
+ state_dict,
1122
+ prefix,
1123
+ local_metadata,
1124
+ strict,
1125
+ missing_keys,
1126
+ unexpected_keys,
1127
+ error_msgs,
1128
+ ):
1129
+ super()._load_from_state_dict(
1130
+ state_dict,
1131
+ prefix,
1132
+ local_metadata,
1133
+ strict,
1134
+ missing_keys,
1135
+ unexpected_keys,
1136
+ error_msgs,
1137
+ )
1138
+ unexpected_copy = list(unexpected_keys)
1139
+
1140
+ for key in unexpected_copy:
1141
+ input_name = key[len(prefix) :]
1142
+ if input_name == "SCB":
1143
+ weight_scb = getattr(self.weight, "SCB", None)
1144
+ if weight_scb is None:
1145
+ # buffers not yet initialized, can't access them directly without quantizing first
1146
+ raise RuntimeError(
1147
+ "Loading a quantized checkpoint into non-quantized Linear8bitLt is "
1148
+ "not supported. Please call module.cuda() before module.load_state_dict()",
1149
+ )
1150
+
1151
+ input_param = state_dict[key]
1152
+ weight_scb.copy_(input_param)
1153
+
1154
+ if self.state.SCB is not None:
1155
+ self.state.SCB = self.weight.SCB
1156
+
1157
+ unexpected_keys.remove(key)
1158
+
1159
+ def init_8bit_state(self):
1160
+ self.state.CB = self.weight.CB
1161
+ self.state.SCB = self.weight.SCB
1162
+ self.weight.CB = None
1163
+ self.weight.SCB = None
1164
+
1165
+ def to(self, *args, **kwargs):
1166
+ # Call the parent to() method to handle standard parameter/buffer movement
1167
+ result = super().to(*args, **kwargs)
1168
+
1169
+ device, _, _, _ = torch._C._nn._parse_to(*args, **kwargs)
1170
+
1171
+ # Handle state tensors if needed.
1172
+ if device is not None:
1173
+ if result.state.CB is not None:
1174
+ result.state.CB = result.state.CB.to(device)
1175
+ if result.state.SCB is not None:
1176
+ result.state.SCB = result.state.SCB.to(device)
1177
+
1178
+ return result
1179
+
1180
+ def forward(self, x: torch.Tensor):
1181
+ self.state.is_training = self.training
1182
+ if self.weight.CB is not None:
1183
+ self.init_8bit_state()
1184
+
1185
+ # weights are cast automatically as Int8Params, but the bias has to be cast manually
1186
+ if self.bias is not None and self.bias.dtype != x.dtype:
1187
+ self.bias.data = self.bias.data.to(x.dtype)
1188
+
1189
+ out = bnb.matmul(x, self.weight, bias=self.bias, state=self.state)
1190
+
1191
+ if not self.state.has_fp16_weights and self.state.CB is not None:
1192
+ self.weight.data = self.state.CB
1193
+
1194
+ return out
1195
+
1196
+
1197
+ class OutlierAwareLinear(nn.Linear):
1198
+ def __init__(self, input_features, output_features, bias=True, device=None):
1199
+ super().__init__(input_features, output_features, bias, device)
1200
+ self.outlier_dim = None
1201
+ self.is_quantized = False
1202
+
1203
+ def forward_with_outliers(self, x, outlier_idx):
1204
+ raise NotImplementedError("Please override the `forward_with_outliers(self, x, outlier_idx)` function")
1205
+
1206
+ def quantize_weight(self, w, outlier_idx):
1207
+ raise NotImplementedError("Please override the `quantize_weights(self, w, outlier_idx)` function")
1208
+
1209
+ def forward(self, x):
1210
+ if self.outlier_dim is None:
1211
+ tracer = OutlierTracer.get_instance()
1212
+ if not tracer.is_initialized():
1213
+ logger.warning("Please use OutlierTracer.initialize(model) before using the OutlierAwareLinear layer")
1214
+ outlier_idx = tracer.get_outliers(self.weight)
1215
+ self.outlier_dim = outlier_idx
1216
+
1217
+ if not self.is_quantized:
1218
+ w = self.quantize_weight(self.weight, self.outlier_dim)
1219
+ self.weight.data.copy_(w)
1220
+ self.is_quantized = True