配置
基类 PreTrainedConfig 实现了加载/保存配置的通用方法,配置可以来自本地文件或目录,也可以来自库提供的预训练模型配置(从 HuggingFace 的 AWS S3 仓库下载)。
每个派生配置类都实现了模型特定的属性。所有配置类中通用的属性包括:hidden_size、num_attention_heads 和 num_hidden_layers。文本模型还额外实现了:vocab_size。
PreTrainedConfig
类 transformers.PreTrainedConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None )
参数
- name_or_path (
str,可选,默认为"") — 如果配置是通过此类方法创建的,则将传递给 PreTrainedModel.from_pretrained() 的字符串存储为pretrained_model_name_or_path。 - output_hidden_states (
bool,可选,默认为False) — 是否让模型返回所有隐藏状态。 - output_attentions (
bool,可选,默认为False) — 是否让模型返回所有注意力。 - return_dict (
bool,可选,默认为True) — 模型是否应返回 ModelOutput 而不是普通元组。 - is_encoder_decoder (
bool,可选,默认为False) — 该模型是否用作编码器/解码器。 - chunk_size_feed_forward (
int,可选,默认为0) — 残差注意力块中所有前馈层的块大小。块大小为0表示前馈层不进行分块。块大小为 n 表示前馈层每次处理n< sequence_length 个嵌入。有关前馈分块的更多信息,请参阅 前馈分块是如何工作的?。 - 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 特定参数
所有配置类的基类。处理所有模型配置中常见的若干参数,以及用于加载/下载/保存配置的方法。
配置文件可以加载并保存到磁盘。加载配置文件并使用该文件初始化模型不会加载模型权重。它仅影响模型的配置。
类属性(由派生类覆盖):
- model_type (
str) — 模型类型的标识符,会被序列化到 JSON 文件中,并在 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
< source >( repo_id: strcommit_message: str | None = Nonecommit_description: str | None = Noneprivate: bool | None = Nonetoken: bool | str | None = Nonerevision: str | None = Nonecreate_pr: bool = Falsemax_shard_size: int | str | None = '50GB'tags: list[str] | None = None )
参数
- 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") — 仅适用于模型。分片前检查点的最大大小。分片后的每个检查点大小都将小于该值。如果以字符串形式表示,则必须为数字后跟单位(例如"5MB")。 - tags (
list[str],可选) — 要推送到 Hub 的标签列表。
将配置文件上传到 🤗 Model Hub。
示例:
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")获取 dataclass 中每个带注解字段的默认值,用于保存 diff-dict。
对于在 v4 中通过自定义 __init__ 创建的 config,它将返回一个空字典,从而保存 self.__dict__ 中的所有键。对于较新的 config,它将返回那些声明为字段而非在 __post_init__ 中声明的默认值键,这会将这些特定字段从序列化的 json 文件中过滤掉。
检查传入的字典及其嵌套字典是否包含 dtype 键,如果该键不为 None,则将 torch.dtype 转换为仅包含类型的字符串。例如,torch.float32 会被转换为 “float32” 字符串,从而可以以 json 格式存储。
from_dict
< source >( config_dict: dict[str, Any]**kwargs ) → PreTrainedConfig
参数
- config_dict (
dict[str, Any]) — 用于实例化配置对象的字典。可以通过调用 get_config_dict() 方法从预训练检查点中获取此类字典。 - kwargs (
dict[str, Any]) — 用于初始化配置对象的额外参数。
返回值
由这些参数实例化的配置对象。
从参数 Python 字典实例化一个 PreTrainedConfig。
from_json_file
< source >( json_file: str | os.PathLike ) → PreTrainedConfig
从参数 JSON 文件的路径实例化一个 PreTrainedConfig。
from_pretrained
< source >( pretrained_model_name_or_path: str | os.PathLikecache_dir: str | os.PathLike | None = Noneforce_download: bool = Falselocal_files_only: bool = Falsetoken: str | bool | None = Nonerevision: str = 'main'**kwargs ) → PreTrainedConfig
参数
- pretrained_model_name_or_path (
str或os.PathLike) — 可以是以下之一:- 一个字符串,即托管在 huggingface.co 模型仓库中的预训练模型配置的 model id。
- 指向一个目录的路径,该目录包含使用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, 为 False,则此函数仅返回最终的配置对象。如果为 True,则此函数返回一个 Tuple(config, unused_kwargs),其中 unused_kwargs 是一个字典,包含那些键不是配置属性的键值对:即 kwargs 中未用于更新 config 且被忽略的部分。如果
True,则此函数返回一个Tuple(config, unused_kwargs),其中 unused_kwargs 是一个字典,包含键不是配置属性的键值对:即kwargs中未用于更新config且被忽略的部分。 - subfolder (
str,可选,默认为"") — 如果相关文件位于 huggingface.co 上模型仓库的子文件夹中,您可以在此处指定该文件夹的名称。 - kwargs (
dict[str, Any], 可选) — kwargs 中任何作为配置属性的键的值,将用于覆盖已加载的值。对于键不是配置属性的键值对,其行为由return_unused_kwargs关键字参数控制。
返回值
从此预训练模型实例化的配置对象。
从预训练模型配置实例化一个 PreTrainedConfig(或其派生类)。
示例:
# 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
< source >( pretrained_model_name_or_path: str | os.PathLike**kwargs ) → tuple[Dict, Dict]
从 pretrained_model_name_or_path 解析为参数字典,用于通过 from_dict 实例化 PreTrainedConfig。
返回用于创建 MTP 模型的 mtp 文本配置。由于 MTP 层是通过实例化与主模型相同的类来创建的,因此我们需要覆盖配置中与索引相关的属性,例如 layer_types 或 mtp_layer_types,以创建正确的 mtp 层并避免层中的索引问题(因为 MTP 层会将层的索引从 0 重新开始)。
get_text_config
< source >( decoder = Noneencoder = None )
返回与模型文本输入(编码器)或文本输出(解码器)相关的文本配置。可以使用 decoder 和 encoder 输入参数来指定我们感兴趣的是模型的哪一端,这对于同时具有文本输入和输出模态的模型非常有用。
使用此方法有三种可能的结果:
- 在大多数模型中,它返回的是原始 config 实例本身。
- 在较新的(2024 年及以后)复合模型中,它返回配置中的文本部分,该部分嵌套在一组有效名称之下。
- 在较旧(2023 年及更早)的复合模型中,当
encoder=True时,它会丢弃仅解码器参数,反之亦然。
返回当前配置是否为自定义代码,即从 hub 加载的代码,或在任何用户特定的模块/会话中定义的代码。
返回当前配置是否为自定义代码,即从 hub 加载的代码,或我们刚刚通过 register_for_auto_class 注册的类。
register_for_auto_class
< source >( auto_class = 'AutoConfig' )
将此注册到指定的 auto 类。此操作仅应用于自定义配置,因为库中的配置已经与 AutoConfig 进行了映射。
save_pretrained
< source >( save_directory: str | os.PathLikepush_to_hub: bool = False**kwargs )
参数
- save_directory (
str或os.PathLike) — 用于保存配置 JSON 文件的目录(如果该目录不存在,则会自动创建)。 - push_to_hub (
bool,可选,默认为False) — 是否在保存模型后将其推送到 Hugging Face 模型库。您可以使用repo_id指定要推送到的仓库(默认使用您命名空间中save_directory的名称)。 - kwargs (
dict[str, Any],可选) — 传递给 push_to_hub() 方法的额外关键字参数。
将配置对象保存到目录 save_directory,以便之后可以使用 from_pretrained() 类方法重新加载。
将此实例序列化为 Python 字典。
移除配置中对应于默认配置属性的所有属性,以提高可读性,同时始终保留类中的 config 属性。序列化为 Python 字典。
to_json_file
< source >( json_file_path: str | os.PathLikeuse_diff: bool = True )
将此实例保存到 JSON 文件中。
to_json_string
< source >( use_diff: bool = True ) → str
将此实例序列化为 JSON 字符串。
使用 config_dict 中的属性更新此类的属性。
使用 update_str 中的属性更新此类的属性。
预期格式为整数、浮点数和字符串保持原样,布尔值则使用 true 或 false。例如:
“n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index”
要修改的键必须已经存在于配置对象中。
在实例上运行类验证器。
@strict 驱动验证的一部分。验证配置的架构。
检查 mlp_layer_types 和 layer_types 是否已正确定义。
@strict 驱动验证的一部分。验证特殊标记的内容。