Transformers 文档

配置

配置

基类 PretrainedConfig 实现了从本地文件或目录加载/保存配置的通用方法,或者从库提供的预训练模型配置(从 HuggingFace 的 AWS S3 仓库下载)加载/保存配置。

每个派生配置类都实现了模型特定的属性。所有配置类中常见的属性包括: hidden_sizenum_attention_headsnum_hidden_layers。文本模型进一步实现了: vocab_size

PretrainedConfig

transformers.PretrainedConfig

< >

( **kwargs )

参数

  • name_or_path (str, 可选, 默认为 "") — 存储传递给 PreTrainedModel.from_pretrained()TFPreTrainedModel.from_pretrained() 的字符串作为 pretrained_model_name_or_path,如果配置是通过此类方法创建的。
  • output_hidden_states (bool, 可选, 默认为 False) — 模型是否应返回所有隐藏状态。
  • output_attentions (bool, optional, defaults to False) — 模型是否应返回所有注意力。
  • return_dict (bool, 可选, 默认为 True) — 模型是否应返回一个ModelOutput而不是一个普通的元组。
  • is_encoder_decoder (bool, optional, defaults to False) — 模型是否用作编码器/解码器。
  • is_decoder (bool, 可选, 默认为 False) — 模型是否用作解码器(如果不是,则用作编码器)。
  • cross_attention_hidden_size** (bool, 可选) — 如果模型在编码器-解码器设置中用作解码器,并且交叉注意力隐藏维度与 self.config.hidden_size 不同,则交叉注意力层的隐藏大小。
  • add_cross_attention (bool, 可选, 默认为 False) — 是否应该向模型添加交叉注意力层。注意,此选项仅适用于可以在 EncoderDecoderModel 类中用作解码器模型的模型,该类包括 AUTO_MODELS_FOR_CAUSAL_LM 中的所有模型。
  • tie_encoder_decoder (bool, 可选, 默认为 False) — 是否所有编码器的权重应该与其对应的解码器权重绑定。这要求编码器和解码器模型具有完全相同的参数名称。
  • prune_heads (Dict[int, List[int]], optional, defaults to {}) — Pruned heads of the model. The keys are the selected layer indices and the associated values, the list of heads to prune in said layer.

    例如 {1: [0, 2], 2: [2, 3]} 将在第1层剪枝头0和2,并在第2层剪枝头2和3。

  • chunk_size_feed_forward (int, 可选, 默认为 0) — 残差注意力块中所有前馈层的块大小。块大小为 0 表示前馈层未被分块。块大小为 n 表示前馈层一次处理 n < sequence_length 嵌入。有关前馈分块的更多信息,请参阅 前馈分块如何工作?.

微调任务的参数

  • 架构 (List[str], 可选) — 可以与模型预训练权重一起使用的模型架构。
  • finetuning_task (str, optional) — 用于微调模型的任务名称。这可以在从原始(TensorFlow 或 PyTorch)检查点转换时使用。
  • id2label (Dict[int, str], optional) — 从索引(例如预测索引或目标索引)到标签的映射。
  • label2id (Dict[str, int], optional) — 从标签到模型索引的映射。
  • num_labels (int, optional) — 添加到模型的最后一层中使用的标签数量,通常用于分类任务。
  • task_specific_params (Dict[str, Any], optional) — 为当前任务存储的额外关键字参数。
  • problem_type (str, 可选) — XxxForSequenceClassification 模型的问题类型。可以是 "regression""single_label_classification""multi_label_classification" 之一。

与分词器相关的参数

  • tokenizer_class (str, optional) — 要使用的关联分词器类的名称(如果未设置,将默认使用与模型关联的分词器)。
  • prefix (str, optional) — 在调用模型之前,应在每个文本开头添加的特定提示。
  • bos_token_id (int, optional) — 流的开始标记的id.
  • pad_token_id (int, optional) — 填充标记的id.
  • eos_token_id (int, optional) — end-of-stream 令牌的 id.
  • decoder_start_token_id (int, optional) — 如果编码器-解码器模型使用不同于bos的标记开始解码,则该标记的id。
  • sep_token_id (int, optional) — 分隔符的id。

PyTorch 特定参数

  • torchscript (bool, 可选, 默认为 False) — 模型是否应与 Torchscript 一起使用。
  • tie_word_embeddings (bool, optional, defaults to True) — 模型是否应该绑定输入和输出的词嵌入。请注意,这仅在模型具有输出词嵌入层时相关。
  • torch_dtype (str, optional) — The dtype of the weights. This attribute can be used to initialize the model to a non-default dtype (which is normally float32) and thus allow for optimal storage allocation. For example, if the saved model is float16, ideally we want to load it back using the minimal amount of memory needed to load float16 weights. Since the config object is stored in plain text, this attribute contains just the floating type string without the torch. prefix. For example, for torch.float16 `torch_dtype is the "float16" string.

    此属性目前在模型加载时未使用,但这在未来的版本中可能会改变。但我们可以通过使用save_pretrained保存dtype来为未来做准备。

TensorFlow 特定参数

  • use_bfloat16 (bool, 可选, 默认为 False) — 模型是否应使用 BFloat16 标量(仅由某些 TensorFlow 模型使用)。
  • tf_legacy_loss (bool, 可选, 默认为 False) — 模型是否应使用旧版 TensorFlow 损失函数。旧版损失函数的输出形状可变,可能不兼容 XLA。此选项用于向后兼容,并将在 Transformers v5 中移除。
  • loss_type (str, 可选) — 模型应使用的损失类型。它应该在 LOSS_MAPPING 的键中,否则损失将 根据模型架构自动推断。

所有配置类的基类。处理所有模型配置共有的几个参数以及加载/下载/保存配置的方法。

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

类属性(由派生类覆盖):

  • model_type (str) — 模型类型的标识符,序列化到JSON文件中,并用于在AutoConfig中重新创建正确的对象。
  • is_composition (bool) — 配置类是否由多个子配置组成。在这种情况下,配置必须从两个或多个类型为PretrainedConfig的配置初始化,例如: EncoderDecoderConfig~RagConfig
  • keys_to_ignore_at_inference (List[str]) — 在推理过程中查看模型的字典输出时,默认忽略的键列表。
  • attribute_map (Dict[str, str]) — 一个将模型特定属性名称映射到标准化属性命名的字典。
  • base_model_tp_plan (Dict[str, Any]) — 一个字典,将基础模型的子模块的完全限定名称(FQNs)映射到当调用model.tensor_parallel时应用于该子模块的张量并行计划。

通用属性(存在于所有子类中):

  • 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 use_temp_dir: typing.Optional[bool] = None commit_message: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None max_shard_size: typing.Union[int, str, NoneType] = '5GB' create_pr: bool = False safe_serialization: bool = True revision: str = None commit_description: str = None tags: typing.Optional[typing.List[str]] = None **deprecated_kwargs )

参数

  • repo_id (str) — 您想要推送配置的仓库名称。当推送到特定组织时,它应包含您的组织名称。
  • use_temp_dir (bool, optional) — 是否使用临时目录来存储推送到 Hub 之前保存的文件。 如果没有名为 repo_id 的目录,则默认为 True,否则为 False
  • commit_message (str, optional) — 推送时提交的消息。默认为 "Upload config".
  • private (bool, 可选) — 是否将仓库设为私有。如果为None(默认值),仓库将为公开,除非组织的默认设置为私有。如果仓库已存在,则忽略此值。
  • token (boolstr, 可选) — 用于远程文件的HTTP承载授权的令牌。如果为 True,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。如果未指定 repo_url,则默认为 True
  • max_shard_size (intstr, 可选, 默认为 "5GB") — 仅适用于模型。分片前检查点的最大大小。分片后的检查点大小将小于此大小。如果以字符串形式表示,需要是数字后跟单位(如 "5MB")。我们默认将其设置为 "5GB",以便用户可以在免费层级的Google Colab实例上轻松加载模型,而不会出现CPU内存不足的问题。
  • create_pr (bool, 可选, 默认为 False) — 是否创建一个带有上传文件的PR或直接提交。
  • safe_serialization (bool, optional, defaults to True) — 是否将模型权重转换为safetensors格式以实现更安全的序列化。
  • revision (str, optional) — 将上传的文件推送到的分支。
  • commit_description (str, optional) — 将要创建的提交的描述
  • 标签 (List[str], 可选) — 推送到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")

dict_torch_dtype_to_str

< >

( d: typing.Dict[str, typing.Any] )

检查传递的字典及其嵌套字典是否具有torch_dtype键,并且如果它不为None, 则将torch.dtype转换为仅包含类型的字符串。例如,torch.float32被转换为“float32” 字符串,然后可以将其存储在json格式中。

from_dict

< >

( config_dict: typing.Dict[str, typing.Any] **kwargs ) PretrainedConfig

参数

  • config_dict (Dict[str, Any]) — 用于实例化配置对象的字典。可以通过利用get_config_dict()方法从预训练检查点中检索到这样的字典。
  • kwargs (Dict[str, Any]) — 用于初始化配置对象的附加参数。

返回

PretrainedConfig

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

从Python参数字典实例化一个PretrainedConfig

from_json_file

< >

( json_file: typing.Union[str, os.PathLike] ) PretrainedConfig

参数

  • json_file (str or os.PathLike) — 包含参数的JSON文件的路径。

返回

PretrainedConfig

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

从参数JSON文件的路径实例化一个PretrainedConfig

from_pretrained

< >

( pretrained_model_name_or_path: typing.Union[str, os.PathLike] cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[bool, str, NoneType] = None revision: str = 'main' **kwargs ) PretrainedConfig

参数

  • pretrained_model_name_or_path (stros.PathLike) — 这可以是以下之一:
    • 一个字符串,表示托管在 huggingface.co 上的模型仓库中的预训练模型配置的 模型 id
    • 一个包含使用 save_pretrained() 方法保存的配置文件的 目录 的路径,例如 ./my_model_directory/
    • 一个保存的配置 JSON 文件 的路径或 URL,例如 ./my_model_directory/configuration.json
  • cache_dir (stros.PathLike, 可选) — 如果不应使用标准缓存,则应缓存下载的预训练模型配置的目录路径。
  • force_download (bool, 可选, 默认为 False) — 是否强制(重新)下载配置文件并覆盖缓存版本(如果存在)。
  • resume_download — 已弃用并被忽略。现在默认情况下,所有下载在可能的情况下都会自动恢复。 将在Transformers的v5版本中移除。
  • proxies (Dict[str, str], 可选) — 一个按协议或端点使用的代理服务器字典,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. 这些代理在每个请求中使用。
  • token (strbool, 可选) — 用于远程文件的HTTP承载授权的令牌。如果为True,或未指定,将使用运行huggingface-cli login时生成的令牌(存储在~/.huggingface中)。
  • revision (str, optional, defaults to "main") — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so revision can be any identifier allowed by git.

    要测试你在Hub上提交的拉取请求,你可以传递revision="refs/pr/"

  • return_unused_kwargs (bool, optional, defaults to False) — If False, then this function returns just the final configuration object.

    如果True,则此函数返回一个Tuple(config, unused_kwargs),其中unused_kwargs是一个由键/值对组成的字典,这些键不是配置属性:即,kwargs中未用于更新config的部分,并且被忽略。

  • 子文件夹 (str, 可选, 默认为 "") — 如果相关文件位于 huggingface.co 上的模型仓库的子文件夹中,您可以在此处指定文件夹名称。
  • kwargs (Dict[str, Any], 可选) — kwargs 中任何键的值如果是配置属性,将用于覆盖已加载的值。关于键/值对中键不是配置属性的行为由 return_unused_kwargs 关键字参数控制。

返回

PretrainedConfig

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

从预训练模型配置中实例化一个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

< >

( pretrained_model_name_or_path: typing.Union[str, os.PathLike] **kwargs ) Tuple[Dict, Dict]

参数

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

返回

Tuple[Dict, Dict]

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

从一个pretrained_model_name_or_path,解析出一个参数字典,用于通过from_dict实例化一个PretrainedConfig

get_text_config

< >

( decoder = False )

返回用于文本IO的配置。在大多数模型上,它是原始的配置实例本身。在特定的复合模型上,它位于一组有效名称下。

如果 decoder 设置为 True,则仅搜索解码器配置名称。

register_for_auto_class

< >

( auto_class = 'AutoConfig' )

参数

  • auto_class (strtype, 可选, 默认为 "AutoConfig") — 用于注册此新配置的自动类。

使用给定的自动类注册此类。这仅应用于自定义配置,因为库中的配置已经通过AutoConfig进行了映射。

此API是实验性的,在接下来的版本中可能会有一些轻微的破坏性更改。

save_pretrained

< >

( save_directory: typing.Union[str, os.PathLike] push_to_hub: bool = False **kwargs )

参数

  • save_directory (str or 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() 类方法重新加载。

to_dict

< >

( ) Dict[str, Any]

返回

Dict[str, Any]

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

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

to_diff_dict

< >

( ) Dict[str, Any]

返回

Dict[str, Any]

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

从配置中移除所有与默认配置属性对应的属性,以提高可读性,并将其序列化为Python字典。

to_json_file

< >

( json_file_path: typing.Union[str, os.PathLike] use_diff: bool = True )

参数

  • json_file_path (stros.PathLike) — 此配置实例的参数将保存到的 JSON 文件的路径。
  • use_diff (bool, 可选, 默认为 True) — 如果设置为 True,只有配置实例与默认 PretrainedConfig() 之间的差异会被序列化到 JSON 文件中。

将此实例保存到JSON文件。

to_json_string

< >

( use_diff: bool = True ) str

参数

  • use_diff (bool, 可选, 默认为 True) — 如果设置为 True,只有配置实例与默认的 PretrainedConfig() 之间的差异会被序列化为 JSON 字符串。

返回

str

包含构成此配置实例的所有属性的字符串,格式为JSON。

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

更新

< >

( config_dict: typing.Dict[str, typing.Any] )

参数

  • config_dict (Dict[str, Any]) — 应该为此类更新的属性字典。

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

update_from_string

< >

( update_str: str )

参数

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

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

预期的格式是整数、浮点数和字符串保持不变,对于布尔值使用truefalse。例如: “n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index”

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

< > Update on GitHub