# 调优器

调优器（或适配器）是一个可以插入到 `torch.nn.Module` 中的模块。`BaseTuner` 是其他调优器的基类，提供了用于准备适配器配置以及用适配器模块替换目标模块的共享方法和属性。`BaseTunerLayer` 是适配器层的基类。它提供了用于管理适配器的方法和属性，例如激活和禁用适配器。

## BaseTuner[[peft.tuners.tuners_utils.BaseTuner]]

#### peft.tuners.tuners_utils.BaseTuner[[peft.tuners.tuners_utils.BaseTuner]]

```python
peft.tuners.tuners_utils.BaseTuner(model, peft_config: Union[PeftConfig, dict[str, PeftConfig]], adapter_name: str, low_cpu_mem_usage: bool = False, state_dict: Optional[dict[str, torch.Tensor]] = None)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L267)

**参数：**

model (`torch.nn.Module`)：将挂载适配器调优层的模型。

forward (`Callable`)：模型的前向方法。

peft_config (`Union[`PeftConfig`, dict[str, PeftConfig]]`)：适配器配置对象，应为 `str` 到 `PeftConfig` 对象的字典。也可以传入一个 PeftConfig 对象，此时将使用默认名称 `adapter` 创建一个新的适配器；或者创建一个新字典，其键为 `adapter_name`，值为该 peft 配置。

config (`dict[str, Any]`) : 模型配置对象，它应该是一个 `str` 到 `Any` 对象的字典。

targeted_module_names (`list[str]`) : 实际被适配的模块名称列表。如果您想快速检查 `config.target_modules` 是否指定正确，此列表会很有用。

targeted_parameter_names (`list[str]`) : 实际被适配的参数名称列表。如果您想快速检查 `config.target_parameters` 是否指定正确，此列表会很有用。

prefix (`str`) : PEFT 方法特有的唯一前缀。例如，LoRA 的前缀为 `"lora_"`。

一个基础调优器模型，为所有可注入到 torch.nn.Module 中的调优器提供通用的方法和属性

要添加一个新的 Tuner 类，需要重写以下方法：

- **_prepare_adapter_config**：一个私有方法，用于最终准备适配器配置，例如在字段 `target_modules` 缺失的情况下。
- **_create_and_replace**：一个私有方法，用于创建适配器模块并替换目标模块。
- **_check_target_module_exists**：一个私有辅助方法，用于检查传入模块的键名是否与 adapter_config 中的任何目标模块匹配。

最简单的方法是查看 `peft.tuners.lora.LoraModel` 类中的实现。

#### delete_adapter[[peft.tuners.tuners_utils.BaseTuner.delete_adapter]]

```python
delete_adapter(adapter_name: str)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L611)

**参数：**

adapter_name (str) : 要删除的适配器名称。

删除现有的适配器。

#### disable_adapter_layers[[peft.tuners.tuners_utils.BaseTuner.disable_adapter_layers]]

```python
disable_adapter_layers()
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L587)

就地禁用所有适配器。

当禁用所有适配器时，模型输出与基础模型的输出相对应。

#### enable_adapter_layers[[peft.tuners.tuners_utils.BaseTuner.enable_adapter_layers]]

```python
enable_adapter_layers()
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L604)

就地启用所有适配器

#### get_model_config[[peft.tuners.tuners_utils.BaseTuner.get_model_config]]

```python
get_model_config(model: nn.Module)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L1441)

**参数：**

model (`nn.Module`) : 用于获取配置的模型。

此方法以字典形式从模型中获取配置。如果模型没有 config 属性，则此方法返回默认配置。

#### inject_adapter[[peft.tuners.tuners_utils.BaseTuner.inject_adapter]]

```python
inject_adapter(model: nn.Module, adapter_name: str, autocast_adapter_dtype: bool = True, low_cpu_mem_usage: bool = False, state_dict: Optional[dict[str, torch.Tensor]] = None)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L841)

**参数：**

model (`nn.Module`) : 要调优的模型。

adapter_name (`str`) : 适配器名称。

autocast_adapter_dtype (`bool`, *可选*) : 是否自动转换适配器数据类型。默认为 `True`。

low_cpu_mem_usage (`bool`, `optional`, 默认为 `False`) : 在 meta 设备上创建空的适配器权重。有助于加快加载过程。

state_dict (`dict`, *可选*，默认为 `None`) : 如果在此处传入 state_dict，适配器将根据 state_dict 中的条目进行注入。当 PEFT 方法的确切 `target_modules` 未知时（例如，因为检查点在创建时未包含元数据），这可能会很有用。请注意，state_dict 中的值不会被使用，仅使用键来确定应进行适配的正确层。

创建适配器层，并用适配器层替换目标模块。如果传入的是非提示调优适配器类，`peft.mapping.get_peft_model` 会在内部调用此方法。

对应的 PEFT 配置直接从 BaseTuner 类的 `peft_config` 属性中获取。

#### merge_adapter[[peft.tuners.tuners_utils.BaseTuner.merge_adapter]]

```python
merge_adapter(adapter_names: Optional[list[str]] = None, safe_merge: bool = False)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L1383)

**参数：**

adapter_names (`list[str]`, *可选*) : 需要合并的适配器名称列表。如果为 `None`，则所有活动适配器都会被合并。默认为 `None`。

safe_merge (`bool`, *可选*) : 如果为 `True`，合并操作将在原始权重的副本上执行，并在合并权重之前检查是否存在 NaN。如果您想检查合并操作是否会产生 NaN，这将非常有用。默认为 `False`。

此方法将适配器层合并到基础模型中。

合并适配器可以加速前向传播。内存中仍会保留适配器权重的一份副本，这是为了能够取消合并适配器。若要在不保留权重于内存的情况下合并适配器权重，请调用 `merge_and_unload`。

一旦某个层合并了适配器权重，其前向传播就仅使用这些权重。因此，如果 `adapter_names` 未涵盖所有处于激活状态的适配器，则其余处于激活状态的适配器将被静默忽略，即使它们仍被报告为处于激活状态。请合并所有处于激活状态的适配器，或先调用 `unmerge_adapter`。请注意，此行为计划在 v1.0 版本中更改。

#### merge_and_unload[[peft.tuners.tuners_utils.BaseTuner.merge_and_unload]]

```python
merge_and_unload(progressbar: bool = False, safe_merge: bool = False, adapter_names: Optional[list[str]] = None)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L784)

**参数：**

progressbar (`bool`) : 是否显示进度条以指示卸载和合并过程（默认值：False）。

safe_merge (`bool`) : 是否启用安全合并检查，以检查适配器权重中是否存在潜在的 Nan。

adapter_names (`List[str]`, *可选*) : 需要合并的适配器名称列表。如果为 None，则所有活动适配器都会被合并。默认为 `None`。

此方法将适配器层合并到基础模型中。

如果希望将基础模型作为独立模型使用，则需要此操作。返回的模型与原始基础模型具有相同的架构。

将返回的模型赋值给一个变量并使用它非常重要，这不是一个原地操作！

示例：

```py
>>> from transformers import AutoModelForCausalLM
>>> from peft import PeftModel

>>> model_id = ...
>>> base_model = AutoModelForCausalLM.from_pretrained(model_id)
>>> peft_model_id = ...
>>> model = PeftModel.from_pretrained(base_model, peft_model_id)
>>> merged_model = model.merge_and_unload()
```

#### set_adapter[[peft.tuners.tuners_utils.BaseTuner.set_adapter]]

```python
set_adapter(adapter_name: str | list[str], inference_mode: bool = False)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L1427)

**参数：**

adapter_name (str, list[str]) : 要设置为激活状态的适配器名称

inference_mode (bool, optional) : 是否应冻结已激活的适配器（即 `requires_grad=False`）。默认值为 False。

设置活动适配器。

#### set_requires_grad[[peft.tuners.tuners_utils.BaseTuner.set_requires_grad]]

```python
set_requires_grad(adapter_names: str | Sequence[str], requires_grad: bool = True)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L628)

**参数：**

adapter_names (`str` 或 `Sequence[str]`) : 需要启用/禁用梯度的适配器名称。

requires_grad (`bool`, *可选*) : 是否启用 (`True`，默认) 或禁用 (`False`)。

在指定的适配器上启用或禁用梯度。

#### supports_lora_conversion[[peft.tuners.tuners_utils.BaseTuner.supports_lora_conversion]]

```python
supports_lora_conversion(adapter_name: str = 'default')
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L1548)

该模型的适配器是否可以转换为 LoRA。

通常，如果 PEFT 方法是加法的，即 W' = W_base + delta_weight，那么这种方式是可行的。

#### 卸载[[peft.tuners.tuners_utils.BaseTuner.unload]]

```python
unload()
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L822)

通过移除所有 PEFT 模块来返回基础模型。

将返回的模型赋值给一个变量并使用它非常重要，这不是一个原地操作！

#### unmerge_adapter[[peft.tuners.tuners_utils.BaseTuner.unmerge_adapter]]

```python
unmerge_adapter()
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L1418)

此方法会从基础模型中取消合并所有已合并的适配器层。

## BaseTunerLayer[[peft.tuners.tuners_utils.BaseTunerLayer]]

#### peft.tuners.tuners_utils.BaseTunerLayer[[peft.tuners.tuners_utils.BaseTunerLayer]]

```python
peft.tuners.tuners_utils.BaseTunerLayer()
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L1914)

**参数：**

active_adapters (Union[List`str`, `str`], *optional*) : 当前激活的适配器名称。

一个调优器层混入类，为所有调优器提供通用的方法和属性。

#### delete_adapter[[peft.tuners.tuners_utils.BaseTunerLayer.delete_adapter]]

```python
delete_adapter(adapter_name: str)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L2173)

**参数：**

adapter_name (`str`) : 要删除的适配器名称

从层中删除适配器

应在所有适配器层上调用此方法，否则会导致状态不一致。

如果已删除的适配器是活动适配器，此方法还会设置一个新的活动适配器。新适配器的选择方式必须是确定性的，以确保在所有层上选择相同的适配器。

#### enable_adapters[[peft.tuners.tuners_utils.BaseTunerLayer.enable_adapters]]

```python
enable_adapters(enabled: bool)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L2087)

**参数：**

enabled (bool) : 为 True 时启用适配器，为 False 时禁用适配器

切换适配器的启用和禁用

负责为适配器权重设置 requires_grad 标志。

#### get_additive_delta[[peft.tuners.tuners_utils.BaseTunerLayer.get_additive_delta]]

```python
get_additive_delta(adapter_name: str = 'default')
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L2345)

**参数：**

adapter_name (`str`) : 适配器的名称。默认为 `"default"`。

返回给定适配器的加性增量权重 W' - W，其中 W 是基础权重，W' 是将适配器合并到基础权重后的权重。这意味着可以通过 `base_weight + module.get_additive_delta(adapter_name)` 重建合并后的权重。

对于加性 PEFT 方法（例如 LoRA、LoKr、LoHa），这与 `get_delta_weight` 等效。对于乘性方法（例如 OFT、BOFT），该方法会构造有效权重 W' 并减去基础权重 W。

在任意适配器处于合并状态时调用此方法会引发 `ValueError`，因为合并操作会修改基础权重，这将导致返回值依赖于当前已合并的适配器。请先取消合并这些适配器。

返回的张量具有适配器层权重（例如 LoRA 的 `lora_A`）的 dtype，而不是基础层权重的 dtype。这是转换后的 LoRA 适配器将使用的 dtype。

该结果由 `convert_to_lora` 使用，以执行基于 SVD 的适配器近似，将其转换为 LoRA 适配器。

默认情况下，这会引发 `NotImplementedError`。支持此功能的 PEFT 方法应重写 `_get_additive_delta` 方法以返回加性增量。

#### get_base_layer[[peft.tuners.tuners_utils.BaseTunerLayer.get_base_layer]]

```python
get_base_layer()
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L1942)

（递归地）获取 base_layer。

当调优层包裹另一个调优层时，这是必需的。

#### get_base_weight[[peft.tuners.tuners_utils.BaseTunerLayer.get_base_weight]]

```python
get_base_weight()
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L1954)

返回基础层的权重。

如果权重经过量化，此操作会负责对其进行反量化。

#### set_adapter[[peft.tuners.tuners_utils.BaseTunerLayer.set_adapter]]

```python
set_adapter(adapter_names: str | list[str], inference_mode: bool = False)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L2132)

**参数：**

adapter_names (`str` 或 `list[str]`) : 要设置为激活状态的适配器名称。

inference_mode (bool, optional) : 是否应冻结已激活的适配器（即 `requires_grad=False`）。默认值为 False。

设置活动适配器。

此外，除非 inference_mode 为 True，否则该函数会将指定的适配器设置为可训练（即 requires_grad=True）。

#### set_base_weight[[peft.tuners.tuners_utils.BaseTunerLayer.set_base_weight]]

```python
set_base_weight(weight_data: torch.Tensor)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L1963)

将基础层的基权重设置为新的张量

这也适用于量化权重。

#### set_requires_grad[[peft.tuners.tuners_utils.BaseTunerLayer.set_requires_grad]]

```python
set_requires_grad(adapter_names: str | Sequence[str], requires_grad: bool = True)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L2217)

**参数：**

adapter_names (`str` 或 `Sequence[str]`) : 需要启用/禁用梯度的适配器名称。

requires_grad (`bool`, *可选*) : 是否启用 (`True`，默认) 或禁用 (`False`)。

在指定的适配器上启用或禁用梯度。

#### set_training[[peft.tuners.tuners_utils.BaseTunerLayer.set_training]]

```python
set_training(adapter_names: str | Sequence[str], training: bool = True)
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L2068)

**参数：**

adapter_names (`str` 或 `Sequence[str]`) : 需要更新训练模式的适配器名称。

training (`bool`, *可选*) : 是否启用（`True`，默认值）或禁用（`False`）训练模式。

在指定的适配器模块上启用或禁用训练模式。

#### supports_lora_conversion[[peft.tuners.tuners_utils.BaseTunerLayer.supports_lora_conversion]]

```python
supports_lora_conversion(adapter_name: str = 'default')
```

[源代码](https://github.com/huggingface/peft/blob/main/src/peft/tuners/tuners_utils.py#L2337)

该层类型是否可以转换为 LoRA。

通常，如果 PEFT 方法是加法的，即 W' = W_base + delta_weight，那么这种方式是可行的。

