quantization_config.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import copy
  17. import importlib.metadata
  18. import json
  19. import os
  20. from dataclasses import dataclass
  21. from enum import Enum
  22. from inspect import Parameter, signature
  23. from typing import Any, Dict, List, Optional, Union
  24. from packaging import version
  25. from ..utils import is_auto_awq_available, is_hqq_available, is_torch_available, is_torchao_available, logging
  26. if is_torch_available():
  27. import torch
  28. logger = logging.get_logger(__name__)
  29. class QuantizationMethod(str, Enum):
  30. BITS_AND_BYTES = "bitsandbytes"
  31. GPTQ = "gptq"
  32. AWQ = "awq"
  33. AQLM = "aqlm"
  34. QUANTO = "quanto"
  35. EETQ = "eetq"
  36. HQQ = "hqq"
  37. COMPRESSED_TENSORS = "compressed-tensors"
  38. FBGEMM_FP8 = "fbgemm_fp8"
  39. TORCHAO = "torchao"
  40. BITNET = "bitnet"
  41. class AWQLinearVersion(str, Enum):
  42. GEMM = "gemm"
  43. GEMV = "gemv"
  44. EXLLAMA = "exllama"
  45. IPEX = "ipex"
  46. @staticmethod
  47. def from_str(version: str):
  48. version = version.lower()
  49. if version == "gemm":
  50. return AWQLinearVersion.GEMM
  51. elif version == "gemv":
  52. return AWQLinearVersion.GEMV
  53. elif version == "exllama":
  54. return AWQLinearVersion.EXLLAMA
  55. elif version == "ipex":
  56. return AWQLinearVersion.IPEX
  57. else:
  58. raise ValueError(f"Unknown AWQLinearVersion {version}")
  59. class AwqBackendPackingMethod(str, Enum):
  60. AUTOAWQ = "autoawq"
  61. LLMAWQ = "llm-awq"
  62. @dataclass
  63. class QuantizationConfigMixin:
  64. """
  65. Mixin class for quantization config
  66. """
  67. quant_method: QuantizationMethod
  68. @classmethod
  69. def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
  70. """
  71. Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters.
  72. Args:
  73. config_dict (`Dict[str, Any]`):
  74. Dictionary that will be used to instantiate the configuration object.
  75. return_unused_kwargs (`bool`,*optional*, defaults to `False`):
  76. Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
  77. `PreTrainedModel`.
  78. kwargs (`Dict[str, Any]`):
  79. Additional parameters from which to initialize the configuration object.
  80. Returns:
  81. [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
  82. """
  83. config = cls(**config_dict)
  84. to_remove = []
  85. for key, value in kwargs.items():
  86. if hasattr(config, key):
  87. setattr(config, key, value)
  88. to_remove.append(key)
  89. for key in to_remove:
  90. kwargs.pop(key, None)
  91. if return_unused_kwargs:
  92. return config, kwargs
  93. else:
  94. return config
  95. def to_json_file(self, json_file_path: Union[str, os.PathLike]):
  96. """
  97. Save this instance to a JSON file.
  98. Args:
  99. json_file_path (`str` or `os.PathLike`):
  100. Path to the JSON file in which this configuration instance's parameters will be saved.
  101. use_diff (`bool`, *optional*, defaults to `True`):
  102. If set to `True`, only the difference between the config instance and the default
  103. `QuantizationConfig()` is serialized to JSON file.
  104. """
  105. with open(json_file_path, "w", encoding="utf-8") as writer:
  106. config_dict = self.to_dict()
  107. json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
  108. writer.write(json_string)
  109. def to_dict(self) -> Dict[str, Any]:
  110. """
  111. Serializes this instance to a Python dictionary. Returns:
  112. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  113. """
  114. return copy.deepcopy(self.__dict__)
  115. def __iter__(self):
  116. """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin"""
  117. for attr, value in copy.deepcopy(self.__dict__).items():
  118. yield attr, value
  119. def __repr__(self):
  120. return f"{self.__class__.__name__} {self.to_json_string()}"
  121. def to_json_string(self, use_diff: bool = True) -> str:
  122. """
  123. Serializes this instance to a JSON string.
  124. Args:
  125. use_diff (`bool`, *optional*, defaults to `True`):
  126. If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
  127. is serialized to JSON string.
  128. Returns:
  129. `str`: String containing all the attributes that make up this configuration instance in JSON format.
  130. """
  131. if use_diff is True:
  132. config_dict = self.to_diff_dict()
  133. else:
  134. config_dict = self.to_dict()
  135. return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
  136. def update(self, **kwargs):
  137. """
  138. Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
  139. returning all the unused kwargs.
  140. Args:
  141. kwargs (`Dict[str, Any]`):
  142. Dictionary of attributes to tentatively update this class.
  143. Returns:
  144. `Dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
  145. """
  146. to_remove = []
  147. for key, value in kwargs.items():
  148. if hasattr(self, key):
  149. setattr(self, key, value)
  150. to_remove.append(key)
  151. # Remove all the attributes that were updated, without modifying the input dict
  152. unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
  153. return unused_kwargs
  154. @dataclass
  155. class HqqConfig(QuantizationConfigMixin):
  156. """
  157. This is wrapper around hqq's BaseQuantizeConfig.
  158. Args:
  159. nbits (`int`, *optional*, defaults to 4):
  160. Number of bits. Supported values are (8, 4, 3, 2, 1).
  161. group_size (`int`, *optional*, defaults to 64):
  162. Group-size value. Supported values are any value that is divisble by weight.shape[axis]).
  163. view_as_float (`bool`, *optional*, defaults to `False`):
  164. View the quantized weight as float (used in distributed training) if set to `True`.
  165. axis (`Optional[int]`, *optional*):
  166. Axis along which grouping is performed. Supported values are 0 or 1.
  167. dynamic_config (dict, *optional*):
  168. Parameters for dynamic configuration. The key is the name tag of the layer and the value is a quantization config.
  169. If set, each layer specified by its id will use its dedicated quantization configuration.
  170. skip_modules (`List[str]`, *optional*, defaults to `['lm_head']`):
  171. List of `nn.Linear` layers to skip.
  172. kwargs (`Dict[str, Any]`, *optional*):
  173. Additional parameters from which to initialize the configuration object.
  174. """
  175. def __init__(
  176. self,
  177. nbits: int = 4,
  178. group_size: int = 64,
  179. view_as_float: bool = False,
  180. axis: Optional[int] = None,
  181. dynamic_config: Optional[dict] = None,
  182. skip_modules: List[str] = ["lm_head"],
  183. **kwargs,
  184. ):
  185. if is_hqq_available():
  186. from hqq.core.quantize import BaseQuantizeConfig as HQQBaseQuantizeConfig
  187. for deprecated_key in ["quant_zero", "quant_scale", "offload_meta"]:
  188. if deprecated_key in kwargs:
  189. logger.info(
  190. deprecated_key + " is deprecated. This parameter will be ignored in quantization settings."
  191. )
  192. if axis is None:
  193. axis = 1
  194. logger.info("Setting axis=1 as faster backends such as TorchAO or BitBlas are only compatible with it.")
  195. if axis not in [0, 1]:
  196. raise ValueError("Invalid axis value. Only 0 and 1 are allowed.")
  197. if dynamic_config is not None:
  198. self.quant_config = {}
  199. for key in dynamic_config:
  200. self.quant_config[key] = HQQBaseQuantizeConfig(**dynamic_config[key])
  201. else:
  202. self.quant_config = HQQBaseQuantizeConfig(
  203. **{
  204. "nbits": nbits,
  205. "group_size": group_size,
  206. "view_as_float": view_as_float,
  207. "axis": axis,
  208. }
  209. )
  210. self.quant_method = QuantizationMethod.HQQ
  211. self.skip_modules = skip_modules
  212. self.post_init()
  213. def post_init(self):
  214. r"""
  215. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  216. """
  217. pass
  218. @classmethod
  219. def from_dict(cls, config: Dict[str, Any]):
  220. """
  221. Override from_dict, used in AutoQuantizationConfig.from_dict in quantizers/auto.py
  222. """
  223. instance = cls()
  224. instance.quant_config = config["quant_config"]
  225. instance.skip_modules = config["skip_modules"]
  226. return instance
  227. def to_dict(self) -> Dict[str, Any]:
  228. """
  229. Serializes this instance to a Python dictionary. Returns:
  230. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  231. """
  232. return {
  233. "quant_config": self.quant_config,
  234. "quant_method": self.quant_method,
  235. "skip_modules": self.skip_modules,
  236. }
  237. def __repr__(self):
  238. config_dict = self.to_dict()
  239. return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
  240. def to_diff_dict(self) -> Dict[str, Any]:
  241. """
  242. Removes all attributes from config which correspond to the default config attributes for better readability and
  243. serializes to a Python dictionary.
  244. Returns:
  245. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
  246. """
  247. config_dict = self.to_dict()
  248. # get the default config dict
  249. default_config_dict = HqqConfig().to_dict()
  250. serializable_config_dict = {}
  251. # only serialize values that differ from the default config
  252. for key, value in config_dict.items():
  253. if value != default_config_dict[key]:
  254. serializable_config_dict[key] = value
  255. return serializable_config_dict
  256. @dataclass
  257. class BitsAndBytesConfig(QuantizationConfigMixin):
  258. """
  259. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  260. loaded using `bitsandbytes`.
  261. This replaces `load_in_8bit` or `load_in_4bit`therefore both options are mutually exclusive.
  262. Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`,
  263. then more arguments will be added to this class.
  264. Args:
  265. load_in_8bit (`bool`, *optional*, defaults to `False`):
  266. This flag is used to enable 8-bit quantization with LLM.int8().
  267. load_in_4bit (`bool`, *optional*, defaults to `False`):
  268. This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from
  269. `bitsandbytes`.
  270. llm_int8_threshold (`float`, *optional*, defaults to 6.0):
  271. This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix
  272. Multiplication for Transformers at Scale` paper: https://arxiv.org/abs/2208.07339 Any hidden states value
  273. that is above this threshold will be considered an outlier and the operation on those values will be done
  274. in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5], but
  275. there are some exceptional systematic outliers that are very differently distributed for large models.
  276. These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of
  277. magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6,
  278. but a lower threshold might be needed for more unstable models (small models, fine-tuning).
  279. llm_int8_skip_modules (`List[str]`, *optional*):
  280. An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as
  281. Jukebox that has several heads in different places and not necessarily at the last position. For example
  282. for `CausalLM` models, the last `lm_head` is kept in its original `dtype`.
  283. llm_int8_enable_fp32_cpu_offload (`bool`, *optional*, defaults to `False`):
  284. This flag is used for advanced use cases and users that are aware of this feature. If you want to split
  285. your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use
  286. this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8
  287. operations will not be run on CPU.
  288. llm_int8_has_fp16_weight (`bool`, *optional*, defaults to `False`):
  289. This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not
  290. have to be converted back and forth for the backward pass.
  291. bnb_4bit_compute_dtype (`torch.dtype` or str, *optional*, defaults to `torch.float32`):
  292. This sets the computational type which might be different than the input type. For example, inputs might be
  293. fp32, but computation can be set to bf16 for speedups.
  294. bnb_4bit_quant_type (`str`, *optional*, defaults to `"fp4"`):
  295. This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types
  296. which are specified by `fp4` or `nf4`.
  297. bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`):
  298. This flag is used for nested quantization where the quantization constants from the first quantization are
  299. quantized again.
  300. bnb_4bit_quant_storage (`torch.dtype` or str, *optional*, defaults to `torch.uint8`):
  301. This sets the storage type to pack the quanitzed 4-bit prarams.
  302. kwargs (`Dict[str, Any]`, *optional*):
  303. Additional parameters from which to initialize the configuration object.
  304. """
  305. def __init__(
  306. self,
  307. load_in_8bit=False,
  308. load_in_4bit=False,
  309. llm_int8_threshold=6.0,
  310. llm_int8_skip_modules=None,
  311. llm_int8_enable_fp32_cpu_offload=False,
  312. llm_int8_has_fp16_weight=False,
  313. bnb_4bit_compute_dtype=None,
  314. bnb_4bit_quant_type="fp4",
  315. bnb_4bit_use_double_quant=False,
  316. bnb_4bit_quant_storage=None,
  317. **kwargs,
  318. ):
  319. self.quant_method = QuantizationMethod.BITS_AND_BYTES
  320. if load_in_4bit and load_in_8bit:
  321. raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
  322. self._load_in_8bit = load_in_8bit
  323. self._load_in_4bit = load_in_4bit
  324. self.llm_int8_threshold = llm_int8_threshold
  325. self.llm_int8_skip_modules = llm_int8_skip_modules
  326. self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload
  327. self.llm_int8_has_fp16_weight = llm_int8_has_fp16_weight
  328. self.bnb_4bit_quant_type = bnb_4bit_quant_type
  329. self.bnb_4bit_use_double_quant = bnb_4bit_use_double_quant
  330. if bnb_4bit_compute_dtype is None:
  331. self.bnb_4bit_compute_dtype = torch.float32
  332. elif isinstance(bnb_4bit_compute_dtype, str):
  333. self.bnb_4bit_compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
  334. elif isinstance(bnb_4bit_compute_dtype, torch.dtype):
  335. self.bnb_4bit_compute_dtype = bnb_4bit_compute_dtype
  336. else:
  337. raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype")
  338. if bnb_4bit_quant_storage is None:
  339. self.bnb_4bit_quant_storage = torch.uint8
  340. elif isinstance(bnb_4bit_quant_storage, str):
  341. if bnb_4bit_quant_storage not in ["float16", "float32", "int8", "uint8", "float64", "bfloat16"]:
  342. raise ValueError(
  343. "`bnb_4bit_quant_storage` must be a valid string (one of 'float16', 'float32', 'int8', 'uint8', 'float64', 'bfloat16') "
  344. )
  345. self.bnb_4bit_quant_storage = getattr(torch, bnb_4bit_quant_storage)
  346. elif isinstance(bnb_4bit_quant_storage, torch.dtype):
  347. self.bnb_4bit_quant_storage = bnb_4bit_quant_storage
  348. else:
  349. raise ValueError("bnb_4bit_quant_storage must be a string or a torch.dtype")
  350. if kwargs:
  351. logger.warning(f"Unused kwargs: {list(kwargs.keys())}. These kwargs are not used in {self.__class__}.")
  352. self.post_init()
  353. @property
  354. def load_in_4bit(self):
  355. return self._load_in_4bit
  356. @load_in_4bit.setter
  357. def load_in_4bit(self, value: bool):
  358. if not isinstance(value, bool):
  359. raise TypeError("load_in_4bit must be a boolean")
  360. if self.load_in_8bit and value:
  361. raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
  362. self._load_in_4bit = value
  363. @property
  364. def load_in_8bit(self):
  365. return self._load_in_8bit
  366. @load_in_8bit.setter
  367. def load_in_8bit(self, value: bool):
  368. if not isinstance(value, bool):
  369. raise TypeError("load_in_8bit must be a boolean")
  370. if self.load_in_4bit and value:
  371. raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
  372. self._load_in_8bit = value
  373. def post_init(self):
  374. r"""
  375. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  376. """
  377. if not isinstance(self.load_in_4bit, bool):
  378. raise TypeError("load_in_4bit must be a boolean")
  379. if not isinstance(self.load_in_8bit, bool):
  380. raise TypeError("load_in_8bit must be a boolean")
  381. if not isinstance(self.llm_int8_threshold, float):
  382. raise TypeError("llm_int8_threshold must be a float")
  383. if self.llm_int8_skip_modules is not None and not isinstance(self.llm_int8_skip_modules, list):
  384. raise TypeError("llm_int8_skip_modules must be a list of strings")
  385. if not isinstance(self.llm_int8_enable_fp32_cpu_offload, bool):
  386. raise TypeError("llm_int8_enable_fp32_cpu_offload must be a boolean")
  387. if not isinstance(self.llm_int8_has_fp16_weight, bool):
  388. raise TypeError("llm_int8_has_fp16_weight must be a boolean")
  389. if self.bnb_4bit_compute_dtype is not None and not isinstance(self.bnb_4bit_compute_dtype, torch.dtype):
  390. raise TypeError("bnb_4bit_compute_dtype must be torch.dtype")
  391. if not isinstance(self.bnb_4bit_quant_type, str):
  392. raise TypeError("bnb_4bit_quant_type must be a string")
  393. if not isinstance(self.bnb_4bit_use_double_quant, bool):
  394. raise TypeError("bnb_4bit_use_double_quant must be a boolean")
  395. if self.load_in_4bit and not version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse(
  396. "0.39.0"
  397. ):
  398. raise ValueError(
  399. "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"
  400. )
  401. def is_quantizable(self):
  402. r"""
  403. Returns `True` if the model is quantizable, `False` otherwise.
  404. """
  405. return self.load_in_8bit or self.load_in_4bit
  406. def quantization_method(self):
  407. r"""
  408. This method returns the quantization method used for the model. If the model is not quantizable, it returns
  409. `None`.
  410. """
  411. if self.load_in_8bit:
  412. return "llm_int8"
  413. elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4":
  414. return "fp4"
  415. elif self.load_in_4bit and self.bnb_4bit_quant_type == "nf4":
  416. return "nf4"
  417. else:
  418. return None
  419. def to_dict(self) -> Dict[str, Any]:
  420. """
  421. Serializes this instance to a Python dictionary. Returns:
  422. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  423. """
  424. output = copy.deepcopy(self.__dict__)
  425. output["bnb_4bit_compute_dtype"] = str(output["bnb_4bit_compute_dtype"]).split(".")[1]
  426. output["bnb_4bit_quant_storage"] = str(output["bnb_4bit_quant_storage"]).split(".")[1]
  427. output["load_in_4bit"] = self.load_in_4bit
  428. output["load_in_8bit"] = self.load_in_8bit
  429. return output
  430. def __repr__(self):
  431. config_dict = self.to_dict()
  432. return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
  433. def to_diff_dict(self) -> Dict[str, Any]:
  434. """
  435. Removes all attributes from config which correspond to the default config attributes for better readability and
  436. serializes to a Python dictionary.
  437. Returns:
  438. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
  439. """
  440. config_dict = self.to_dict()
  441. # get the default config dict
  442. default_config_dict = BitsAndBytesConfig().to_dict()
  443. serializable_config_dict = {}
  444. # only serialize values that differ from the default config
  445. for key, value in config_dict.items():
  446. if value != default_config_dict[key]:
  447. serializable_config_dict[key] = value
  448. return serializable_config_dict
  449. class ExllamaVersion(int, Enum):
  450. ONE = 1
  451. TWO = 2
  452. @dataclass
  453. class GPTQConfig(QuantizationConfigMixin):
  454. """
  455. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  456. loaded using `optimum` api for gptq quantization relying on auto_gptq backend.
  457. Args:
  458. bits (`int`):
  459. The number of bits to quantize to, supported numbers are (2, 3, 4, 8).
  460. tokenizer (`str` or `PreTrainedTokenizerBase`, *optional*):
  461. The tokenizer used to process the dataset. You can pass either:
  462. - A custom tokenizer object.
  463. - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
  464. - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
  465. using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
  466. dataset (`Union[List[str]]`, *optional*):
  467. The dataset used for quantization. You can provide your own dataset in a list of string or just use the
  468. original datasets used in GPTQ paper ['wikitext2','c4','c4-new']
  469. group_size (`int`, *optional*, defaults to 128):
  470. The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
  471. damp_percent (`float`, *optional*, defaults to 0.1):
  472. The percent of the average Hessian diagonal to use for dampening. Recommended value is 0.1.
  473. desc_act (`bool`, *optional*, defaults to `False`):
  474. Whether to quantize columns in order of decreasing activation size. Setting it to False can significantly
  475. speed up inference but the perplexity may become slightly worse. Also known as act-order.
  476. sym (`bool`, *optional*, defaults to `True`):
  477. Whether to use symetric quantization.
  478. true_sequential (`bool`, *optional*, defaults to `True`):
  479. Whether to perform sequential quantization even within a single Transformer block. Instead of quantizing
  480. the entire block at once, we perform layer-wise quantization. As a result, each layer undergoes
  481. quantization using inputs that have passed through the previously quantized layers.
  482. use_cuda_fp16 (`bool`, *optional*, defaults to `False`):
  483. Whether or not to use optimized cuda kernel for fp16 model. Need to have model in fp16.
  484. model_seqlen (`int`, *optional*):
  485. The maximum sequence length that the model can take.
  486. block_name_to_quantize (`str`, *optional*):
  487. The transformers block name to quantize. If None, we will infer the block name using common patterns (e.g. model.layers)
  488. module_name_preceding_first_block (`List[str]`, *optional*):
  489. The layers that are preceding the first Transformer block.
  490. batch_size (`int`, *optional*, defaults to 1):
  491. The batch size used when processing the dataset
  492. pad_token_id (`int`, *optional*):
  493. The pad token id. Needed to prepare the dataset when `batch_size` > 1.
  494. use_exllama (`bool`, *optional*):
  495. Whether to use exllama backend. Defaults to `True` if unset. Only works with `bits` = 4.
  496. max_input_length (`int`, *optional*):
  497. The maximum input length. This is needed to initialize a buffer that depends on the maximum expected input
  498. length. It is specific to the exllama backend with act-order.
  499. exllama_config (`Dict[str, Any]`, *optional*):
  500. The exllama config. You can specify the version of the exllama kernel through the `version` key. Defaults
  501. to `{"version": 1}` if unset.
  502. cache_block_outputs (`bool`, *optional*, defaults to `True`):
  503. Whether to cache block outputs to reuse as inputs for the succeeding block.
  504. modules_in_block_to_quantize (`List[List[str]]`, *optional*):
  505. List of list of module names to quantize in the specified block. This argument is useful to exclude certain linear modules from being quantized.
  506. The block to quantize can be specified by setting `block_name_to_quantize`. We will quantize each list sequentially. If not set, we will quantize all linear layers.
  507. Example: `modules_in_block_to_quantize =[["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj"], ["self_attn.o_proj"]]`.
  508. In this example, we will first quantize the q,k,v layers simultaneously since they are independent.
  509. Then, we will quantize `self_attn.o_proj` layer with the q,k,v layers quantized. This way, we will get
  510. better results since it reflects the real input `self_attn.o_proj` will get when the model is quantized.
  511. """
  512. def __init__(
  513. self,
  514. bits: int,
  515. tokenizer: Any = None,
  516. dataset: Optional[Union[List[str], str]] = None,
  517. group_size: int = 128,
  518. damp_percent: float = 0.1,
  519. desc_act: bool = False,
  520. sym: bool = True,
  521. true_sequential: bool = True,
  522. use_cuda_fp16: bool = False,
  523. model_seqlen: Optional[int] = None,
  524. block_name_to_quantize: Optional[str] = None,
  525. module_name_preceding_first_block: Optional[List[str]] = None,
  526. batch_size: int = 1,
  527. pad_token_id: Optional[int] = None,
  528. use_exllama: Optional[bool] = None,
  529. max_input_length: Optional[int] = None,
  530. exllama_config: Optional[Dict[str, Any]] = None,
  531. cache_block_outputs: bool = True,
  532. modules_in_block_to_quantize: Optional[List[List[str]]] = None,
  533. **kwargs,
  534. ):
  535. self.quant_method = QuantizationMethod.GPTQ
  536. self.bits = bits
  537. self.tokenizer = tokenizer
  538. self.dataset = dataset
  539. self.group_size = group_size
  540. self.damp_percent = damp_percent
  541. self.desc_act = desc_act
  542. self.sym = sym
  543. self.true_sequential = true_sequential
  544. self.use_cuda_fp16 = use_cuda_fp16
  545. self.model_seqlen = model_seqlen
  546. self.block_name_to_quantize = block_name_to_quantize
  547. self.module_name_preceding_first_block = module_name_preceding_first_block
  548. self.batch_size = batch_size
  549. self.pad_token_id = pad_token_id
  550. self.use_exllama = use_exllama
  551. self.max_input_length = max_input_length
  552. self.exllama_config = exllama_config
  553. self.disable_exllama = kwargs.pop("disable_exllama", None)
  554. self.cache_block_outputs = cache_block_outputs
  555. self.modules_in_block_to_quantize = modules_in_block_to_quantize
  556. self.post_init()
  557. def get_loading_attributes(self):
  558. attibutes_dict = copy.deepcopy(self.__dict__)
  559. loading_attibutes = ["disable_exllama", "use_exllama", "exllama_config", "use_cuda_fp16", "max_input_length"]
  560. loading_attibutes_dict = {i: j for i, j in attibutes_dict.items() if i in loading_attibutes}
  561. return loading_attibutes_dict
  562. def post_init(self):
  563. r"""
  564. Safety checker that arguments are correct
  565. """
  566. if self.bits not in [2, 3, 4, 8]:
  567. raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}")
  568. if self.group_size != -1 and self.group_size <= 0:
  569. raise ValueError("group_size must be greater than 0 or equal to -1")
  570. if not (0 < self.damp_percent < 1):
  571. raise ValueError("damp_percent must between 0 and 1.")
  572. if self.dataset is not None:
  573. if isinstance(self.dataset, str):
  574. if self.dataset in ["ptb", "ptb-new"]:
  575. raise ValueError(
  576. f"""{self.dataset} dataset was deprecated. You can only choose between
  577. ['wikitext2','c4','c4-new']"""
  578. )
  579. if self.dataset not in ["wikitext2", "c4", "c4-new"]:
  580. raise ValueError(
  581. f"""You have entered a string value for dataset. You can only choose between
  582. ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
  583. )
  584. elif not isinstance(self.dataset, list):
  585. raise ValueError(
  586. f"""dataset needs to be either a list of string or a value in
  587. ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
  588. )
  589. if self.disable_exllama is None and self.use_exllama is None:
  590. # New default behaviour
  591. self.use_exllama = True
  592. elif self.disable_exllama is not None and self.use_exllama is None:
  593. # Follow pattern of old config
  594. logger.warning(
  595. "Using `disable_exllama` is deprecated and will be removed in version 4.37. Use `use_exllama` instead and specify the version with `exllama_config`."
  596. "The value of `use_exllama` will be overwritten by `disable_exllama` passed in `GPTQConfig` or stored in your config file."
  597. )
  598. self.use_exllama = not self.disable_exllama
  599. self.disable_exllama = None
  600. elif self.disable_exllama is not None and self.use_exllama is not None:
  601. # Only happens if user explicitly passes in both arguments
  602. raise ValueError("Cannot specify both `disable_exllama` and `use_exllama`. Please use just `use_exllama`")
  603. if self.exllama_config is None:
  604. self.exllama_config = {"version": ExllamaVersion.ONE}
  605. else:
  606. if "version" not in self.exllama_config:
  607. raise ValueError("`exllama_config` needs to have a `version` key.")
  608. elif self.exllama_config["version"] not in [ExllamaVersion.ONE, ExllamaVersion.TWO]:
  609. exllama_version = self.exllama_config["version"]
  610. raise ValueError(
  611. f"Only supported versions are in [ExllamaVersion.ONE, ExllamaVersion.TWO] - not recognized version {exllama_version}"
  612. )
  613. if self.bits == 4 and self.use_exllama:
  614. if self.exllama_config["version"] == ExllamaVersion.ONE:
  615. logger.info(
  616. "You have activated exllama backend. Note that you can get better inference "
  617. "speed using exllamav2 kernel by setting `exllama_config`."
  618. )
  619. elif self.exllama_config["version"] == ExllamaVersion.TWO:
  620. optimum_version = version.parse(importlib.metadata.version("optimum"))
  621. autogptq_version = version.parse(importlib.metadata.version("auto_gptq"))
  622. if optimum_version <= version.parse("1.13.2") or autogptq_version <= version.parse("0.4.2"):
  623. raise ValueError(
  624. f"You need optimum > 1.13.2 and auto-gptq > 0.4.2 . Make sure to have that version installed - detected version : optimum {optimum_version} and autogptq {autogptq_version}"
  625. )
  626. if self.modules_in_block_to_quantize is not None:
  627. optimum_version = version.parse(importlib.metadata.version("optimum"))
  628. if optimum_version < version.parse("1.15.0"):
  629. raise ValueError(
  630. "You current version of `optimum` does not support `modules_in_block_to_quantize` quantization argument, please upgrade `optimum` package to a version superior than 1.15.0 ."
  631. )
  632. def to_dict(self):
  633. config_dict = super().to_dict()
  634. config_dict.pop("disable_exllama", None)
  635. return config_dict
  636. def to_dict_optimum(self):
  637. """
  638. Get compatible dict for optimum gptq config
  639. """
  640. quant_dict = self.to_dict()
  641. # make it compatible with optimum config
  642. quant_dict["disable_exllama"] = not self.use_exllama
  643. return quant_dict
  644. @classmethod
  645. def from_dict_optimum(cls, config_dict):
  646. """
  647. Get compatible class with optimum gptq config dict
  648. """
  649. if "disable_exllama" in config_dict:
  650. config_dict["use_exllama"] = not config_dict["disable_exllama"]
  651. # switch to None to not trigger the warning
  652. config_dict["disable_exllama"] = None
  653. config = cls(**config_dict)
  654. return config
  655. @dataclass
  656. class AwqConfig(QuantizationConfigMixin):
  657. """
  658. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  659. loaded using `auto-awq` library awq quantization relying on auto_awq backend.
  660. Args:
  661. bits (`int`, *optional*, defaults to 4):
  662. The number of bits to quantize to.
  663. group_size (`int`, *optional*, defaults to 128):
  664. The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
  665. zero_point (`bool`, *optional*, defaults to `True`):
  666. Whether to use zero point quantization.
  667. version (`AWQLinearVersion`, *optional*, defaults to `AWQLinearVersion.GEMM`):
  668. The version of the quantization algorithm to use. GEMM is better for big batch_size (e.g. >= 8) otherwise,
  669. GEMV is better (e.g. < 8 ). GEMM models are compatible with Exllama kernels.
  670. backend (`AwqBackendPackingMethod`, *optional*, defaults to `AwqBackendPackingMethod.AUTOAWQ`):
  671. The quantization backend. Some models might be quantized using `llm-awq` backend. This is useful for users
  672. that quantize their own models using `llm-awq` library.
  673. do_fuse (`bool`, *optional*, defaults to `False`):
  674. Whether to fuse attention and mlp layers together for faster inference
  675. fuse_max_seq_len (`int`, *optional*):
  676. The Maximum sequence length to generate when using fusing.
  677. modules_to_fuse (`dict`, *optional*, default to `None`):
  678. Overwrite the natively supported fusing scheme with the one specified by the users.
  679. modules_to_not_convert (`list`, *optional*, default to `None`):
  680. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  681. some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
  682. Note you cannot quantize directly with transformers, please refer to `AutoAWQ` documentation for quantizing HF models.
  683. exllama_config (`Dict[str, Any]`, *optional*):
  684. You can specify the version of the exllama kernel through the `version` key, the maximum sequence
  685. length through the `max_input_len` key, and the maximum batch size through the `max_batch_size` key.
  686. Defaults to `{"version": 2, "max_input_len": 2048, "max_batch_size": 8}` if unset.
  687. """
  688. def __init__(
  689. self,
  690. bits: int = 4,
  691. group_size: int = 128,
  692. zero_point: bool = True,
  693. version: AWQLinearVersion = AWQLinearVersion.GEMM,
  694. backend: AwqBackendPackingMethod = AwqBackendPackingMethod.AUTOAWQ,
  695. do_fuse: Optional[bool] = None,
  696. fuse_max_seq_len: Optional[int] = None,
  697. modules_to_fuse: Optional[dict] = None,
  698. modules_to_not_convert: Optional[List] = None,
  699. exllama_config: Optional[Dict[str, int]] = None,
  700. **kwargs,
  701. ):
  702. self.quant_method = QuantizationMethod.AWQ
  703. self.bits = bits
  704. self.group_size = group_size
  705. self.zero_point = zero_point
  706. self.version = version
  707. self.backend = backend
  708. self.fuse_max_seq_len = fuse_max_seq_len
  709. self.modules_to_not_convert = modules_to_not_convert
  710. self.exllama_config = exllama_config
  711. self.modules_to_fuse = modules_to_fuse
  712. if do_fuse is None:
  713. self.do_fuse = modules_to_fuse is not None and len(modules_to_fuse) > 0
  714. else:
  715. self.do_fuse = do_fuse
  716. self.fuse_max_seq_len = fuse_max_seq_len
  717. self.post_init()
  718. def post_init(self):
  719. r"""
  720. Safety checker that arguments are correct
  721. """
  722. if self.backend not in [AwqBackendPackingMethod.AUTOAWQ, AwqBackendPackingMethod.LLMAWQ]:
  723. raise ValueError(
  724. f"Only supported quantization backends in {AwqBackendPackingMethod.AUTOAWQ} and {AwqBackendPackingMethod.LLMAWQ} - not recognized backend {self.backend}"
  725. )
  726. self.version = AWQLinearVersion.from_str(self.version)
  727. if self.version not in [
  728. AWQLinearVersion.GEMM,
  729. AWQLinearVersion.GEMV,
  730. AWQLinearVersion.EXLLAMA,
  731. AWQLinearVersion.IPEX,
  732. ]:
  733. raise ValueError(
  734. f"Only supported versions are in [AWQLinearVersion.GEMM, AWQLinearVersion.GEMV, AWQLinearVersion.EXLLAMA, AWQLinearVersion.IPEX] - not recognized version {self.version}"
  735. )
  736. if self.backend == AwqBackendPackingMethod.LLMAWQ:
  737. compute_capability = torch.cuda.get_device_capability()
  738. major, minor = compute_capability
  739. if major < 8:
  740. raise ValueError("LLM-AWQ backend is only supported on GPUs with compute capability >= 8.0")
  741. if self.do_fuse and self.fuse_max_seq_len is None:
  742. raise ValueError(
  743. "You cannot enable fused modules without specifying a `fuse_max_seq_len`, make sure to pass a valid `fuse_max_seq_len` for your usecase"
  744. )
  745. if self.do_fuse:
  746. awq_version_supports_fusing = False
  747. MIN_AWQ_VERSION = "0.1.7"
  748. if is_auto_awq_available():
  749. awq_version_supports_fusing = version.parse(importlib.metadata.version("autoawq")) >= version.parse(
  750. MIN_AWQ_VERSION
  751. )
  752. if not awq_version_supports_fusing:
  753. raise ValueError(
  754. f"You current version of `autoawq` does not support module fusing, please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}."
  755. )
  756. if self.modules_to_not_convert is not None:
  757. awq_version_supports_non_conversion = False
  758. MIN_AWQ_VERSION = "0.1.8"
  759. if is_auto_awq_available():
  760. awq_version_supports_non_conversion = version.parse(
  761. importlib.metadata.version("autoawq")
  762. ) >= version.parse(MIN_AWQ_VERSION)
  763. if not awq_version_supports_non_conversion:
  764. raise ValueError(
  765. f"You current version of `autoawq` does not support module quantization skipping, please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}."
  766. )
  767. if self.do_fuse and self.modules_to_fuse is not None:
  768. required_keys = [
  769. "hidden_size",
  770. "num_attention_heads",
  771. "num_key_value_heads",
  772. "mlp",
  773. "attention",
  774. "layernorm",
  775. "use_alibi",
  776. ]
  777. if not all(key in self.modules_to_fuse for key in required_keys):
  778. raise ValueError(
  779. f"Required fields are missing in the fusing mapping, required fields are {required_keys}"
  780. )
  781. if self.version == AWQLinearVersion.EXLLAMA:
  782. awq_version_supports_exllama = False
  783. MIN_AWQ_VERSION = "0.2.0"
  784. if is_auto_awq_available():
  785. awq_version_supports_exllama = version.parse(importlib.metadata.version("autoawq")) >= version.parse(
  786. MIN_AWQ_VERSION
  787. )
  788. if not awq_version_supports_exllama:
  789. raise ValueError(
  790. f"You current version of `autoawq` does not support exllama backend, "
  791. f"please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}."
  792. )
  793. if self.exllama_config is None:
  794. self.exllama_config = {"version": ExllamaVersion.TWO, "max_input_len": 2048, "max_batch_size": 8}
  795. else:
  796. if "version" not in self.exllama_config:
  797. raise ValueError("`exllama_config` needs to have a `version` key.")
  798. elif self.exllama_config["version"] not in [ExllamaVersion.ONE, ExllamaVersion.TWO]:
  799. exllama_version = self.exllama_config["version"]
  800. raise ValueError(
  801. f"Only supported versions are in [ExllamaVersion.ONE, ExllamaVersion.TWO] - not recognized version {exllama_version}"
  802. )
  803. def get_loading_attributes(self):
  804. attibutes_dict = copy.deepcopy(self.__dict__)
  805. loading_attibutes = ["version", "do_fuse", "modules_to_fuse", "fuse_max_seq_len", "exllama_config"]
  806. loading_attibutes_dict = {i: j for i, j in attibutes_dict.items() if i in loading_attibutes}
  807. return loading_attibutes_dict
  808. @dataclass
  809. class AqlmConfig(QuantizationConfigMixin):
  810. """
  811. This is a wrapper class about `aqlm` parameters.
  812. Args:
  813. in_group_size (`int`, *optional*, defaults to 8):
  814. The group size along the input dimension.
  815. out_group_size (`int`, *optional*, defaults to 1):
  816. The group size along the output dimension. It's recommended to always use 1.
  817. num_codebooks (`int`, *optional*, defaults to 1):
  818. Number of codebooks for the Additive Quantization procedure.
  819. nbits_per_codebook (`int`, *optional*, defaults to 16):
  820. Number of bits encoding a single codebook vector. Codebooks size is 2**nbits_per_codebook.
  821. linear_weights_not_to_quantize (`Optional[List[str]]`, *optional*):
  822. List of full paths of `nn.Linear` weight parameters that shall not be quantized.
  823. kwargs (`Dict[str, Any]`, *optional*):
  824. Additional parameters from which to initialize the configuration object.
  825. """
  826. def __init__(
  827. self,
  828. in_group_size: int = 8,
  829. out_group_size: int = 1,
  830. num_codebooks: int = 1,
  831. nbits_per_codebook: int = 16,
  832. linear_weights_not_to_quantize: Optional[List[str]] = None,
  833. **kwargs,
  834. ):
  835. self.quant_method = QuantizationMethod.AQLM
  836. self.in_group_size = in_group_size
  837. self.out_group_size = out_group_size
  838. self.num_codebooks = num_codebooks
  839. self.nbits_per_codebook = nbits_per_codebook
  840. self.linear_weights_not_to_quantize = linear_weights_not_to_quantize
  841. self.post_init()
  842. def post_init(self):
  843. r"""
  844. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  845. """
  846. if not isinstance(self.in_group_size, int):
  847. raise TypeError("in_group_size must be a float")
  848. if not isinstance(self.out_group_size, int):
  849. raise TypeError("out_group_size must be a float")
  850. if not isinstance(self.num_codebooks, int):
  851. raise TypeError("num_codebooks must be a float")
  852. if not isinstance(self.nbits_per_codebook, int):
  853. raise TypeError("nbits_per_codebook must be a float")
  854. if self.linear_weights_not_to_quantize is not None and not isinstance(
  855. self.linear_weights_not_to_quantize, list
  856. ):
  857. raise ValueError("linear_weights_not_to_quantize must be a list of strings")
  858. if self.linear_weights_not_to_quantize is None:
  859. self.linear_weights_not_to_quantize = []
  860. @dataclass
  861. class QuantoConfig(QuantizationConfigMixin):
  862. """
  863. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  864. loaded using `quanto`.
  865. Args:
  866. weights (`str`, *optional*, defaults to `"int8"`):
  867. The target dtype for the weights after quantization. Supported values are ("float8","int8","int4","int2")
  868. activations (`str`, *optional*):
  869. The target dtype for the activations after quantization. Supported values are (None,"int8","float8")
  870. modules_to_not_convert (`list`, *optional*, default to `None`):
  871. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  872. some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
  873. """
  874. def __init__(
  875. self,
  876. weights="int8",
  877. activations=None,
  878. modules_to_not_convert: Optional[List] = None,
  879. **kwargs,
  880. ):
  881. self.quant_method = QuantizationMethod.QUANTO
  882. self.weights = weights
  883. self.activations = activations
  884. self.modules_to_not_convert = modules_to_not_convert
  885. self.post_init()
  886. def post_init(self):
  887. r"""
  888. Safety checker that arguments are correct
  889. """
  890. accepted_weights = ["float8", "int8", "int4", "int2"]
  891. accepted_activations = [None, "int8", "float8"]
  892. if self.weights not in accepted_weights:
  893. raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
  894. if self.activations not in accepted_activations:
  895. raise ValueError(f"Only support weights in {accepted_activations} but found {self.activations}")
  896. @dataclass
  897. class EetqConfig(QuantizationConfigMixin):
  898. """
  899. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  900. loaded using `eetq`.
  901. Args:
  902. weights (`str`, *optional*, defaults to `"int8"`):
  903. The target dtype for the weights. Supported value is only "int8"
  904. modules_to_not_convert (`list`, *optional*, default to `None`):
  905. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  906. some modules left in their original precision.
  907. """
  908. def __init__(
  909. self,
  910. weights: str = "int8",
  911. modules_to_not_convert: Optional[List] = None,
  912. **kwargs,
  913. ):
  914. self.quant_method = QuantizationMethod.EETQ
  915. self.weights = weights
  916. self.modules_to_not_convert = modules_to_not_convert
  917. self.post_init()
  918. def post_init(self):
  919. r"""
  920. Safety checker that arguments are correct
  921. """
  922. accepted_weights = ["int8"]
  923. if self.weights not in accepted_weights:
  924. raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
  925. class CompressedTensorsConfig(QuantizationConfigMixin):
  926. """
  927. This is a wrapper class that handles compressed-tensors quantization config options.
  928. It is a wrapper around `compressed_tensors.QuantizationConfig`
  929. Args:
  930. config_groups (`typing.Dict[str, typing.Union[ForwardRef('QuantizationScheme'), typing.List[str]]]`, *optional*):
  931. dictionary mapping group name to a quantization scheme definition
  932. format (`str`, *optional*, defaults to `"dense"`):
  933. format the model is represented as
  934. quantization_status (`QuantizationStatus`, *optional*, defaults to `"initialized"`):
  935. status of model in the quantization lifecycle, ie 'initialized', 'calibration', 'frozen'
  936. kv_cache_scheme (`typing.Union[QuantizationArgs, NoneType]`, *optional*):
  937. specifies quantization of the kv cache. If None, kv cache is not quantized.
  938. global_compression_ratio (`typing.Union[float, NoneType]`, *optional*):
  939. 0-1 float percentage of model compression
  940. ignore (`typing.Union[typing.List[str], NoneType]`, *optional*):
  941. layer names or types to not quantize, supports regex prefixed by 're:'
  942. sparsity_config (`typing.Dict[str, typing.Any]`, *optional*):
  943. configuration for sparsity compression
  944. quant_method (`str`, *optional*, defaults to `"compressed-tensors"`):
  945. do not override, should be compressed-tensors
  946. """
  947. def __init__(
  948. self,
  949. config_groups: Dict[str, Union["QuantizationScheme", List[str]]] = None, # noqa: F821
  950. format: str = "dense",
  951. quantization_status: "QuantizationStatus" = "initialized", # noqa: F821
  952. kv_cache_scheme: Optional["QuantizationArgs"] = None, # noqa: F821
  953. global_compression_ratio: Optional[float] = None,
  954. ignore: Optional[List[str]] = None,
  955. sparsity_config: Dict[str, Any] = None,
  956. quant_method: str = "compressed-tensors",
  957. **kwargs,
  958. ):
  959. from compressed_tensors import QuantizationConfig
  960. from compressed_tensors.config import SparsityCompressionConfig
  961. self.quantization_config = None
  962. self.sparsity_config = None
  963. # parse from dict to load nested QuantizationScheme objects
  964. if config_groups or kv_cache_scheme:
  965. self.quantization_config = QuantizationConfig.parse_obj(
  966. {
  967. "config_groups": config_groups,
  968. "quant_method": quant_method,
  969. "format": format,
  970. "quantization_status": quantization_status,
  971. "kv_cache_scheme": kv_cache_scheme,
  972. "global_compression_ratio": global_compression_ratio,
  973. "ignore": ignore,
  974. **kwargs,
  975. }
  976. )
  977. if sparsity_config:
  978. self.sparsity_config = SparsityCompressionConfig.load_from_registry(
  979. sparsity_config.get("format"), **sparsity_config
  980. )
  981. super().__init__(quant_method=QuantizationMethod.COMPRESSED_TENSORS)
  982. @classmethod
  983. def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
  984. """
  985. Instantiates a [`CompressedTensorsConfig`] from a Python dictionary of parameters.
  986. Optionally unwraps any args from the nested quantization_config
  987. Args:
  988. config_dict (`Dict[str, Any]`):
  989. Dictionary that will be used to instantiate the configuration object.
  990. return_unused_kwargs (`bool`,*optional*, defaults to `False`):
  991. Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
  992. `PreTrainedModel`.
  993. kwargs (`Dict[str, Any]`):
  994. Additional parameters from which to initialize the configuration object.
  995. Returns:
  996. [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
  997. """
  998. if "quantization_config" in config_dict:
  999. config_dict = dict(
  1000. sparsity_config=config_dict.get("sparsity_config"),
  1001. **config_dict["quantization_config"],
  1002. )
  1003. return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs)
  1004. def to_dict(self) -> Dict[str, Any]:
  1005. """
  1006. Serializes this instance to a Python dictionary. Returns:
  1007. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  1008. """
  1009. quantization_config = self.quantization_config.dict() if self.quantization_config is not None else None
  1010. sparsity_config = self.sparsity_config.dict() if self.sparsity_config is not None else None
  1011. return {
  1012. "quantization_config": quantization_config,
  1013. "sparsity_config": sparsity_config,
  1014. }
  1015. def to_diff_dict(self) -> Dict[str, Any]:
  1016. """
  1017. Removes all attributes from config which correspond to the default config attributes for better readability and
  1018. serializes to a Python dictionary.
  1019. Returns:
  1020. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
  1021. """
  1022. config_dict = self.to_dict()
  1023. # get the default config dict
  1024. default_config_dict = CompressedTensorsConfig().to_dict()
  1025. serializable_config_dict = {}
  1026. # only serialize values that differ from the default config
  1027. for key, value in config_dict.items():
  1028. if value != default_config_dict[key]:
  1029. serializable_config_dict[key] = value
  1030. return serializable_config_dict
  1031. @dataclass
  1032. class FbgemmFp8Config(QuantizationConfigMixin):
  1033. """
  1034. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  1035. loaded using fbgemm fp8 quantization.
  1036. Args:
  1037. activation_scale_ub (`float`, *optional*, defaults to 1200.0):
  1038. The activation scale upper bound. This is used when quantizing the input activation.
  1039. modules_to_not_convert (`list`, *optional*, default to `None`):
  1040. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  1041. some modules left in their original precision.
  1042. """
  1043. def __init__(
  1044. self,
  1045. activation_scale_ub: float = 1200.0,
  1046. modules_to_not_convert: Optional[List] = None,
  1047. **kwargs,
  1048. ):
  1049. self.quant_method = QuantizationMethod.FBGEMM_FP8
  1050. self.activation_scale_ub = activation_scale_ub
  1051. self.modules_to_not_convert = modules_to_not_convert
  1052. def get_loading_attributes(self):
  1053. attibutes_dict = copy.deepcopy(self.__dict__)
  1054. loading_attibutes = ["activation_scale_ub"]
  1055. loading_attibutes_dict = {i: j for i, j in attibutes_dict.items() if i in loading_attibutes}
  1056. return loading_attibutes_dict
  1057. @dataclass
  1058. class TorchAoConfig(QuantizationConfigMixin):
  1059. """This is a config class for torchao quantization/sparsity techniques.
  1060. Args:
  1061. quant_type (`str`):
  1062. The type of quantization we want to use, currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.
  1063. modules_to_not_convert (`list`, *optional*, default to `None`):
  1064. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  1065. some modules left in their original precision.
  1066. kwargs (`Dict[str, Any]`, *optional*):
  1067. The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments
  1068. `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in
  1069. https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques
  1070. Example:
  1071. ```python
  1072. quantization_config = TorchAoConfig("int4_weight_only", group_size=32)
  1073. # int4_weight_only quant is only working with *torch.bfloat16* dtype right now
  1074. model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
  1075. ```
  1076. """
  1077. def __init__(self, quant_type: str, modules_to_not_convert: Optional[List] = None, **kwargs):
  1078. self.quant_method = QuantizationMethod.TORCHAO
  1079. self.quant_type = quant_type
  1080. self.modules_to_not_convert = modules_to_not_convert
  1081. # when we load from serailized config, "quant_type_kwargs" will be the key
  1082. if "quant_type_kwargs" in kwargs:
  1083. self.quant_type_kwargs = kwargs["quant_type_kwargs"]
  1084. else:
  1085. self.quant_type_kwargs = kwargs
  1086. self.post_init()
  1087. def post_init(self):
  1088. r"""
  1089. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  1090. """
  1091. if not version.parse(importlib.metadata.version("torchao")) >= version.parse("0.4.0"):
  1092. raise ValueError("Requires torchao 0.4.0 version and above")
  1093. _STR_TO_METHOD = self._get_torchao_quant_type_to_method()
  1094. if self.quant_type not in _STR_TO_METHOD.keys():
  1095. raise ValueError(
  1096. f"Requested quantization type: {self.quant_type} is not supported yet, please add support in TorchAoConfig and TorchAoHfQuantizer."
  1097. )
  1098. method = _STR_TO_METHOD[self.quant_type]
  1099. sig = signature(method)
  1100. all_kwargs = [
  1101. param.name
  1102. for param in sig.parameters.values()
  1103. if param.kind in [Parameter.KEYWORD_ONLY, Parameter.POSITIONAL_OR_KEYWORD]
  1104. ]
  1105. for k in self.quant_type_kwargs:
  1106. if k not in all_kwargs:
  1107. raise ValueError(
  1108. f"Unexpected keyword arg: {k} for API: {method}, accepted keyword args are: {all_kwargs}"
  1109. )
  1110. def _get_torchao_quant_type_to_method(self):
  1111. if is_torchao_available():
  1112. from torchao.quantization import (
  1113. int4_weight_only,
  1114. int8_dynamic_activation_int8_weight,
  1115. int8_weight_only,
  1116. )
  1117. return {
  1118. "int4_weight_only": int4_weight_only,
  1119. "int8_weight_only": int8_weight_only,
  1120. "int8_dynamic_activation_int8_weight": int8_dynamic_activation_int8_weight,
  1121. }
  1122. else:
  1123. raise ValueError(
  1124. "TorchAoConfig requires torchao to be installed, please install with `pip install torchao`"
  1125. )
  1126. def get_apply_tensor_subclass(self):
  1127. _STR_TO_METHOD = self._get_torchao_quant_type_to_method()
  1128. return _STR_TO_METHOD[self.quant_type](**self.quant_type_kwargs)
  1129. def __repr__(self):
  1130. return f"{self.quant_type}({', '.join(str(k) + '=' + str(v) for k, v in self.kwargs.items())})"
  1131. @dataclass
  1132. class BitNetConfig(QuantizationConfigMixin):
  1133. def __init__(
  1134. self,
  1135. modules_to_not_convert: Optional[List] = None,
  1136. **kwargs,
  1137. ):
  1138. self.quant_method = QuantizationMethod.BITNET
  1139. self.modules_to_not_convert = modules_to_not_convert
  1140. self.post_init()
  1141. def post_init(self):
  1142. r"""
  1143. Safety checker that arguments are correct
  1144. """
  1145. pass