quantization_config.py 94 KB

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