Skip to content

PEFT

Diffusers supports loading adapters such as LoRA with the PEFT library with the loaders.peft.PeftAdapterMixin class. This allows modeling classes in Diffusers like UNet2DConditionModel, SD3Transformer2DModel to operate with an adapter.

Tip

Refer to the Inference with PEFT tutorial for an overview of how to use PEFT in Diffusers for inference.

mindone.diffusers.loaders.peft.PeftAdapterMixin

A class containing all functions for loading and using adapters weights that are supported in PEFT library. For more details about adapters and injecting them in a base model, check out the PEFT documentation.

Install the latest version of PEFT, and use this mixin to:

  • Attach new adapters in the model.
  • Attach multiple adapters and iteratively activate/deactivate them.
  • Activate/deactivate all adapters from the model.
  • Get a list of the active adapters.
Source code in mindone/diffusers/loaders/peft.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
class PeftAdapterMixin:
    """
    A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
    more details about adapters and injecting them in a base model, check out the PEFT
    [documentation](https://huggingface.co/docs/peft/index).

    Install the latest version of PEFT, and use this mixin to:

    - Attach new adapters in the model.
    - Attach multiple adapters and iteratively activate/deactivate them.
    - Activate/deactivate all adapters from the model.
    - Get a list of the active adapters.
    """

    _hf_peft_config_loaded = False

    @classmethod
    # Copied from diffusers.loaders.lora_base.LoraBaseMixin._optionally_disable_offloading
    def _optionally_disable_offloading(cls, _pipeline):
        raise NotImplementedError("`_optionally_disable_offloading()` is not implemented.")

    def load_lora_adapter(self, pretrained_model_name_or_path_or_dict, prefix="transformer", **kwargs):
        r"""
        Loads a LoRA adapter into the underlying model.

        Parameters:
            pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
                Can be either:

                    - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
                      the Hub.
                    - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
                      with [`ModelMixin.save_pretrained`].
                    - A [torch state
                      dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

            prefix (`str`, *optional*): Prefix to filter the state dict.

            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            local_files_only (`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to `True`, the model
                won't be downloaded from the Hub.
            token (`str` or *bool*, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            subfolder (`str`, *optional*, defaults to `""`):
                The subfolder location of a model file within a larger model repository on the Hub or locally.
            network_alphas (`Dict[str, float]`):
                The value of the network alpha used for stable learning and preventing underflow. This value has the
                same meaning as the `--network_alpha` option in the kohya-ss trainer script. Refer to [this
                link](https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning).
        """
        from mindone.diffusers._peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
        from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

        cache_dir = kwargs.pop("cache_dir", None)
        force_download = kwargs.pop("force_download", False)
        proxies = kwargs.pop("proxies", None)
        local_files_only = kwargs.pop("local_files_only", None)
        token = kwargs.pop("token", None)
        revision = kwargs.pop("revision", None)
        subfolder = kwargs.pop("subfolder", None)
        weight_name = kwargs.pop("weight_name", None)
        use_safetensors = kwargs.pop("use_safetensors", None)
        adapter_name = kwargs.pop("adapter_name", None)
        network_alphas = kwargs.pop("network_alphas", None)
        allow_pickle = False

        user_agent = {
            "file_type": "attn_procs_weights",
            "framework": "pytorch",
        }

        state_dict = _fetch_state_dict(
            pretrained_model_name_or_path_or_dict=pretrained_model_name_or_path_or_dict,
            weight_name=weight_name,
            use_safetensors=use_safetensors,
            local_files_only=local_files_only,
            cache_dir=cache_dir,
            force_download=force_download,
            proxies=proxies,
            token=token,
            revision=revision,
            subfolder=subfolder,
            user_agent=user_agent,
            allow_pickle=allow_pickle,
        )
        if network_alphas is not None and prefix is None:
            raise ValueError("`network_alphas` cannot be None when `prefix` is None.")

        if prefix is not None:
            keys = list(state_dict.keys())
            model_keys = [k for k in keys if k.startswith(f"{prefix}.")]
            if len(model_keys) > 0:
                state_dict = {k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in model_keys}

        if len(state_dict) > 0:
            if adapter_name in getattr(self, "peft_config", {}):
                raise ValueError(
                    f"Adapter name {adapter_name} already in use in the model - please select a new adapter name."
                )

            # check with first key if is not in peft format
            first_key = next(iter(state_dict.keys()))
            if "lora_A" not in first_key:
                state_dict = convert_unet_state_dict_to_peft(state_dict)

            rank = {}
            for key, val in state_dict.items():
                # Cannot figure out rank from lora layers that don't have atleast 2 dimensions.
                # Bias layers in LoRA only have a single dimension
                if "lora_B" in key and val.ndim > 1:
                    rank[key] = val.shape[1]

            if network_alphas is not None and len(network_alphas) >= 1:
                alpha_keys = [k for k in network_alphas.keys() if k.startswith(f"{prefix}.")]
                network_alphas = {k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys}

            lora_config_kwargs = get_peft_kwargs(rank, network_alpha_dict=network_alphas, peft_state_dict=state_dict)
            lora_config_kwargs = _maybe_adjust_config(lora_config_kwargs)

            if "use_dora" in lora_config_kwargs:
                if lora_config_kwargs["use_dora"]:
                    if is_peft_version("<", "0.9.0"):
                        raise ValueError(
                            "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
                        )
                else:
                    if is_peft_version("<", "0.9.0"):
                        lora_config_kwargs.pop("use_dora")

            if "lora_bias" in lora_config_kwargs:
                if lora_config_kwargs["lora_bias"]:
                    if is_peft_version("<=", "0.13.2"):
                        raise ValueError(
                            "You need `peft` 0.14.0 at least to use `lora_bias` in LoRAs. Please upgrade your installation of `peft`."
                        )
                else:
                    if is_peft_version("<=", "0.13.2"):
                        lora_config_kwargs.pop("lora_bias")

            lora_config = LoraConfig(**lora_config_kwargs)
            # adapter_name
            if adapter_name is None:
                adapter_name = get_adapter_name(self)

            # To handle scenarios where we cannot successfully set state dict. If it's unsucessful,
            # we should also delete the `peft_config` associated to the `adapter_name`.
            try:
                inject_adapter_in_model(lora_config, self, adapter_name=adapter_name)
                incompatible_keys = set_peft_model_state_dict(self, state_dict, adapter_name)
            except RuntimeError as e:
                for module in self.modules():
                    if isinstance(module, BaseTunerLayer):
                        active_adapters = module.active_adapters
                        for active_adapter in active_adapters:
                            if adapter_name in active_adapter:
                                module.delete_adapter(adapter_name)

                self.peft_config.pop(adapter_name)
                logger.error(f"Loading {adapter_name} was unsucessful with the following error: \n{e}")
                raise

            warn_msg = ""
            if incompatible_keys is not None:
                # Check only for unexpected keys.
                unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
                if unexpected_keys:
                    lora_unexpected_keys = [k for k in unexpected_keys if "lora_" in k and adapter_name in k]
                    if lora_unexpected_keys:
                        warn_msg = (
                            f"Loading adapter weights from state_dict led to unexpected keys found in the model:"
                            f" {', '.join(lora_unexpected_keys)}. "
                        )

                # Filter missing keys specific to the current adapter.
                missing_keys = getattr(incompatible_keys, "missing_keys", None)
                if missing_keys:
                    lora_missing_keys = [k for k in missing_keys if "lora_" in k and adapter_name in k]
                    if lora_missing_keys:
                        warn_msg += (
                            f"Loading adapter weights from state_dict led to missing keys in the model:"
                            f" {', '.join(lora_missing_keys)}."
                        )

            if warn_msg:
                logger.warning(warn_msg)

    def save_lora_adapter(
        self,
        save_directory,
        adapter_name: str = "default",
        upcast_before_saving: bool = False,
        safe_serialization: bool = True,
        weight_name: Optional[str] = None,
    ):
        """
        Save the LoRA parameters corresponding to the underlying model.

        Arguments:
            save_directory (`str` or `os.PathLike`):
                Directory to save LoRA parameters to. Will be created if it doesn't exist.
            adapter_name: (`str`, defaults to "default"): The name of the adapter to serialize. Useful when the
                underlying model has multiple adapters loaded.
            upcast_before_saving (`bool`, defaults to `False`):
                Whether to cast the underlying model to `torch.float32` before serialization.
            save_function (`Callable`):
                The function to use to save the state dictionary. Useful during distributed training when you need to
                replace `torch.save` with another method. Can be configured with the environment variable
                `DIFFUSERS_SAVE_MODE`.
            safe_serialization (`bool`, *optional*, defaults to `True`):
                Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
            weight_name: (`str`, *optional*, defaults to `None`): Name of the file to serialize the state dict with.
        """
        from mindone.diffusers._peft.utils import get_peft_model_state_dict

        from .lora_base import LORA_WEIGHT_NAME, LORA_WEIGHT_NAME_SAFE

        if adapter_name is None:
            adapter_name = get_adapter_name(self)

        if adapter_name not in getattr(self, "peft_config", {}):
            raise ValueError(f"Adapter name {adapter_name} not found in the model.")

        lora_layers_to_save = get_peft_model_state_dict(
            self.to(dtype=ms.float32 if upcast_before_saving else None), adapter_name=adapter_name
        )
        if os.path.isfile(save_directory):
            raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")

        if safe_serialization:

            def save_function(weights, filename):
                return save_file(weights, filename, metadata={"format": "np"})

        else:
            save_function = ms.save_checkpoint

        os.makedirs(save_directory, exist_ok=True)

        if weight_name is None:
            if safe_serialization:
                weight_name = LORA_WEIGHT_NAME_SAFE
            else:
                weight_name = LORA_WEIGHT_NAME

        # TODO: we could consider saving the `peft_config` as well.
        save_path = Path(save_directory, weight_name).as_posix()
        save_function(lora_layers_to_save, save_path)
        logger.info(f"Model weights saved in {save_path}")

    def set_adapters(
        self,
        adapter_names: Union[List[str], str],
        weights: Optional[Union[float, Dict, List[float], List[Dict], List[None]]] = None,
    ):
        """
        Set the currently active adapters for use in the UNet.

        Args:
            adapter_names (`List[str]` or `str`):
                The names of the adapters to use.
            adapter_weights (`Union[List[float], float]`, *optional*):
                The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
                adapters.

        Example:

        ```py
        from mindone.diffusers import AutoPipelineForText2Image
        import mindspore

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
        )
        pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
        pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
        ```
        """
        adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names

        # Expand weights into a list, one entry per adapter
        # examples for e.g. 2 adapters:  [{...}, 7] -> [7,7] ; None -> [None, None]
        if not isinstance(weights, list):
            weights = [weights] * len(adapter_names)

        if len(adapter_names) != len(weights):
            raise ValueError(
                f"Length of adapter names {len(adapter_names)} is not equal to the length of their weights {len(weights)}."
            )

        # Set None values to default of 1.0
        # e.g. [{...}, 7] -> [{...}, 7] ; [None, None] -> [1.0, 1.0]
        weights = [w if w is not None else 1.0 for w in weights]

        # e.g. [{...}, 7] -> [{expanded dict...}, 7]
        scale_expansion_fn = _SET_ADAPTER_SCALE_FN_MAPPING[self.__class__.__name__]
        weights = scale_expansion_fn(self, weights)

        set_weights_and_activate_adapters(self, adapter_names, weights)

    def add_adapter(self, adapter_config, adapter_name: str = "default") -> None:
        r"""
        Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
        to the adapter to follow the convention of the PEFT library.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT
        [documentation](https://huggingface.co/docs/peft).

        Args:
            adapter_config (`[~peft.PeftConfig]`):
                The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
                methods.
            adapter_name (`str`, *optional*, defaults to `"default"`):
                The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
        """
        from mindone.diffusers._peft import PeftConfig, inject_adapter_in_model

        if not self._hf_peft_config_loaded:
            self._hf_peft_config_loaded = True
        elif adapter_name in self.peft_config:
            raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")

        if not isinstance(adapter_config, PeftConfig):
            raise ValueError(f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead.")

        # Unlike transformers, here we don't need to retrieve the name_or_path of the unet as the loading logic is
        # handled by the `load_lora_layers` or `StableDiffusionLoraLoaderMixin`. Therefore we set it to `None` here.
        adapter_config.base_model_name_or_path = None
        inject_adapter_in_model(adapter_config, self, adapter_name)
        self.set_adapter(adapter_name)

    def set_adapter(self, adapter_name: Union[str, List[str]]) -> None:
        """
        Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).

        Args:
            adapter_name (Union[str, List[str]])):
                The list of adapters to set or the adapter name in the case of a single adapter.
        """
        if not self._hf_peft_config_loaded:
            raise ValueError("No adapter loaded. Please load an adapter first.")

        if isinstance(adapter_name, str):
            adapter_name = [adapter_name]

        missing = set(adapter_name) - set(self.peft_config)
        if len(missing) > 0:
            raise ValueError(
                f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
                f" current loaded adapters are: {list(self.peft_config.keys())}"
            )

        from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

        _adapters_has_been_set = False

        for _, module in self.cells_and_names():
            if isinstance(module, BaseTunerLayer):
                if hasattr(module, "set_adapter"):
                    module.set_adapter(adapter_name)
                elif not hasattr(module, "set_adapter"):
                    raise RuntimeError("'BaseTunerLayer' object has no attribute 'set_adapter'")
                _adapters_has_been_set = True

        if not _adapters_has_been_set:
            raise ValueError(
                "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
            )

    def disable_adapters(self) -> None:
        r"""
        Disable all adapters attached to the model and fallback to inference with the base model only.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).
        """
        if not self._hf_peft_config_loaded:
            raise ValueError("No adapter loaded. Please load an adapter first.")

        from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

        for _, module in self.cells_and_names():
            if isinstance(module, BaseTunerLayer):
                if hasattr(module, "enable_adapters"):
                    module.enable_adapters(enabled=False)
                else:
                    raise RuntimeError("'BaseTunerLayer' object has no attribute 'enable_adapters'")

    def enable_adapters(self) -> None:
        """
        Enable adapters that are attached to the model. The model uses `self.active_adapters()` to retrieve the list of
        adapters to enable.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).
        """
        if not self._hf_peft_config_loaded:
            raise ValueError("No adapter loaded. Please load an adapter first.")

        from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

        for _, module in self.cells_and_names():
            if isinstance(module, BaseTunerLayer):
                if hasattr(module, "enable_adapters"):
                    module.enable_adapters(enabled=True)
                else:
                    raise RuntimeError("'BaseTunerLayer' object has no attribute 'enable_adapters'")

    def active_adapters(self) -> List[str]:
        """
        Gets the current list of active adapters of the model.

        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        [documentation](https://huggingface.co/docs/peft).
        """
        if not self._hf_peft_config_loaded:
            raise ValueError("No adapter loaded. Please load an adapter first.")

        from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

        for _, module in self.cells_and_names():
            if isinstance(module, BaseTunerLayer):
                return module.active_adapter

    def fuse_lora(self, lora_scale=1.0, safe_fusing=False, adapter_names=None):
        self.lora_scale = lora_scale
        self._safe_fusing = safe_fusing
        self.apply(partial(self._fuse_lora_apply, adapter_names=adapter_names))

    def _fuse_lora_apply(self, module, adapter_names=None):
        from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

        merge_kwargs = {"safe_merge": self._safe_fusing}

        if isinstance(module, BaseTunerLayer):
            if self.lora_scale != 1.0:
                module.scale_layer(self.lora_scale)

            # For BC with previous PEFT versions, we need to check the signature
            # of the `merge` method to see if it supports the `adapter_names` argument.
            supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
            if "adapter_names" in supported_merge_kwargs:
                merge_kwargs["adapter_names"] = adapter_names
            elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
                raise RuntimeError("The `adapter_names` argument is not supported with `BaseTunerLayer.merge`")

            module.merge(**merge_kwargs)

    def unfuse_lora(self):
        self.apply(self._unfuse_lora_apply)

    def _unfuse_lora_apply(self, module):
        from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

        if isinstance(module, BaseTunerLayer):
            module.unmerge()

    def unload_lora(self):
        from ..utils import recurse_remove_peft_layers

        recurse_remove_peft_layers(self)
        if hasattr(self, "peft_config"):
            del self.peft_config

    def disable_lora(self):
        """
        Disable the UNet's active LoRA layers.

        Example:

        ```py
        from mindone.diffusers import AutoPipelineForText2Image
        import mindspore

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
        )
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
        )
        pipeline.disable_lora()
        ```
        """
        set_adapter_layers(self, enabled=False)

    def enable_lora(self):
        """
        Enable the UNet's active LoRA layers.

        Example:

        ```py
        from mindone.diffusers import AutoPipelineForText2Image
        import mindspore

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
        )
        pipeline.enable_lora()
        ```
        """
        set_adapter_layers(self, enabled=True)

    def delete_adapters(self, adapter_names: Union[List[str], str]):
        """
        Delete an adapter's LoRA layers from the UNet.

        Args:
            adapter_names (`Union[List[str], str]`):
                The names (single string or list of strings) of the adapter to delete.

        Example:

        ```py
        from mindone.diffusers import AutoPipelineForText2Image
        import mindspore

        pipeline = AutoPipelineForText2Image.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
        ).to("cuda")
        pipeline.load_lora_weights(
            "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
        )
        pipeline.delete_adapters("cinematic")
        ```
        """
        if isinstance(adapter_names, str):
            adapter_names = [adapter_names]

        for adapter_name in adapter_names:
            delete_adapter_layers(self, adapter_name)

            # Pop also the corresponding adapter from the config
            if hasattr(self, "peft_config"):
                self.peft_config.pop(adapter_name, None)

mindone.diffusers.loaders.peft.PeftAdapterMixin.active_adapters()

Gets the current list of active adapters of the model.

If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT documentation.

Source code in mindone/diffusers/loaders/peft.py
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def active_adapters(self) -> List[str]:
    """
    Gets the current list of active adapters of the model.

    If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
    [documentation](https://huggingface.co/docs/peft).
    """
    if not self._hf_peft_config_loaded:
        raise ValueError("No adapter loaded. Please load an adapter first.")

    from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

    for _, module in self.cells_and_names():
        if isinstance(module, BaseTunerLayer):
            return module.active_adapter

mindone.diffusers.loaders.peft.PeftAdapterMixin.add_adapter(adapter_config, adapter_name='default')

Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned to the adapter to follow the convention of the PEFT library.

If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT documentation.

PARAMETER DESCRIPTION
adapter_config

The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt methods.

TYPE: `[~peft.PeftConfig]`

adapter_name

The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.

TYPE: `str`, *optional*, defaults to `"default"` DEFAULT: 'default'

Source code in mindone/diffusers/loaders/peft.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
def add_adapter(self, adapter_config, adapter_name: str = "default") -> None:
    r"""
    Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
    to the adapter to follow the convention of the PEFT library.

    If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT
    [documentation](https://huggingface.co/docs/peft).

    Args:
        adapter_config (`[~peft.PeftConfig]`):
            The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
            methods.
        adapter_name (`str`, *optional*, defaults to `"default"`):
            The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
    """
    from mindone.diffusers._peft import PeftConfig, inject_adapter_in_model

    if not self._hf_peft_config_loaded:
        self._hf_peft_config_loaded = True
    elif adapter_name in self.peft_config:
        raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")

    if not isinstance(adapter_config, PeftConfig):
        raise ValueError(f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead.")

    # Unlike transformers, here we don't need to retrieve the name_or_path of the unet as the loading logic is
    # handled by the `load_lora_layers` or `StableDiffusionLoraLoaderMixin`. Therefore we set it to `None` here.
    adapter_config.base_model_name_or_path = None
    inject_adapter_in_model(adapter_config, self, adapter_name)
    self.set_adapter(adapter_name)

mindone.diffusers.loaders.peft.PeftAdapterMixin.delete_adapters(adapter_names)

Delete an adapter's LoRA layers from the UNet.

PARAMETER DESCRIPTION
adapter_names

The names (single string or list of strings) of the adapter to delete.

TYPE: `Union[List[str], str]`

from mindone.diffusers import AutoPipelineForText2Image
import mindspore

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
).to("cuda")
pipeline.load_lora_weights(
    "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
)
pipeline.delete_adapters("cinematic")
Source code in mindone/diffusers/loaders/peft.py
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def delete_adapters(self, adapter_names: Union[List[str], str]):
    """
    Delete an adapter's LoRA layers from the UNet.

    Args:
        adapter_names (`Union[List[str], str]`):
            The names (single string or list of strings) of the adapter to delete.

    Example:

    ```py
    from mindone.diffusers import AutoPipelineForText2Image
    import mindspore

    pipeline = AutoPipelineForText2Image.from_pretrained(
        "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
    ).to("cuda")
    pipeline.load_lora_weights(
        "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
    )
    pipeline.delete_adapters("cinematic")
    ```
    """
    if isinstance(adapter_names, str):
        adapter_names = [adapter_names]

    for adapter_name in adapter_names:
        delete_adapter_layers(self, adapter_name)

        # Pop also the corresponding adapter from the config
        if hasattr(self, "peft_config"):
            self.peft_config.pop(adapter_name, None)

mindone.diffusers.loaders.peft.PeftAdapterMixin.disable_adapters()

Disable all adapters attached to the model and fallback to inference with the base model only.

If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT documentation.

Source code in mindone/diffusers/loaders/peft.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def disable_adapters(self) -> None:
    r"""
    Disable all adapters attached to the model and fallback to inference with the base model only.

    If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
    [documentation](https://huggingface.co/docs/peft).
    """
    if not self._hf_peft_config_loaded:
        raise ValueError("No adapter loaded. Please load an adapter first.")

    from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

    for _, module in self.cells_and_names():
        if isinstance(module, BaseTunerLayer):
            if hasattr(module, "enable_adapters"):
                module.enable_adapters(enabled=False)
            else:
                raise RuntimeError("'BaseTunerLayer' object has no attribute 'enable_adapters'")

mindone.diffusers.loaders.peft.PeftAdapterMixin.disable_lora()

Disable the UNet's active LoRA layers.

Example:

from mindone.diffusers import AutoPipelineForText2Image
import mindspore

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
)
pipeline.load_lora_weights(
    "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
)
pipeline.disable_lora()
Source code in mindone/diffusers/loaders/peft.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def disable_lora(self):
    """
    Disable the UNet's active LoRA layers.

    Example:

    ```py
    from mindone.diffusers import AutoPipelineForText2Image
    import mindspore

    pipeline = AutoPipelineForText2Image.from_pretrained(
        "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
    )
    pipeline.load_lora_weights(
        "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
    )
    pipeline.disable_lora()
    ```
    """
    set_adapter_layers(self, enabled=False)

mindone.diffusers.loaders.peft.PeftAdapterMixin.enable_adapters()

Enable adapters that are attached to the model. The model uses self.active_adapters() to retrieve the list of adapters to enable.

If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT documentation.

Source code in mindone/diffusers/loaders/peft.py
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
def enable_adapters(self) -> None:
    """
    Enable adapters that are attached to the model. The model uses `self.active_adapters()` to retrieve the list of
    adapters to enable.

    If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
    [documentation](https://huggingface.co/docs/peft).
    """
    if not self._hf_peft_config_loaded:
        raise ValueError("No adapter loaded. Please load an adapter first.")

    from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

    for _, module in self.cells_and_names():
        if isinstance(module, BaseTunerLayer):
            if hasattr(module, "enable_adapters"):
                module.enable_adapters(enabled=True)
            else:
                raise RuntimeError("'BaseTunerLayer' object has no attribute 'enable_adapters'")

mindone.diffusers.loaders.peft.PeftAdapterMixin.enable_lora()

Enable the UNet's active LoRA layers.

Example:

from mindone.diffusers import AutoPipelineForText2Image
import mindspore

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
).to("cuda")
pipeline.load_lora_weights(
    "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
)
pipeline.enable_lora()
Source code in mindone/diffusers/loaders/peft.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
def enable_lora(self):
    """
    Enable the UNet's active LoRA layers.

    Example:

    ```py
    from mindone.diffusers import AutoPipelineForText2Image
    import mindspore

    pipeline = AutoPipelineForText2Image.from_pretrained(
        "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
    ).to("cuda")
    pipeline.load_lora_weights(
        "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
    )
    pipeline.enable_lora()
    ```
    """
    set_adapter_layers(self, enabled=True)

mindone.diffusers.loaders.peft.PeftAdapterMixin.load_lora_adapter(pretrained_model_name_or_path_or_dict, prefix='transformer', **kwargs)

Loads a LoRA adapter into the underlying model.

PARAMETER DESCRIPTION
pretrained_model_name_or_path_or_dict

Can be either:

- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
  the Hub.
- A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
  with [`ModelMixin.save_pretrained`].
- A [torch state
  dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

TYPE: `str` or `os.PathLike` or `dict`

prefix

Prefix to filter the state dict.

TYPE: `str`, *optional* DEFAULT: 'transformer'

cache_dir

Path to a directory where a downloaded pretrained model configuration is cached if the standard cache is not used.

TYPE: `Union[str, os.PathLike]`, *optional*

force_download

Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist.

TYPE: `bool`, *optional*, defaults to `False`

proxies

A dictionary of proxy servers to use by protocol or endpoint, for example, {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request.

TYPE: `Dict[str, str]`, *optional*

local_files_only

Whether to only load local model weights and configuration files or not. If set to True, the model won't be downloaded from the Hub.

TYPE: `bool`, *optional*, defaults to `False`

token

The token to use as HTTP bearer authorization for remote files. If True, the token generated from diffusers-cli login (stored in ~/.huggingface) is used.

TYPE: `str` or *bool*, *optional*

revision

The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier allowed by Git.

TYPE: `str`, *optional*, defaults to `"main"`

subfolder

The subfolder location of a model file within a larger model repository on the Hub or locally.

TYPE: `str`, *optional*, defaults to `""`

network_alphas

The value of the network alpha used for stable learning and preventing underflow. This value has the same meaning as the --network_alpha option in the kohya-ss trainer script. Refer to this link.

TYPE: `Dict[str, float]`

Source code in mindone/diffusers/loaders/peft.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def load_lora_adapter(self, pretrained_model_name_or_path_or_dict, prefix="transformer", **kwargs):
    r"""
    Loads a LoRA adapter into the underlying model.

    Parameters:
        pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
            Can be either:

                - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
                  the Hub.
                - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
                  with [`ModelMixin.save_pretrained`].
                - A [torch state
                  dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

        prefix (`str`, *optional*): Prefix to filter the state dict.

        cache_dir (`Union[str, os.PathLike]`, *optional*):
            Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
            is not used.
        force_download (`bool`, *optional*, defaults to `False`):
            Whether or not to force the (re-)download of the model weights and configuration files, overriding the
            cached versions if they exist.
        proxies (`Dict[str, str]`, *optional*):
            A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
            'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
        local_files_only (`bool`, *optional*, defaults to `False`):
            Whether to only load local model weights and configuration files or not. If set to `True`, the model
            won't be downloaded from the Hub.
        token (`str` or *bool*, *optional*):
            The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
            `diffusers-cli login` (stored in `~/.huggingface`) is used.
        revision (`str`, *optional*, defaults to `"main"`):
            The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
            allowed by Git.
        subfolder (`str`, *optional*, defaults to `""`):
            The subfolder location of a model file within a larger model repository on the Hub or locally.
        network_alphas (`Dict[str, float]`):
            The value of the network alpha used for stable learning and preventing underflow. This value has the
            same meaning as the `--network_alpha` option in the kohya-ss trainer script. Refer to [this
            link](https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning).
    """
    from mindone.diffusers._peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
    from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

    cache_dir = kwargs.pop("cache_dir", None)
    force_download = kwargs.pop("force_download", False)
    proxies = kwargs.pop("proxies", None)
    local_files_only = kwargs.pop("local_files_only", None)
    token = kwargs.pop("token", None)
    revision = kwargs.pop("revision", None)
    subfolder = kwargs.pop("subfolder", None)
    weight_name = kwargs.pop("weight_name", None)
    use_safetensors = kwargs.pop("use_safetensors", None)
    adapter_name = kwargs.pop("adapter_name", None)
    network_alphas = kwargs.pop("network_alphas", None)
    allow_pickle = False

    user_agent = {
        "file_type": "attn_procs_weights",
        "framework": "pytorch",
    }

    state_dict = _fetch_state_dict(
        pretrained_model_name_or_path_or_dict=pretrained_model_name_or_path_or_dict,
        weight_name=weight_name,
        use_safetensors=use_safetensors,
        local_files_only=local_files_only,
        cache_dir=cache_dir,
        force_download=force_download,
        proxies=proxies,
        token=token,
        revision=revision,
        subfolder=subfolder,
        user_agent=user_agent,
        allow_pickle=allow_pickle,
    )
    if network_alphas is not None and prefix is None:
        raise ValueError("`network_alphas` cannot be None when `prefix` is None.")

    if prefix is not None:
        keys = list(state_dict.keys())
        model_keys = [k for k in keys if k.startswith(f"{prefix}.")]
        if len(model_keys) > 0:
            state_dict = {k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in model_keys}

    if len(state_dict) > 0:
        if adapter_name in getattr(self, "peft_config", {}):
            raise ValueError(
                f"Adapter name {adapter_name} already in use in the model - please select a new adapter name."
            )

        # check with first key if is not in peft format
        first_key = next(iter(state_dict.keys()))
        if "lora_A" not in first_key:
            state_dict = convert_unet_state_dict_to_peft(state_dict)

        rank = {}
        for key, val in state_dict.items():
            # Cannot figure out rank from lora layers that don't have atleast 2 dimensions.
            # Bias layers in LoRA only have a single dimension
            if "lora_B" in key and val.ndim > 1:
                rank[key] = val.shape[1]

        if network_alphas is not None and len(network_alphas) >= 1:
            alpha_keys = [k for k in network_alphas.keys() if k.startswith(f"{prefix}.")]
            network_alphas = {k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys}

        lora_config_kwargs = get_peft_kwargs(rank, network_alpha_dict=network_alphas, peft_state_dict=state_dict)
        lora_config_kwargs = _maybe_adjust_config(lora_config_kwargs)

        if "use_dora" in lora_config_kwargs:
            if lora_config_kwargs["use_dora"]:
                if is_peft_version("<", "0.9.0"):
                    raise ValueError(
                        "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
                    )
            else:
                if is_peft_version("<", "0.9.0"):
                    lora_config_kwargs.pop("use_dora")

        if "lora_bias" in lora_config_kwargs:
            if lora_config_kwargs["lora_bias"]:
                if is_peft_version("<=", "0.13.2"):
                    raise ValueError(
                        "You need `peft` 0.14.0 at least to use `lora_bias` in LoRAs. Please upgrade your installation of `peft`."
                    )
            else:
                if is_peft_version("<=", "0.13.2"):
                    lora_config_kwargs.pop("lora_bias")

        lora_config = LoraConfig(**lora_config_kwargs)
        # adapter_name
        if adapter_name is None:
            adapter_name = get_adapter_name(self)

        # To handle scenarios where we cannot successfully set state dict. If it's unsucessful,
        # we should also delete the `peft_config` associated to the `adapter_name`.
        try:
            inject_adapter_in_model(lora_config, self, adapter_name=adapter_name)
            incompatible_keys = set_peft_model_state_dict(self, state_dict, adapter_name)
        except RuntimeError as e:
            for module in self.modules():
                if isinstance(module, BaseTunerLayer):
                    active_adapters = module.active_adapters
                    for active_adapter in active_adapters:
                        if adapter_name in active_adapter:
                            module.delete_adapter(adapter_name)

            self.peft_config.pop(adapter_name)
            logger.error(f"Loading {adapter_name} was unsucessful with the following error: \n{e}")
            raise

        warn_msg = ""
        if incompatible_keys is not None:
            # Check only for unexpected keys.
            unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
            if unexpected_keys:
                lora_unexpected_keys = [k for k in unexpected_keys if "lora_" in k and adapter_name in k]
                if lora_unexpected_keys:
                    warn_msg = (
                        f"Loading adapter weights from state_dict led to unexpected keys found in the model:"
                        f" {', '.join(lora_unexpected_keys)}. "
                    )

            # Filter missing keys specific to the current adapter.
            missing_keys = getattr(incompatible_keys, "missing_keys", None)
            if missing_keys:
                lora_missing_keys = [k for k in missing_keys if "lora_" in k and adapter_name in k]
                if lora_missing_keys:
                    warn_msg += (
                        f"Loading adapter weights from state_dict led to missing keys in the model:"
                        f" {', '.join(lora_missing_keys)}."
                    )

        if warn_msg:
            logger.warning(warn_msg)

mindone.diffusers.loaders.peft.PeftAdapterMixin.save_lora_adapter(save_directory, adapter_name='default', upcast_before_saving=False, safe_serialization=True, weight_name=None)

Save the LoRA parameters corresponding to the underlying model.

PARAMETER DESCRIPTION
save_directory

Directory to save LoRA parameters to. Will be created if it doesn't exist.

TYPE: `str` or `os.PathLike`

adapter_name

(str, defaults to "default"): The name of the adapter to serialize. Useful when the underlying model has multiple adapters loaded.

TYPE: str DEFAULT: 'default'

upcast_before_saving

Whether to cast the underlying model to torch.float32 before serialization.

TYPE: `bool`, defaults to `False` DEFAULT: False

save_function

The function to use to save the state dictionary. Useful during distributed training when you need to replace torch.save with another method. Can be configured with the environment variable DIFFUSERS_SAVE_MODE.

TYPE: `Callable`

safe_serialization

Whether to save the model using safetensors or the traditional PyTorch way with pickle.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

weight_name

(str, optional, defaults to None): Name of the file to serialize the state dict with.

TYPE: Optional[str] DEFAULT: None

Source code in mindone/diffusers/loaders/peft.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def save_lora_adapter(
    self,
    save_directory,
    adapter_name: str = "default",
    upcast_before_saving: bool = False,
    safe_serialization: bool = True,
    weight_name: Optional[str] = None,
):
    """
    Save the LoRA parameters corresponding to the underlying model.

    Arguments:
        save_directory (`str` or `os.PathLike`):
            Directory to save LoRA parameters to. Will be created if it doesn't exist.
        adapter_name: (`str`, defaults to "default"): The name of the adapter to serialize. Useful when the
            underlying model has multiple adapters loaded.
        upcast_before_saving (`bool`, defaults to `False`):
            Whether to cast the underlying model to `torch.float32` before serialization.
        save_function (`Callable`):
            The function to use to save the state dictionary. Useful during distributed training when you need to
            replace `torch.save` with another method. Can be configured with the environment variable
            `DIFFUSERS_SAVE_MODE`.
        safe_serialization (`bool`, *optional*, defaults to `True`):
            Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
        weight_name: (`str`, *optional*, defaults to `None`): Name of the file to serialize the state dict with.
    """
    from mindone.diffusers._peft.utils import get_peft_model_state_dict

    from .lora_base import LORA_WEIGHT_NAME, LORA_WEIGHT_NAME_SAFE

    if adapter_name is None:
        adapter_name = get_adapter_name(self)

    if adapter_name not in getattr(self, "peft_config", {}):
        raise ValueError(f"Adapter name {adapter_name} not found in the model.")

    lora_layers_to_save = get_peft_model_state_dict(
        self.to(dtype=ms.float32 if upcast_before_saving else None), adapter_name=adapter_name
    )
    if os.path.isfile(save_directory):
        raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")

    if safe_serialization:

        def save_function(weights, filename):
            return save_file(weights, filename, metadata={"format": "np"})

    else:
        save_function = ms.save_checkpoint

    os.makedirs(save_directory, exist_ok=True)

    if weight_name is None:
        if safe_serialization:
            weight_name = LORA_WEIGHT_NAME_SAFE
        else:
            weight_name = LORA_WEIGHT_NAME

    # TODO: we could consider saving the `peft_config` as well.
    save_path = Path(save_directory, weight_name).as_posix()
    save_function(lora_layers_to_save, save_path)
    logger.info(f"Model weights saved in {save_path}")

mindone.diffusers.loaders.peft.PeftAdapterMixin.set_adapter(adapter_name)

Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.

If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT documentation.

PARAMETER DESCRIPTION
adapter_name

The list of adapters to set or the adapter name in the case of a single adapter.

TYPE: Union[str, List[str]]

Source code in mindone/diffusers/loaders/peft.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
def set_adapter(self, adapter_name: Union[str, List[str]]) -> None:
    """
    Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.

    If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
    [documentation](https://huggingface.co/docs/peft).

    Args:
        adapter_name (Union[str, List[str]])):
            The list of adapters to set or the adapter name in the case of a single adapter.
    """
    if not self._hf_peft_config_loaded:
        raise ValueError("No adapter loaded. Please load an adapter first.")

    if isinstance(adapter_name, str):
        adapter_name = [adapter_name]

    missing = set(adapter_name) - set(self.peft_config)
    if len(missing) > 0:
        raise ValueError(
            f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
            f" current loaded adapters are: {list(self.peft_config.keys())}"
        )

    from mindone.diffusers._peft.tuners.tuners_utils import BaseTunerLayer

    _adapters_has_been_set = False

    for _, module in self.cells_and_names():
        if isinstance(module, BaseTunerLayer):
            if hasattr(module, "set_adapter"):
                module.set_adapter(adapter_name)
            elif not hasattr(module, "set_adapter"):
                raise RuntimeError("'BaseTunerLayer' object has no attribute 'set_adapter'")
            _adapters_has_been_set = True

    if not _adapters_has_been_set:
        raise ValueError(
            "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
        )

mindone.diffusers.loaders.peft.PeftAdapterMixin.set_adapters(adapter_names, weights=None)

Set the currently active adapters for use in the UNet.

PARAMETER DESCRIPTION
adapter_names

The names of the adapters to use.

TYPE: `List[str]` or `str`

adapter_weights

The adapter(s) weights to use with the UNet. If None, the weights are set to 1.0 for all the adapters.

TYPE: `Union[List[float], float]`, *optional*

from mindone.diffusers import AutoPipelineForText2Image
import mindspore

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
).to("cuda")
pipeline.load_lora_weights(
    "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
)
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
Source code in mindone/diffusers/loaders/peft.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def set_adapters(
    self,
    adapter_names: Union[List[str], str],
    weights: Optional[Union[float, Dict, List[float], List[Dict], List[None]]] = None,
):
    """
    Set the currently active adapters for use in the UNet.

    Args:
        adapter_names (`List[str]` or `str`):
            The names of the adapters to use.
        adapter_weights (`Union[List[float], float]`, *optional*):
            The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
            adapters.

    Example:

    ```py
    from mindone.diffusers import AutoPipelineForText2Image
    import mindspore

    pipeline = AutoPipelineForText2Image.from_pretrained(
        "stabilityai/stable-diffusion-xl-base-1.0", mindspore_dtype=mindspore.float16
    ).to("cuda")
    pipeline.load_lora_weights(
        "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
    )
    pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
    pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
    ```
    """
    adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names

    # Expand weights into a list, one entry per adapter
    # examples for e.g. 2 adapters:  [{...}, 7] -> [7,7] ; None -> [None, None]
    if not isinstance(weights, list):
        weights = [weights] * len(adapter_names)

    if len(adapter_names) != len(weights):
        raise ValueError(
            f"Length of adapter names {len(adapter_names)} is not equal to the length of their weights {len(weights)}."
        )

    # Set None values to default of 1.0
    # e.g. [{...}, 7] -> [{...}, 7] ; [None, None] -> [1.0, 1.0]
    weights = [w if w is not None else 1.0 for w in weights]

    # e.g. [{...}, 7] -> [{expanded dict...}, 7]
    scale_expansion_fn = _SET_ADAPTER_SCALE_FN_MAPPING[self.__class__.__name__]
    weights = scale_expansion_fn(self, weights)

    set_weights_and_activate_adapters(self, adapter_names, weights)