diff --git a/src/transformers/integrations/peft.py b/src/transformers/integrations/peft.py index 193c39e42854..b5d9814769b8 100644 --- a/src/transformers/integrations/peft.py +++ b/src/transformers/integrations/peft.py @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +import copy import inspect import json import os @@ -21,6 +22,12 @@ from .._typing import PeftConfigLike from ..conversion_mapping import get_model_conversion_mapping +from ..core_model_loading import ( + WeightConverter, + WeightRenaming, + dot_natural_key, + rename_source_key, +) from ..utils import ( CONFIG_NAME, cached_file, @@ -33,7 +40,7 @@ logging, ) from ..utils.hub import DownloadKwargs -from ..utils.loading_report import log_state_dict_report +from ..utils.loading_report import LoadStateDictInfo, log_state_dict_report if is_torch_available(): @@ -77,6 +84,45 @@ class PeftAdapterMixin: _prepare_peft_hotswap_kwargs: dict | None = None peft_config: dict[str, PeftConfigLike] + def _resolve_adapter_state_dict( + self, adapter_state_dict: dict[str, "torch.Tensor"] | None, checkpoint_files + ) -> dict[str, torch.Tensor]: + # Materialize the adapter state dict from `adapter_state_dict` or `checkpoint_files`. Used by paths + # that bypass `self._load_pretrained_model` (which would otherwise read the files itself). + from ..modeling_utils import load_state_dict + + all_pointer = set() + if adapter_state_dict is not None: + merged_state_dict = adapter_state_dict + elif ( + checkpoint_files is not None + and checkpoint_files[0].endswith(".safetensors") + and adapter_state_dict is None + ): + merged_state_dict = {} + for file in checkpoint_files: + file_pointer = safe_open(file, framework="pt", device="cpu") + all_pointer.add(file_pointer) + for k in file_pointer.keys(): + merged_state_dict[k] = file_pointer.get_tensor(k) + # Checkpoints are .bin + elif checkpoint_files is not None: + merged_state_dict = {} + for ckpt_file in checkpoint_files: + merged_state_dict.update(load_state_dict(ckpt_file)) + else: + raise ValueError("Neither a state dict nor checkpoint files were found.") + + return merged_state_dict + + def _set_peft_inference_mode(self) -> None: + from peft.tuners.tuners_utils import BaseTunerLayer + + self.eval() + for module in self.modules(): + if isinstance(module, BaseTunerLayer): + module.requires_grad_(False) + def load_adapter( self, peft_model_id: str | None = None, @@ -157,7 +203,7 @@ def load_adapter( from peft import PeftType from peft.utils.save_and_load import _maybe_shard_state_dict_for_tp - from ..modeling_utils import LoadStateDictConfig, _get_resolved_checkpoint_files, load_state_dict + from ..modeling_utils import LoadStateDictConfig, _get_resolved_checkpoint_files if local_files_only: kwargs["local_files_only"] = True @@ -232,12 +278,8 @@ def load_adapter( # Create and add fresh new adapters into the model, unless the weights are hotswapped inject_adapter_in_model(peft_config, self, adapter_name) - adapter_key_markers = {adapter_name} - if peft_config is not None and getattr(peft_config, "peft_type", None) is not None: - adapter_key_markers.add(peft_config.peft_type.value.lower()) - def is_adapter_key(key: str) -> bool: - return any(marker in key for marker in adapter_key_markers) + return adapter_name in key.split(".") if not self._hf_peft_config_loaded: self._hf_peft_config_loaded = True @@ -274,8 +316,6 @@ def is_adapter_key(key: str) -> bool: device_map = getattr(self, "hf_device_map", {"": self.device}) - # If the model is tensor parallel, we handle the sharding of the state dict here since the logic in `self._load_pretrained_model` - # is not compatible with the way PEFT adapter should be sharded. has_tp_adapters = False for module in self.modules(): tp_info = getattr(module, "_tp_info", None) @@ -284,35 +324,82 @@ def is_adapter_key(key: str) -> bool: break if has_tp_adapters: - all_pointer = set() - if adapter_state_dict is not None: - merged_state_dict = adapter_state_dict - elif ( - checkpoint_files is not None - and checkpoint_files[0].endswith(".safetensors") - and adapter_state_dict is None - ): - merged_state_dict = {} - for file in checkpoint_files: - file_pointer = safe_open(file, framework="pt", device="cpu") - all_pointer.add(file_pointer) - for k in file_pointer.keys(): - merged_state_dict[k] = file_pointer.get_tensor(k) - # Checkpoints are .bin - elif checkpoint_files is not None: - merged_state_dict = {} - for ckpt_file in checkpoint_files: - merged_state_dict.update(load_state_dict(ckpt_file)) - else: - raise ValueError("Neither a state dict nor checkpoint files were found.") - - adapter_state_dict = merged_state_dict + adapter_state_dict = self._resolve_adapter_state_dict(adapter_state_dict, checkpoint_files) if any(not isinstance(v, torch.Tensor) for v in adapter_state_dict.values()): raise ValueError("Expected all values in the adapter state dict to be tensors.") _maybe_shard_state_dict_for_tp(self, adapter_state_dict, adapter_name) + if hotswap: + # Bypass the standard loader and use PEFT's hotswap path so that LoRA weights whose rank differs from the + # existing adapter's are copied (and zero-padded) in place rather than triggering a "size mismatch" reinit, + # and so the LoRA scaling is updated alongside the weights. + from peft.utils.hotswap import check_hotswap_configs_compatible, hotswap_adapter_from_state_dict + from peft.utils.transformers_weight_conversion import convert_peft_config_for_transformers + + # The PEFT config conversion for v5 architecture changes is normally applied in-place by + # inject_adapter_in_model, which is skipped when hotswapping, so it needs to be applied explicitly. + convert_peft_config_for_transformers(peft_config, self, weight_conversions) + + adapter_state_dict = self._resolve_adapter_state_dict(adapter_state_dict, checkpoint_files) + + # Need to apply conversions manually as we don't use _load_pretrained_model. Same logic as in: + # https://github.com/huggingface/transformers/blob/a8f150d35d5863971db1e5c1dbc2a1c265f27f96/src/transformers/core_model_loading.py#L1222 + renamings = [r for r in peft_weight_conversions if isinstance(r, WeightRenaming)] + converters = [c for c in peft_weight_conversions if isinstance(c, WeightConverter)] + pattern_to_converter = {p: c for c in converters for p in c.source_patterns} + meta_state_dict = self.state_dict() + conversion_mapping: dict[str, WeightConverter] = {} + processed_state_dict = {} + # Sort by `dot_natural_key` so converters such as MergeModulelist collect experts in numeric order. + for key, value in sorted(adapter_state_dict.items(), key=lambda kv: dot_natural_key(kv[0])): + renamed_key, source_pattern = rename_source_key( + key, renamings, converters, self.base_model_prefix, meta_state_dict + ) + if renamed_key not in meta_state_dict and key in meta_state_dict: # see #44396 ff + # Key should probably not have been renamed but we might need the `prefix` to be added. + renamed_key, source_pattern = rename_source_key( + key, [], [], base_model_prefix=self.base_model_prefix, meta_state_dict=meta_state_dict + ) + + if source_pattern is not None: + # A WeightConverter matched: bucket the tensor so its operations can run over all siblings. + mapping = conversion_mapping.setdefault( + renamed_key, copy.deepcopy(pattern_to_converter[source_pattern]) + ) + mapping.add_tensor(renamed_key, key, source_pattern, value) + else: + processed_state_dict[renamed_key] = value + + for layer_name, mapping in conversion_mapping.items(): + realized = mapping.convert(layer_name, model=self, config=self.config) + for target_name, param in realized.items(): + processed_state_dict[target_name] = param[0] if isinstance(param, list) else param + + check_hotswap_configs_compatible(self.peft_config[adapter_name], peft_config) + try: + hotswap_adapter_from_state_dict( + model=self, + state_dict=processed_state_dict, + adapter_name=adapter_name, + config=peft_config, + ) + except Exception as e: + logger.error(f"Hotswapping {adapter_name} was unsuccessful with the following error:\n{e}") + raise + + if peft_config.inference_mode: + self._set_peft_inference_mode() + + return LoadStateDictInfo( + missing_keys=set(), + unexpected_keys=set(), + mismatched_keys=set(), + error_msgs=[], + conversion_errors={}, + ) + load_config = replace( load_config, pretrained_model_name_or_path=peft_model_id, @@ -332,12 +419,7 @@ def is_adapter_key(key: str) -> bool: ) if peft_config.inference_mode: - from peft.tuners.tuners_utils import BaseTunerLayer - - self.eval() - for module in self.modules(): - if isinstance(module, BaseTunerLayer): - module.requires_grad_(False) + self._set_peft_inference_mode() loading_info.missing_keys = {k for k in loading_info.missing_keys if is_adapter_key(k)} @@ -348,6 +430,19 @@ def is_adapter_key(key: str) -> bool: loading_info=loading_info, logger=logger, ) + + if self._prepare_peft_hotswap_kwargs is not None: + # Apply once, after the first adapter has been loaded but before the model is + # compiled, so the LoRA layers get padded up to target_rank and a later adapter + # with a different rank can be hot-swapped in without recompiling. + from peft.utils.hotswap import prepare_model_for_compiled_hotswap + + prepare_model_for_compiled_hotswap(self, config=peft_config, **self._prepare_peft_hotswap_kwargs) + self._prepare_peft_hotswap_kwargs = None + + if peft_config.inference_mode: + self._set_peft_inference_mode() + return loading_info def enable_peft_hotswap( diff --git a/tests/peft_integration/test_peft_integration.py b/tests/peft_integration/test_peft_integration.py index 3334da810685..fd332a56a80d 100644 --- a/tests/peft_integration/test_peft_integration.py +++ b/tests/peft_integration/test_peft_integration.py @@ -53,6 +53,12 @@ import torch +# Tiny Mixtral + a LoRA checkpoint saved in the pre-v5 format (i.e. when the MoE experts still were individual nn.Linear +# layers instead of fused 3d nn.Parameters), thus requiring weight conversion at load time. +MIXTRAL_MODEL_ID = "hf-internal-testing/Mixtral-tiny" +MIXTRAL_PRE_V5_LORA_ID = "peft-internal-testing/mixtral-pre-v5-lora" + + @require_peft @require_torch class PeftTesterMixin: @@ -1118,8 +1124,8 @@ def test_non_lora_add_adapter(self): @require_peft_greater_or_equal("0.20.0") def test_mixtral_lora_conversion(self): inputs = torch.arange(10).view(1, -1).to(torch_device) - model_name = "hf-internal-testing/Mixtral-tiny" - adapter_name = "peft-internal-testing/mixtral-pre-v5-lora" + model_name = MIXTRAL_MODEL_ID + adapter_name = MIXTRAL_PRE_V5_LORA_ID # original logits were: # tensor([[[ 0.2676, 0.3870, 0.2956, ..., 0.4624, 0.1966, 0.2539], @@ -1160,33 +1166,41 @@ def tearDown(self): torch.compiler.reset() gc.collect() - def _check_model_hotswap(self, *, rank1, rank2, do_compile): + def _check_model_hotswap( + self, *, rank1, rank2, do_compile, model_id="hf-internal-testing/tiny-random-OPTForCausalLM" + ): # utility method that checks that we can successfully hotswap adapters, with the model outputs corresponding to # the respective adapters from peft import LoraConfig torch.manual_seed(0) - model_id = "hf-internal-testing/tiny-random-OPTForCausalLM" + model = AutoModelForCausalLM.from_pretrained(model_id).to(torch_device) input = torch.randint(0, 100, (1, 10)).to(torch_device) with torch.inference_mode(): base_output = model(input).logits # create 2 adapters - model.add_adapter(LoraConfig(r=rank1, init_lora_weights=False), adapter_name="adapter_1") + model.add_adapter( + LoraConfig(r=rank1, init_lora_weights=False, target_modules=["q_proj", "v_proj"]), adapter_name="adapter_1" + ) with torch.inference_mode(): lora_1_output = model(input).logits # second adapter may have a different rank - model.add_adapter(LoraConfig(r=rank2, init_lora_weights=False), adapter_name="adapter_2") + model.add_adapter( + LoraConfig(r=rank2, init_lora_weights=False, target_modules=["q_proj", "v_proj"]), adapter_name="adapter_2" + ) model.set_adapter("adapter_2") with torch.inference_mode(): lora_2_output = model(input).logits # sanity checks - self.assertFalse(torch.allclose(base_output, lora_1_output, atol=1e-6, rtol=1e-6)) - self.assertFalse(torch.allclose(base_output, lora_2_output, atol=1e-6, rtol=1e-6)) - self.assertFalse(torch.allclose(lora_1_output, lora_2_output, atol=1e-6, rtol=1e-6)) + atol = 2e-3 + rtol = 1e-6 + self.assertFalse(torch.allclose(base_output, lora_1_output, atol=atol, rtol=rtol)) + self.assertFalse(torch.allclose(base_output, lora_2_output, atol=atol, rtol=rtol)) + self.assertFalse(torch.allclose(lora_1_output, lora_2_output, atol=atol, rtol=rtol)) with tempfile.TemporaryDirectory() as tmpdirname: path_1 = os.path.join(tmpdirname, "adapter_1") @@ -1204,26 +1218,32 @@ def _check_model_hotswap(self, *, rank1, rank2, do_compile): model.enable_peft_hotswap(target_rank=max(rank1, rank2)) # load the first adapter without hotswap (hotswap requires an existing adapter) - model.load_adapter(path_1, adapter_name="adapter_1") + model.load_adapter(path_1, adapter_name="adapter_1", is_trainable=False) if do_compile: # compile the model after loading the first adapter - model = torch.compile(model, mode="reduce-overhead") + if "mixtral" not in model_id.lower(): + model = torch.compile(model, mode="reduce-overhead") + else: + # The tiny mixtral model is incompatible with 'reduce-overhead', resulting in: + # > torch.AcceleratorError: CUDA error: operation failed due to a previous error during capture + # For the purpose of this test, 'reduce-overhead' is not material, so we drop it here. + model = torch.compile(model) with torch.inference_mode(): lora_1_output_loaded = model(input).logits - self.assertTrue(torch.allclose(lora_1_output, lora_1_output_loaded, atol=1e-6, rtol=1e-6)) + self.assertTrue(torch.allclose(lora_1_output, lora_1_output_loaded, atol=atol, rtol=rtol)) # hotswap in adapter_2 again, output should be same as lora_2_output if enable_hotswap: # after calling enable_peft_hotswap, hotswap will automatically be enabled - model.load_adapter(path_2, adapter_name="adapter_1") + model.load_adapter(path_2, adapter_name="adapter_1", is_trainable=False) else: # enable_peft_hotswap was not called, need to explicitly pass hotswap=True - model.load_adapter(path_2, adapter_name="adapter_1", hotswap=True) + model.load_adapter(path_2, adapter_name="adapter_1", hotswap=True, is_trainable=False) with torch.inference_mode(): lora_2_output_loaded = model(input).logits - self.assertTrue(torch.allclose(lora_2_output, lora_2_output_loaded, atol=1e-6, rtol=1e-6)) + self.assertTrue(torch.allclose(lora_2_output, lora_2_output_loaded, atol=atol, rtol=rtol)) def test_hotswap_wrong_peft_type_raises(self): # only LoRA is supported for now @@ -1374,3 +1394,74 @@ def test_maybe_load_adapters_path_not_overwritten_for_complete_model(self): # Load from the saved path and make sure it actually loads despite # the invalid adapter config path AutoModel.from_pretrained(tmp_dir) + + def test_mixtral_hotswap_without_compile_works(self): + # test a model that uses weight conversion + self._check_model_hotswap(rank1=7, rank2=13, do_compile=False, model_id=MIXTRAL_MODEL_ID) + + def test_mixtral_hotswap_with_compile_works(self): + # test a model that uses weight conversion + with ( + torch._dynamo.config.patch(error_on_recompile=True), + torch._inductor.utils.fresh_inductor_cache(), + ): + self._check_model_hotswap(rank1=8, rank2=8, do_compile=True, model_id=MIXTRAL_MODEL_ID) + + def _check_pre_v5_lora_hotswap_with_conversion(self, *, do_compile): + # Check that hotswapping works for a LoRA checkpoint that was saved in the pre-v5 format (here: trained on + # Mixtral when the MoE experts still were individual nn.Linear layers). Loading such a checkpoint requires the + # adapter weights to be converted to the new architecture (fused 3d nn.Parameter experts). The normal loading + # path applies the conversion in `_load_pretrained_model` (covered by `test_mixtral_lora_conversion`), but the + # hotswap path bypasses it and needs to apply the conversion itself, which is what this test checks: the + # hotswapped adapter must produce the same outputs as the same checkpoint loaded through the normal path. + atol, rtol = 2e-3, 1e-6 + inputs = torch.arange(10).view(1, -1).to(torch_device) + + model = AutoModelForCausalLM.from_pretrained(MIXTRAL_MODEL_ID).to(torch_device) + model.eval() + with torch.inference_mode(): + base_logits = model(inputs).logits + + # load the pre-v5 checkpoint through the normal (non-hotswap) path to obtain the reference output + model.load_adapter(MIXTRAL_PRE_V5_LORA_ID, adapter_name="default", is_trainable=False) + if do_compile: + # Compile with the eager backend: the converted checkpoint targets nn.Parameters (the fused expert + # weights), which relies on nn.utils.parametrize and leads to graph breaks that can affect the outputs + # with the inductor backend, see the equivalent test_hotswap_lora_target_parameters in PEFT. + model = torch.compile(model, backend="eager") + + with torch.inference_mode(): + lora_logits = model(inputs).logits + # sanity check: the adapter influences the output + self.assertFalse(torch.allclose(base_logits, lora_logits, atol=atol, rtol=rtol)) + + # scramble the LoRA weights so that we can tell whether hotswapping actually swapped in the checkpoint + # weights (hotswapping the same checkpoint onto pristine weights would hide a silent no-op) + torch.manual_seed(0) + with torch.no_grad(): + for name, param in model.named_parameters(): + if "lora_" in name: + param.add_(torch.randn_like(param)) + with torch.inference_mode(): + scrambled_logits = model(inputs).logits + self.assertFalse(torch.allclose(lora_logits, scrambled_logits, atol=atol, rtol=rtol)) + + # hotswap the same pre-v5 checkpoint; the weight conversion has to be applied by the hotswap code path + model.load_adapter(MIXTRAL_PRE_V5_LORA_ID, adapter_name="default", hotswap=True, is_trainable=False) + with torch.inference_mode(): + hotswapped_logits = model(inputs).logits + self.assertTrue(torch.allclose(lora_logits, hotswapped_logits, atol=atol, rtol=rtol)) + + @require_peft_greater_or_equal("0.20.0") + def test_mixtral_pre_v5_lora_hotswap_without_compile_works(self): + # hotswapping a checkpoint that requires weight conversion + self._check_pre_v5_lora_hotswap_with_conversion(do_compile=False) + + @require_peft_greater_or_equal("0.20.0") + def test_mixtral_pre_v5_lora_hotswap_with_compile_works(self): + # Hotswapping a checkpoint that requires weight conversion, with the model compiled. Contrary to the other + # compile tests, error_on_recompile is not used here: LoRA adapters targeting nn.Parameters (as the converted + # checkpoint does for the fused expert weights) rely on nn.utils.parametrize, which triggers recompilation + # independently of hotswapping (see the equivalent test_hotswap_lora_target_parameters in PEFT). This test + # therefore only checks correctness of the hotswapped outputs under compilation, not recompilation avoidance. + self._check_pre_v5_lora_hotswap_with_conversion(do_compile=True)