# 配置

基类 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 实现了从本地文件或目录加载/保存配置，或从库提供的预训练模型配置（从 HuggingFace 的 AWS S3 仓库下载）的通用方法。

每个派生配置类都实现了模型特定的属性。所有配置类中通用的属性包括：`hidden_size`、`num_attention_heads` 和 `num_hidden_layers`。文本模型还额外实现了：`vocab_size`。

## PreTrainedConfig[[transformers.PreTrainedConfig]]

#### transformers.PreTrainedConfig[[transformers.PreTrainedConfig]]

```python
transformers.PreTrainedConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L299)

**参数：**

name_or_path (`str`，*可选*，默认为 `""`)：如果配置是通过 [PreTrainedModel.from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法创建的，则存储传递给该方法的字符串作为 `pretrained_model_name_or_path`。

output_hidden_states (`bool`，*可选*，默认为 `False`)：模型是否应返回所有隐藏状态。

output_attentions (`bool`，*可选*，默认为 `False`)：模型是否应返回所有注意力。

return_dict (`bool`，*可选*，默认为 `True`)：模型是否应返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而非普通元组。

is_encoder_decoder (`bool`，*可选*，默认为 `False`)：模型是否用作编码器/解码器。

chunk_size_feed_forward (`int`，*可选*，默认为 `0`)：残差注意力块中所有前馈层的块大小。块大小为 `0` 表示前馈层不进行分块。块大小为 n 表示前馈层每次处理 `n` < sequence_length 个嵌入。有关前馈分块的更多信息，请参阅 [前馈分块是如何工作的？](../glossary.html#feed-forward-chunking)。

per_layer_config (`dict[int | str, dict[str, Any]]`, *可选*) : 从层索引到配置属性覆盖的稀疏映射。每个键是一个层索引，每个值包含该层与全局配置不同的属性。

tie_last_hidden_states (`bool`，*可选*)：是否应将 `hidden_states[-1]` 设为经过最终归一化后的 `last_hidden_state`，而不是归一化前的隐藏状态。如果未设置，则使用模型的内置默认值。

**用于微调任务的参数：**

architectures (`list[str]`, *可选*) : 可与模型预训练权重一起使用的模型架构。

id2label (`dict[int, str]`，*可选*)：从索引（例如预测索引或目标索引）到标签的映射。

label2id (`dict[str, int]`，*可选*)：模型中标签到索引的映射。

num_labels (`int`, *可选*) : 添加到模型最后一层中使用的标签数量，通常用于分类任务。

problem_type (`str`, *可选*) : `XxxForSequenceClassification` 模型的问题类型。可以是 `"regression"`、`"single_label_classification"` 或 `"multi_label_classification"` 之一。

**PyTorch 特定参数：**

dtype (`str`, *可选*) : 权重的 `dtype`。此属性可用于将模型初始化为非默认的 `dtype`（通常为 `float32`），从而实现最优的存储分配。例如，如果保存的模型是 `float16`，理想情况下我们希望使用加载 `float16` 权重所需的最小内存将其加载回来。

所有配置类的基类。处理所有模型配置中常见的若干参数，并提供用于加载、下载和保存配置的方法。

配置文件可以加载并保存到磁盘。加载配置文件并使用该文件初始化模型**不会**加载模型权重。它仅影响模型的配置。

类属性（由派生类覆盖）：

- **model_type** (`str`) -- 模型类型的标识符，会被序列化到 JSON 文件中，并在 [AutoConfig](/docs/transformers/main/zh/model_doc/auto#transformers.AutoConfig) 中用于重建正确的对象。
- **attribute_map** (`dict[str, str]`) -- 一个字典，将模型特定的属性名称映射到属性的标准化命名。
- **base_model_tp_plan** (`dict[str, Any]`) -- 一个字典，将基础模型的子模块 FQN 映射到在调用 `model.tensor_parallel` 时应用于该子模块的张量并行计划。
- **base_model_fsdp_plan** (`dict[Any, str]`) -- 一个字典，将基础模型的子模块映射到 FSDP2 分片策略（例如 `"free_full_weight"` / `"keep_full_weight"`）。键可以是通配符模块路径（例如 `"layers.*"`）或路径元组（组合到单个 `fully_shard` 调用中）。
- **base_model_pp_plan** (`dict[str, tuple[list[str]]]`) -- 一个字典，将基础模型的子模块映射到流水线并行计划，以便用户将子模块放置在合适的设备上。

通用属性（存在于所有子类中）：

- **vocab_size** (`int`) -- 词汇表中的 token 数量，同时也是嵌入矩阵的第一维（对于没有文本模态的模型，如 ViT，此属性可能缺失）。
- **hidden_size** (`int`) -- 模型的隐藏层大小。
- **num_attention_heads** (`int`) -- 模型中多头注意力层所使用的注意力头数量。
- **num_hidden_layers** (`int`) -- 模型中的块数。

在模型配置中设置序列生成参数已被弃用。为了向后兼容，加载其中部分参数仍然可行，但尝试覆盖它们将抛出异常——您应在 [~transformers.GenerationConfig] 中设置这些参数。有关各个参数的更多信息，请参阅 [~transformers.GenerationConfig] 的文档。

#### push_to_hub[[transformers.PreTrainedConfig.push_to_hub]]

```python
push_to_hub(repo_id: str, commit_message: str | None = None, commit_description: str | None = None, private: bool | None = None, token: bool | str | None = None, revision: str | None = None, create_pr: bool = False, max_shard_size: int | str | None = '50GB', tags: list[str] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/utils/hub.py#L822)

**参数：**

repo_id (`str`) : 要推送配置的目标仓库名称。推送到特定组织时，应包含该组织的名称。

commit_message (`str`，*可选*)：推送时提交的说明信息。默认值为 `"Upload config"`。

commit_description (`str`, *可选*) : 将创建的提交的描述

private (`bool`，*可选*)：是否将仓库设为私有。如果为 `None`（默认值），除非组织的默认设置为私有，否则仓库将是公开的。如果仓库已存在，则忽略此值。

token (`bool` 或 `str`，*可选*) : 用于远程文件的 HTTP bearer 授权令牌。如果为 `True`（默认值），将使用运行 `hf auth login` 时生成的令牌（存储在 `~/.huggingface` 中）。

revision (`str`, *可选*) : 推送上传文件的目标分支。

create_pr (`bool`，*可选*，默认为 `False`)：是否使用上传的文件创建 PR，还是直接提交。

max_shard_size (`int` 或 `str`，*可选*，默认为 `"50GB"`)：仅适用于模型。在分片之前，检查点（checkpoint）的最大大小。分片后的每个检查点大小都将小于此值。如果以字符串形式表示，则必须为数字后跟单位（例如 `"5MB"`）。

tags (`list[str]`，*可选*)：要推送到 Hub 的标签列表。

将配置文件上传到 🤗 Model Hub。

示例：

```python
from transformers import AutoConfig

config = AutoConfig.from_pretrained("google-bert/bert-base-cased")

# Push the config to your namespace with the name "my-finetuned-bert".
config.push_to_hub("my-finetuned-bert")

# Push the config to an organization with the name "my-finetuned-bert".
config.push_to_hub("huggingface/my-finetuned-bert")
```

#### default_config_fields[[transformers.PreTrainedConfig.default_config_fields]]

```python
default_config_fields()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1474)

获取 dataclass 中每个带注解字段的默认值，用于保存 diff-dict。对于在 v4 中通过自定义 `__init__` 创建的 config，它将返回一个空字典，从而保存 `self.__dict__` 中的所有键。对于较新的 config，它将返回声明为字段（而非在 `__post_init__` 中）的具有默认值的键，从而仅将这些特定字段从序列化的 json 文件中过滤掉。

#### dict_dtype_to_str[[transformers.PreTrainedConfig.dict_dtype_to_str]]

```python
dict_dtype_to_str(d: dict[str, Any])
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1395)

检查传入的字典及其嵌套字典是否包含 *dtype* 键，如果该键不为 None，则将 torch.dtype 转换为仅包含类型的字符串。例如，`torch.float32` 会被转换为 *"float32"* 字符串，从而可以以 json 格式存储。

#### from_dict[[transformers.PreTrainedConfig.from_dict]]

```python
from_dict(config_dict: dict[str, Any], **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1054)

**参数：**

config_dict (`dict[str, Any]`) : 用于实例化配置对象的字典。可以通过调用 [get_config_dict()](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig.get_config_dict) 方法从预训练检查点中获取这样的字典。

kwargs (`dict[str, Any]`) : 用于初始化配置对象的额外参数。

**返回：** [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)

由这些参数实例化的配置对象。

从参数 Python 字典实例化一个 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)。

#### from_json_file[[transformers.PreTrainedConfig.from_json_file]]

```python
from_json_file(json_file: str | os.PathLike)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1115)

**参数：**

json_file (`str` 或 `os.PathLike`)：包含参数的 JSON 文件的路径。

**返回：** [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)

从该 JSON 文件实例化的配置对象。

从参数 JSON 文件的路径实例化一个 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)。

#### from_pretrained[[transformers.PreTrainedConfig.from_pretrained]]

```python
from_pretrained(pretrained_model_name_or_path: str | os.PathLike, cache_dir: str | os.PathLike | None = None, force_download: bool = False, local_files_only: bool = False, token: str | bool | None = None, revision: str = 'main', **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L797)

**参数：**

pretrained_model_name_or_path (`str` 或 `os.PathLike`) : 可以是以下之一： - 一个字符串，即托管在 huggingface.co 模型仓库中的预训练模型配置的 *model id*。 - 指向一个*目录*的路径，该目录包含使用 [save_pretrained()](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig.save_pretrained) 方法保存的配置文件，例如 `./my_model_directory/`。 - 指向已保存的配置 JSON *文件*的路径，例如 `./my_model_directory/configuration.json`。

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

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

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

token (`str` 或 `bool`，*可选*) : 用于远程文件的 HTTP bearer 授权令牌。如果为 `True` 或未指定，将使用运行 `hf auth login` 时生成的令牌（存储在 `~/.huggingface` 中）。

revision (`str`, *可选*，默认为 `"main"`) : 要使用的特定模型版本。由于我们在 huggingface.co 上使用基于 git 的系统来存储模型和其他工件，因此它可以是分支名称、标签名称或提交 id，`revision` 可以是 git 允许的任何标识符。    若要测试您在 Hub 上创建的拉取请求，可以传入 `revision="refs/pr/<pr_number>"`。

return_unused_kwargs (`bool`，*可选*，默认为 `False`)：如果为 `False`，则此函数仅返回最终的配置对象。如果为 `True`，则此函数返回一个 `Tuple(config, unused_kwargs)`，其中 *unused_kwargs* 是一个字典，包含那些键不是配置属性的键值对：即 `kwargs` 中未用于更新 `config` 且被忽略的部分。

subfolder (`str`，*可选*，默认为 `""`)：如果相关文件位于 huggingface.co 上模型仓库的子文件夹中，可在此处指定该文件夹的名称。

kwargs (`dict[str, Any]`，*可选*)：kwargs 中任何作为配置属性的键对应的值，将用于覆盖已加载的值。对于键*不是*配置属性的键值对，其行为由 `return_unused_kwargs` 关键字参数控制。

**返回：** [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)

从此预训练模型实例化的配置对象。

从预训练模型配置实例化一个 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)（或其派生类）。

示例：

```python
# We can't instantiate directly the base class *PreTrainedConfig* so let's show the examples on a
# derived class: BertConfig
config = BertConfig.from_pretrained(
    "google-bert/bert-base-uncased"
)  # Download configuration from huggingface.co and cache.
config = BertConfig.from_pretrained(
    "./test/saved_model/"
)  # E.g. config (or model) was saved using *save_pretrained('./test/saved_model/')*
config = BertConfig.from_pretrained("./test/saved_model/my_configuration.json")
config = BertConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False)
assert config.output_attentions == True
config, unused_kwargs = BertConfig.from_pretrained(
    "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
)
assert config.output_attentions == True
assert unused_kwargs == {"foo": False}
```

#### get_config_dict[[transformers.PreTrainedConfig.get_config_dict]]

```python
get_config_dict(pretrained_model_name_or_path: str | os.PathLike, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L909)

**参数：**

pretrained_model_name_or_path (`str` 或 `os.PathLike`)：我们想要从中获取参数字典的预训练检查点的标识符。

**返回：** `tuple[Dict, Dict]`

用于实例化配置对象的字典。

从 `pretrained_model_name_or_path` 解析为参数字典，用于通过 `from_dict` 实例化 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)。

#### get_mtp_config[[transformers.PreTrainedConfig.get_mtp_config]]

```python
get_mtp_config()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1596)

返回用于创建 MTP 模型的 mtp 文本配置。由于 MTP 层通过实例化与主模型相同的类来创建，我们需要覆盖配置中与索引相关的属性，例如 `layer_types` 或 `mtp_layer_types`，以创建正确的 mtp 层并避免层中的索引问题（因为 MTP 层会将层的索引从 0 重新开始）。

#### get_text_config[[transformers.PreTrainedConfig.get_text_config]]

```python
get_text_config(decoder = None, encoder = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1519)

**参数：**

decoder (`Optional[bool]`, *可选*) : 如果设置为 `True`，则仅搜索解码器配置名称。

encoder (`Optional[bool]`, *可选*) : 如果设置为 `True`，则仅搜索编码器配置名称。

返回与模型文本输入（编码器）或文本输出（解码器）相关的文本配置。可以使用 `decoder` 和 `encoder` 输入参数来指定我们关注的是模型的哪一端，这对于同时具有文本输入和输出模态的模型非常有用。

使用此方法有三种可能的结果：
1. 在大多数模型中，它返回的是原始 config 实例本身。
2. 在较新的（2024 年及以后）复合模型中，它返回配置中的文本部分，该部分嵌套在一组有效名称之下。
3. 在较旧（2023 年及更早）的复合模型中，当 `encoder=True` 时，它会丢弃仅解码器参数，反之亦然。

#### is_custom_code[[transformers.PreTrainedConfig.is_custom_code]]

```python
is_custom_code()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1468)

返回当前配置是否为自定义代码，即从 hub 加载的代码，或在任何用户特定的模块/会话中定义的代码。

#### is_remote_code[[transformers.PreTrainedConfig.is_remote_code]]

```python
is_remote_code()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1462)

返回当前配置是否为自定义代码，即从 hub 加载的代码，或我们刚刚通过 `register_for_auto_class` 注册的类。

#### register_for_auto_class[[transformers.PreTrainedConfig.register_for_auto_class]]

```python
register_for_auto_class(auto_class = 'AutoConfig')
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1440)

**参数：**

auto_class (`str` 或 `type`，*可选*，默认为 `"AutoConfig"`)：用于将此新配置注册到的自动类。

将此注册到指定的 auto 类。此操作仅应用于自定义配置，因为库中的配置已经与 `AutoConfig` 进行了映射。

#### save_pretrained[[transformers.PreTrainedConfig.save_pretrained]]

```python
save_pretrained(save_directory: str | os.PathLike, push_to_hub: bool = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L735)

**参数：**

save_directory (`str` 或 `os.PathLike`) : 用于保存配置 JSON 文件的目录（如果该目录不存在，则会自动创建）。

push_to_hub (`bool`，*可选*，默认为 `False`)：是否在保存模型后将其推送到 Hugging Face 模型库。您可以通过 `repo_id` 指定要推送到的仓库（默认使用您命名空间中 `save_directory` 的名称）。

kwargs (`dict[str, Any]`，*可选*)：传递给 [push_to_hub()](/docs/transformers/main/zh/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) 方法的额外关键字参数。

将配置对象保存到目录 `save_directory`，以便之后可以使用 [from_pretrained()](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig.from_pretrained) 类方法重新加载。

#### to_dict[[transformers.PreTrainedConfig.to_dict]]

```python
to_dict()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1261)

**返回：** `dict[str, Any]`

构成此配置实例的所有属性的字典。

将此实例序列化为 Python 字典。

#### to_diff_dict[[transformers.PreTrainedConfig.to_diff_dict]]

```python
to_diff_dict()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1199)

**返回：** dict[str, Any]

构成此配置实例的所有属性的字典。

移除配置中对应于默认配置属性的所有属性，以提高可读性，同时始终保留类中的 `config` 属性。序列化为 Python 字典。

#### to_json_file[[transformers.PreTrainedConfig.to_json_file]]

```python
to_json_file(json_file_path: str | os.PathLike, use_diff: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1333)

**参数：**

json_file_path (`str` 或 `os.PathLike`)：用于保存此配置实例参数的 JSON 文件的路径。

use_diff (`bool`，*可选*，默认为 `True`)：如果设置为 `True`，则仅将配置实例与默认 `PreTrainedConfig()` 之间的差异序列化到 JSON 文件中。

将此实例保存到 JSON 文件中。

#### to_json_string[[transformers.PreTrainedConfig.to_json_string]]

```python
to_json_string(use_diff: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1311)

**参数：**

use_diff (`bool`，*可选*，默认为 `True`)：如果设置为 `True`，则仅将配置实例与默认 `PreTrainedConfig()` 之间的差异序列化为 JSON 字符串。

**返回：** `str`

包含构成此配置实例的所有属性的字符串，以 JSON 格式表示。

将此实例序列化为 JSON 字符串。

#### 更新[[transformers.PreTrainedConfig.update]]

```python
update(config_dict: dict[str, Any])
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1347)

**参数：**

config_dict (`dict[str, Any]`) : 应为此类更新的属性字典。

使用 `config_dict` 中的属性更新此类的属性。

#### update_from_string[[transformers.PreTrainedConfig.update_from_string]]

```python
update_from_string(update_str: str)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L1357)

**参数：**

update_str (`str`) : 包含应为此类更新的属性的字符串。

使用 `update_str` 中的属性更新此类的属性。

预期格式为整数、浮点数和字符串保持原样，布尔值则使用 `true` 或 `false`。例如："n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"

要修改的键必须已经存在于配置对象中。

#### 验证[[transformers.PreTrainedConfig.validate]]

```python
validate()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/huggingface_hub/dataclasses.py#L247)

在实例上运行类验证器。

#### validate_architecture[[transformers.PreTrainedConfig.validate_architecture]]

```python
validate_architecture()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L670)

`@strict` 驱动验证的一部分。验证配置的架构。

#### validate_layer_type[[transformers.PreTrainedConfig.validate_layer_type]]

```python
validate_layer_type()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L703)

检查 `mlp_layer_types` 和 `layer_types` 是否已正确定义。

#### validate_token_ids[[transformers.PreTrainedConfig.validate_token_ids]]

```python
validate_token_ids()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/configuration_utils.py#L687)

`@strict` 驱动验证的一部分。验证特殊标记的内容。

