# PEFT

Diffusers 支持通过 [PeftAdapterMixin](/docs/diffusers/v0.43.0/zh/api/loaders/peft#diffusers.loaders.PeftAdapterMixin) 类，使用 [PEFT](https://huggingface.co/docs/peft/index) 库加载 [LoRA](../../tutorials/using_peft_for_inference) 等适配器。这使得 Diffusers 中的 [UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel)、[SD3Transformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/sd3_transformer2d#diffusers.SD3Transformer2DModel) 等建模类能够配合适配器运行。

> [!TIP]
> 有关如何在 Diffusers 中使用 PEFT 进行推理的概述，请参阅 [使用 PEFT 进行推理](../../tutorials/using_peft_for_inference) 教程。

## PeftAdapterMixin[[diffusers.loaders.PeftAdapterMixin]]

#### diffusers.loaders.PeftAdapterMixin[[diffusers.loaders.PeftAdapterMixin]]

```python
diffusers.loaders.PeftAdapterMixin()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L62)

一个包含所有用于加载和使用 PEFT 库支持的适配器权重的函数的类。有关适配器及其在基础模型中注入的更多详细信息，请参阅 PEFT [文档](https://huggingface.co/docs/peft/index)。

安装 PEFT 的最新版本，并使用此混入类来：

- 在模型中附加新的适配器。
- 附加多个适配器并迭代地激活/停用它们。
- 激活/停用模型中的所有适配器。
- 获取活动适配器的列表。

#### active_adapters[[diffusers.loaders.PeftAdapterMixin.active_adapters]]

```python
active_adapters()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L652)

获取模型当前激活的适配器列表。

如果您对适配器和 PEFT 方法不熟悉，我们邀请您阅读 PEFT 的[文档](https://huggingface.co/docs/peft)以了解更多相关信息。

#### add_adapter[[diffusers.loaders.PeftAdapterMixin.add_adapter]]

```python
add_adapter(adapter_config, adapter_name: str = 'default')
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L518)

**参数：**

adapter_config (`[~peft.PeftConfig]`)：要添加的适配器的配置；支持的适配器包括非前缀调优和适配提示方法。

adapter_name (`str`，*可选*，默认为 `"default"`)：要添加的适配器名称。如果未传入名称，则会自动为适配器分配一个默认名称。

为当前模型添加一个新的适配器用于训练。如果未传入适配器名称，则会按照 PEFT 库的约定为该适配器分配一个默认名称。

如果您对适配器和 PEFT 方法不熟悉，我们邀请您阅读 PEFT [文档](https://huggingface.co/docs/peft)以了解更多相关信息。

#### delete_adapters[[diffusers.loaders.PeftAdapterMixin.delete_adapters]]

```python
delete_adapters(adapter_names: list[str] | str)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L777)

**参数：**

adapter_names (`list[str, str]`) : 要删除的适配器名称（单个字符串或字符串列表）。

从底层模型中删除适配器的 LoRA 层。

示例：

```py
from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights(
    "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
)
pipeline.unet.delete_adapters("cinematic")
```

#### disable_adapters[[diffusers.loaders.PeftAdapterMixin.disable_adapters]]

```python
disable_adapters()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L607)

禁用所有附加到模型上的适配器，并回退到仅使用基础模型进行推理。

如果您对适配器和 PEFT 方法不熟悉，我们邀请您阅读 PEFT 的[文档](https://huggingface.co/docs/peft)以了解更多相关信息。

#### disable_lora[[diffusers.loaders.PeftAdapterMixin.disable_lora]]

```python
disable_lora()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L731)

禁用底层模型中处于激活状态的 LoRA 层。

示例：

```py
from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights(
    "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
)
pipeline.unet.disable_lora()
```

#### enable_adapters[[diffusers.loaders.PeftAdapterMixin.enable_adapters]]

```python
enable_adapters()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L629)

启用附加到模型的适配器。模型使用 `self.active_adapters()` 获取要启用的适配器列表。

如果您对适配器和 PEFT 方法不熟悉，我们邀请您阅读 PEFT 的[文档](https://huggingface.co/docs/peft)以了解更多相关信息。

#### enable_lora[[diffusers.loaders.PeftAdapterMixin.enable_lora]]

```python
enable_lora()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L754)

启用底层模型的激活 LoRA 层。

示例：

```py
from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights(
    "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
)
pipeline.unet.enable_lora()
```

#### enable_lora_hotswap[[diffusers.loaders.PeftAdapterMixin.enable_lora_hotswap]]

```python
enable_lora_hotswap(target_rank: int = 128, check_compiled: typing.Literal['error', 'warn', 'ignore'] = 'error')
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L815)

**参数：**

target_rank (`int`，*可选*，默认为 `128`)：所有将加载的适配器中的最高秩。

check_compiled (`str`，*可选*，默认为 `"error"`)：当模型已被编译时如何处理，通常应避免这种情况。可选值：- "error"（默认）：抛出错误 - "warn"：发出警告 - "ignore"：不做任何处理

启用 LoRA 适配器的热替换功能。

仅在热切换适配器且模型已编译，或所加载适配器的秩不同时，才需要调用此方法。

#### load_lora_adapter[[diffusers.loaders.PeftAdapterMixin.load_lora_adapter]]

```python
load_lora_adapter(pretrained_model_name_or_path_or_dict, prefix = 'transformer', hotswap: bool = False, **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L85)

**参数：**

pretrained_model_name_or_path_or_dict (`str` 或 `os.PathLike` 或 `dict`) : 可以是以下之一： - 一个字符串，即托管在 Hub 上的预训练模型的 *model id*（例如 `google/ddpm-celebahq-256`）。 - 一个指向 *目录* 的路径（例如 `./my_model_directory`），其中包含使用 [ModelMixin.save_pretrained()](/docs/diffusers/v0.43.0/zh/api/models/overview#diffusers.ModelMixin.save_pretrained) 保存的模型权重。 - 一个 [torch state dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict)。

prefix (`str`, *可选*) : 用于过滤 state dict 的前缀。

cache_dir (`str | os.PathLike`，*可选*)：如果未使用标准缓存，则已下载的预训练模型配置将缓存到的目录路径。

force_download (`bool`，*可选*，默认为 `False`)：是否强制（重新）下载模型权重和配置文件，如果存在缓存版本则覆盖它们。

proxies (`dict[str, str]`，*可选*)：一个字典，用于按协议或端点指定要使用的代理服务器，例如 `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`。每次请求都会使用这些代理。

local_files_only (`bool`，*可选*，默认为 `False`)：是否仅加载本地模型权重和配置文件。如果设置为 `True`，则不会从 Hub 下载模型。

token (`str` 或 *bool*，*可选*) : 用于远程文件的 HTTP 承载者授权令牌。如果为 `True`，则使用由 `diffusers-cli login` 生成的令牌（存储在 `~/.huggingface` 中）。

revision (`str`，*可选*，默认为 `"main"`)：要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID，或 Git 允许的任何标识符。

subfolder (`str`，*可选*，默认为 `""`)：模型文件在 Hub 或本地的大型模型仓库中的子文件夹位置。

network_alphas (`dict[str, float]`) : 用于稳定学习和防止下溢的网络 alpha 值。该值与 kohya-ss 训练脚本中的 `--network_alpha` 选项含义相同。请参阅 [此链接](https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning)。

low_cpu_mem_usage (`bool`，*可选*)：通过仅加载预训练的 LoRA 权重而不初始化随机权重，来加快模型加载速度。

hotswap : (`bool`，*可选*) 默认为 `False`。是否就地用新加载的适配器替换现有的（LoRA）适配器。这意味着，不会加载额外的适配器，而是将现有适配器的权重替换为新适配器的权重。这种方式可能更快且更节省内存。然而，热替换的主要优势在于，当模型使用 torch.compile 编译时，加载新适配器无需重新编译模型。使用热替换时，传入的 `adapter_name` 应为已加载适配器的名称。 如果新适配器和旧适配器的秩和/或 LoRA alpha（即缩放）不同，在加载适配器之前需要调用一个额外方法： ```py pipeline = ...  # load diffusers pipeline max_rank = ...  # the highest rank among all LoRAs that you want to load # call *before* compiling and loading the LoRA adapter pipeline.enable_lora_hotswap(target_rank=max_rank) pipeline.load_lora_weights(file_name) # optionally compile the model now ``` 请注意，目前尚不支持对文本编码器适配器进行热替换。该技术还有一些其他限制，详见此处：https://huggingface.co/docs/peft/main/en/package_reference/hotswap

metadata : LoRA 适配器元数据。如果提供了该参数，则不会使用通过 state dict 推断出的元数据来初始化 `LoraConfig`。

将 LoRA 适配器加载到底层模型中。

#### save_lora_adapter[[diffusers.loaders.PeftAdapterMixin.save_lora_adapter]]

```python
save_lora_adapter(save_directory, adapter_name: str = 'default', upcast_before_saving: bool = False, safe_serialization: bool = True, weight_name: str | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L394)

**参数：**

save_directory (`str` 或 `os.PathLike`)：用于保存 LoRA 参数的目录。如果该目录不存在，将自动创建。

adapter_name : (`str`，默认为 "default")：要序列化的适配器名称。当底层模型加载了多个适配器时，此参数非常有用。

upcast_before_saving (`bool`，默认为 `False`)：是否在序列化之前将底层模型转换为 `torch.float32`。

safe_serialization (`bool`，*可选*，默认为 `True`)：是否使用 `safetensors` 保存模型，还是使用传统的 PyTorch 方式（通过 `pickle`）。

weight_name : (`str`, *可选*，默认为 `None`)：用于序列化 state dict 的文件名。

保存与底层模型对应的 LoRA 参数。

#### set_adapter[[diffusers.loaders.PeftAdapterMixin.set_adapter]]

```python
set_adapter(adapter_name: str | list[str])
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L558)

**参数：**

adapter_name (str | list[str])) : 要设置的适配器列表，或在单个适配器的情况下为适配器名称。

通过强制模型仅使用该适配器并禁用其他适配器，来设置特定的适配器。

如果您对适配器和 PEFT 方法不熟悉，我们邀请您阅读 PEFT 的[文档](https://huggingface.co/docs/peft)以了解更多相关信息。

#### set_adapters[[diffusers.loaders.PeftAdapterMixin.set_adapters]]

```python
set_adapters(adapter_names: list[str] | str, weights: float | dict | list[float] | list[dict] | list[None] | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/peft.py#L462)

**参数：**

adapter_names (`list[str]` 或 `str`) : 要使用的适配器名称。

weights (`Union[List[float], float]`，*可选*)：用于 UNet 的适配器权重。如果为 `None`，则所有适配器的权重均设置为 `1.0`。

设置当前在扩散网络（例如 unet、transformer 等）中使用的活动适配器。

示例：

```py
from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.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.unet.set_adapters(["cinematic", "pixel"], weights=[0.5, 0.5])
```

