peft.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. # Copyright 2023 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import copy
  15. import inspect
  16. import json
  17. import os
  18. import re
  19. from dataclasses import replace
  20. from typing import TYPE_CHECKING, Any, Literal, Optional
  21. from ..conversion_mapping import (
  22. _MODEL_TO_CONVERSION_PATTERN,
  23. get_checkpoint_conversion_mapping,
  24. get_model_conversion_mapping,
  25. )
  26. from ..core_model_loading import (
  27. Concatenate,
  28. ConversionOps,
  29. MergeModulelist,
  30. Transpose,
  31. WeightConverter,
  32. WeightRenaming,
  33. )
  34. from ..utils import (
  35. CONFIG_NAME,
  36. cached_file,
  37. check_peft_version,
  38. extract_commit_hash,
  39. find_adapter_config_file,
  40. is_accelerate_available,
  41. is_peft_available,
  42. is_torch_available,
  43. logging,
  44. )
  45. from ..utils.hub import DownloadKwargs
  46. from ..utils.loading_report import log_state_dict_report
  47. if is_torch_available():
  48. import torch
  49. if is_accelerate_available():
  50. from accelerate import dispatch_model
  51. from accelerate.utils import get_balanced_memory, infer_auto_device_map
  52. # Minimum PEFT version supported for the integration
  53. MIN_PEFT_VERSION = "0.18.0"
  54. logger = logging.get_logger(__name__)
  55. if TYPE_CHECKING:
  56. from ..modeling_utils import LoadStateDictConfig
  57. # TODO: remove once PEFT < 0.19 no longer supported
  58. def _block_diag_3d(tensors: list[torch.Tensor]) -> torch.Tensor:
  59. if len(tensors) < 2:
  60. raise ValueError(f"_block_diag_3d expects at least 2 tensors, got {len(tensors)}")
  61. if any(t.dim() != 3 for t in tensors):
  62. raise ValueError("_block_diag_3d expects all tensors to be 3d.")
  63. num_experts = tensors[0].shape[0]
  64. if any(t.shape[0] != num_experts for t in tensors):
  65. raise ValueError("All tensors passed to _block_diag_3d must have the same number of experts.")
  66. lora_b_block_diag = []
  67. for i in range(num_experts):
  68. lora_b_block_diag.append(torch.block_diag(*[tensor[i] for tensor in tensors]))
  69. return torch.stack(lora_b_block_diag, dim=0)
  70. # TODO: remove once PEFT < 0.19 no longer supported
  71. class PeftConcatenate(Concatenate):
  72. """Convert per-expert LoRA weights to merged weights.
  73. When the base weights are fused, e.g. W01 = [W0, W1], the LoRA weights also need to be fused. To achieve this
  74. correctly, concatenate the LoRA A weights along the r (rank) dimension. This doesn't require a new Operation. But
  75. for LoRA B, the weights need to be merged in a block diagonal fashion to achieve the correct result.
  76. To illustrate:
  77. Before:
  78. W0' = W0 + A0 @ B0
  79. W1' = W1 + A1 @ B1
  80. After:
  81. W01' = W01 + A01 @ B01_bd
  82. where:
  83. A01 = [A0, A1]
  84. B01_bd = [[B0, 0], [0, B1]]
  85. This class is responsible for merging LoRA B in this block-diagonal fashion. Assuming that we fuse N weights, it
  86. should look like this:
  87. 1. LoRA B is 2-dim
  88. Normal LoRA weight of shape (out_feat, rank), the output shape should be (N * out_feat, N * rank).
  89. 2. LoRA B is 3-dim
  90. MoE LoRA weight of shape (experts, out_feat, rank), the output shape should be (experts, N * out_feat, N * rank).
  91. After this, the experts x rank dimension are flattened, as PEFT expects 2d tensors for LoRA.
  92. """
  93. @torch.no_grad
  94. def convert(
  95. self,
  96. input_dict: dict[str, list[torch.Tensor]],
  97. source_patterns: list[str],
  98. target_patterns: list[str],
  99. full_layer_name: str,
  100. **kwargs,
  101. ) -> dict[str, list[torch.Tensor]]:
  102. dims = [v.dim() for v in input_dict.values()]
  103. if set(dims) not in ({2}, {3}):
  104. raise ValueError(
  105. f"To convert this LoRA adapter, the LoRA weights all need to have either 2 or 3 dims, got {set(dims)}"
  106. )
  107. # Keep source order stable (e.g. w1 before w3 for Mixtral) to preserve gate/up semantics.
  108. ordered_tensors = [
  109. input_dict[source_pattern] for source_pattern in source_patterns if source_pattern in input_dict
  110. ]
  111. if len(ordered_tensors) != len(input_dict):
  112. missing = set(input_dict) - set(source_patterns)
  113. raise ValueError(
  114. "Collected tensors contain keys not present in source_patterns. "
  115. f"Unexpected keys: {sorted(missing)}; source_patterns={source_patterns}"
  116. )
  117. if set(dims) == {2}:
  118. output_dict = {full_layer_name: torch.block_diag(*ordered_tensors)}
  119. else:
  120. # with r being the LoRA rank and n being the number of fused weights:
  121. out = _block_diag_3d(ordered_tensors) # shape = experts, n*out_feat, 2*r
  122. out = torch.permute(out, (2, 0, 1)) # shape = 2*r, experts, n*out_feat
  123. out = out.flatten(0, 1) # shape = 2*r * experts, n*out_feat
  124. out = out.T
  125. output_dict = {full_layer_name: out}
  126. return output_dict
  127. @property
  128. def reverse_op(self) -> ConversionOps:
  129. raise NotImplementedError("Reversing PEFT LoRA MoE conversions is not supported yet.")
  130. # TODO: remove once PEFT < 0.19 no longer supported
  131. class FlattenDims(ConversionOps):
  132. """
  133. Flatten the tensors along the given dimensions
  134. """
  135. def __init__(self, dims: int | tuple[int, ...]):
  136. if isinstance(dims, int):
  137. dims = (dims,)
  138. self.dims = dims
  139. @torch.no_grad
  140. def convert(
  141. self,
  142. input_dict: dict[str, list[torch.Tensor]],
  143. source_patterns: list[str],
  144. target_patterns: list[str],
  145. config,
  146. **kwargs,
  147. ) -> dict[str, list[torch.Tensor]]:
  148. output_dict = {k: v.flatten(*self.dims) for k, v in input_dict.items()}
  149. return output_dict
  150. @property
  151. def reverse_op(self) -> ConversionOps:
  152. raise NotImplementedError("Reversing flatteing operatio is not supported.")
  153. def __repr__(self):
  154. return f"{self.__class__.__name__}(dims={self.dims})"
  155. # TODO: remove once PEFT < 0.19 no longer supported
  156. class PermuteDims(ConversionOps):
  157. """
  158. Permute the tensors along the given dimensions
  159. """
  160. def __init__(self, dims: tuple[int, ...]):
  161. self.dims = dims
  162. @torch.no_grad
  163. def convert(
  164. self,
  165. input_dict: dict[str, list[torch.Tensor]],
  166. source_patterns: list[str],
  167. target_patterns: list[str],
  168. config,
  169. **kwargs,
  170. ) -> dict[str, list[torch.Tensor]]:
  171. output_dict = {k: v.permute(*self.dims) for k, v in input_dict.items()}
  172. return output_dict
  173. @property
  174. def reverse_op(self) -> ConversionOps:
  175. raise NotImplementedError("Reversing flatteing operatio is not supported yet.")
  176. def __repr__(self):
  177. return f"{self.__class__.__name__}(dims={self.dims})"
  178. # TODO: remove once PEFT < 0.19 no longer supported
  179. def build_peft_weight_mapping(
  180. weight_conversions: list[WeightConverter | WeightRenaming] | None, adapter_name: str, peft_config=None
  181. ) -> list[WeightConverter | WeightRenaming]:
  182. # We iterate over all the operations of the original model and simply edit them to apply to the PEFT adapter when
  183. # appropriate.
  184. # Note: This function is used in PEFT, changing it requires coordination.
  185. if not weight_conversions:
  186. return []
  187. # strip "base_model.model" and add adapter name
  188. new_weight_conversions = [WeightRenaming("base_model.model.model.", "model.")]
  189. prefixes = set()
  190. from peft.mapping import PEFT_TYPE_TO_PREFIX_MAPPING
  191. peft_type = getattr(peft_config, "peft_type", None)
  192. if peft_type in PEFT_TYPE_TO_PREFIX_MAPPING:
  193. prefixes.add(PEFT_TYPE_TO_PREFIX_MAPPING[peft_type])
  194. else:
  195. prefixes.update(PEFT_TYPE_TO_PREFIX_MAPPING.values())
  196. for prefix in sorted(prefixes):
  197. escaped_prefix = re.escape(prefix)
  198. new_weight_conversions.append(
  199. WeightRenaming(
  200. source_patterns=rf"({escaped_prefix}[^\.]*)",
  201. target_patterns=rf"\1.{adapter_name}",
  202. )
  203. )
  204. for orig_conversion in weight_conversions:
  205. if isinstance(orig_conversion, WeightRenaming):
  206. new_weight_conversions.append(orig_conversion)
  207. continue
  208. if len(orig_conversion.target_patterns) == 1 and orig_conversion.target_patterns[0].endswith("gate_up_proj"):
  209. # gate_up_proj requires both merging the experts and concatenating for the fusion of w1 and w3
  210. for lora in ("lora_A", "lora_B"): # TODO: lora_embedding_A and lora_embedding_B
  211. # deal with operations
  212. peft_weight_operations = []
  213. for op in orig_conversion.operations:
  214. if isinstance(op, Concatenate):
  215. if lora == "lora_B": # block diagonal concat
  216. peft_weight_operations.append(PeftConcatenate(dim=op.dim))
  217. else: # normal concat + flatten
  218. peft_weight_operations.append(op)
  219. peft_weight_operations.append(FlattenDims(dims=(0, 1)))
  220. elif isinstance(op, MergeModulelist):
  221. peft_weight_operations.append(op)
  222. # TODO: this assumption may not hold for models != mixtral
  223. # For source, we capture the original weights + the lora weights
  224. new_source_patterns = []
  225. for pat in list(orig_conversion.source_patterns):
  226. # we replace the weight pattern to colllect loras
  227. pat = pat.rsplit(".", 1)[0]
  228. # note: the source state_dict does *not* contain the adapter name
  229. new_source_patterns.append(f"{pat}.{lora}.*")
  230. # the gate_up_proj is the innner PEFT ParamWrapper, so we need to use base_layer
  231. pat = orig_conversion.target_patterns[0]
  232. pat = pat.replace("gate_up_proj", "base_layer")
  233. # we make sure the target key is correct, add '.weight' because the parameter is targeted directly
  234. new_target_patterns = [f"{pat}.{lora}.{adapter_name}.weight"]
  235. # Instantiate a new object that correctly post process patterns if needed
  236. new_conversion = orig_conversion.__class__(
  237. source_patterns=new_source_patterns,
  238. target_patterns=new_target_patterns,
  239. distributed_operation=orig_conversion.distributed_operation,
  240. quantization_operation=orig_conversion.quantization_operation,
  241. operations=peft_weight_operations,
  242. )
  243. new_weight_conversions.append(new_conversion)
  244. elif len(orig_conversion.target_patterns) == 1 and orig_conversion.target_patterns[0].endswith("down_proj"):
  245. # down_proj only requires merging of experts
  246. for lora in ("lora_A", "lora_B"): # TODO: lora_embedding_A and lora_embedding_B
  247. peft_weight_operations = []
  248. for op in orig_conversion.operations:
  249. if isinstance(op, MergeModulelist):
  250. peft_weight_operations.append(op)
  251. if lora == "lora_A":
  252. peft_weight_operations.append(FlattenDims(dims=(0, 1)))
  253. else:
  254. peft_weight_operations.append(PermuteDims(dims=(2, 0, 1)))
  255. peft_weight_operations.append(FlattenDims(dims=(0, 1)))
  256. peft_weight_operations.append(Transpose(dim0=0, dim1=1))
  257. # TODO: this assumption may not hold for models != mixtral
  258. # For source, we capture the original weights + the lora weights
  259. new_source_patterns = []
  260. for pat in list(orig_conversion.source_patterns):
  261. # we replace the weight pattern to colllect loras
  262. pat = pat.rsplit(".", 1)[0]
  263. # note: the source state_dict does *not* contain the adapter name
  264. new_source_patterns.append(f"{pat}.{lora}.*")
  265. # the down_proj is the outer PEFT ParamWrapper, so we remove the prefix
  266. pat = orig_conversion.target_patterns[0]
  267. pat = pat.replace(".down_proj", "")
  268. # we make sure the target key is correct, add '.weight' because the parameter is targeted directly
  269. new_target_patterns = [f"{pat}.{lora}.{adapter_name}.weight"]
  270. # Instantiate a new object that correctly post process patterns if needed
  271. new_conversion = orig_conversion.__class__(
  272. source_patterns=new_source_patterns,
  273. target_patterns=new_target_patterns,
  274. distributed_operation=orig_conversion.distributed_operation,
  275. quantization_operation=orig_conversion.quantization_operation,
  276. operations=peft_weight_operations,
  277. )
  278. new_weight_conversions.append(new_conversion)
  279. return new_weight_conversions
  280. # The main reason we have to explicit this is because the conversion mapping
  281. # has the full layer name, while the config do not. We coould regex match but
  282. # this is more explicit and less error prone.
  283. # Note: this is used in PEFT, changing it requires coordiation.
  284. # TODO: remove once PEFT < 0.19 no longer supported
  285. _MOE_TARGET_MODULE_MAPPING: dict[str, dict[str, str]] = {
  286. "mixtral": {
  287. "gate": "gate.weight",
  288. "w1": "gate_up_proj",
  289. "w3": "gate_up_proj",
  290. "w2": "down_proj",
  291. },
  292. "qwen2_moe": {
  293. "gate": "gate.weight",
  294. "gate_proj": "gate_up_proj",
  295. "up_proj": "gate_up_proj",
  296. "down_proj": "down_proj",
  297. },
  298. }
  299. # Note: this is used in PEFT, changing it requires coordiation.
  300. # TODO: remove once PEFT < 0.19 no longer supported
  301. _MOE_FUSED_TARGETS: dict[str, dict[str, set[str]]] = {
  302. # use lists for dict values to ensure stable order
  303. "mixtral": {"gate_up_proj": ["w1", "w3"]},
  304. "qwen2_moe": {"gate_up_proj": ["gate_proj", "up_proj"]},
  305. }
  306. # TODO: remove once PEFT < 0.19 no longer supported
  307. def patch_moe_parameter_targeting(model, peft_config):
  308. """PEFT currently assumes that expert layers are of shape
  309. (expert, in, out)
  310. but with Mixtral in transformers v5 this is not true anymore.
  311. This will be addressed in PEFT >0.19 until then we need to handle
  312. it here for now.
  313. """
  314. from functools import wraps
  315. import peft
  316. model_type = getattr(model.config, "model_type", None)
  317. if get_checkpoint_conversion_mapping(model_type) is not None:
  318. update_layer = peft.tuners.lora.layer.ParamWrapper.update_layer
  319. @wraps(update_layer)
  320. def new_update_layer(layer, *args, **kwargs):
  321. did_swap = getattr(layer, "_did_swap_in_out_features", False)
  322. if not did_swap and layer.parameter_name in ("down_proj", "gate_up_proj"):
  323. tmp_in_features = layer.in_features
  324. layer.in_features = layer.out_features
  325. layer.out_features = tmp_in_features
  326. layer._did_swap_in_out_features = True
  327. return update_layer(layer, *args, **kwargs)
  328. peft.tuners.lora.layer.ParamWrapper.update_layer = new_update_layer
  329. class PeftAdapterMixin:
  330. """
  331. A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
  332. more details about adapters and injecting them on a transformer-based model, check out the documentation of PEFT
  333. library: https://huggingface.co/docs/peft/index
  334. Currently supported PEFT methods are all non-prompt learning methods (LoRA, IA³, etc.). Other PEFT models such as
  335. prompt tuning, prompt learning are out of scope as these adapters are not "injectable" into a torch module. For
  336. using these methods, please refer to the usage guide of PEFT library.
  337. With this mixin, if the correct PEFT version is installed (>= 0.18.0), it is possible to:
  338. - Load an adapter stored on a local path or in a remote Hub repository, and inject it in the model
  339. - Attach new adapters in the model and train them with Trainer or by your own.
  340. - Attach multiple adapters and iteratively activate / deactivate them
  341. - Activate / deactivate all adapters from the model.
  342. - Get the `state_dict` of the active adapter.
  343. """
  344. _hf_peft_config_loaded = False
  345. _prepare_peft_hotswap_kwargs: dict | None = None
  346. def load_adapter(
  347. self,
  348. peft_model_id: str | None = None,
  349. adapter_name: str | None = None,
  350. peft_config: dict[str, Any] | None = None,
  351. adapter_state_dict: dict[str, "torch.Tensor"] | None = None,
  352. low_cpu_mem_usage: bool = False,
  353. is_trainable: bool = False,
  354. hotswap: bool | Literal["auto"] = "auto",
  355. local_files_only: bool = False,
  356. adapter_kwargs: dict[str, Any] | None = None,
  357. load_config: Optional["LoadStateDictConfig"] = None,
  358. **kwargs,
  359. ) -> None:
  360. """
  361. Load adapter weights from file or remote Hub folder. If you are not familiar with adapters and PEFT methods, we
  362. invite you to read more about them on PEFT official documentation: https://huggingface.co/docs/peft
  363. Requires PEFT to be installed as a backend to load the adapter weights.
  364. Args:
  365. peft_model_id (`str`, *optional*):
  366. The identifier of the model to look for on the Hub, or a local path to the saved adapter config file
  367. and adapter weights.
  368. adapter_name (`str`, *optional*):
  369. The adapter name to use. If not set, will use the name "default".
  370. load_config (`LoadStateDictConfig`, *optional*):
  371. A load configuration to reuse when pulling adapter weights, typically from `from_pretrained`.
  372. kwargs (`dict[str, Any]`, *optional*):
  373. Additional `LoadStateDictConfig` fields passed as keyword arguments.
  374. peft_config (`dict[str, Any]`, *optional*):
  375. The configuration of the adapter to add, supported adapters are all non-prompt learning configs (LoRA,
  376. IA³, etc). This argument is used in case users directly pass PEFT state dicts.
  377. adapter_state_dict (`dict[str, torch.Tensor]`, *optional*):
  378. The state dict of the adapter to load. This argument is used in case users directly pass PEFT state
  379. dicts.
  380. low_cpu_mem_usage (`bool`, *optional*, defaults to `False`):
  381. Reduce memory usage while loading the PEFT adapter. This should also speed up the loading process.
  382. is_trainable (`bool`, *optional*, defaults to `False`):
  383. Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be
  384. used for inference.
  385. hotswap : (`"auto"` or `bool`, *optional*, defaults to `"auto"`)
  386. Whether to substitute an existing (LoRA) adapter with the newly loaded adapter in-place. This means
  387. that, instead of loading an additional adapter, this will take the existing adapter weights and replace
  388. them with the weights of the new adapter. This can be faster and more memory efficient. However, the
  389. main advantage of hotswapping is that when the model is compiled with torch.compile, loading the new
  390. adapter does not require recompilation of the model. When using hotswapping, the passed `adapter_name`
  391. should be the name of an already loaded adapter.
  392. If the new adapter and the old adapter have different ranks and/or LoRA alphas (i.e. scaling), you need
  393. to call an additional method before loading the adapter:
  394. ```py
  395. model = AutoModel.from_pretrained(...)
  396. max_rank = ... # the highest rank among all LoRAs that you want to load
  397. # call *before* compiling and loading the LoRA adapter
  398. model.enable_peft_hotswap(target_rank=max_rank)
  399. model.load_adapter(file_name_1, adapter_name="default")
  400. # optionally compile the model now
  401. model = torch.compile(model, ...)
  402. output_1 = model(...)
  403. # now you can hotswap the 2nd adapter, use the same name as for the 1st
  404. # hotswap is activated by default since enable_peft_hotswap was called
  405. model.load_adapter(file_name_2, adapter_name="default")
  406. output_2 = model(...)
  407. ```
  408. By default, hotswap is disabled and requires passing `hotswap=True`. If you called
  409. `enable_peft_hotswap` first, it is enabled. You can still manually disable it in that case by passing
  410. `hotswap=False`.
  411. Note that hotswapping comes with a couple of limitations documented here:
  412. https://huggingface.co/docs/peft/main/en/package_reference/hotswap
  413. adapter_kwargs (`dict[str, Any]`, *optional*):
  414. Additional keyword arguments passed along to the `from_pretrained` method of the adapter config and
  415. `find_adapter_config_file` method.
  416. """
  417. from peft import PeftType
  418. from ..modeling_utils import LoadStateDictConfig, _get_resolved_checkpoint_files
  419. if local_files_only:
  420. kwargs["local_files_only"] = True
  421. base_load_config = load_config.__dict__ if load_config is not None else {}
  422. base_load_config.update(kwargs)
  423. base_load_config.setdefault("pretrained_model_name_or_path", None)
  424. load_config = LoadStateDictConfig(**base_load_config)
  425. peft_model_id = peft_model_id or load_config.pretrained_model_name_or_path
  426. if hotswap == "auto":
  427. # if user called model.enable_peft_hotswap and this is not the first adapter, enable hotswap
  428. hotswap_enabled = getattr(self, "_hotswap_enabled", False)
  429. not_first_adapter = bool(self._hf_peft_config_loaded and (adapter_name in self.peft_config))
  430. hotswap = hotswap_enabled and not_first_adapter
  431. if hotswap:
  432. if (not self._hf_peft_config_loaded) or (adapter_name not in self.peft_config):
  433. raise ValueError(
  434. "To hotswap an adapter, there must already be an existing adapter with the same adapter name."
  435. )
  436. if any(conf.peft_type != PeftType.LORA for conf in self.peft_config.values()):
  437. raise ValueError("Hotswapping is currently only supported for LoRA, please set `hotswap=False`.")
  438. adapter_name = adapter_name if adapter_name is not None else "default"
  439. adapter_kwargs = adapter_kwargs or {}
  440. from peft import PeftConfig, inject_adapter_in_model
  441. if self._hf_peft_config_loaded and (not hotswap) and (adapter_name in self.peft_config):
  442. raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
  443. elif hotswap and ((not self._hf_peft_config_loaded) or (adapter_name not in self.peft_config)):
  444. raise ValueError(
  445. "To hotswap an adapter, there must already be an existing adapter with the same adapter name."
  446. )
  447. if peft_model_id is None and (adapter_state_dict is None and peft_config is None):
  448. raise ValueError(
  449. "You should either pass a `peft_model_id` or a `peft_config` and `adapter_state_dict` to load an adapter."
  450. )
  451. if peft_config is None:
  452. load_config.download_kwargs.update(**adapter_kwargs)
  453. adapter_config_file = find_adapter_config_file(
  454. peft_model_id,
  455. **load_config.download_kwargs,
  456. )
  457. if adapter_config_file is None:
  458. raise ValueError(
  459. f"adapter model file not found in {peft_model_id}. Make sure you are passing the correct path to the "
  460. "adapter model."
  461. )
  462. peft_config = PeftConfig.from_pretrained(
  463. peft_model_id,
  464. **load_config.download_kwargs,
  465. )
  466. weight_conversions = get_model_conversion_mapping(self)
  467. # TODO: remove once PEFT < 0.19 is dropped, use peft.utils.transformers_weight_conversion
  468. peft_config = convert_peft_config_for_transformers(peft_config, model=self, conversions=weight_conversions)
  469. if hasattr(peft_config, "inference_mode"):
  470. peft_config.inference_mode = not is_trainable
  471. peft_weight_conversions = build_peft_weight_mapping(weight_conversions, adapter_name, peft_config=peft_config)
  472. patch_moe_parameter_targeting(model=self, peft_config=peft_config)
  473. if not hotswap:
  474. # Create and add fresh new adapters into the model, unless the weights are hotswapped
  475. inject_adapter_in_model(peft_config, self, adapter_name)
  476. if not self._hf_peft_config_loaded:
  477. self._hf_peft_config_loaded = True
  478. if adapter_state_dict is None:
  479. adapter_filenames = ["adapter_model.safetensors", "adapter_model.bin"]
  480. if load_config.use_safetensors is False:
  481. adapter_filenames.reverse()
  482. checkpoint_files = sharded_metadata = None
  483. last_error = None
  484. for adapter_filename in adapter_filenames:
  485. try:
  486. checkpoint_files, sharded_metadata = _get_resolved_checkpoint_files(
  487. pretrained_model_name_or_path=peft_model_id,
  488. variant=None,
  489. gguf_file=None,
  490. use_safetensors=(
  491. load_config.use_safetensors if adapter_filename.endswith(".safetensors") else False
  492. ),
  493. user_agent=None,
  494. is_remote_code=False,
  495. transformers_explicit_filename=adapter_filename,
  496. download_kwargs=load_config.download_kwargs,
  497. )
  498. break
  499. except OSError as error:
  500. last_error = error
  501. if checkpoint_files is None:
  502. raise last_error or OSError("Could not download either a .bin or a .safetensors adapter file.")
  503. else:
  504. checkpoint_files, sharded_metadata = [], {}
  505. device_map = getattr(self, "hf_device_map", {"": self.device})
  506. load_config = replace(
  507. load_config,
  508. pretrained_model_name_or_path=peft_model_id,
  509. sharded_metadata=sharded_metadata,
  510. weight_mapping=peft_weight_conversions,
  511. device_map=device_map,
  512. )
  513. loading_info, _ = self._load_pretrained_model(
  514. model=self,
  515. state_dict=adapter_state_dict,
  516. checkpoint_files=checkpoint_files,
  517. load_config=load_config,
  518. # pass expected keys explicitly, otherwise they are determined from the state_dict, which can contain
  519. # unexpected entries, like "layer.SCB" from a bnb layer.
  520. expected_keys=[n for n, _ in self.named_parameters()],
  521. )
  522. if peft_config.inference_mode:
  523. from peft.tuners.tuners_utils import BaseTunerLayer
  524. self.eval()
  525. for module in self.modules():
  526. if isinstance(module, BaseTunerLayer):
  527. module.requires_grad_(False)
  528. adapter_key_markers = {adapter_name}
  529. if peft_config is not None and getattr(peft_config, "peft_type", None) is not None:
  530. adapter_key_markers.add(peft_config.peft_type.value.lower())
  531. def is_adapter_key(key: str) -> bool:
  532. return any(marker in key for marker in adapter_key_markers)
  533. loading_info.missing_keys = {k for k in loading_info.missing_keys if is_adapter_key(k)}
  534. log_state_dict_report(
  535. model=self,
  536. pretrained_model_name_or_path=load_config.pretrained_model_name_or_path,
  537. ignore_mismatched_sizes=load_config.ignore_mismatched_sizes,
  538. loading_info=loading_info,
  539. logger=logger,
  540. )
  541. def enable_peft_hotswap(
  542. self, target_rank: int = 128, check_compiled: Literal["error", "warn", "ignore"] = "error"
  543. ) -> None:
  544. """Enables the possibility to hotswap PEFT adapters with different ranks, or, if the model is compiled, without
  545. triggering recompilation.
  546. Right now, hotswapping is only supported for LoRA.
  547. Calling this method is only required when hotswapping adapters and if the model is compiled or if the ranks of
  548. the loaded adapters differ. If the ranks are all identical and the model is not compiled, hotswapping works
  549. without calling this method first.
  550. Args:
  551. target_rank (`int`, *optional*, defaults to `128`):
  552. The highest rank among all the adapters that will be loaded.
  553. check_compiled (`str`, *optional*, defaults to `"error"`):
  554. How to handle the case when the model is already compiled, which should generally be avoided. The
  555. options are:
  556. - "error" (default): raise an error
  557. - "warn": issue a warning
  558. - "ignore": do nothing
  559. """
  560. if getattr(self, "peft_config", {}):
  561. if check_compiled == "error":
  562. raise RuntimeError("Call `enable_peft_hotswap` before loading the first adapter.")
  563. elif check_compiled == "warn":
  564. logger.warning(
  565. "It is recommended to call `enable_peft_hotswap` before loading the first adapter to avoid recompilation."
  566. )
  567. elif check_compiled != "ignore":
  568. raise ValueError(
  569. f"check_compiles should be one of 'error', 'warn', or 'ignore', got '{check_compiled}' instead."
  570. )
  571. self._hotswap_enabled = True
  572. self._prepare_peft_hotswap_kwargs = {"target_rank": target_rank, "check_compiled": check_compiled}
  573. def add_adapter(self, adapter_config, adapter_name: str | None = None) -> None:
  574. r"""
  575. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  576. official documentation: https://huggingface.co/docs/peft
  577. Adds a fresh new adapter to the current model for training purpose. If no adapter name is passed, a default
  578. name is assigned to the adapter to follow the convention of PEFT library (in PEFT we use "default" as the
  579. default adapter name).
  580. Note that the newly added adapter is not automatically activated. To activate it, use `model.set_adapter`.
  581. Args:
  582. adapter_config (`~peft.PeftConfig`):
  583. The configuration of the adapter to add, supported adapters are non-prompt learning methods (LoRA,
  584. IA³, etc.).
  585. adapter_name (`str`, *optional*, defaults to `"default"`):
  586. The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
  587. """
  588. check_peft_version(min_version=MIN_PEFT_VERSION)
  589. from peft import PeftConfig, inject_adapter_in_model
  590. adapter_name = adapter_name or "default"
  591. if not self._hf_peft_config_loaded:
  592. self._hf_peft_config_loaded = True
  593. elif adapter_name in self.peft_config:
  594. raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
  595. if not isinstance(adapter_config, PeftConfig):
  596. raise TypeError(f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead.")
  597. # Retrieve the name or path of the model, one could also use self.config._name_or_path
  598. # but to be consistent with what we do in PEFT: https://github.com/huggingface/peft/blob/6e783780ca9df3a623992cc4d1d665001232eae0/src/peft/mapping.py#L100
  599. adapter_config.base_model_name_or_path = self.__dict__.get("name_or_path", None)
  600. # TODO: WE NEED TOO APPLY OUR DYNAMIC WEIGHT CONVERSION AT SOME POINT HERE!
  601. inject_adapter_in_model(adapter_config, self, adapter_name)
  602. self.set_adapter(adapter_name)
  603. def set_adapter(self, adapter_name: list[str] | str) -> None:
  604. """
  605. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  606. official documentation: https://huggingface.co/docs/peft
  607. Sets a specific adapter by forcing the model to use a that adapter and disable the other adapters.
  608. Args:
  609. adapter_name (`Union[list[str], str]`):
  610. The name of the adapter to set. Can be also a list of strings to set multiple adapters.
  611. """
  612. check_peft_version(min_version=MIN_PEFT_VERSION)
  613. if not self._hf_peft_config_loaded:
  614. raise ValueError("No adapter loaded. Please load an adapter first.")
  615. elif isinstance(adapter_name, list):
  616. missing = set(adapter_name) - set(self.peft_config)
  617. if len(missing) > 0:
  618. raise ValueError(
  619. f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
  620. f" current loaded adapters are: {list(self.peft_config.keys())}"
  621. )
  622. elif adapter_name not in self.peft_config:
  623. raise ValueError(
  624. f"Adapter with name {adapter_name} not found. Please pass the correct adapter name among {list(self.peft_config.keys())}"
  625. )
  626. from peft.tuners.tuners_utils import BaseTunerLayer
  627. from peft.utils import ModulesToSaveWrapper
  628. _adapters_has_been_set = False
  629. for _, module in self.named_modules():
  630. if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)):
  631. module.set_adapter(adapter_name)
  632. _adapters_has_been_set = True
  633. if not _adapters_has_been_set:
  634. raise ValueError(
  635. "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
  636. )
  637. def disable_adapters(self) -> None:
  638. r"""
  639. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  640. official documentation: https://huggingface.co/docs/peft
  641. Disable all adapters that are attached to the model. This leads to inferring with the base model only.
  642. """
  643. check_peft_version(min_version=MIN_PEFT_VERSION)
  644. if not self._hf_peft_config_loaded:
  645. raise ValueError("No adapter loaded. Please load an adapter first.")
  646. from peft.tuners.tuners_utils import BaseTunerLayer
  647. from peft.utils import ModulesToSaveWrapper
  648. for _, module in self.named_modules():
  649. if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)):
  650. module.enable_adapters(enabled=False)
  651. def enable_adapters(self) -> None:
  652. """
  653. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  654. official documentation: https://huggingface.co/docs/peft
  655. Enable adapters that are attached to the model.
  656. """
  657. check_peft_version(min_version=MIN_PEFT_VERSION)
  658. if not self._hf_peft_config_loaded:
  659. raise ValueError("No adapter loaded. Please load an adapter first.")
  660. from peft.tuners.tuners_utils import BaseTunerLayer
  661. for _, module in self.named_modules():
  662. if isinstance(module, BaseTunerLayer):
  663. module.enable_adapters(enabled=True)
  664. def active_adapters(self) -> list[str]:
  665. """
  666. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  667. official documentation: https://huggingface.co/docs/peft
  668. Gets the current active adapters of the model. In case of multi-adapter inference (combining multiple adapters
  669. for inference) returns the list of all active adapters so that users can deal with them accordingly.
  670. For previous PEFT versions (that does not support multi-adapter inference), `module.active_adapter` will return
  671. a single string.
  672. """
  673. check_peft_version(min_version=MIN_PEFT_VERSION)
  674. if not self._hf_peft_config_loaded:
  675. raise ValueError("No adapter loaded. Please load an adapter first.")
  676. from peft.tuners.tuners_utils import BaseTunerLayer
  677. for _, module in self.named_modules():
  678. if isinstance(module, BaseTunerLayer):
  679. active_adapters = module.active_adapter
  680. break
  681. # For previous PEFT versions
  682. if isinstance(active_adapters, str):
  683. active_adapters = [active_adapters]
  684. return active_adapters
  685. def get_adapter_state_dict(self, adapter_name: str | None = None, state_dict: dict | None = None) -> dict:
  686. """
  687. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  688. official documentation: https://huggingface.co/docs/peft
  689. Gets the adapter state dict that should only contain the weights tensors of the specified adapter_name adapter.
  690. If no adapter_name is passed, the active adapter is used.
  691. Args:
  692. adapter_name (`str`, *optional*):
  693. The name of the adapter to get the state dict from. If no name is passed, the active adapter is used.
  694. state_dict (nested dictionary of `torch.Tensor`, *optional*)
  695. The state dictionary of the model. Will default to `self.state_dict()`, but can be used if special
  696. precautions need to be taken when recovering the state dictionary of a model (like when using model
  697. parallelism).
  698. """
  699. check_peft_version(min_version=MIN_PEFT_VERSION)
  700. if not self._hf_peft_config_loaded:
  701. raise ValueError("No adapter loaded. Please load an adapter first.")
  702. from peft import get_peft_model_state_dict
  703. if adapter_name is None:
  704. adapter_name = self.active_adapters()[0]
  705. adapter_state_dict = get_peft_model_state_dict(self, state_dict=state_dict, adapter_name=adapter_name)
  706. return adapter_state_dict
  707. def _dispatch_accelerate_model(
  708. self,
  709. device_map: str,
  710. max_memory: int | None = None,
  711. offload_folder: str | None = None,
  712. offload_index: int | None = None,
  713. ) -> None:
  714. """
  715. Optional re-dispatch the model and attach new hooks to the model in case the model has been loaded with
  716. accelerate (i.e. with `device_map=xxx`)
  717. Args:
  718. device_map (`str` or `dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
  719. A map that specifies where each submodule should go. It doesn't need to be refined to each
  720. parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
  721. same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
  722. like `1`) on which the model will be allocated, the device map will map the entire model to this
  723. device. Passing `device_map = 0` means put the whole model on GPU 0.
  724. To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
  725. more information about each option see [designing a device
  726. map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
  727. max_memory (`Dict`, *optional*):
  728. A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
  729. GPU and the available CPU RAM if unset.
  730. offload_folder (`str` or `os.PathLike`, *optional*):
  731. If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
  732. offload_index (`int`, *optional*):
  733. The offload_index argument to be passed to `accelerate.dispatch_model` method.
  734. """
  735. dispatch_model_kwargs = {}
  736. # Safety checker for previous `accelerate` versions
  737. # `offload_index` was introduced in https://github.com/huggingface/accelerate/pull/873/
  738. if "offload_index" in inspect.signature(dispatch_model).parameters:
  739. dispatch_model_kwargs["offload_index"] = offload_index
  740. no_split_module_classes = self._no_split_modules
  741. if device_map != "sequential":
  742. max_memory = get_balanced_memory(
  743. self,
  744. max_memory=max_memory,
  745. no_split_module_classes=no_split_module_classes,
  746. low_zero=(device_map == "balanced_low_0"),
  747. )
  748. if isinstance(device_map, str):
  749. device_map = infer_auto_device_map(
  750. self, max_memory=max_memory, no_split_module_classes=no_split_module_classes
  751. )
  752. dispatch_model(
  753. self,
  754. device_map=device_map,
  755. offload_dir=offload_folder,
  756. **dispatch_model_kwargs,
  757. )
  758. def delete_adapter(self, adapter_names: list[str] | str) -> None:
  759. """
  760. Delete a PEFT adapter from the underlying model.
  761. Args:
  762. adapter_names (`Union[list[str], str]`):
  763. The name(s) of the adapter(s) to delete.
  764. """
  765. check_peft_version(min_version=MIN_PEFT_VERSION)
  766. if not self._hf_peft_config_loaded:
  767. raise ValueError("No adapter loaded. Please load an adapter first.")
  768. from peft.functional import delete_adapter
  769. if isinstance(adapter_names, str):
  770. adapter_names = [adapter_names]
  771. # Check that all adapter names are present in the config
  772. missing_adapters = [name for name in adapter_names if name not in self.peft_config]
  773. if missing_adapters:
  774. raise ValueError(
  775. f"The following adapter(s) are not present and cannot be deleted: {', '.join(missing_adapters)}"
  776. )
  777. prefixes = [f"{self.peft_config[adapter_name].peft_type.value.lower()}_" for adapter_name in adapter_names]
  778. for adapter_name, prefix in zip(adapter_names, prefixes):
  779. delete_adapter(self, adapter_name=adapter_name, prefix=prefix)
  780. # For transformers integration - we need to pop the adapter from the config
  781. if getattr(self, "_hf_peft_config_loaded", False) and hasattr(self, "peft_config"):
  782. self.peft_config.pop(adapter_name, None)
  783. # In case all adapters are deleted, we need to delete the config
  784. # and make sure to set the flag to False
  785. if len(self.peft_config) == 0:
  786. del self.peft_config
  787. self._hf_peft_config_loaded = False
  788. def maybe_load_adapters(
  789. pretrained_model_name_or_path,
  790. download_kwargs: DownloadKwargs,
  791. **adapter_kwargs,
  792. ):
  793. if pretrained_model_name_or_path is None or not is_peft_available():
  794. return None, pretrained_model_name_or_path, adapter_kwargs
  795. token = download_kwargs.get("token")
  796. if download_kwargs.get("commit_hash") is None:
  797. resolved_config_file = cached_file(
  798. pretrained_model_name_or_path,
  799. CONFIG_NAME,
  800. cache_dir=download_kwargs.get("cache_dir"),
  801. force_download=bool(download_kwargs.get("force_download", False)),
  802. proxies=download_kwargs.get("proxies"),
  803. local_files_only=bool(download_kwargs.get("local_files_only", False)),
  804. token=token,
  805. revision=download_kwargs.get("revision"),
  806. subfolder=download_kwargs.get("subfolder"),
  807. _raise_exceptions_for_gated_repo=False,
  808. _raise_exceptions_for_missing_entries=False,
  809. _raise_exceptions_for_connection_errors=False,
  810. )
  811. download_kwargs["commit_hash"] = extract_commit_hash(resolved_config_file, None)
  812. _adapter_model_path = adapter_kwargs.pop("_adapter_model_path", None)
  813. token_from_adapter_kwargs = adapter_kwargs.pop("token", None)
  814. if _adapter_model_path is None:
  815. peft_kwargs = adapter_kwargs.copy()
  816. for arg_name in ("cache_dir", "proxies", "subfolder"): # don't override revision
  817. if (arg_name not in peft_kwargs) and (arg_name in download_kwargs):
  818. peft_kwargs[arg_name] = download_kwargs[arg_name]
  819. if "commit_hash" in download_kwargs:
  820. peft_kwargs["_commit_hash"] = download_kwargs["commit_hash"]
  821. peft_kwargs["force_download"] = bool(download_kwargs.get("force_download", False))
  822. peft_kwargs["local_files_only"] = bool(download_kwargs.get("local_files_only", False))
  823. peft_kwargs["token"] = token or token_from_adapter_kwargs
  824. _adapter_model_path = find_adapter_config_file(
  825. pretrained_model_name_or_path,
  826. **peft_kwargs,
  827. )
  828. if _adapter_model_path is not None and os.path.isfile(_adapter_model_path):
  829. with open(_adapter_model_path, "r", encoding="utf-8") as f:
  830. _adapter_model_path = pretrained_model_name_or_path
  831. # Only override the model name/path if the current value doesn't point to a
  832. # complete model with an embedded adapter so that local models with embedded
  833. # adapters will load from the local base model rather than pull the base
  834. # model named in the adapter's config from the hub.
  835. if not os.path.exists(pretrained_model_name_or_path) or not os.path.exists(
  836. os.path.join(pretrained_model_name_or_path, CONFIG_NAME)
  837. ):
  838. pretrained_model_name_or_path = json.load(f)["base_model_name_or_path"]
  839. return _adapter_model_path, pretrained_model_name_or_path, adapter_kwargs
  840. #####################
  841. # weight conversion #
  842. #####################
  843. # With transformers v5, we need to convert some weights to reflect updated model architectures. If users have trained
  844. # PEFT adapters for these models, they also need to be updated. This may require updating the PEFT config too. The
  845. # logic for this is found below. Right now, only LoRA is supported.
  846. # TODO: remove once PEFT < 0.19 no longer supported
  847. def _convert_peft_config_moe(peft_config, model_type: str):
  848. base_model_type = _MODEL_TO_CONVERSION_PATTERN.get(model_type, None)
  849. if base_model_type is None:
  850. return peft_config
  851. target_module_mapping = _MOE_TARGET_MODULE_MAPPING[base_model_type]
  852. fused_targets = _MOE_FUSED_TARGETS.get(base_model_type, {})
  853. peft_config.target_parameters = set(peft_config.target_parameters or [])
  854. peft_config.target_modules = set(peft_config.target_modules or [])
  855. if not hasattr(peft_config, "rank_pattern") or peft_config.rank_pattern is None:
  856. peft_config.rank_pattern = {}
  857. if not hasattr(peft_config, "alpha_pattern") or peft_config.alpha_pattern is None:
  858. peft_config.alpha_pattern = {}
  859. new_target_parameters = peft_config.target_parameters.copy()
  860. remaining_target_modules = set()
  861. matched_targets: dict[str, set[str]] = {new_name: set() for new_name in fused_targets}
  862. for target in peft_config.target_modules:
  863. mapped_new_name = None
  864. mapped_old_name = None
  865. for old_name, new_name in target_module_mapping.items():
  866. if (target == old_name) or target.endswith(f".{old_name}"):
  867. mapped_new_name = new_name
  868. mapped_old_name = old_name
  869. break
  870. if mapped_new_name is None:
  871. remaining_target_modules.add(target)
  872. continue
  873. new_target_parameters.add(mapped_new_name)
  874. if mapped_new_name in fused_targets and mapped_old_name is not None:
  875. matched_targets.setdefault(mapped_new_name, set()).add(mapped_old_name)
  876. for new_name, required_old_targets in fused_targets.items():
  877. present_targets = matched_targets.get(new_name, set())
  878. if 0 < len(present_targets) < len(required_old_targets):
  879. missing = ", ".join(sorted(required_old_targets - present_targets))
  880. present = ", ".join(sorted(present_targets))
  881. raise ValueError(
  882. f"Cannot convert PEFT target(s) {present} without also targeting {missing} because they are fused into {new_name}."
  883. )
  884. if len(present_targets) == len(required_old_targets) and len(required_old_targets) > 1:
  885. peft_config.rank_pattern[rf".*\.{re.escape(new_name)}"] = peft_config.r * len(required_old_targets)
  886. # Preserve per-branch LoRA scaling after fusion.
  887. # Example: w1 + w3 => r doubles, so alpha must also double to keep alpha/r unchanged.
  888. peft_config.alpha_pattern[rf".*\.{re.escape(new_name)}"] = peft_config.lora_alpha * len(
  889. required_old_targets
  890. )
  891. peft_config.target_parameters = new_target_parameters
  892. peft_config.target_modules = remaining_target_modules
  893. return peft_config
  894. # TODO: remove once PEFT < 0.19 no longer supported
  895. def convert_peft_config_for_transformers(peft_config, model: torch.nn.Module, conversions: list[Any] | None):
  896. """
  897. Convert the PEFT config of models whose architecture changed from transformers v4 to v5.
  898. For most models, this requires no changes, this mostly affects some MoE models like Mixtral.
  899. """
  900. # If, for any reason, we cannot apply conversion, we just return the PEFT config as is.
  901. from peft import PeftType # avoid circular import
  902. if peft_config.peft_type != PeftType.LORA:
  903. # weight conversion is currently only supported for LoRA
  904. return peft_config
  905. if not hasattr(model, "config"):
  906. # not a transformer model
  907. return peft_config
  908. if not hasattr(model.config, "model_type"):
  909. # not a transformer model
  910. return peft_config
  911. peft_config = copy.deepcopy(peft_config) # don't mutate the original config
  912. model_type = getattr(model.config, "model_type", None)
  913. if get_checkpoint_conversion_mapping(model_type) is not None:
  914. peft_config = _convert_peft_config_moe(peft_config, model_type)
  915. return peft_config