From 62277daf144f7f28cffab9fbcd8883e211d5e0a0 Mon Sep 17 00:00:00 2001 From: Ziyu Lin <104151270+LinZiyuu@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:28:33 +0800 Subject: [PATCH 1/2] [LoRA] Ignore Megatron fields in LoRA adapter metadata `_create_lora_config` passed a checkpoint's `lora_adapter_metadata` to `LoraConfig` as-is. That metadata can set `megatron_config` and `megatron_core`, which make peft build Megatron tensor-parallel layers by importing the module named in `megatron_core`. Diffusers models never use these layers, so drop both fields from the metadata and warn when a checkpoint requests Megatron. Regularly saved adapters always carry the two fields with their default values (`LoraConfig.to_dict()` includes them), so the warning only fires when `megatron_config` is set. --- src/diffusers/utils/peft_utils.py | 14 +++++++- tests/lora/test_peft_utils.py | 56 ++++++++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/src/diffusers/utils/peft_utils.py b/src/diffusers/utils/peft_utils.py index 7e3f865d6cef..82252f04837c 100644 --- a/src/diffusers/utils/peft_utils.py +++ b/src/diffusers/utils/peft_utils.py @@ -517,13 +517,25 @@ def _create_lokr_config(state_dict, metadata): raise TypeError("`LoKrConfig` class could not be instantiated.") from e +# `LoraConfig` fields that make peft import a module by name (`importlib.import_module(megatron_core)` when +# `megatron_config` is set). Diffusers models never use Megatron tensor-parallel layers, so these are not taken from +# the adapter metadata stored in a LoRA checkpoint. +_LORA_METADATA_IGNORED_KEYS = ("megatron_config", "megatron_core") + + def _create_lora_config( state_dict, network_alphas, metadata, rank_pattern_dict, is_unet=True, model_state_dict=None, adapter_name=None ): from peft import LoraConfig if metadata is not None: - lora_config_kwargs = metadata + # Every saved `LoraConfig` carries these keys with their defaults, so only warn when Megatron was requested. + if metadata.get("megatron_config") is not None: + logger.warning( + "Ignoring `megatron_config` and `megatron_core` from the LoRA adapter metadata: Megatron " + "tensor-parallel layers are not supported when loading LoRA adapters in Diffusers." + ) + lora_config_kwargs = {k: v for k, v in metadata.items() if k not in _LORA_METADATA_IGNORED_KEYS} else: lora_config_kwargs = get_peft_kwargs( rank_pattern_dict, diff --git a/tests/lora/test_peft_utils.py b/tests/lora/test_peft_utils.py index 262c4fa41f93..6e4e375621f2 100644 --- a/tests/lora/test_peft_utils.py +++ b/tests/lora/test_peft_utils.py @@ -12,7 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -from diffusers.utils.peft_utils import get_peft_kwargs +import logging + +import torch + +from diffusers.utils import peft_utils +from diffusers.utils.peft_utils import _create_lora_config, get_peft_kwargs + +from ..testing_utils import CaptureLogger, require_peft_backend def _rank_dict(module_ranks): @@ -112,3 +119,50 @@ def test_text_encoder_alpha_pattern_handles_mlp_and_text_projection(): kwargs = get_peft_kwargs({"m.lora_B.weight": 4}, network_alphas, peft_state_dict, is_unet=False) assert kwargs["lora_alpha"] == 8.0 assert kwargs["alpha_pattern"] == {"encoder.layers.0.mlp.fc2": 4.0} + + +class _TinyAttention(torch.nn.Module): + def __init__(self): + super().__init__() + self.to_q = torch.nn.Linear(4, 4) + self.to_v = torch.nn.Linear(4, 4) + + +def _lora_metadata(**extra): + return {"r": 4, "lora_alpha": 8, "target_modules": ["to_q", "to_v"], **extra} + + +@require_peft_backend +def test_lora_metadata_megatron_fields_are_ignored(): + # A checkpoint's adapter metadata must not be able to switch peft to Megatron layers, which imports the + # module named by `megatron_core`. + from peft import LoraConfig, inject_adapter_in_model + from peft.tuners.lora import Linear as LoraLinear + + metadata = _lora_metadata(megatron_core="megatron.core", megatron_config={"params_dtype": "float32"}) + peft_utils.logger.setLevel(logging.WARNING) + with CaptureLogger(peft_utils.logger) as cap_logger: + config = _create_lora_config(state_dict={}, network_alphas=None, metadata=metadata, rank_pattern_dict={}) + + assert config.megatron_config is None + assert config.megatron_core == LoraConfig().megatron_core + assert (config.r, config.lora_alpha, set(config.target_modules)) == (4, 8, {"to_q", "to_v"}) + assert "megatron_config" in metadata + assert "Ignoring `megatron_config`" in cap_logger.out + + model = inject_adapter_in_model(config, _TinyAttention(), adapter_name="default") + assert isinstance(model.to_q, LoraLinear) + + +@require_peft_backend +def test_lora_metadata_with_default_megatron_fields_does_not_warn(): + # `LoraConfig.to_dict()` always includes the Megatron fields, so a regularly saved adapter carries them with + # their default values. + from peft import LoraConfig + + metadata = _lora_metadata(megatron_core=LoraConfig().megatron_core, megatron_config=None) + peft_utils.logger.setLevel(logging.WARNING) + with CaptureLogger(peft_utils.logger) as cap_logger: + _create_lora_config(state_dict={}, network_alphas=None, metadata=metadata, rank_pattern_dict={}) + + assert "megatron" not in cap_logger.out From ef255c39d003e3521d20a967a781587c10305f32 Mon Sep 17 00:00:00 2001 From: LinZiyu <221020063@fzu.edu.cn> Date: Thu, 3 Dec 2026 13:38:59 +0800 Subject: [PATCH 2/2] [LoRA] Test Megatron metadata filtering through load_lora_adapter Move the tests off the private `_create_lora_config` and into `LoraTesterMixin`, so they go through `save_lora_adapter` / `load_lora_adapter` for every model using the mixin. Also check the `peft_config` stored on the model after loading. --- tests/lora/test_peft_utils.py | 56 +----------------------------- tests/models/testing_utils/lora.py | 43 +++++++++++++++++++++++ 2 files changed, 44 insertions(+), 55 deletions(-) diff --git a/tests/lora/test_peft_utils.py b/tests/lora/test_peft_utils.py index 6e4e375621f2..262c4fa41f93 100644 --- a/tests/lora/test_peft_utils.py +++ b/tests/lora/test_peft_utils.py @@ -12,14 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import logging - -import torch - -from diffusers.utils import peft_utils -from diffusers.utils.peft_utils import _create_lora_config, get_peft_kwargs - -from ..testing_utils import CaptureLogger, require_peft_backend +from diffusers.utils.peft_utils import get_peft_kwargs def _rank_dict(module_ranks): @@ -119,50 +112,3 @@ def test_text_encoder_alpha_pattern_handles_mlp_and_text_projection(): kwargs = get_peft_kwargs({"m.lora_B.weight": 4}, network_alphas, peft_state_dict, is_unet=False) assert kwargs["lora_alpha"] == 8.0 assert kwargs["alpha_pattern"] == {"encoder.layers.0.mlp.fc2": 4.0} - - -class _TinyAttention(torch.nn.Module): - def __init__(self): - super().__init__() - self.to_q = torch.nn.Linear(4, 4) - self.to_v = torch.nn.Linear(4, 4) - - -def _lora_metadata(**extra): - return {"r": 4, "lora_alpha": 8, "target_modules": ["to_q", "to_v"], **extra} - - -@require_peft_backend -def test_lora_metadata_megatron_fields_are_ignored(): - # A checkpoint's adapter metadata must not be able to switch peft to Megatron layers, which imports the - # module named by `megatron_core`. - from peft import LoraConfig, inject_adapter_in_model - from peft.tuners.lora import Linear as LoraLinear - - metadata = _lora_metadata(megatron_core="megatron.core", megatron_config={"params_dtype": "float32"}) - peft_utils.logger.setLevel(logging.WARNING) - with CaptureLogger(peft_utils.logger) as cap_logger: - config = _create_lora_config(state_dict={}, network_alphas=None, metadata=metadata, rank_pattern_dict={}) - - assert config.megatron_config is None - assert config.megatron_core == LoraConfig().megatron_core - assert (config.r, config.lora_alpha, set(config.target_modules)) == (4, 8, {"to_q", "to_v"}) - assert "megatron_config" in metadata - assert "Ignoring `megatron_config`" in cap_logger.out - - model = inject_adapter_in_model(config, _TinyAttention(), adapter_name="default") - assert isinstance(model.to_q, LoraLinear) - - -@require_peft_backend -def test_lora_metadata_with_default_megatron_fields_does_not_warn(): - # `LoraConfig.to_dict()` always includes the Megatron fields, so a regularly saved adapter carries them with - # their default values. - from peft import LoraConfig - - metadata = _lora_metadata(megatron_core=LoraConfig().megatron_core, megatron_config=None) - peft_utils.logger.setLevel(logging.WARNING) - with CaptureLogger(peft_utils.logger) as cap_logger: - _create_lora_config(state_dict={}, network_alphas=None, metadata=metadata, rank_pattern_dict={}) - - assert "megatron" not in cap_logger.out diff --git a/tests/models/testing_utils/lora.py b/tests/models/testing_utils/lora.py index 5a29c4c94d99..2754ae77f10c 100644 --- a/tests/models/testing_utils/lora.py +++ b/tests/models/testing_utils/lora.py @@ -53,6 +53,7 @@ if is_peft_available(): from peft import LoraConfig + from peft.tuners.lora import Linear as LoraLinear from peft.tuners.tuners_utils import BaseTunerLayer from peft.utils import get_peft_model_state_dict @@ -241,6 +242,48 @@ def test_lora_adapter_wrong_metadata_raises_error(self, tmp_path): model.load_lora_adapter(tmp_path, prefix=None, use_safetensors=True) assert "`LoraConfig` class could not be instantiated" in str(exc_info.value) + @pytest.mark.parametrize("megatron_requested", [True, False]) + def test_lora_adapter_metadata_megatron_fields_are_ignored(self, tmp_path, megatron_requested): + init_dict = self.get_init_dict() + model = self.model_class(**init_dict).to(torch_device) + + denoiser_lora_config = LoraConfig( + r=4, + lora_alpha=4, + target_modules=["to_q", "to_k", "to_v", "to_out.0"], + init_lora_weights=False, + use_dora=False, + ) + model.add_adapter(denoiser_lora_config) + model.save_lora_adapter(tmp_path) + model_file = os.path.join(tmp_path, "pytorch_lora_weights.safetensors") + + # A saved adapter always carries the Megatron fields with their defaults. Make the metadata request Megatron + # layers, which would make peft import the module named by `megatron_core`. + lora_adapter_metadata = denoiser_lora_config.to_dict() + if megatron_requested: + lora_adapter_metadata.update(megatron_core="megatron.core", megatron_config={"params_dtype": "float32"}) + for key, value in lora_adapter_metadata.items(): + if isinstance(value, set): + lora_adapter_metadata[key] = list(value) + metadata = {"format": "pt", LORA_ADAPTER_METADATA_KEY: json.dumps(lora_adapter_metadata, sort_keys=True)} + safetensors.torch.save_file(safetensors.torch.load_file(model_file), model_file, metadata=metadata) + + model.unload_lora() + logger = logging.get_logger("diffusers.utils.peft_utils") + logger.setLevel(logging.WARNING) + with CaptureLogger(logger) as cap_logger: + model.load_lora_adapter(tmp_path, prefix=None, use_safetensors=True) + + loaded_config = model.peft_config["default_0"] + assert loaded_config.megatron_config is None + assert loaded_config.megatron_core == LoraConfig().megatron_core + assert ("Ignoring `megatron_config`" in cap_logger.out) == megatron_requested + + lora_layers = [module for module in model.modules() if isinstance(module, BaseTunerLayer)] + assert lora_layers, "LoRA layers not set correctly" + assert all(isinstance(module, LoraLinear) for module in lora_layers) + def _flatten_output(self, output): # Some models (e.g. Z-Image) return a list of per-sample tensors — flatten so the tensor comparisons in # the tests below work regardless of the output layout.