peft.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 importlib
  15. import inspect
  16. import re
  17. from typing import Any, Optional, Union
  18. from packaging import version
  19. from ..utils import (
  20. check_peft_version,
  21. find_adapter_config_file,
  22. is_accelerate_available,
  23. is_peft_available,
  24. is_torch_available,
  25. logging,
  26. )
  27. if is_torch_available():
  28. import torch
  29. if is_accelerate_available():
  30. from accelerate import dispatch_model
  31. from accelerate.utils import get_balanced_memory, infer_auto_device_map
  32. # Minimum PEFT version supported for the integration
  33. MIN_PEFT_VERSION = "0.5.0"
  34. logger = logging.get_logger(__name__)
  35. # DO NOT MODIFY, KEPT FOR BC ONLY
  36. VLMS = [
  37. "aria",
  38. "ayavision",
  39. "emu3",
  40. "fuyu",
  41. "gotocr2",
  42. "gemma3",
  43. "internvl",
  44. "llava", # all llava prefixed models fall under this check
  45. "mistral3",
  46. "mllama",
  47. "paligemma",
  48. "qwen2vl",
  49. "qwen2_5_vl",
  50. "videollava",
  51. "vipllava",
  52. ]
  53. class PeftAdapterMixin:
  54. """
  55. A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
  56. more details about adapters and injecting them on a transformer-based model, check out the documentation of PEFT
  57. library: https://huggingface.co/docs/peft/index
  58. Currently supported PEFT methods are all non-prompt learning methods (LoRA, IA³, etc.). Other PEFT models such as
  59. prompt tuning, prompt learning are out of scope as these adapters are not "injectable" into a torch module. For
  60. using these methods, please refer to the usage guide of PEFT library.
  61. With this mixin, if the correct PEFT version is installed, it is possible to:
  62. - Load an adapter stored on a local path or in a remote Hub repository, and inject it in the model
  63. - Attach new adapters in the model and train them with Trainer or by your own.
  64. - Attach multiple adapters and iteratively activate / deactivate them
  65. - Activate / deactivate all adapters from the model.
  66. - Get the `state_dict` of the active adapter.
  67. """
  68. _hf_peft_config_loaded = False
  69. def load_adapter(
  70. self,
  71. peft_model_id: Optional[str] = None,
  72. adapter_name: Optional[str] = None,
  73. revision: Optional[str] = None,
  74. token: Optional[str] = None,
  75. device_map: str = "auto",
  76. max_memory: Optional[str] = None,
  77. offload_folder: Optional[str] = None,
  78. offload_index: Optional[int] = None,
  79. peft_config: Optional[dict[str, Any]] = None,
  80. adapter_state_dict: Optional[dict[str, "torch.Tensor"]] = None,
  81. low_cpu_mem_usage: bool = False,
  82. is_trainable: bool = False,
  83. adapter_kwargs: Optional[dict[str, Any]] = None,
  84. ) -> None:
  85. """
  86. Load adapter weights from file or remote Hub folder. If you are not familiar with adapters and PEFT methods, we
  87. invite you to read more about them on PEFT official documentation: https://huggingface.co/docs/peft
  88. Requires PEFT to be installed as a backend to load the adapter weights.
  89. Args:
  90. peft_model_id (`str`, *optional*):
  91. The identifier of the model to look for on the Hub, or a local path to the saved adapter config file
  92. and adapter weights.
  93. adapter_name (`str`, *optional*):
  94. The adapter name to use. If not set, will use the name "default".
  95. revision (`str`, *optional*, defaults to `"main"`):
  96. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  97. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  98. identifier allowed by git.
  99. > [!TIP]
  100. > To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
  101. token (`str`, `optional`):
  102. Whether to use authentication token to load the remote folder. Useful to load private repositories
  103. that are on HuggingFace Hub. You might need to call `hf auth login` and paste your tokens to
  104. cache it.
  105. device_map (`str` or `dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
  106. A map that specifies where each submodule should go. It doesn't need to be refined to each
  107. parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
  108. same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
  109. like `1`) on which the model will be allocated, the device map will map the entire model to this
  110. device. Passing `device_map = 0` means put the whole model on GPU 0.
  111. To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
  112. more information about each option see [designing a device
  113. map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
  114. max_memory (`Dict`, *optional*):
  115. A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
  116. GPU and the available CPU RAM if unset.
  117. offload_folder (`str` or `os.PathLike`, `optional`):
  118. If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
  119. offload_index (`int`, `optional`):
  120. `offload_index` argument to be passed to `accelerate.dispatch_model` method.
  121. peft_config (`dict[str, Any]`, *optional*):
  122. The configuration of the adapter to add, supported adapters are all non-prompt learning configs (LoRA,
  123. IA³, etc). This argument is used in case users directly pass PEFT state dicts.
  124. adapter_state_dict (`dict[str, torch.Tensor]`, *optional*):
  125. The state dict of the adapter to load. This argument is used in case users directly pass PEFT state
  126. dicts.
  127. low_cpu_mem_usage (`bool`, *optional*, defaults to `False`):
  128. Reduce memory usage while loading the PEFT adapter. This should also speed up the loading process.
  129. Requires PEFT version 0.13.0 or higher.
  130. is_trainable (`bool`, *optional*, defaults to `False`):
  131. Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be
  132. used for inference.
  133. adapter_kwargs (`dict[str, Any]`, *optional*):
  134. Additional keyword arguments passed along to the `from_pretrained` method of the adapter config and
  135. `find_adapter_config_file` method.
  136. """
  137. check_peft_version(min_version=MIN_PEFT_VERSION)
  138. # peft only supports low_cpu_mem_usage starting from v0.13.0
  139. peft_load_kwargs = {}
  140. key_mapping = adapter_kwargs.pop("key_mapping", None) if adapter_kwargs is not None else None
  141. if key_mapping is None and any(allowed_name in self.__class__.__name__.lower() for allowed_name in VLMS):
  142. key_mapping = self._checkpoint_conversion_mapping
  143. if low_cpu_mem_usage:
  144. min_version_lcmu = "0.13.0"
  145. if version.parse(importlib.metadata.version("peft")) >= version.parse(min_version_lcmu):
  146. peft_load_kwargs["low_cpu_mem_usage"] = low_cpu_mem_usage
  147. else:
  148. raise ValueError(
  149. "The version of PEFT you are using does not support `low_cpu_mem_usage` yet, "
  150. f"please install PEFT >= {min_version_lcmu}."
  151. )
  152. adapter_name = adapter_name if adapter_name is not None else "default"
  153. if adapter_kwargs is None:
  154. adapter_kwargs = {}
  155. from peft import PeftConfig, inject_adapter_in_model, load_peft_weights
  156. from peft.utils import set_peft_model_state_dict
  157. if self._hf_peft_config_loaded and adapter_name in self.peft_config:
  158. raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
  159. if peft_model_id is None and (adapter_state_dict is None and peft_config is None):
  160. raise ValueError(
  161. "You should either pass a `peft_model_id` or a `peft_config` and `adapter_state_dict` to load an adapter."
  162. )
  163. if "device" not in adapter_kwargs:
  164. device = self.device if not hasattr(self, "hf_device_map") else list(self.hf_device_map.values())[0]
  165. else:
  166. device = adapter_kwargs.pop("device")
  167. # To avoid PEFT errors later on with safetensors.
  168. if isinstance(device, torch.device):
  169. device = str(device)
  170. # We keep `revision` in the signature for backward compatibility
  171. if revision is not None and "revision" not in adapter_kwargs:
  172. adapter_kwargs["revision"] = revision
  173. elif revision is not None and "revision" in adapter_kwargs and revision != adapter_kwargs["revision"]:
  174. logger.error(
  175. "You passed a `revision` argument both in `adapter_kwargs` and as a standalone argument. "
  176. "The one in `adapter_kwargs` will be used."
  177. )
  178. # Override token with adapter_kwargs' token
  179. if "token" in adapter_kwargs:
  180. token = adapter_kwargs.pop("token")
  181. if peft_config is None:
  182. adapter_config_file = find_adapter_config_file(
  183. peft_model_id,
  184. token=token,
  185. **adapter_kwargs,
  186. )
  187. if adapter_config_file is None:
  188. raise ValueError(
  189. f"adapter model file not found in {peft_model_id}. Make sure you are passing the correct path to the "
  190. "adapter model."
  191. )
  192. peft_config = PeftConfig.from_pretrained(
  193. peft_model_id,
  194. token=token,
  195. **adapter_kwargs,
  196. )
  197. peft_config.inference_mode = not is_trainable
  198. # Create and add fresh new adapters into the model.
  199. inject_adapter_in_model(peft_config, self, adapter_name, **peft_load_kwargs)
  200. if not self._hf_peft_config_loaded:
  201. self._hf_peft_config_loaded = True
  202. if peft_model_id is not None:
  203. adapter_state_dict = load_peft_weights(peft_model_id, token=token, device=device, **adapter_kwargs)
  204. # We need to pre-process the state dict to remove unneeded prefixes - for backward compatibility
  205. processed_adapter_state_dict = {}
  206. prefix = "base_model.model."
  207. for key, value in adapter_state_dict.items():
  208. if key.startswith(prefix):
  209. new_key = key[len(prefix) :]
  210. else:
  211. new_key = key
  212. if key_mapping:
  213. for pattern, replacement in key_mapping.items():
  214. new_key, n_replace = re.subn(pattern, replacement, new_key)
  215. # Early exit of the loop
  216. if n_replace > 0:
  217. break
  218. processed_adapter_state_dict[new_key] = value
  219. # Load state dict
  220. incompatible_keys = set_peft_model_state_dict(
  221. self, processed_adapter_state_dict, adapter_name, **peft_load_kwargs
  222. )
  223. if incompatible_keys is not None:
  224. err_msg = ""
  225. origin_name = peft_model_id if peft_model_id is not None else "state_dict"
  226. # Check for unexpected keys.
  227. if hasattr(incompatible_keys, "unexpected_keys") and len(incompatible_keys.unexpected_keys) > 0:
  228. err_msg = (
  229. f"Loading adapter weights from {origin_name} led to unexpected keys not found in the model: "
  230. f"{', '.join(incompatible_keys.unexpected_keys)}. "
  231. )
  232. # Check for missing keys.
  233. missing_keys = getattr(incompatible_keys, "missing_keys", None)
  234. if missing_keys:
  235. # Filter missing keys specific to the current adapter, as missing base model keys are expected.
  236. lora_missing_keys = [k for k in missing_keys if "lora_" in k and adapter_name in k]
  237. if lora_missing_keys:
  238. err_msg += (
  239. f"Loading adapter weights from {origin_name} led to missing keys in the model: "
  240. f"{', '.join(lora_missing_keys)}"
  241. )
  242. if err_msg:
  243. logger.warning(err_msg)
  244. if peft_config.inference_mode:
  245. self.eval()
  246. # Re-dispatch model and hooks in case the model is offloaded to CPU / Disk.
  247. if (
  248. (getattr(self, "hf_device_map", None) is not None)
  249. and (len(set(self.hf_device_map.values()).intersection({"cpu", "disk"})) > 0)
  250. and len(self.peft_config) == 1
  251. ):
  252. self._dispatch_accelerate_model(
  253. device_map=device_map,
  254. max_memory=max_memory,
  255. offload_folder=offload_folder,
  256. offload_index=offload_index,
  257. )
  258. def add_adapter(self, adapter_config, adapter_name: Optional[str] = None) -> None:
  259. r"""
  260. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  261. official documentation: https://huggingface.co/docs/peft
  262. Adds a fresh new adapter to the current model for training purpose. If no adapter name is passed, a default
  263. name is assigned to the adapter to follow the convention of PEFT library (in PEFT we use "default" as the
  264. default adapter name).
  265. Note that the newly added adapter is not automatically activated. To activate it, use `model.set_adapter`.
  266. Args:
  267. adapter_config (`~peft.PeftConfig`):
  268. The configuration of the adapter to add, supported adapters are non-prompt learning methods (LoRA,
  269. IA³, etc.).
  270. adapter_name (`str`, *optional*, defaults to `"default"`):
  271. The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
  272. """
  273. check_peft_version(min_version=MIN_PEFT_VERSION)
  274. from peft import PeftConfig, inject_adapter_in_model
  275. adapter_name = adapter_name or "default"
  276. if not self._hf_peft_config_loaded:
  277. self._hf_peft_config_loaded = True
  278. elif adapter_name in self.peft_config:
  279. raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
  280. if not isinstance(adapter_config, PeftConfig):
  281. raise TypeError(f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead.")
  282. # Retrieve the name or path of the model, one could also use self.config._name_or_path
  283. # but to be consistent with what we do in PEFT: https://github.com/huggingface/peft/blob/6e783780ca9df3a623992cc4d1d665001232eae0/src/peft/mapping.py#L100
  284. adapter_config.base_model_name_or_path = self.__dict__.get("name_or_path", None)
  285. inject_adapter_in_model(adapter_config, self, adapter_name)
  286. self.set_adapter(adapter_name)
  287. def set_adapter(self, adapter_name: Union[list[str], str]) -> None:
  288. """
  289. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  290. official documentation: https://huggingface.co/docs/peft
  291. Sets a specific adapter by forcing the model to use a that adapter and disable the other adapters.
  292. Args:
  293. adapter_name (`Union[list[str], str]`):
  294. The name of the adapter to set. Can be also a list of strings to set multiple adapters.
  295. """
  296. check_peft_version(min_version=MIN_PEFT_VERSION)
  297. if not self._hf_peft_config_loaded:
  298. raise ValueError("No adapter loaded. Please load an adapter first.")
  299. elif isinstance(adapter_name, list):
  300. missing = set(adapter_name) - set(self.peft_config)
  301. if len(missing) > 0:
  302. raise ValueError(
  303. f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
  304. f" current loaded adapters are: {list(self.peft_config.keys())}"
  305. )
  306. elif adapter_name not in self.peft_config:
  307. raise ValueError(
  308. f"Adapter with name {adapter_name} not found. Please pass the correct adapter name among {list(self.peft_config.keys())}"
  309. )
  310. from peft.tuners.tuners_utils import BaseTunerLayer
  311. from peft.utils import ModulesToSaveWrapper
  312. _adapters_has_been_set = False
  313. for _, module in self.named_modules():
  314. if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)):
  315. # For backward compatibility with previous PEFT versions
  316. if hasattr(module, "set_adapter"):
  317. module.set_adapter(adapter_name)
  318. else:
  319. module.active_adapter = adapter_name
  320. _adapters_has_been_set = True
  321. if not _adapters_has_been_set:
  322. raise ValueError(
  323. "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
  324. )
  325. def disable_adapters(self) -> None:
  326. r"""
  327. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  328. official documentation: https://huggingface.co/docs/peft
  329. Disable all adapters that are attached to the model. This leads to inferring with the base model only.
  330. """
  331. check_peft_version(min_version=MIN_PEFT_VERSION)
  332. if not self._hf_peft_config_loaded:
  333. raise ValueError("No adapter loaded. Please load an adapter first.")
  334. from peft.tuners.tuners_utils import BaseTunerLayer
  335. from peft.utils import ModulesToSaveWrapper
  336. for _, module in self.named_modules():
  337. if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)):
  338. # The recent version of PEFT need to call `enable_adapters` instead
  339. if hasattr(module, "enable_adapters"):
  340. module.enable_adapters(enabled=False)
  341. else:
  342. module.disable_adapters = True
  343. def enable_adapters(self) -> None:
  344. """
  345. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  346. official documentation: https://huggingface.co/docs/peft
  347. Enable adapters that are attached to the model.
  348. """
  349. check_peft_version(min_version=MIN_PEFT_VERSION)
  350. if not self._hf_peft_config_loaded:
  351. raise ValueError("No adapter loaded. Please load an adapter first.")
  352. from peft.tuners.tuners_utils import BaseTunerLayer
  353. for _, module in self.named_modules():
  354. if isinstance(module, BaseTunerLayer):
  355. # The recent version of PEFT need to call `enable_adapters` instead
  356. if hasattr(module, "enable_adapters"):
  357. module.enable_adapters(enabled=True)
  358. else:
  359. module.disable_adapters = False
  360. def active_adapters(self) -> list[str]:
  361. """
  362. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  363. official documentation: https://huggingface.co/docs/peft
  364. Gets the current active adapters of the model. In case of multi-adapter inference (combining multiple adapters
  365. for inference) returns the list of all active adapters so that users can deal with them accordingly.
  366. For previous PEFT versions (that does not support multi-adapter inference), `module.active_adapter` will return
  367. a single string.
  368. """
  369. check_peft_version(min_version=MIN_PEFT_VERSION)
  370. if not is_peft_available():
  371. raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
  372. if not self._hf_peft_config_loaded:
  373. raise ValueError("No adapter loaded. Please load an adapter first.")
  374. from peft.tuners.tuners_utils import BaseTunerLayer
  375. for _, module in self.named_modules():
  376. if isinstance(module, BaseTunerLayer):
  377. active_adapters = module.active_adapter
  378. break
  379. # For previous PEFT versions
  380. if isinstance(active_adapters, str):
  381. active_adapters = [active_adapters]
  382. return active_adapters
  383. def get_adapter_state_dict(self, adapter_name: Optional[str] = None, state_dict: Optional[dict] = None) -> dict:
  384. """
  385. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
  386. official documentation: https://huggingface.co/docs/peft
  387. Gets the adapter state dict that should only contain the weights tensors of the specified adapter_name adapter.
  388. If no adapter_name is passed, the active adapter is used.
  389. Args:
  390. adapter_name (`str`, *optional*):
  391. The name of the adapter to get the state dict from. If no name is passed, the active adapter is used.
  392. state_dict (nested dictionary of `torch.Tensor`, *optional*)
  393. The state dictionary of the model. Will default to `self.state_dict()`, but can be used if special
  394. precautions need to be taken when recovering the state dictionary of a model (like when using model
  395. parallelism).
  396. """
  397. check_peft_version(min_version=MIN_PEFT_VERSION)
  398. if not self._hf_peft_config_loaded:
  399. raise ValueError("No adapter loaded. Please load an adapter first.")
  400. from peft import get_peft_model_state_dict
  401. if adapter_name is None:
  402. adapter_name = self.active_adapters()[0]
  403. adapter_state_dict = get_peft_model_state_dict(self, state_dict=state_dict, adapter_name=adapter_name)
  404. return adapter_state_dict
  405. def _dispatch_accelerate_model(
  406. self,
  407. device_map: str,
  408. max_memory: Optional[int] = None,
  409. offload_folder: Optional[str] = None,
  410. offload_index: Optional[int] = None,
  411. ) -> None:
  412. """
  413. Optional re-dispatch the model and attach new hooks to the model in case the model has been loaded with
  414. accelerate (i.e. with `device_map=xxx`)
  415. Args:
  416. device_map (`str` or `dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
  417. A map that specifies where each submodule should go. It doesn't need to be refined to each
  418. parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
  419. same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
  420. like `1`) on which the model will be allocated, the device map will map the entire model to this
  421. device. Passing `device_map = 0` means put the whole model on GPU 0.
  422. To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
  423. more information about each option see [designing a device
  424. map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
  425. max_memory (`Dict`, *optional*):
  426. A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
  427. GPU and the available CPU RAM if unset.
  428. offload_folder (`str` or `os.PathLike`, *optional*):
  429. If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
  430. offload_index (`int`, *optional*):
  431. The offload_index argument to be passed to `accelerate.dispatch_model` method.
  432. """
  433. dispatch_model_kwargs = {}
  434. # Safety checker for previous `accelerate` versions
  435. # `offload_index` was introduced in https://github.com/huggingface/accelerate/pull/873/
  436. if "offload_index" in inspect.signature(dispatch_model).parameters:
  437. dispatch_model_kwargs["offload_index"] = offload_index
  438. no_split_module_classes = self._no_split_modules
  439. if device_map != "sequential":
  440. max_memory = get_balanced_memory(
  441. self,
  442. max_memory=max_memory,
  443. no_split_module_classes=no_split_module_classes,
  444. low_zero=(device_map == "balanced_low_0"),
  445. )
  446. if isinstance(device_map, str):
  447. device_map = infer_auto_device_map(
  448. self, max_memory=max_memory, no_split_module_classes=no_split_module_classes
  449. )
  450. dispatch_model(
  451. self,
  452. device_map=device_map,
  453. offload_dir=offload_folder,
  454. **dispatch_model_kwargs,
  455. )
  456. def delete_adapter(self, adapter_names: Union[list[str], str]) -> None:
  457. """
  458. Delete a PEFT adapter from the underlying model.
  459. Args:
  460. adapter_names (`Union[list[str], str]`):
  461. The name(s) of the adapter(s) to delete.
  462. """
  463. check_peft_version(min_version=MIN_PEFT_VERSION)
  464. min_version_delete_adapter = "0.18.0"
  465. if not self._hf_peft_config_loaded:
  466. raise ValueError("No adapter loaded. Please load an adapter first.")
  467. # TODO: delete old version once support for PEFT < 0.18.0 is dropped
  468. def old_delete_adapter(model, adapter_name, prefix=None):
  469. from peft.tuners.tuners_utils import BaseTunerLayer
  470. from peft.utils import ModulesToSaveWrapper
  471. has_modules_to_save = False
  472. for module in model.modules():
  473. if isinstance(module, ModulesToSaveWrapper):
  474. has_modules_to_save |= True
  475. continue
  476. if isinstance(module, BaseTunerLayer):
  477. if hasattr(module, "delete_adapter"):
  478. module.delete_adapter(adapter_name)
  479. else:
  480. raise ValueError(
  481. "The version of PEFT you are using is not compatible, please use a version that is greater than 0.6.1"
  482. )
  483. if has_modules_to_save:
  484. logger.warning(
  485. "The deleted adapter contains modules_to_save, which could not be deleted. For this to work, PEFT version "
  486. f">= {min_version_delete_adapter} is required."
  487. )
  488. if version.parse(importlib.metadata.version("peft")) >= version.parse(min_version_delete_adapter):
  489. from peft.functional import delete_adapter
  490. else:
  491. delete_adapter = old_delete_adapter
  492. if isinstance(adapter_names, str):
  493. adapter_names = [adapter_names]
  494. # Check that all adapter names are present in the config
  495. missing_adapters = [name for name in adapter_names if name not in self.peft_config]
  496. if missing_adapters:
  497. raise ValueError(
  498. f"The following adapter(s) are not present and cannot be deleted: {', '.join(missing_adapters)}"
  499. )
  500. prefixes = [f"{self.peft_config[adapter_name].peft_type.value.lower()}_" for adapter_name in adapter_names]
  501. for adapter_name, prefix in zip(adapter_names, prefixes):
  502. delete_adapter(self, adapter_name=adapter_name, prefix=prefix)
  503. # For transformers integration - we need to pop the adapter from the config
  504. if getattr(self, "_hf_peft_config_loaded", False) and hasattr(self, "peft_config"):
  505. self.peft_config.pop(adapter_name, None)
  506. # In case all adapters are deleted, we need to delete the config
  507. # and make sure to set the flag to False
  508. if len(self.peft_config) == 0:
  509. del self.peft_config
  510. self._hf_peft_config_loaded = False