配置
基类 PretrainedConfig 实现了从本地文件或目录加载/保存配置的通用方法,或者从库提供的预训练模型配置(从 HuggingFace 的 AWS S3 仓库下载)加载/保存配置。
每个派生配置类都实现了模型特定的属性。所有配置类中常见的属性包括:
hidden_size
、num_attention_heads
和 num_hidden_layers
。文本模型进一步实现了:
vocab_size
。
PretrainedConfig
类 transformers.PretrainedConfig
< source >( **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 toFalse
) — 模型是否应返回所有注意力。 - return_dict (
bool
, 可选, 默认为True
) — 模型是否应返回一个ModelOutput而不是一个普通的元组。 - is_encoder_decoder (
bool
, optional, defaults toFalse
) — 模型是否用作编码器/解码器。 - 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 toTrue
) — 模型是否应该绑定输入和输出的词嵌入。请注意,这仅在模型具有输出词嵌入层时相关。 - torch_dtype (
str
, optional) — Thedtype
of the weights. This attribute can be used to initialize the model to a non-defaultdtype
(which is normallyfloat32
) and thus allow for optimal storage allocation. For example, if the saved model isfloat16
, ideally we want to load it back using the minimal amount of memory needed to loadfloat16
weights. Since the config object is stored in plain text, this attribute contains just the floating type string without thetorch.
prefix. For example, fortorch.float16
`torch_dtype
is the"float16"
string.此属性目前在模型加载时未使用,但这在未来的版本中可能会改变。但我们可以通过使用save_pretrained保存dtype来为未来做准备。
TensorFlow 特定参数
所有配置类的基类。处理所有模型配置共有的几个参数以及加载/下载/保存配置的方法。
可以加载并保存配置文件到磁盘。加载配置文件并使用此文件初始化模型不会加载模型权重。它只影响模型的配置。
类属性(由派生类覆盖):
- 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
< source >( 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 (
bool
或str
, 可选) — 用于远程文件的HTTP承载授权的令牌。如果为True
,将使用运行huggingface-cli login
时生成的令牌(存储在~/.huggingface
中)。如果未指定repo_url
,则默认为True
。 - max_shard_size (
int
或str
, 可选, 默认为"5GB"
) — 仅适用于模型。分片前检查点的最大大小。分片后的检查点大小将小于此大小。如果以字符串形式表示,需要是数字后跟单位(如"5MB"
)。我们默认将其设置为"5GB"
,以便用户可以在免费层级的Google Colab实例上轻松加载模型,而不会出现CPU内存不足的问题。 - create_pr (
bool
, 可选, 默认为False
) — 是否创建一个带有上传文件的PR或直接提交。 - safe_serialization (
bool
, optional, defaults toTrue
) — 是否将模型权重转换为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")
检查传递的字典及其嵌套字典是否具有torch_dtype键,并且如果它不为None,
则将torch.dtype转换为仅包含类型的字符串。例如,torch.float32
被转换为“float32”
字符串,然后可以将其存储在json格式中。
from_dict
< source >( config_dict: typing.Dict[str, typing.Any] **kwargs ) → PretrainedConfig
参数
- config_dict (
Dict[str, Any]
) — 用于实例化配置对象的字典。可以通过利用get_config_dict()方法从预训练检查点中检索到这样的字典。 - kwargs (
Dict[str, Any]
) — 用于初始化配置对象的附加参数。
从这些参数实例化的配置对象。
从Python参数字典实例化一个PretrainedConfig。
from_json_file
< source >( json_file: typing.Union[str, os.PathLike] ) → PretrainedConfig
从参数JSON文件的路径实例化一个PretrainedConfig。
from_pretrained
< source >( 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 (
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
) — 是否强制(重新)下载配置文件并覆盖缓存版本(如果存在)。 - resume_download — 已弃用并被忽略。现在默认情况下,所有下载在可能的情况下都会自动恢复。 将在Transformers的v5版本中移除。
- proxies (
Dict[str, str]
, 可选) — 一个按协议或端点使用的代理服务器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.
这些代理在每个请求中使用。 - token (
str
或bool
, 可选) — 用于远程文件的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, sorevision
can be any identifier allowed by git.要测试你在Hub上提交的拉取请求,你可以传递
revision="refs/pr/
。" - return_unused_kwargs (
bool
, optional, defaults toFalse
) — IfFalse
, 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(或派生类)。
示例:
# 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: typing.Union[str, os.PathLike] **kwargs ) → Tuple[Dict, Dict]
从一个pretrained_model_name_or_path
,解析出一个参数字典,用于通过from_dict
实例化一个PretrainedConfig。
返回用于文本IO的配置。在大多数模型上,它是原始的配置实例本身。在特定的复合模型上,它位于一组有效名称下。
如果 decoder
设置为 True
,则仅搜索解码器配置名称。
register_for_auto_class
< source >( auto_class = 'AutoConfig' )
使用给定的自动类注册此类。这仅应用于自定义配置,因为库中的配置已经通过AutoConfig
进行了映射。
此API是实验性的,在接下来的版本中可能会有一些轻微的破坏性更改。
save_pretrained
< source >( save_directory: typing.Union[str, os.PathLike] push_to_hub: bool = False **kwargs )
参数
- save_directory (
str
oros.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字典。
从配置中移除所有与默认配置属性对应的属性,以提高可读性,并将其序列化为Python字典。
to_json_file
< source >( json_file_path: typing.Union[str, os.PathLike] use_diff: bool = True )
将此实例保存到JSON文件。
to_json_string
< source >( use_diff: bool = True ) → str
将此实例序列化为JSON字符串。
更新
< source >( config_dict: typing.Dict[str, typing.Any] )
使用config_dict
中的属性更新此类的属性。
使用update_str
中的属性更新此类的属性。
预期的格式是整数、浮点数和字符串保持不变,对于布尔值使用true
或false
。例如:
“n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index”
要更改的键必须已经存在于配置对象中。