Transformers 文档
配置
并获得增强的文档体验
开始使用
配置
基类 PreTrainedConfig 实现了从本地文件或目录加载/保存配置的通用方法,也可以从库中提供的预训练模型配置(从 HuggingFace 的 AWS S3 仓库下载)中加载/保存。
每个派生配置类都实现了模型特定的属性。所有配置类中都存在的常见属性有:hidden_size、num_attention_heads 和 num_hidden_layers。文本模型进一步实现了:vocab_size。
PreTrainedConfig
class transformers.PreTrainedConfig
< 源 >( output_hidden_states: bool = False output_attentions: bool = False return_dict: bool = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False architectures: list[str] | None = None id2label: dict[int, str] | None = None label2id: dict[str, int] | None = None num_labels: int | None = None problem_type: str | None = None **kwargs )
参数
- 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 嵌入。有关前馈分块的更多信息,请参阅 前馈分块的工作原理?。
微调任务的参数
- 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 中重新创建正确的对象。 - has_no_defaults_at_init (
bool) — 配置类是否可以在不提供输入参数的情况下初始化。某些配置需要在初始化时定义输入并且没有默认值,通常这些是复合配置(但不一定是),例如 EncoderDecoderConfig 或 ~RagConfig。它们必须从两个或更多个 PreTrainedConfig 类型的配置初始化。 - keys_to_ignore_at_inference (
list[str]) — 在推理过程中查看模型字典输出时默认忽略的键列表。 - attribute_map (
dict[str, str]) — 将模型特定属性名称映射到标准化属性名称的字典。 - base_model_tp_plan (
dict[str, Any]) — 将基本模型的子模块 FQN 映射到当调用model.tensor_parallel时应用于该子模块的张量并行计划的字典。 - base_model_pp_plan (
dict[str, tuple[list[str]]]) — 将基本模型的子模块映射到管道并行计划的字典,该计划使用户能够将子模块放置在适当的设备上。
通用属性(所有子类中都存在)
- vocab_size (
int) — 词汇表中的标记数量,也是嵌入矩阵的第一个维度(对于没有文本模态的模型,例如 ViT,此属性可能缺失)。 - hidden_size (
int) — 模型的隐藏大小。 - num_attention_heads (
int) — 模型多头注意力层中使用的注意力头数量。 - num_hidden_layers (
int) — 模型中的块数量。
在模型配置中设置序列生成参数已弃用。为了向后兼容,仍然可以加载其中一些参数,但尝试覆盖它们将抛出异常 — 您应该在 [~transformers.GenerationConfig] 中设置它们。有关各个参数的更多信息,请查看 [~transformers.GenerationConfig] 的文档。
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 )
参数
- 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")检查传入的字典及其嵌套字典是否包含 dtype 键,如果存在且不为 None,则将 torch.dtype 转换为仅包含类型名称的字符串。例如,torch.float32 将转换为字符串 “float32”,然后可以以 json 格式存储。
from_dict
< 源 >( config_dict: dict **kwargs ) → PreTrainedConfig
参数
- config_dict (
dict[str, Any]) — 将用于实例化配置对象的字典。此类字典可以通过利用 get_config_dict() 方法从预训练检查点中检索。 - kwargs (
dict[str, Any]) — 用于初始化配置对象的其他参数。
从这些参数实例化的配置对象。
从 Python 参数字典实例化 PreTrainedConfig。
from_json_file
< 源 >( json_file: str | os.PathLike ) → PreTrainedConfig
从 JSON 参数文件路径实例化 PreTrainedConfig。
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 ) → PreTrainedConfig
参数
- pretrained_model_name_or_path (
str或os.PathLike) — 这可以是:- 一个字符串,即托管在 huggingface.co 模型仓库中的预训练模型配置的 模型 ID。
- 一个 目录 的路径,其中包含使用 save_pretrained() 方法保存的配置文件,例如
./my_model_directory/。 - 一个保存的配置 JSON 文件 的路径或 URL,例如
./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") — 要使用的特定模型版本。它可以是分支名称、标签名称或提交 ID,因为我们使用基于 Git 的系统在 huggingface.co 上存储模型和其他工件,因此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 (或派生类)。
示例
# 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。
get_text_config
< source >( decoder = None encoder = None )
返回与模型文本输入(编码器)或文本输出(解码器)相关的文本配置。decoder 和 encoder 输入参数可用于指定我们感兴趣的模型端点,这对于同时具有文本输入和输出模态的模型很有用。
使用此方法可能会出现三种结果
- 在大多数模型上,它返回原始配置实例本身。
- 在较新的 (2024+) 复合模型上,它返回配置的文本部分,该部分嵌套在一组有效名称下。
- 在较旧的 (2023-) 复合模型上,当
encoder=True时,它会丢弃仅解码器参数,反之亦然。
register_for_auto_class
< source >( auto_class = 'AutoConfig' )
将此类别注册到给定的自动类。这仅应用于自定义配置,因为库中的配置已映射到 AutoConfig。
save_pretrained
< source >( save_directory: str | os.PathLike push_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.PathLike use_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”
要更改的键必须已存在于配置对象中。