quantization_config.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990
  1. #!/usr/bin/env python
  2. # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
  3. # Modifications Copyright (C) 2025, Advanced Micro Devices, Inc. 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 typing import Any, Optional, Union
  23. from packaging import version
  24. from ..utils import (
  25. is_compressed_tensors_available,
  26. is_hqq_available,
  27. is_quark_available,
  28. is_torch_available,
  29. is_torchao_available,
  30. logging,
  31. )
  32. if is_torch_available():
  33. import torch
  34. logger = logging.get_logger(__name__)
  35. class QuantizationMethod(str, Enum):
  36. BITS_AND_BYTES = "bitsandbytes"
  37. GPTQ = "gptq"
  38. AWQ = "awq"
  39. AQLM = "aqlm"
  40. VPTQ = "vptq"
  41. QUANTO = "quanto"
  42. EETQ = "eetq"
  43. HIGGS = "higgs"
  44. HQQ = "hqq"
  45. COMPRESSED_TENSORS = "compressed-tensors"
  46. FBGEMM_FP8 = "fbgemm_fp8"
  47. TORCHAO = "torchao"
  48. BITNET = "bitnet"
  49. SPQR = "spqr"
  50. FP8 = "fp8"
  51. QUARK = "quark"
  52. FPQUANT = "fp_quant"
  53. AUTOROUND = "auto-round"
  54. MXFP4 = "mxfp4"
  55. METAL = "metal"
  56. FOUR_OVER_SIX = "fouroversix"
  57. SINQ = "sinq"
  58. class AwqFormat(str, Enum):
  59. GEMM = "gemm"
  60. GEMV = "gemv"
  61. GEMV_FAST = "gemv_fast"
  62. LLM_AWQ = "llm-awq"
  63. class AwqBackend(str, Enum):
  64. LEGACY_AWQ = "autoawq"
  65. AUTO = "auto"
  66. AUTO_TRAINABLE = "auto_trainable"
  67. MACHETE = "machete"
  68. MARLIN = "marlin"
  69. EXLLAMA_V2 = "exllama_v2"
  70. EXLLAMA_V1 = "exllama_v1"
  71. GEMM = "gemm"
  72. GEMM_TRITON = "gemm_triton"
  73. GEMV = "gemv"
  74. GEMV_FAST = "gemv_fast"
  75. TORCH_AWQ = "torch_awq"
  76. TORCH_FUSED_AWQ = "torch_fused_awq"
  77. @dataclass
  78. class QuantizationConfigMixin:
  79. """
  80. Mixin class for quantization config
  81. """
  82. quant_method: QuantizationMethod
  83. @classmethod
  84. def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
  85. """
  86. Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters.
  87. Args:
  88. config_dict (`dict[str, Any]`):
  89. Dictionary that will be used to instantiate the configuration object.
  90. return_unused_kwargs (`bool`,*optional*, defaults to `False`):
  91. Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
  92. `PreTrainedModel`.
  93. kwargs (`dict[str, Any]`):
  94. Additional parameters from which to initialize the configuration object.
  95. Returns:
  96. [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
  97. """
  98. config = cls(**config_dict)
  99. to_remove = []
  100. for key, value in kwargs.items():
  101. if hasattr(config, key):
  102. setattr(config, key, value)
  103. to_remove.append(key)
  104. for key in to_remove:
  105. kwargs.pop(key, None)
  106. if return_unused_kwargs:
  107. return config, kwargs
  108. else:
  109. return config
  110. def to_json_file(self, json_file_path: str | os.PathLike):
  111. """
  112. Save this instance to a JSON file.
  113. Args:
  114. json_file_path (`str` or `os.PathLike`):
  115. Path to the JSON file in which this configuration instance's parameters will be saved.
  116. use_diff (`bool`, *optional*, defaults to `True`):
  117. If set to `True`, only the difference between the config instance and the default
  118. `QuantizationConfig()` is serialized to JSON file.
  119. """
  120. with open(json_file_path, "w", encoding="utf-8") as writer:
  121. config_dict = self.to_dict()
  122. json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
  123. writer.write(json_string)
  124. def to_dict(self) -> dict[str, Any]:
  125. """
  126. Serializes this instance to a Python dictionary. Returns:
  127. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  128. """
  129. return copy.deepcopy(self.__dict__)
  130. def __iter__(self):
  131. """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin"""
  132. yield from copy.deepcopy(self.__dict__).items()
  133. def __repr__(self):
  134. return f"{self.__class__.__name__} {self.to_json_string()}"
  135. def to_diff_dict(self) -> dict[str, Any]:
  136. """
  137. Default behavior: no diffing implemented for this config.
  138. """
  139. return self.to_dict()
  140. def to_json_string(self, use_diff: bool = True) -> str:
  141. """
  142. Serializes this instance to a JSON string.
  143. Args:
  144. use_diff (`bool`, *optional*, defaults to `True`):
  145. If set to `True`, only the difference between the config instance and the default `PreTrainedConfig()`
  146. is serialized to JSON string.
  147. Returns:
  148. `str`: String containing all the attributes that make up this configuration instance in JSON format.
  149. """
  150. config_dict = self.to_diff_dict() if use_diff else self.to_dict()
  151. return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
  152. def update(self, **kwargs):
  153. """
  154. Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
  155. returning all the unused kwargs.
  156. Args:
  157. kwargs (`dict[str, Any]`):
  158. Dictionary of attributes to tentatively update this class.
  159. Returns:
  160. `dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
  161. """
  162. to_remove = []
  163. for key, value in kwargs.items():
  164. if hasattr(self, key):
  165. setattr(self, key, value)
  166. to_remove.append(key)
  167. # Remove all the attributes that were updated, without modifying the input dict
  168. unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
  169. return unused_kwargs
  170. @dataclass
  171. class AutoRoundConfig(QuantizationConfigMixin):
  172. """This is a wrapper class about all possible attributes and features that you can play with a model that has been
  173. loaded AutoRound quantization.
  174. Args:
  175. bits (`int`, *optional*, defaults to 4):
  176. The number of bits to quantize to, supported numbers are (2, 3, 4, 8).
  177. group_size (`int`, *optional*, defaults to 128): Group-size value
  178. sym (`bool`, *optional*, defaults to `True`): Symmetric quantization or not
  179. backend (`str`, *optional*, defaults to `"auto"`): The kernel to use, e.g., ipex,marlin, exllamav2, triton, etc. Ref. https://github.com/intel/auto-round?tab=readme-ov-file#specify-backend
  180. """
  181. def __init__(
  182. self,
  183. bits: int = 4,
  184. group_size: int = 128,
  185. sym: bool = True,
  186. backend: str = "auto",
  187. **kwargs,
  188. ):
  189. self.bits = bits
  190. self.group_size = group_size
  191. self.sym = sym
  192. self.backend = backend
  193. self.packing_format = "auto_round:gptq"
  194. if kwargs is not None:
  195. for key, value in kwargs.items():
  196. setattr(self, key, value)
  197. self.quant_method = QuantizationMethod.AUTOROUND
  198. self.post_init()
  199. def post_init(self):
  200. r"""Safety checker that arguments are correct."""
  201. if self.bits not in [2, 3, 4, 8]:
  202. raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}")
  203. if self.group_size != -1 and self.group_size <= 0:
  204. raise ValueError("group_size must be greater than 0 or equal to -1")
  205. def get_loading_attributes(self):
  206. loading_attributes_dict = {"backend": self.backend}
  207. return loading_attributes_dict
  208. def to_dict(self):
  209. config_dict = super().to_dict()
  210. return config_dict
  211. @classmethod
  212. def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
  213. quant_method = config_dict["quant_method"]
  214. if "auto-round" not in quant_method and "gptq" not in quant_method and "awq" not in quant_method:
  215. raise NotImplementedError(
  216. "Failed to convert to auto_round format. Only `gptqv1`, `awq`, and `auto-round` formats are supported."
  217. )
  218. if "gptq" in quant_method and "meta" in config_dict:
  219. raise NotImplementedError("Failed to convert gptq format to auto_round format. Only supports `gptqv1`")
  220. if "awq" in quant_method and config_dict.get("version", "gemm") != "gemm":
  221. raise NotImplementedError(
  222. "Failed to convert awq format to auto_round format. Only supports awq format with gemm version"
  223. )
  224. if "auto-round" not in quant_method:
  225. config_dict["packing_format"] = f"auto_round:{quant_method}"
  226. return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs)
  227. @dataclass
  228. class HqqConfig(QuantizationConfigMixin):
  229. """
  230. This is wrapper around hqq's BaseQuantizeConfig.
  231. Args:
  232. nbits (`int`, *optional*, defaults to 4):
  233. Number of bits. Supported values are (8, 4, 3, 2, 1).
  234. group_size (`int`, *optional*, defaults to 64):
  235. Group-size value. Supported values are any value that is divisible by weight.shape[axis]).
  236. view_as_float (`bool`, *optional*, defaults to `False`):
  237. View the quantized weight as float (used in distributed training) if set to `True`.
  238. axis (`Optional[int]`, *optional*):
  239. Axis along which grouping is performed. Supported values are 0 or 1.
  240. dynamic_config (dict, *optional*):
  241. Parameters for dynamic configuration. The key is the name tag of the layer and the value is a quantization config.
  242. If set, each layer specified by its id will use its dedicated quantization configuration.
  243. skip_modules (`list[str]`, *optional*, defaults to `['lm_head']`):
  244. List of `nn.Linear` layers to skip.
  245. kwargs (`dict[str, Any]`, *optional*):
  246. Additional parameters from which to initialize the configuration object.
  247. """
  248. def __init__(
  249. self,
  250. nbits: int = 4,
  251. group_size: int = 64,
  252. view_as_float: bool = False,
  253. axis: int | None = None,
  254. dynamic_config: dict | None = None,
  255. skip_modules: list[str] = ["lm_head"],
  256. **kwargs,
  257. ):
  258. if is_hqq_available():
  259. from hqq.core.quantize import BaseQuantizeConfig as HQQBaseQuantizeConfig
  260. else:
  261. raise ImportError(
  262. "A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`."
  263. )
  264. if axis is None:
  265. axis = 1
  266. logger.info("Setting axis=1 as faster backends such as TorchAO or BitBlas are only compatible with it.")
  267. if axis not in [0, 1]:
  268. raise ValueError("Invalid axis value. Only 0 and 1 are allowed.")
  269. if dynamic_config is not None:
  270. self.quant_config = {}
  271. for key in dynamic_config:
  272. self.quant_config[key] = HQQBaseQuantizeConfig(**dynamic_config[key])
  273. else:
  274. self.quant_config = HQQBaseQuantizeConfig(
  275. nbits=nbits, group_size=group_size, view_as_float=view_as_float, axis=axis
  276. )
  277. self.quant_method = QuantizationMethod.HQQ
  278. self.skip_modules = skip_modules
  279. self.post_init()
  280. def post_init(self):
  281. r"""
  282. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  283. """
  284. @classmethod
  285. def from_dict(cls, config: dict[str, Any]):
  286. """
  287. Override from_dict, used in AutoQuantizationConfig.from_dict in quantizers/auto.py
  288. """
  289. instance = cls()
  290. instance.quant_config = config["quant_config"]
  291. instance.skip_modules = config["skip_modules"]
  292. return instance
  293. def to_dict(self) -> dict[str, Any]:
  294. """
  295. Serializes this instance to a Python dictionary. Returns:
  296. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  297. """
  298. return {
  299. "quant_config": self.quant_config,
  300. "quant_method": self.quant_method,
  301. "skip_modules": self.skip_modules,
  302. }
  303. def __repr__(self):
  304. config_dict = self.to_dict()
  305. return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
  306. def to_diff_dict(self) -> dict[str, Any]:
  307. """
  308. Removes all attributes from config which correspond to the default config attributes for better readability and
  309. serializes to a Python dictionary.
  310. Returns:
  311. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
  312. """
  313. config_dict = self.to_dict()
  314. # get the default config dict
  315. default_config_dict = HqqConfig().to_dict()
  316. serializable_config_dict = {}
  317. # only serialize values that differ from the default config
  318. for key, value in config_dict.items():
  319. if value != default_config_dict[key]:
  320. serializable_config_dict[key] = value
  321. return serializable_config_dict
  322. @dataclass
  323. class BitsAndBytesConfig(QuantizationConfigMixin):
  324. """
  325. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  326. loaded using `bitsandbytes`.
  327. Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`,
  328. then more arguments will be added to this class.
  329. Args:
  330. load_in_8bit (`bool`, *optional*, defaults to `False`):
  331. This flag is used to enable 8-bit quantization with LLM.int8().
  332. load_in_4bit (`bool`, *optional*, defaults to `False`):
  333. This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from
  334. `bitsandbytes`.
  335. llm_int8_threshold (`float`, *optional*, defaults to 6.0):
  336. This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix
  337. Multiplication for Transformers at Scale` paper: https://huggingface.co/papers/2208.07339 Any hidden states value
  338. that is above this threshold will be considered an outlier and the operation on those values will be done
  339. in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5], but
  340. there are some exceptional systematic outliers that are very differently distributed for large models.
  341. These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of
  342. magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6,
  343. but a lower threshold might be needed for more unstable models (small models, fine-tuning).
  344. llm_int8_skip_modules (`list[str]`, *optional*):
  345. An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as
  346. Jukebox that has several heads in different places and not necessarily at the last position. For example
  347. for `CausalLM` models, the last `lm_head` is kept in its original `dtype`.
  348. llm_int8_enable_fp32_cpu_offload (`bool`, *optional*, defaults to `False`):
  349. This flag is used for advanced use cases and users that are aware of this feature. If you want to split
  350. your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use
  351. this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8
  352. operations will not be run on CPU.
  353. llm_int8_has_fp16_weight (`bool`, *optional*, defaults to `False`):
  354. This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not
  355. have to be converted back and forth for the backward pass.
  356. bnb_4bit_compute_dtype (`torch.dtype` or str, *optional*, defaults to `torch.float32`):
  357. This sets the computational type which might be different than the input type. For example, inputs might be
  358. fp32, but computation can be set to bf16 for speedups.
  359. bnb_4bit_quant_type (`str`, *optional*, defaults to `"fp4"`):
  360. This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types
  361. which are specified by `fp4` or `nf4`.
  362. bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`):
  363. This flag is used for nested quantization where the quantization constants from the first quantization are
  364. quantized again.
  365. bnb_4bit_quant_storage (`torch.dtype` or str, *optional*, defaults to `torch.uint8`):
  366. This sets the storage type to pack the quantized 4-bit params.
  367. kwargs (`dict[str, Any]`, *optional*):
  368. Additional parameters from which to initialize the configuration object.
  369. """
  370. def __init__(
  371. self,
  372. load_in_8bit=False,
  373. load_in_4bit=False,
  374. llm_int8_threshold=6.0,
  375. llm_int8_skip_modules=None,
  376. llm_int8_enable_fp32_cpu_offload=False,
  377. llm_int8_has_fp16_weight=False,
  378. bnb_4bit_compute_dtype=None,
  379. bnb_4bit_quant_type="fp4",
  380. bnb_4bit_use_double_quant=False,
  381. bnb_4bit_quant_storage=None,
  382. **kwargs,
  383. ):
  384. self.quant_method = QuantizationMethod.BITS_AND_BYTES
  385. if load_in_4bit and load_in_8bit:
  386. raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
  387. self._load_in_8bit = load_in_8bit
  388. self._load_in_4bit = load_in_4bit
  389. self.llm_int8_threshold = llm_int8_threshold
  390. self.llm_int8_skip_modules = llm_int8_skip_modules
  391. self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload
  392. self.llm_int8_has_fp16_weight = llm_int8_has_fp16_weight
  393. self.bnb_4bit_quant_type = bnb_4bit_quant_type
  394. self.bnb_4bit_use_double_quant = bnb_4bit_use_double_quant
  395. if bnb_4bit_compute_dtype is None:
  396. self.bnb_4bit_compute_dtype = torch.float32
  397. elif isinstance(bnb_4bit_compute_dtype, str):
  398. self.bnb_4bit_compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
  399. elif isinstance(bnb_4bit_compute_dtype, torch.dtype):
  400. self.bnb_4bit_compute_dtype = bnb_4bit_compute_dtype
  401. else:
  402. raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype")
  403. if bnb_4bit_quant_storage is None:
  404. self.bnb_4bit_quant_storage = torch.uint8
  405. elif isinstance(bnb_4bit_quant_storage, str):
  406. if bnb_4bit_quant_storage not in ["float16", "float32", "int8", "uint8", "float64", "bfloat16"]:
  407. raise ValueError(
  408. "`bnb_4bit_quant_storage` must be a valid string (one of 'float16', 'float32', 'int8', 'uint8', 'float64', 'bfloat16') "
  409. )
  410. self.bnb_4bit_quant_storage = getattr(torch, bnb_4bit_quant_storage)
  411. elif isinstance(bnb_4bit_quant_storage, torch.dtype):
  412. self.bnb_4bit_quant_storage = bnb_4bit_quant_storage
  413. else:
  414. raise ValueError("bnb_4bit_quant_storage must be a string or a torch.dtype")
  415. if kwargs:
  416. logger.info(f"Unused kwargs: {list(kwargs.keys())}. These kwargs are not used in {self.__class__}.")
  417. self.post_init()
  418. @property
  419. def load_in_4bit(self):
  420. return self._load_in_4bit
  421. @load_in_4bit.setter
  422. def load_in_4bit(self, value: bool):
  423. if not isinstance(value, bool):
  424. raise TypeError("load_in_4bit must be a boolean")
  425. if self.load_in_8bit and value:
  426. raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
  427. self._load_in_4bit = value
  428. @property
  429. def load_in_8bit(self):
  430. return self._load_in_8bit
  431. @load_in_8bit.setter
  432. def load_in_8bit(self, value: bool):
  433. if not isinstance(value, bool):
  434. raise TypeError("load_in_8bit must be a boolean")
  435. if self.load_in_4bit and value:
  436. raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
  437. self._load_in_8bit = value
  438. def post_init(self):
  439. r"""
  440. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  441. """
  442. if not isinstance(self.load_in_4bit, bool):
  443. raise TypeError("load_in_4bit must be a boolean")
  444. if not isinstance(self.load_in_8bit, bool):
  445. raise TypeError("load_in_8bit must be a boolean")
  446. if not isinstance(self.llm_int8_threshold, float):
  447. raise TypeError("llm_int8_threshold must be a float")
  448. if self.llm_int8_skip_modules is not None and not isinstance(self.llm_int8_skip_modules, list):
  449. raise TypeError("llm_int8_skip_modules must be a list of strings")
  450. if not isinstance(self.llm_int8_enable_fp32_cpu_offload, bool):
  451. raise TypeError("llm_int8_enable_fp32_cpu_offload must be a boolean")
  452. if not isinstance(self.llm_int8_has_fp16_weight, bool):
  453. raise TypeError("llm_int8_has_fp16_weight must be a boolean")
  454. if self.bnb_4bit_compute_dtype is not None and not isinstance(self.bnb_4bit_compute_dtype, torch.dtype):
  455. raise TypeError("bnb_4bit_compute_dtype must be torch.dtype")
  456. if not isinstance(self.bnb_4bit_quant_type, str):
  457. raise TypeError("bnb_4bit_quant_type must be a string")
  458. if not isinstance(self.bnb_4bit_use_double_quant, bool):
  459. raise TypeError("bnb_4bit_use_double_quant must be a boolean")
  460. def is_quantizable(self):
  461. r"""
  462. Returns `True` if the model is quantizable, `False` otherwise.
  463. """
  464. return self.load_in_8bit or self.load_in_4bit
  465. def quantization_method(self):
  466. r"""
  467. This method returns the quantization method used for the model. If the model is not quantizable, it returns
  468. `None`.
  469. """
  470. if self.load_in_8bit:
  471. return "llm_int8"
  472. elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4":
  473. return "fp4"
  474. elif self.load_in_4bit and self.bnb_4bit_quant_type == "nf4":
  475. return "nf4"
  476. else:
  477. return None
  478. def to_dict(self) -> dict[str, Any]:
  479. """
  480. Serializes this instance to a Python dictionary. Returns:
  481. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  482. """
  483. output = copy.deepcopy(self.__dict__)
  484. output["bnb_4bit_compute_dtype"] = str(output["bnb_4bit_compute_dtype"]).split(".")[1]
  485. output["bnb_4bit_quant_storage"] = str(output["bnb_4bit_quant_storage"]).split(".")[1]
  486. output["load_in_4bit"] = self.load_in_4bit
  487. output["load_in_8bit"] = self.load_in_8bit
  488. return output
  489. def __repr__(self):
  490. config_dict = self.to_dict()
  491. return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
  492. def to_diff_dict(self) -> dict[str, Any]:
  493. """
  494. Removes all attributes from config which correspond to the default config attributes for better readability and
  495. serializes to a Python dictionary.
  496. Returns:
  497. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
  498. """
  499. config_dict = self.to_dict()
  500. # get the default config dict
  501. default_config_dict = BitsAndBytesConfig().to_dict()
  502. serializable_config_dict = {}
  503. # only serialize values that differ from the default config
  504. for key, value in config_dict.items():
  505. if value != default_config_dict[key]:
  506. serializable_config_dict[key] = value
  507. return serializable_config_dict
  508. class ExllamaVersion(int, Enum):
  509. ONE = 1
  510. TWO = 2
  511. @dataclass
  512. class GPTQConfig(QuantizationConfigMixin):
  513. """
  514. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  515. loaded using `optimum` api for GPTQ quantization relying on the gptqmodel backend.
  516. Args:
  517. bits (`int`):
  518. The number of bits to quantize to, supported numbers are (2, 3, 4, 8).
  519. tokenizer (`str` or `PreTrainedTokenizerBase`, *optional*):
  520. The tokenizer used to process the dataset. You can pass either:
  521. - A custom tokenizer object.
  522. - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
  523. - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
  524. using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
  525. dataset (`Union[list[str]]`, *optional*):
  526. The dataset used for quantization. You can provide your own dataset in a list of string or just use the
  527. original datasets used in GPTQ paper ['wikitext2','c4','c4-new']
  528. group_size (`int`, *optional*, defaults to 128):
  529. The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
  530. damp_percent (`float`, *optional*, defaults to 0.1):
  531. The percent of the average Hessian diagonal to use for dampening. Recommended value is 0.1.
  532. desc_act (`bool`, *optional*, defaults to `False`):
  533. Whether to quantize columns in order of decreasing activation size. Setting it to False can significantly
  534. speed up inference but the perplexity may become slightly worse. Also known as act-order.
  535. act_group_aware (`bool`, *optional*, defaults to `True`):
  536. Use GAR (group aware activation order) during quantization. Has measurable positive impact on quantization
  537. quality. Only applicable when `desc_act = False`. Will forced to be `False` when `desc_act = True`.
  538. sym (`bool`, *optional*, defaults to `True`):
  539. Whether to use symmetric quantization.
  540. true_sequential (`bool`, *optional*, defaults to `True`):
  541. Whether to perform sequential quantization even within a single Transformer block. Instead of quantizing
  542. the entire block at once, we perform layer-wise quantization. As a result, each layer undergoes
  543. quantization using inputs that have passed through the previously quantized layers.
  544. format (`str`, *optional*, defaults to `"gptq"`):
  545. GPTQ weight format. `gptq` (v1) is supported by gptqmodel. `gptq_v2` is gptqmodel only.
  546. meta (`dict[str, any]`, *optional*):
  547. Properties, such as tooling:version, that do not directly contributes to quantization or quant inference are stored in meta.
  548. i.e. `meta.quantizer`: ["optimum:_version_", "gptqmodel:_version_"]
  549. backend (`str`, *optional*):
  550. Controls which kernel to use. Valid values for gptqmodel are `auto`, `auto_trainable` and more. Ref gptqmodel backends:
  551. https://github.com/ModelCloud/GPTQModel/blob/main/gptqmodel/utils/backend.py
  552. model_seqlen (`int`, *optional*):
  553. The maximum sequence length that the model can take.
  554. block_name_to_quantize (`str`, *optional*):
  555. The transformers block name to quantize. If None, we will infer the block name using common patterns (e.g. model.layers)
  556. module_name_preceding_first_block (`list[str]`, *optional*):
  557. The layers that are preceding the first Transformer block.
  558. batch_size (`int`, *optional*, defaults to 1):
  559. The batch size used when processing the dataset
  560. pad_token_id (`int`, *optional*):
  561. The pad token id. Needed to prepare the dataset when `batch_size` > 1.
  562. max_input_length (`int`, *optional*):
  563. The maximum input length. This is needed to initialize a buffer that depends on the maximum expected input
  564. length. It is specific to the exllama backend with act-order.
  565. cache_block_outputs (`bool`, *optional*, defaults to `True`):
  566. Whether to cache block outputs to reuse as inputs for the succeeding block.
  567. modules_in_block_to_quantize (`list[list[str]]`, *optional*):
  568. List of list of module names to quantize in the specified block. This argument is useful to exclude certain linear modules from being quantized.
  569. 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.
  570. Example: `modules_in_block_to_quantize =[["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj"], ["self_attn.o_proj"]]`.
  571. In this example, we will first quantize the q,k,v layers simultaneously since they are independent.
  572. Then, we will quantize `self_attn.o_proj` layer with the q,k,v layers quantized. This way, we will get
  573. better results since it reflects the real input `self_attn.o_proj` will get when the model is quantized.
  574. """
  575. def __init__(
  576. self,
  577. bits: int,
  578. tokenizer: Any = None,
  579. dataset: list[str] | str | None = None,
  580. group_size: int = 128,
  581. damp_percent: float = 0.1,
  582. desc_act: bool = False,
  583. act_group_aware: bool = True,
  584. sym: bool = True,
  585. true_sequential: bool = True,
  586. format: str = "gptq",
  587. meta: dict[str, Any] | None = None,
  588. backend: str | None = None,
  589. model_seqlen: int | None = None,
  590. block_name_to_quantize: str | None = None,
  591. module_name_preceding_first_block: list[str] | None = None,
  592. batch_size: int = 1,
  593. pad_token_id: int | None = None,
  594. max_input_length: int | None = None,
  595. cache_block_outputs: bool = True,
  596. modules_in_block_to_quantize: list[list[str]] | None = None,
  597. **kwargs,
  598. ):
  599. self.quant_method = QuantizationMethod.GPTQ
  600. self.bits = bits
  601. self.tokenizer = tokenizer
  602. self.dataset = dataset
  603. self.group_size = group_size
  604. self.damp_percent = damp_percent
  605. self.desc_act = desc_act
  606. self.act_group_aware = act_group_aware
  607. self.sym = sym
  608. self.true_sequential = true_sequential
  609. self.format = format.lower()
  610. # Compatible with legacy field: checkpoint_format
  611. if kwargs.get("checkpoint_format") is not None:
  612. self.format = kwargs.pop("checkpoint_format").lower()
  613. self.meta = meta
  614. self.backend = backend.lower() if isinstance(backend, str) else backend
  615. self.model_seqlen = model_seqlen
  616. self.block_name_to_quantize = block_name_to_quantize
  617. self.module_name_preceding_first_block = module_name_preceding_first_block
  618. self.batch_size = batch_size
  619. self.pad_token_id = pad_token_id
  620. self.max_input_length = max_input_length
  621. self.cache_block_outputs = cache_block_outputs
  622. self.modules_in_block_to_quantize = modules_in_block_to_quantize
  623. self.post_init()
  624. def get_loading_attributes(self):
  625. attributes_dict = copy.deepcopy(self.__dict__)
  626. loading_attributes = ["max_input_length", "backend"]
  627. loading_attributes_dict = {i: j for i, j in attributes_dict.items() if i in loading_attributes}
  628. return loading_attributes_dict
  629. def post_init(self):
  630. r"""
  631. Safety checker that arguments are correct
  632. """
  633. if self.bits not in [2, 3, 4, 8]:
  634. raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}")
  635. if self.group_size != -1 and self.group_size <= 0:
  636. raise ValueError("group_size must be greater than 0 or equal to -1")
  637. if not (0 < self.damp_percent < 1):
  638. raise ValueError("damp_percent must between 0 and 1.")
  639. if self.dataset is not None:
  640. if isinstance(self.dataset, str):
  641. if self.dataset not in ["wikitext2", "c4", "c4-new"]:
  642. raise ValueError(
  643. f"""You have entered a string value for dataset. You can only choose between
  644. ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
  645. )
  646. elif not isinstance(self.dataset, list):
  647. raise ValueError(
  648. f"""dataset needs to be either a list of string or a value in
  649. ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
  650. )
  651. # act_group_order is only applicable when `desc_act = False`
  652. if self.desc_act and self.act_group_aware:
  653. self.act_group_aware = False
  654. logger.warning("`act_group_aware` has been auto-disabled as it is not compatible with `desc_act = True`.")
  655. # make sure backend default stays consistent with gptqmodel expectations
  656. if self.backend is None:
  657. self.backend = "auto"
  658. if self.modules_in_block_to_quantize is not None:
  659. optimum_version = version.parse(importlib.metadata.version("optimum"))
  660. if optimum_version < version.parse("1.15.0"):
  661. raise ValueError(
  662. "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 ."
  663. )
  664. def to_dict(self) -> dict[str, Any]:
  665. config_dict = super().to_dict()
  666. # Compatible with legacy field: checkpoint_format
  667. config_dict["checkpoint_format"] = self.format
  668. return config_dict
  669. def to_dict_optimum(self):
  670. """
  671. Get compatible dict for optimum gptq config
  672. """
  673. return self.to_dict()
  674. @classmethod
  675. def from_dict_optimum(cls, config_dict):
  676. """
  677. Get compatible class with optimum gptq config dict
  678. """
  679. config = cls(**config_dict)
  680. return config
  681. @dataclass
  682. class AwqConfig(GPTQConfig):
  683. """
  684. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  685. loaded using `auto-awq` library awq quantization relying on auto_awq backend.
  686. Args:
  687. bits (`int`, *optional*, defaults to 4):
  688. The number of bits to quantize to.
  689. group_size (`int`, *optional*, defaults to 128):
  690. The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
  691. zero_point (`bool`, *optional*, defaults to `True`):
  692. Whether to use zero point quantization.
  693. backend (`AwqBackend`, *optional*, defaults to `AwqBackend.AUTO`):
  694. The quantization backend.
  695. modules_to_not_convert (`list`, *optional*, default to `None`):
  696. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  697. some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
  698. Note you cannot quantize directly with transformers, please refer to `AutoAWQ` documentation for quantizing HF models.
  699. """
  700. def __init__(
  701. self,
  702. bits: int = 4,
  703. group_size: int = 128,
  704. zero_point: bool = True,
  705. backend: AwqBackend = AwqBackend.AUTO,
  706. modules_to_not_convert: list | None = None,
  707. **kwargs,
  708. ):
  709. format = kwargs.pop("format", AwqFormat.GEMM)
  710. # Compatible with legacy field: version
  711. if kwargs.get("version") is not None:
  712. format = kwargs.pop("version").lower()
  713. # Compatible with legacy backend
  714. if backend == AwqBackend.LEGACY_AWQ:
  715. backend = AwqBackend.AUTO
  716. self.zero_point = zero_point
  717. self.modules_to_not_convert = modules_to_not_convert
  718. super().__init__(bits=bits, group_size=group_size, backend=backend, format=format, **kwargs)
  719. self.quant_method = QuantizationMethod.AWQ
  720. def post_init(self):
  721. r"""
  722. Safety checker that arguments are correct
  723. """
  724. if self.backend == "llm-awq":
  725. self.format = AwqFormat.LLM_AWQ
  726. self.backend = AwqBackend.AUTO
  727. if self.format not in AwqFormat.__members__.values():
  728. raise ValueError(f"Invalid format '{self.format}'. Must be one of: {[b.value for b in AwqFormat]}")
  729. if self.backend not in AwqBackend.__members__.values():
  730. raise ValueError(f"Invalid backend '{self.backend}'. Must be one of: {[b.value for b in AwqBackend]}")
  731. def to_dict(self) -> dict[str, Any]:
  732. config_dict = super().to_dict()
  733. config_dict.pop("checkpoint_format")
  734. # Compatible with legacy field: version
  735. config_dict["version"] = self.format
  736. return config_dict
  737. @dataclass
  738. class AqlmConfig(QuantizationConfigMixin):
  739. """
  740. This is a wrapper class about `aqlm` parameters.
  741. Args:
  742. in_group_size (`int`, *optional*, defaults to 8):
  743. The group size along the input dimension.
  744. out_group_size (`int`, *optional*, defaults to 1):
  745. The group size along the output dimension. It's recommended to always use 1.
  746. num_codebooks (`int`, *optional*, defaults to 1):
  747. Number of codebooks for the Additive Quantization procedure.
  748. nbits_per_codebook (`int`, *optional*, defaults to 16):
  749. Number of bits encoding a single codebook vector. Codebooks size is 2**nbits_per_codebook.
  750. linear_weights_not_to_quantize (`Optional[list[str]]`, *optional*):
  751. List of full paths of `nn.Linear` weight parameters that shall not be quantized.
  752. kwargs (`dict[str, Any]`, *optional*):
  753. Additional parameters from which to initialize the configuration object.
  754. """
  755. def __init__(
  756. self,
  757. in_group_size: int = 8,
  758. out_group_size: int = 1,
  759. num_codebooks: int = 1,
  760. nbits_per_codebook: int = 16,
  761. linear_weights_not_to_quantize: list[str] | None = None,
  762. **kwargs,
  763. ):
  764. self.quant_method = QuantizationMethod.AQLM
  765. self.in_group_size = in_group_size
  766. self.out_group_size = out_group_size
  767. self.num_codebooks = num_codebooks
  768. self.nbits_per_codebook = nbits_per_codebook
  769. self.linear_weights_not_to_quantize = linear_weights_not_to_quantize
  770. self.post_init()
  771. def post_init(self):
  772. r"""
  773. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  774. """
  775. if not isinstance(self.in_group_size, int):
  776. raise TypeError("in_group_size must be a float")
  777. if not isinstance(self.out_group_size, int):
  778. raise TypeError("out_group_size must be a float")
  779. if not isinstance(self.num_codebooks, int):
  780. raise TypeError("num_codebooks must be a float")
  781. if not isinstance(self.nbits_per_codebook, int):
  782. raise TypeError("nbits_per_codebook must be a float")
  783. if self.linear_weights_not_to_quantize is not None and not isinstance(
  784. self.linear_weights_not_to_quantize, list
  785. ):
  786. raise ValueError("linear_weights_not_to_quantize must be a list of strings")
  787. if self.linear_weights_not_to_quantize is None:
  788. self.linear_weights_not_to_quantize = []
  789. @dataclass
  790. class VptqLayerConfig(QuantizationConfigMixin):
  791. """
  792. This is used to explain vptq config params for each layer
  793. Args:
  794. enable_norm (`bool`, *optional*, defaults to `True`): to control if we have scale/bias for fp-weight
  795. enable_perm (`bool`, *optional*, defaults to `True`): to perm input_channel or not
  796. group_num (`int`, *optional*, defaults to `1`): how many single groups for vector-quantization
  797. group_size (`int`, *optional*, defaults to `-1`): depends on out-features
  798. indices_as_float (`bool`, *optional*, defaults to `False`): for Finetuning
  799. is_indice_packed (`bool`, *optional*, defaults to `True`): should always be True
  800. num_centroids (`list`, *optional*, defaults to `[-1, -1]`): centroid numbers of clusters
  801. num_res_centroids (`list`, *optional*, defaults to `[-1, -1]`): ditto for residual
  802. outlier_size (`int`, *optional*, defaults to `1`): outliers
  803. vector_lens (`list`, *optional*, defaults to `[-1, -1]`): centroid vector length in quantization
  804. """
  805. def __init__(
  806. self,
  807. enable_norm: bool = True,
  808. enable_perm: bool = True,
  809. group_num: int = 1,
  810. group_size: int = -1,
  811. in_features: int = -1,
  812. indices_as_float: bool = False,
  813. is_indice_packed: bool = True,
  814. num_centroids: list = [-1, -1],
  815. num_res_centroids: list = [-1, -1],
  816. out_features: int = -1,
  817. outlier_size: int = 0,
  818. vector_lens: list = [-1, -1],
  819. **kwargs,
  820. ):
  821. self.enable_norm = enable_norm
  822. self.enable_perm = enable_perm
  823. self.group_num = group_num
  824. self.group_size = group_size
  825. self.in_features = in_features
  826. self.indices_as_float = indices_as_float
  827. self.is_indice_packed = is_indice_packed
  828. self.num_centroids = num_centroids
  829. self.num_res_centroids = num_res_centroids
  830. self.out_features = out_features
  831. self.outlier_size = outlier_size
  832. self.vector_lens = vector_lens
  833. self.post_init()
  834. def post_init(self):
  835. r"""
  836. Safety checker that arguments are correct
  837. """
  838. if self.is_indice_packed is False:
  839. raise ValueError("is_indice_packed should always be True")
  840. @dataclass
  841. class VptqConfig(QuantizationConfigMixin):
  842. """
  843. This is a wrapper class about `vptq` parameters.
  844. Args:
  845. enable_proxy_error (`bool`, *optional*, defaults to `False`): calculate proxy error for each layer
  846. config_for_layers (`Dict`, *optional*, defaults to `{}`): quantization params for each layer
  847. shared_layer_config (`Dict`, *optional*, defaults to `{}`): shared quantization params among layers
  848. modules_to_not_convert (`list`, *optional*, default to `None`):
  849. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  850. some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
  851. kwargs (`dict[str, Any]`, *optional*):
  852. Additional parameters from which to initialize the configuration object.
  853. """
  854. def __init__(
  855. self,
  856. enable_proxy_error: bool = False,
  857. config_for_layers: dict[str, Any] = {},
  858. shared_layer_config: dict[str, Any] = {},
  859. modules_to_not_convert: list | None = None,
  860. **kwargs,
  861. ):
  862. self.quant_method = QuantizationMethod.VPTQ
  863. self.enable_proxy_error = enable_proxy_error
  864. self.config_for_layers: dict[str, Any] = config_for_layers
  865. self.shared_layer_config: dict[str, Any] = shared_layer_config
  866. self.modules_to_not_convert = modules_to_not_convert
  867. self.post_init()
  868. def post_init(self):
  869. r"""
  870. Safety checker that arguments are correct
  871. """
  872. for layer_param in self.config_for_layers.values():
  873. VptqLayerConfig(**layer_param)
  874. if self.enable_proxy_error is True:
  875. raise ValueError("enable_proxy_error should always be False until we support training")
  876. @dataclass
  877. class QuantoConfig(QuantizationConfigMixin):
  878. """
  879. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  880. loaded using `quanto`.
  881. Args:
  882. weights (`str`, *optional*, defaults to `"int8"`):
  883. The target dtype for the weights after quantization. Supported values are ("float8","int8","int4","int2")
  884. activations (`str`, *optional*):
  885. The target dtype for the activations after quantization. Supported values are (None,"int8","float8")
  886. modules_to_not_convert (`list`, *optional*, default to `None`):
  887. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  888. some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
  889. """
  890. def __init__(
  891. self,
  892. weights="int8",
  893. activations=None,
  894. modules_to_not_convert: list | None = None,
  895. **kwargs,
  896. ):
  897. self.quant_method = QuantizationMethod.QUANTO
  898. self.weights = weights
  899. self.activations = activations
  900. self.modules_to_not_convert = modules_to_not_convert
  901. self.post_init()
  902. def post_init(self):
  903. r"""
  904. Safety checker that arguments are correct
  905. """
  906. accepted_weights = ["float8", "int8", "int4", "int2"]
  907. accepted_activations = [None, "int8", "float8"]
  908. if self.weights not in accepted_weights:
  909. raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
  910. if self.activations not in accepted_activations:
  911. raise ValueError(f"Only support weights in {accepted_activations} but found {self.activations}")
  912. @dataclass
  913. class EetqConfig(QuantizationConfigMixin):
  914. """
  915. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  916. loaded using `eetq`.
  917. Args:
  918. weights (`str`, *optional*, defaults to `"int8"`):
  919. The target dtype for the weights. Supported value is only "int8"
  920. modules_to_not_convert (`list`, *optional*, default to `None`):
  921. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  922. some modules left in their original precision.
  923. """
  924. def __init__(
  925. self,
  926. weights: str = "int8",
  927. modules_to_not_convert: list | None = None,
  928. **kwargs,
  929. ):
  930. self.quant_method = QuantizationMethod.EETQ
  931. self.weights = weights
  932. self.modules_to_not_convert = modules_to_not_convert
  933. self.post_init()
  934. def post_init(self):
  935. r"""
  936. Safety checker that arguments are correct
  937. """
  938. accepted_weights = ["int8"]
  939. if self.weights not in accepted_weights:
  940. raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
  941. class CompressedTensorsConfig(QuantizationConfigMixin):
  942. """
  943. This is a wrapper class that handles compressed-tensors quantization config options.
  944. It is a wrapper around `compressed_tensors.QuantizationConfig`
  945. Args:
  946. config_groups (`typing.dict[str, typing.Union[ForwardRef('QuantizationScheme'), typing.list[str]]]`, *optional*):
  947. dictionary mapping group name to a quantization scheme definition
  948. format (`str`, *optional*, defaults to `"dense"`):
  949. format the model is represented as. Set `run_compressed` True to execute model as the
  950. compressed format if not `dense`
  951. quantization_status (`QuantizationStatus`, *optional*, defaults to `"initialized"`):
  952. status of model in the quantization lifecycle, ie 'initialized', 'calibration', 'frozen'
  953. kv_cache_scheme (`typing.Union[QuantizationArgs, NoneType]`, *optional*):
  954. specifies quantization of the kv cache. If None, kv cache is not quantized.
  955. global_compression_ratio (`typing.Union[float, NoneType]`, *optional*):
  956. 0-1 float percentage of model compression
  957. ignore (`typing.Union[typing.list[str], NoneType]`, *optional*):
  958. layer names or types to not quantize, supports regex prefixed by 're:'
  959. sparsity_config (`typing.dict[str, typing.Any]`, *optional*):
  960. configuration for sparsity compression
  961. quant_method (`str`, *optional*, defaults to `"compressed-tensors"`):
  962. do not override, should be compressed-tensors
  963. run_compressed (`bool`, *optional*, defaults to `True`): alter submodules (usually linear) in order to
  964. emulate compressed model execution if True, otherwise use default submodule
  965. """
  966. def __init__(
  967. self,
  968. config_groups: dict[str, Union["QuantizationScheme", list[str]]] | None = None, # noqa: F821
  969. format: str = "dense",
  970. quantization_status: "QuantizationStatus" = "initialized", # noqa: F821
  971. kv_cache_scheme: Optional["QuantizationArgs"] = None, # noqa: F821
  972. global_compression_ratio: float | None = None,
  973. ignore: list[str] | None = None,
  974. sparsity_config: dict[str, Any] | None = None,
  975. quant_method: str = "compressed-tensors",
  976. run_compressed: bool = True,
  977. **kwargs,
  978. ):
  979. if is_compressed_tensors_available():
  980. from compressed_tensors.config import SparsityCompressionConfig
  981. from compressed_tensors.quantization import QuantizationConfig
  982. else:
  983. raise ImportError(
  984. "compressed_tensors is not installed and is required for compressed-tensors quantization. Please install it with `pip install compressed-tensors`."
  985. )
  986. self.quantization_config = None
  987. self.sparsity_config = None
  988. self.run_compressed = run_compressed
  989. # parse from dict to load nested QuantizationScheme objects
  990. if config_groups or kv_cache_scheme:
  991. self.quantization_config = QuantizationConfig.model_validate(
  992. {
  993. "config_groups": config_groups,
  994. "quant_method": quant_method,
  995. "format": format,
  996. "quantization_status": quantization_status,
  997. "kv_cache_scheme": kv_cache_scheme,
  998. "global_compression_ratio": global_compression_ratio,
  999. "ignore": ignore,
  1000. **kwargs,
  1001. }
  1002. )
  1003. if sparsity_config:
  1004. self.sparsity_config = SparsityCompressionConfig.load_from_registry(
  1005. sparsity_config.get("format"), **sparsity_config
  1006. )
  1007. self.quant_method = QuantizationMethod.COMPRESSED_TENSORS
  1008. def post_init(self):
  1009. if self.run_compressed:
  1010. if self.is_sparsification_compressed:
  1011. logger.warning(
  1012. "`run_compressed` is only supported for quantized_compressed models"
  1013. " and not for sparsified models. Setting `run_compressed=False`"
  1014. )
  1015. self.run_compressed = False
  1016. elif not self.is_quantization_compressed:
  1017. logger.warning(
  1018. "`run_compressed` is only supported for compressed models. Setting `run_compressed=False`"
  1019. )
  1020. self.run_compressed = False
  1021. @classmethod
  1022. def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
  1023. """
  1024. Instantiates a [`CompressedTensorsConfig`] from a Python dictionary of parameters.
  1025. Optionally unwraps any args from the nested quantization_config
  1026. Args:
  1027. config_dict (`dict[str, Any]`):
  1028. Dictionary that will be used to instantiate the configuration object.
  1029. return_unused_kwargs (`bool`,*optional*, defaults to `False`):
  1030. Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
  1031. `PreTrainedModel`.
  1032. kwargs (`dict[str, Any]`):
  1033. Additional parameters from which to initialize the configuration object.
  1034. Returns:
  1035. [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
  1036. """
  1037. if "quantization_config" in config_dict:
  1038. config_dict = dict(
  1039. sparsity_config=config_dict.get("sparsity_config"),
  1040. **config_dict["quantization_config"],
  1041. )
  1042. return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs)
  1043. def to_dict(self) -> dict[str, Any]:
  1044. """
  1045. Quantization config to be added to config.json
  1046. Serializes this instance to a Python dictionary. Returns:
  1047. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  1048. """
  1049. quantization_config = {}
  1050. if self.quantization_config is not None:
  1051. quantization_config = self.quantization_config.model_dump()
  1052. else:
  1053. quantization_config["quant_method"] = QuantizationMethod.COMPRESSED_TENSORS
  1054. if self.sparsity_config is not None:
  1055. quantization_config["sparsity_config"] = self.sparsity_config.model_dump()
  1056. else:
  1057. quantization_config["sparsity_config"] = {}
  1058. return quantization_config
  1059. def to_diff_dict(self) -> dict[str, Any]:
  1060. """
  1061. Removes all attributes from config which correspond to the default config attributes for better readability and
  1062. serializes to a Python dictionary.
  1063. Returns:
  1064. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
  1065. """
  1066. config_dict = self.to_dict()
  1067. # get the default config dict
  1068. default_config_dict = CompressedTensorsConfig().to_dict()
  1069. serializable_config_dict = {}
  1070. # only serialize values that differ from the default config
  1071. for key, value in config_dict.items():
  1072. if key not in default_config_dict or value != default_config_dict[key]:
  1073. serializable_config_dict[key] = value
  1074. return serializable_config_dict
  1075. def get_loading_attributes(self):
  1076. return {"run_compressed": self.run_compressed}
  1077. @property
  1078. def is_quantized(self):
  1079. return bool(self.quantization_config) and bool(self.quantization_config.config_groups)
  1080. @property
  1081. def is_quantization_compressed(self):
  1082. from compressed_tensors.quantization import QuantizationStatus
  1083. qc = self.quantization_config
  1084. return self.is_quantized and (qc is not None and qc.quantization_status == QuantizationStatus.COMPRESSED)
  1085. @property
  1086. def is_sparsification_compressed(self):
  1087. from compressed_tensors.config import (
  1088. CompressionFormat,
  1089. SparsityCompressionConfig,
  1090. )
  1091. return (
  1092. isinstance(self.sparsity_config, SparsityCompressionConfig)
  1093. and self.sparsity_config.format != CompressionFormat.dense.value
  1094. )
  1095. @dataclass
  1096. class FbgemmFp8Config(QuantizationConfigMixin):
  1097. """
  1098. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  1099. loaded using fbgemm fp8 quantization.
  1100. Args:
  1101. activation_scale_ub (`float`, *optional*, defaults to 1200.0):
  1102. The activation scale upper bound. This is used when quantizing the input activation.
  1103. modules_to_not_convert (`list`, *optional*, default to `None`):
  1104. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  1105. some modules left in their original precision.
  1106. """
  1107. def __init__(
  1108. self,
  1109. activation_scale_ub: float = 1200.0,
  1110. modules_to_not_convert: list | None = None,
  1111. **kwargs,
  1112. ):
  1113. self.quant_method = QuantizationMethod.FBGEMM_FP8
  1114. self.activation_scale_ub = activation_scale_ub
  1115. self.modules_to_not_convert = modules_to_not_convert
  1116. def get_loading_attributes(self):
  1117. attributes_dict = copy.deepcopy(self.__dict__)
  1118. loading_attributes = ["activation_scale_ub"]
  1119. loading_attributes_dict = {i: j for i, j in attributes_dict.items() if i in loading_attributes}
  1120. return loading_attributes_dict
  1121. @dataclass
  1122. class HiggsConfig(QuantizationConfigMixin):
  1123. """
  1124. HiggsConfig is a configuration class for quantization using the HIGGS method.
  1125. Args:
  1126. bits (int, *optional*, defaults to 4):
  1127. Number of bits to use for quantization. Can be 2, 3 or 4. Default is 4.
  1128. p (int, *optional*, defaults to 2):
  1129. Quantization grid dimension. 1 and 2 are supported. 2 is always better in practice. Default is 2.
  1130. modules_to_not_convert (`list`, *optional*, default to ["lm_head"]):
  1131. List of linear layers that should not be quantized.
  1132. hadamard_size (int, *optional*, defaults to 512):
  1133. Hadamard size for the HIGGS method. Default is 512. Input dimension of matrices is padded to this value. Decreasing this below 512 will reduce the quality of the quantization.
  1134. group_size (int, *optional*, defaults to 256):
  1135. Group size for the HIGGS method. Can be 64, 128 or 256. Decreasing it barely affects the performance. Default is 256. Must be a divisor of hadamard_size.
  1136. tune_metadata ('dict', *optional*, defaults to {}):
  1137. Module-wise metadata (gemm block shapes, GPU metadata, etc.) for saving the kernel tuning results. Default is an empty dictionary. Is set automatically during tuning.
  1138. """
  1139. def __init__(
  1140. self,
  1141. bits: int = 4,
  1142. p: int = 2,
  1143. modules_to_not_convert: list[str] | None = None,
  1144. hadamard_size: int = 512,
  1145. group_size: int = 256,
  1146. tune_metadata: dict[str, Any] | None = None,
  1147. **kwargs,
  1148. ):
  1149. if tune_metadata is None:
  1150. tune_metadata = {}
  1151. self.quant_method = QuantizationMethod.HIGGS
  1152. self.bits = bits
  1153. self.p = p
  1154. self.modules_to_not_convert = modules_to_not_convert
  1155. self.hadamard_size = hadamard_size
  1156. self.group_size = group_size
  1157. self.tune_metadata = tune_metadata
  1158. self.post_init()
  1159. def post_init(self):
  1160. r"""
  1161. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  1162. """
  1163. if self.bits not in [2, 3, 4]:
  1164. raise ValueError("bits must be 2, 3, or 4")
  1165. if self.p not in [1, 2]:
  1166. raise ValueError("p must be 1 or 2. 2 is always better in practice")
  1167. if self.group_size not in [64, 128, 256]:
  1168. raise ValueError("group_size must be 64, 128, or 256")
  1169. if self.hadamard_size % self.group_size != 0:
  1170. raise ValueError("hadamard_size must be divisible by group_size")
  1171. @dataclass
  1172. class FPQuantConfig(QuantizationConfigMixin):
  1173. """
  1174. FPQuantConfig is a configuration class for quantization using the FPQuant method.
  1175. Args:
  1176. forward_dtype (`str`, *optional*, defaults to `"nvfp4"`):
  1177. The dtype to use for the forward pass.
  1178. forward_method (`str`, *optional*, defaults to `"abs_max"`):
  1179. The scaling to use for the forward pass. Can be `"abs_max"` or `"quest"`. `"abs_max"` is better for PTQ, `"quest"` is better for QAT.
  1180. backward_dtype (`str`, *optional*, defaults to `"bf16"`):
  1181. The dtype to use for the backward pass.
  1182. store_master_weights (`bool`, *optional*, defaults to `False`):
  1183. Whether to store the master weights. Needed for QAT over layer weights.
  1184. hadamard_group_size (`int`, *optional*):
  1185. The group size for the hadamard transform before quantization for `"quest"` it matches the MXFP4 group size (32). If `None`, it will be set to 16 for `"nvfp4"` and 32 for `"mxfp4"`.
  1186. pseudoquantization (`bool`, *optional*, defaults to `False`):
  1187. Whether to use Triton-based pseudo-quantization. Is mandatory for non-Blackwell GPUs. Doesn't provide any speedup. For debugging purposes.
  1188. transform_init (`str`, *optional*, defaults to `"hadamard"`): a method to initialize the pre-processing matrix with. Can be `"hadamard"`, `"identity"` or `"gsr"`.
  1189. modules_to_not_convert (`list`, *optional*):
  1190. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  1191. some modules left in their original precision.
  1192. """
  1193. def __init__(
  1194. self,
  1195. forward_dtype: str = "nvfp4",
  1196. forward_method: str = "abs_max",
  1197. backward_dtype: str = "bf16",
  1198. store_master_weights: bool = False,
  1199. hadamard_group_size: int | None = None,
  1200. pseudoquantization: bool = False,
  1201. transform_init: str = "hadamard",
  1202. modules_to_not_convert: list[str] | None = None,
  1203. **kwargs,
  1204. ):
  1205. self.forward_dtype = forward_dtype
  1206. self.forward_method = forward_method
  1207. self.backward_dtype = backward_dtype
  1208. self.store_master_weights = store_master_weights
  1209. self.hadamard_group_size = hadamard_group_size
  1210. self.pseudoquantization = pseudoquantization
  1211. self.transform_init = transform_init
  1212. self.modules_to_not_convert = modules_to_not_convert
  1213. self.quant_method = QuantizationMethod.FPQUANT
  1214. self.post_init()
  1215. def post_init(self):
  1216. r"""
  1217. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  1218. """
  1219. if self.hadamard_group_size is None:
  1220. if self.forward_dtype == "nvfp4":
  1221. self.hadamard_group_size = 16
  1222. else:
  1223. self.hadamard_group_size = 32
  1224. if self.forward_dtype == "mxfp4":
  1225. if self.forward_method not in ["abs_max", "quest"]:
  1226. raise ValueError("Only 'abs_max' and 'quest' are supported for forward_method for 'mxfp4'.")
  1227. if self.hadamard_group_size is None:
  1228. self.hadamard_group_size = 32
  1229. if self.hadamard_group_size not in [32, 64, 128]:
  1230. raise ValueError("Only a `hadamard_group_size` of [32, 64, 128] is supported for 'mxfp4'.")
  1231. elif self.forward_dtype == "nvfp4":
  1232. if self.forward_method != "abs_max":
  1233. raise ValueError("Only 'abs_max' is supported for forward_method for 'nvfp4'.")
  1234. if self.hadamard_group_size is None:
  1235. self.hadamard_group_size = 16
  1236. if self.hadamard_group_size not in [16, 32, 64, 128]:
  1237. raise ValueError("Only a `hadamard_group_size` of [16, 32, 64, 128] is supported for 'nvfp4'.")
  1238. else:
  1239. raise ValueError("Only 'mxfp4' and 'nvfp4' are supported for forward_dtype for now.")
  1240. if self.backward_dtype not in ["bf16", "mxfp8", "mxfp4"]:
  1241. raise ValueError("Only 'bf16', 'mxfp8' and 'mxfp4' are supported for backward_dtype for now.")
  1242. if self.backward_dtype != "bf16" and self.forward_dtype != "mxfp4":
  1243. raise ValueError("Only 'mxfp4' forward is compatible with non-bf16 backwards for now.")
  1244. if self.transform_init not in ["hadamard", "identity", "gsr"]:
  1245. raise ValueError("Only 'hadamard', 'identity' and 'gsr' are supported for transform_init.")
  1246. if self.modules_to_not_convert is None:
  1247. self.modules_to_not_convert = ["lm_head"]
  1248. @dataclass
  1249. class TorchAoConfig(QuantizationConfigMixin):
  1250. """Config class for torchao quantization/sparsity techniques.
  1251. Args:
  1252. quant_type (`AOBaseConfig`):
  1253. A torchao `AOBaseConfig` instance specifying the quantization type, e.g.
  1254. `Int4WeightOnlyConfig(group_size=32)`, `Int8WeightOnlyConfig()`,
  1255. `Int8DynamicActivationInt8WeightConfig()`, `Float8WeightOnlyConfig()`, etc.
  1256. modules_to_not_convert (`list`, *optional*, default to `None`):
  1257. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  1258. some modules left in their original precision.
  1259. include_input_output_embeddings (`bool`, *optional*, defaults to `False`):
  1260. Whether to include embedding in quantization or not, input embedding will be removed from
  1261. the module_not_to_convert list as well if this flag is set.
  1262. untie_embedding_weights (`bool`, *optional*, defaults to `False`):
  1263. Whether to untie the weights when we are quantizing input embedding weights that is tied
  1264. to other weights.
  1265. Example:
  1266. ```python
  1267. from torchao.quantization import Int4WeightOnlyConfig
  1268. quantization_config = TorchAoConfig(Int4WeightOnlyConfig(group_size=32))
  1269. model = AutoModelForCausalLM.from_pretrained(
  1270. model_id, device_map="cuda", torch_dtype=torch.bfloat16, quantization_config=quantization_config
  1271. )
  1272. ```
  1273. """
  1274. quant_method: QuantizationMethod
  1275. quant_type: "AOBaseConfig" # noqa: F821
  1276. modules_to_not_convert: list | None
  1277. include_input_output_embeddings: bool
  1278. untie_embedding_weights: bool
  1279. def __init__(
  1280. self,
  1281. quant_type: "AOBaseConfig", # noqa: F821
  1282. modules_to_not_convert: list | None = None,
  1283. include_input_output_embeddings: bool = False,
  1284. untie_embedding_weights: bool = False,
  1285. **kwargs,
  1286. ):
  1287. self.quant_method = QuantizationMethod.TORCHAO
  1288. self.quant_type = quant_type
  1289. self.modules_to_not_convert = modules_to_not_convert
  1290. self.include_input_output_embeddings = include_input_output_embeddings
  1291. self.untie_embedding_weights = untie_embedding_weights
  1292. self.post_init()
  1293. def post_init(self):
  1294. """Validate configuration and set defaults."""
  1295. if not is_torchao_available():
  1296. raise ValueError("TorchAoConfig requires torchao to be installed. Install with `pip install torchao`")
  1297. if isinstance(self.quant_type, str):
  1298. raise ValueError(
  1299. f"String-based quantization type '{self.quant_type}' is no longer supported. "
  1300. f"Please use the corresponding Config object directly, e.g. "
  1301. f"TorchAoConfig(Int4WeightOnlyConfig(group_size=32)) instead of "
  1302. f"TorchAoConfig('int4_weight_only', group_size=32)."
  1303. )
  1304. from torchao.quantization.quant_api import AOBaseConfig
  1305. if not isinstance(self.quant_type, AOBaseConfig):
  1306. raise TypeError(f"quant_type must be an AOBaseConfig instance, got {type(self.quant_type)}")
  1307. def get_apply_tensor_subclass(self):
  1308. """Return the quantization config to apply."""
  1309. return self.quant_type
  1310. def to_dict(self):
  1311. """Convert configuration to a dictionary."""
  1312. d = super().to_dict()
  1313. from torchao.core.config import config_to_dict
  1314. d["quant_type"] = {"default": config_to_dict(self.quant_type)}
  1315. return d
  1316. @classmethod
  1317. def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
  1318. """Create configuration from a dictionary."""
  1319. from torchao.core.config import config_from_dict
  1320. config_dict = config_dict.copy()
  1321. quant_type = config_dict.pop("quant_type")
  1322. # Check if we only have one key which is "default"
  1323. # In the future we may update this
  1324. assert len(quant_type) == 1 and "default" in quant_type, (
  1325. "Expected only one key 'default' in quant_type dictionary"
  1326. )
  1327. quant_type = quant_type["default"]
  1328. quant_type = config_from_dict(quant_type)
  1329. return cls(quant_type=quant_type, **config_dict)
  1330. @dataclass
  1331. class BitNetQuantConfig(QuantizationConfigMixin):
  1332. """
  1333. Configuration class for applying BitNet quantization.
  1334. Args:
  1335. modules_to_not_convert (`Optional[List]`, *optional*):
  1336. Optionally, provides a list of full paths of `nn.Linear` weight parameters
  1337. that shall not be quantized. Defaults to None.
  1338. linear_class (`str`, *optional*, defaults to `"bitlinear"`):
  1339. The type of linear class to use. Can be either `bitlinear` or `autobitlinear`.
  1340. quantization_mode (`str`, *optional*, defaults to `"offline"`):
  1341. The quantization mode to use. Can be either `online` or `offline`.
  1342. In `online` mode, the weight quantization parameters are calculated dynamically
  1343. during each forward pass (e.g., based on the current weight values). This can
  1344. adapt to weight changes during training (Quantization-Aware Training - QAT).
  1345. In `offline` mode, quantization parameters are pre-calculated *before* inference.
  1346. These parameters are then fixed and loaded into the quantized model. This
  1347. generally results in lower runtime overhead compared to online quantization.
  1348. use_rms_norm (`bool`, *optional*, defaults to `False`):
  1349. Whether to apply RMSNorm on the activations before quantization. This matches the original BitNet paper's approach
  1350. of normalizing activations before quantization/packing.
  1351. rms_norm_eps (`float`, *optional*, defaults to 1e-06):
  1352. The epsilon value used in the RMSNorm layer for numerical stability.
  1353. kwargs (`dict[str, Any]`, *optional*):
  1354. Additional keyword arguments that may be used by specific quantization
  1355. backends or future versions.
  1356. """
  1357. def __init__(
  1358. self,
  1359. modules_to_not_convert: list | None = None,
  1360. linear_class: str = "bitlinear",
  1361. quantization_mode: str = "offline",
  1362. use_rms_norm: bool = False,
  1363. rms_norm_eps: float | None = 1e-6,
  1364. **kwargs,
  1365. ):
  1366. if linear_class not in ["bitlinear", "autobitlinear"]:
  1367. raise ValueError(f"linear_class must be either 'bitlinear' or 'autobitlinear', but got {linear_class}")
  1368. if quantization_mode not in ["online", "offline"]:
  1369. raise ValueError(f"quantization_mode must be either 'online' or 'offline', but got {quantization_mode}")
  1370. self.quant_method = QuantizationMethod.BITNET
  1371. self.modules_to_not_convert = modules_to_not_convert
  1372. self.linear_class = linear_class
  1373. self.quantization_mode = quantization_mode
  1374. self.use_rms_norm = use_rms_norm
  1375. self.rms_norm_eps = rms_norm_eps
  1376. self.post_init()
  1377. def post_init(self):
  1378. r"""
  1379. Safety checker that arguments are correct
  1380. """
  1381. @dataclass
  1382. class SpQRConfig(QuantizationConfigMixin):
  1383. """
  1384. This is a wrapper class about `spqr` parameters. Refer to the original publication for more details.
  1385. Args:
  1386. bits (`int`, *optional*, defaults to 3):
  1387. Specifies the bit count for the weights and first order zero-points and scales.
  1388. Currently only bits = 3 is supported.
  1389. beta1 (`int`, *optional*, defaults to 16):
  1390. SpQR tile width. Currently only beta1 = 16 is supported.
  1391. beta2 (`int`, *optional*, defaults to 16):
  1392. SpQR tile height. Currently only beta2 = 16 is supported.
  1393. shapes (`Optional`, *optional*):
  1394. A dictionary holding the shape of each object. We need this because it's impossible
  1395. to deduce the exact size of the parameters just from bits, beta1, beta2.
  1396. modules_to_not_convert (`Optional[list[str]]`, *optional*):
  1397. Optionally, provides a list of full paths of `nn.Linear` weight parameters that shall not be quantized.
  1398. Defaults to None.
  1399. kwargs (`dict[str, Any]`, *optional*):
  1400. Additional parameters from which to initialize the configuration object.
  1401. """
  1402. def __init__(
  1403. self,
  1404. bits: int = 3,
  1405. beta1: int = 16,
  1406. beta2: int = 16,
  1407. shapes: dict[str, int] | None = None,
  1408. modules_to_not_convert: list[str] | None = None,
  1409. **kwargs,
  1410. ):
  1411. if shapes is None:
  1412. shapes = {}
  1413. self.shapes = shapes
  1414. self.quant_method = QuantizationMethod.SPQR
  1415. self.bits = bits
  1416. self.beta1 = beta1
  1417. self.beta2 = beta2
  1418. self.modules_to_not_convert = modules_to_not_convert
  1419. self.post_init()
  1420. def post_init(self):
  1421. r"""
  1422. Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
  1423. """
  1424. if not isinstance(self.bits, int):
  1425. raise TypeError("bits must be an int")
  1426. if not isinstance(self.beta1, int):
  1427. raise TypeError("beta1 must be an int")
  1428. if not isinstance(self.beta2, int):
  1429. raise TypeError("beta2 must be an int")
  1430. if self.bits != 3:
  1431. raise ValueError("SpQR currently only supports bits = 3")
  1432. if self.beta1 != 16:
  1433. raise ValueError("SpQR currently only supports beta1 = 16")
  1434. if self.beta2 != 16:
  1435. raise ValueError("SpQR currently only supports beta2 = 16")
  1436. if not isinstance(self.shapes, dict):
  1437. raise TypeError("shapes must be a dict")
  1438. @dataclass
  1439. class FineGrainedFP8Config(QuantizationConfigMixin):
  1440. """
  1441. FineGrainedFP8Config is a configuration class for fine-grained FP8 quantization used mainly for deepseek models.
  1442. Args:
  1443. activation_scheme (`str`, *optional*, defaults to `"dynamic"`):
  1444. The scheme used for activation, the defaults and only support scheme for now is "dynamic".
  1445. weight_block_size (`typing.tuple[int, int]`, *optional*, defaults to `(128, 128)`):
  1446. The size of the weight blocks for quantization, default is (128, 128).
  1447. dequantize (`bool`, *optional*, defaults to `False`):
  1448. Whether to dequantize the model during loading.
  1449. modules_to_not_convert (`list`, *optional*):
  1450. A list of module names that should not be converted during quantization.
  1451. """
  1452. def __init__(
  1453. self,
  1454. activation_scheme: str = "dynamic",
  1455. weight_block_size: tuple[int, int] = (128, 128),
  1456. dequantize: bool = False,
  1457. modules_to_not_convert: list | None = None,
  1458. **kwargs,
  1459. ):
  1460. self.quant_method = QuantizationMethod.FP8
  1461. self.modules_to_not_convert = modules_to_not_convert
  1462. self.activation_scheme = activation_scheme
  1463. self.weight_block_size = weight_block_size
  1464. self.dequantize = dequantize
  1465. self.post_init()
  1466. def post_init(self):
  1467. r"""
  1468. Safety checker that arguments are correct
  1469. """
  1470. self.activation_scheme = self.activation_scheme.lower()
  1471. if self.activation_scheme not in ["dynamic", "static"]:
  1472. raise ValueError(f"Activation scheme {self.activation_scheme} not supported")
  1473. if self.weight_block_size is not None and len(self.weight_block_size) != 2:
  1474. raise ValueError("weight_block_size must be a tuple of two integers")
  1475. if self.weight_block_size is not None and (self.weight_block_size[0] <= 0 or self.weight_block_size[1] <= 0):
  1476. raise ValueError("weight_block_size must be a tuple of two positive integers")
  1477. def get_loading_attributes(self):
  1478. return {"dequantize": self.dequantize}
  1479. class QuarkConfig(QuantizationConfigMixin):
  1480. def __init__(
  1481. self,
  1482. **kwargs,
  1483. ):
  1484. if is_torch_available() and is_quark_available():
  1485. from quark import __version__ as quark_version
  1486. from quark.torch.export.config.config import JsonExporterConfig
  1487. from quark.torch.export.main_export.quant_config_parser import QuantConfigParser
  1488. from quark.torch.quantization.config.config import Config
  1489. else:
  1490. raise ImportError(
  1491. "Quark is not installed. Please refer to https://quark.docs.amd.com/latest/install.html."
  1492. )
  1493. # This might be e.g. `"fp8"` or `"awq"`.
  1494. self.custom_mode = kwargs["quant_method"]
  1495. self.legacy = "export" not in kwargs
  1496. if self.custom_mode in ["awq", "fp8"]:
  1497. # Legacy (quark<1.0) or custom export.
  1498. self.quant_config = QuantConfigParser.from_custom_config(kwargs, is_bias_quantized=False)
  1499. self.json_export_config = JsonExporterConfig()
  1500. else:
  1501. self.quant_config = Config.from_dict(kwargs)
  1502. if "export" in kwargs:
  1503. # TODO: Remove this check once configuration version is handled natively by Quark.
  1504. if "min_kv_scale" in kwargs["export"] and version.parse(quark_version) < version.parse("0.8"):
  1505. min_kv_scale = kwargs["export"].pop("min_kv_scale")
  1506. logger.warning(
  1507. f"The parameter `min_kv_scale={min_kv_scale}` was found in the model config.json's `quantization_config.export` configuration, but this parameter is supported only for quark>=0.8. Ignoring this configuration parameter. Please update the `amd-quark` package."
  1508. )
  1509. self.json_export_config = JsonExporterConfig(**kwargs["export"])
  1510. else:
  1511. # Legacy (quark<1.0) or custom export.
  1512. self.json_export_config = JsonExporterConfig()
  1513. self.quant_method = QuantizationMethod.QUARK
  1514. @dataclass
  1515. class Mxfp4Config(QuantizationConfigMixin):
  1516. """
  1517. This is a wrapper class about all possible attributes and features that you can play with a model that has been
  1518. loaded using mxfp4 quantization.
  1519. Args:
  1520. modules_to_not_convert (`list`, *optional*, default to `None`):
  1521. The list of modules to not quantize, useful for quantizing models that explicitly require to have
  1522. some modules left in their original precision.
  1523. dequantize (`bool`, *optional*, default to `False`):
  1524. Whether we dequantize the model to bf16 precision or not
  1525. """
  1526. def __init__(
  1527. self,
  1528. modules_to_not_convert: list | None = None,
  1529. dequantize: bool = False,
  1530. **kwargs,
  1531. ):
  1532. self.quant_method = QuantizationMethod.MXFP4
  1533. self.modules_to_not_convert = modules_to_not_convert
  1534. self.dequantize = dequantize
  1535. def get_loading_attributes(self):
  1536. return {"dequantize": self.dequantize}
  1537. def to_dict(self) -> dict[str, Any]:
  1538. """
  1539. Serializes this instance to a Python dictionary. Returns:
  1540. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  1541. """
  1542. return {"quant_method": self.quant_method, "modules_to_not_convert": self.modules_to_not_convert}
  1543. class MetalConfig(QuantizationConfigMixin):
  1544. """
  1545. Configuration class for Metal affine quantization targeting Apple Silicon (MPS) devices.
  1546. This quantization method uses the ``mlx-quantization-metal-kernels`` Metal kernels from the Hugging Face Hub
  1547. to perform affine quantization (scales + qbiases) with configurable bit-width and group size.
  1548. The quantized weights are packed into ``uint32`` tensors and the forward pass uses fused
  1549. dequantization + matmul Metal kernels.
  1550. """
  1551. def __init__(
  1552. self,
  1553. bits: int = 4,
  1554. group_size: int = 64,
  1555. modules_to_not_convert: list | None = None,
  1556. dequantize: bool = False,
  1557. **kwargs,
  1558. ):
  1559. self.quant_method = QuantizationMethod.METAL
  1560. self.bits = bits
  1561. self.group_size = group_size
  1562. self.modules_to_not_convert = modules_to_not_convert
  1563. self.dequantize = dequantize
  1564. self.post_init()
  1565. def post_init(self):
  1566. if self.bits not in (2, 4, 8):
  1567. raise ValueError(f"Metal quantization only supports bits in {{2, 4, 8}}, got {self.bits}")
  1568. if self.group_size <= 0:
  1569. raise ValueError(f"group_size must be positive, got {self.group_size}")
  1570. def get_loading_attributes(self):
  1571. return {"dequantize": self.dequantize}
  1572. def to_dict(self) -> dict[str, Any]:
  1573. return {
  1574. "quant_method": self.quant_method,
  1575. "bits": self.bits,
  1576. "group_size": self.group_size,
  1577. "modules_to_not_convert": self.modules_to_not_convert,
  1578. }
  1579. @dataclass
  1580. class FourOverSixConfig(QuantizationConfigMixin):
  1581. """
  1582. This is a wrapper class containing all options for quantization with `fouroversix`. In brief,
  1583. Four Over Six is a modification to NVFP4 quantization which adaptively scales the largest value
  1584. in each block of 16 FP4 values to either 4 or 6. Selecting a scale of 6 uses the full range of
  1585. FP4 values, but selecting a scale of 4 allows for a more uniform distribution of quantization
  1586. error. Refer to the original publication for more details: https://arxiv.org/abs/2512.02010.
  1587. Args:
  1588. activation_scale_rule (`str`, *optional*):
  1589. Scaling rule to use when selecting a scale for blocks in activation tensors. If not
  1590. provided, `scale_rule` is used.
  1591. dtype (`str`, default "nvfp4", *optional*, defaults to `"nvfp4"`):
  1592. The data type to use for the layer's weights, activations, and tensors. Can be
  1593. `"nvfp4"` or `"mxfp4"`.
  1594. gradient_scale_rule (`str`, *optional*):
  1595. Scaling rule to use when selecting a scale for blocks in gradient tensors. If not
  1596. provided, `scale_rule` is used.
  1597. keep_master_weights (`bool`, default False, *optional*, defaults to `False`):
  1598. Whether to keep the master weights. If `True`, high-precision weights are kept at all
  1599. times and weights are quantized online in each forward pass. This is useful for
  1600. quantized training.
  1601. matmul_backend (`str`, *optional*):
  1602. The backend to use for matrix multiplications. Can be `"cutlass"` or `"pytorch"`. If
  1603. not provided, CUTLASS will be used if available and PyTorch will be used otherwise.
  1604. output_dtype (`str`, *optional*, defaults to `"bfloat16"`):
  1605. The data type to use for the output of the layer. Can be `"bfloat16"` or `"float16"`.
  1606. quantize_backend (`str`, *optional*):
  1607. The backend to use for quantization. Can be `"cuda"`, `"triton"`, or `"pytorch"`. If
  1608. not provided, the fastest backend will be selected based on your environment, and based
  1609. on the options supported by each backend. Typically, `"cuda"` will be used for
  1610. inference, `"triton"` will be used for training, and `"pytorch"` will be used on
  1611. non-CUDA devices.
  1612. scale_rule (`str`, default "mse", *optional*, defaults to `"mse"`):
  1613. Rule to use when selecting block scales. Can be `"mse"`, `"mae"`, or `"abs_max"` for
  1614. Four Over Six, `"static_6"` for default NVFP4 quantization, or `"static_4"` to scale
  1615. all blocks to a maximum value of 4.
  1616. weight_scale_2d (`bool`, default False, *optional*, defaults to `False`):
  1617. Whether to compute scale factors on weight tensors in 2D blocks. This should be done
  1618. during training.
  1619. weight_scale_rule (`str`, *optional*):
  1620. Scaling rule to use when selecting a scale for blocks in weight tensors. If not
  1621. provided, `scale_rule` is used.
  1622. module_config_overrides (`dict[str, dict[str, Any]]`, *optional*):
  1623. A dictionary of module-specific configuration overrides. Keys should be module names, and
  1624. values should be dictionaries containing the quantization configuration for that module.
  1625. This can be used to override the default configuration for specific modules.
  1626. modules_to_not_convert (`list[str]`, *optional*, defaults to `['lm_head']`):
  1627. The list of modules to exclude from quantization. By default, the `lm_head` is excluded.
  1628. """
  1629. def __init__(
  1630. self,
  1631. activation_scale_rule: str | None = None,
  1632. dtype: str = "nvfp4",
  1633. gradient_scale_rule: str | None = None,
  1634. keep_master_weights: bool = False,
  1635. matmul_backend: str | None = None,
  1636. output_dtype: str | None = "bfloat16",
  1637. quantize_backend: str | None = None,
  1638. scale_rule: str = "mse",
  1639. weight_scale_2d: bool = False,
  1640. weight_scale_rule: str | None = None,
  1641. module_config_overrides: dict[str, dict[str, Any]] | None = None,
  1642. modules_to_not_convert: list[str] | None = ["lm_head"],
  1643. **kwargs,
  1644. ):
  1645. self.quant_method = QuantizationMethod.FOUR_OVER_SIX
  1646. self.activation_scale_rule = activation_scale_rule
  1647. self.dtype = dtype
  1648. self.gradient_scale_rule = gradient_scale_rule
  1649. self.keep_master_weights = keep_master_weights
  1650. self.matmul_backend = matmul_backend
  1651. self.quantize_backend = quantize_backend
  1652. self.output_dtype = output_dtype
  1653. self.scale_rule = scale_rule
  1654. self.weight_scale_2d = weight_scale_2d
  1655. self.weight_scale_rule = weight_scale_rule
  1656. self.module_config_overrides = module_config_overrides
  1657. self.modules_to_not_convert = modules_to_not_convert
  1658. class SinqConfig(QuantizationConfigMixin):
  1659. """
  1660. Quantization config for SINQ / A-SINQ.
  1661. Pass this to:
  1662. AutoModel.from_pretrained(..., quantization_config=SinqConfig(...))
  1663. Args:
  1664. nbits (`int`, default 4):
  1665. Quantization bits for weights.
  1666. group_size (`int`, default 64):
  1667. Group size used in SINQ weight quantization (must be multiple of 8).
  1668. tiling_mode (`str`, default "1D"):
  1669. Tiling mode for SINQ (typically "1D"; "2D" if supported in your backend).
  1670. method (`str`, default "sinq"):
  1671. "sinq" – calibration-free weight-only SINQ
  1672. "asinq" – A-SINQ (activation-aware), not supported in Hugging Face. Please refer to the official SINQ repository.
  1673. modules_to_not_convert (`list[str]`, *optional*):
  1674. List of module names/prefixes to keep in full precision.
  1675. **kwargs:
  1676. Extra user arguments (kept in `_extra_kwargs` for round-tripping).
  1677. """
  1678. def __init__(
  1679. self,
  1680. nbits: int = 4,
  1681. group_size: int = 64,
  1682. tiling_mode: str = "1D",
  1683. method: str = "sinq", # "sinq" | "asinq"
  1684. modules_to_not_convert: list[str] | None = None,
  1685. **kwargs: Any,
  1686. ):
  1687. self.quant_method = QuantizationMethod.SINQ
  1688. self.nbits = nbits
  1689. self.group_size = group_size
  1690. self.tiling_mode = tiling_mode
  1691. self.method = method
  1692. self.modules_to_not_convert = modules_to_not_convert
  1693. self._extra_kwargs: dict[str, Any] = dict(kwargs)
  1694. self.post_init()
  1695. def post_init(self):
  1696. self.nbits = int(self.nbits)
  1697. self.group_size = int(self.group_size)
  1698. self.tiling_mode = str(self.tiling_mode)
  1699. self.method = str(self.method).lower()
  1700. # Validation
  1701. if not isinstance(self.nbits, int):
  1702. raise TypeError("`nbits` must be convertible to an int")
  1703. if not isinstance(self.group_size, int):
  1704. raise TypeError("`group_size` must be convertible to an int")
  1705. if not isinstance(self.tiling_mode, str):
  1706. raise TypeError("`tiling_mode` must be convertible to a string")
  1707. if self.method not in {"sinq", "asinq"}:
  1708. raise ValueError(f"`method` must be either 'sinq' or 'asinq', got {self.method}")
  1709. if self.group_size is not None and self.group_size % 8 != 0:
  1710. logger.warning(
  1711. f"SINQ: group_size={self.group_size} is not a multiple of 8; this may be rejected by the backend."
  1712. )