Transformers 文档

分词器

分词器

分词器负责为模型准备输入。该库包含所有模型的分词器。大多数分词器有两种版本:完整的Python实现和基于Rust库🤗 Tokenizers的“快速”实现。“快速”实现允许:

  1. 特别是在进行批量分词时,速度显著提升
  2. 用于在原始字符串(字符和单词)和标记空间之间进行映射的附加方法(例如,获取包含给定字符的标记的索引或与给定标记对应的字符范围)。

基类 PreTrainedTokenizerPreTrainedTokenizerFast 实现了将字符串输入编码为模型输入的常见方法(见下文),并且可以从本地文件或目录实例化/保存 Python 和 “Fast” 分词器,或者从库提供的预训练分词器(从 HuggingFace 的 AWS S3 仓库下载)实例化/保存。它们都依赖于 PreTrainedTokenizerBase,其中包含了常见方法,以及 SpecialTokensMixin

PreTrainedTokenizerPreTrainedTokenizerFast 因此实现了使用所有分词器的主要方法:

  • 分词(将字符串拆分为子词标记字符串),将标记字符串转换为ID并转换回来,以及编码/解码(即分词并转换为整数)。
  • 以独立于底层结构(BPE、SentencePiece…)的方式向词汇表中添加新标记。
  • 管理特殊标记(如掩码、句子开头等):添加它们,将它们分配给分词器中的属性以便于访问,并确保它们在分词过程中不会被拆分。

BatchEncoding 保存了 PreTrainedTokenizerBase 编码方法(__call__, encode_plusbatch_encode_plus)的输出,并且是从 Python 字典派生的。当分词器是纯 Python 分词器时,这个类的行为就像一个标准的 Python 字典,并保存了由这些方法计算的各种模型输入(input_ids, attention_mask…)。当分词器是“快速”分词器时(即由 HuggingFace tokenizers 库支持),这个类还提供了 几种高级对齐方法,可以用于在原始字符串(字符和单词)和 标记空间之间进行映射(例如,获取包含给定字符的标记的索引或与给定标记对应的字符范围)。

多模态分词器

除此之外,每个分词器都可以是一个“多模态”分词器,这意味着分词器将包含所有相关的特殊标记作为分词器属性的一部分,以便更容易访问。例如,如果分词器是从像LLaVA这样的视觉语言模型加载的,你将能够访问tokenizer.image_token_id来获取用作占位符的特殊图像标记。

要为任何类型的tokenizer启用额外的特殊标记,您必须添加以下行并保存tokenizer。额外的特殊标记不必与模态相关,可以是模型经常需要访问的任何内容。在下面的代码中,位于output_dir的tokenizer将直接访问三个额外的特殊标记。

vision_tokenizer = AutoTokenizer.from_pretrained(
    "llava-hf/llava-1.5-7b-hf",
    extra_special_tokens={"image_token": "<image>", "boi_token": "<image_start>", "eoi_token": "<image_end>"}
)
print(vision_tokenizer.image_token, vision_tokenizer.image_token_id)
("<image>", 32000)

预训练分词器

transformers.PreTrainedTokenizer

< >

( **kwargs )

参数

  • model_max_length (int, optional) — 变压器模型输入的最大长度(以标记数计)。当使用from_pretrained()加载分词器时,这将设置为存储在max_model_input_sizes中的关联模型的值(见上文)。如果未提供值,则默认为VERY_LARGE_INTEGER (int(1e30))。
  • padding_side (str, 可选) — 模型应在哪一侧应用填充。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • truncation_side (str, optional) — 模型应在哪一侧应用截断。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • chat_template (str, optional) — 一个Jinja模板字符串,用于格式化聊天消息列表。有关完整描述,请参见 https://huggingface.co/docs/transformers/chat_templating.
  • model_input_names (List[string], 可选) — 模型前向传递接受的输入列表(如 "token_type_ids""attention_mask")。默认值从同名的类属性中选取。
  • bos_token (strtokenizers.AddedToken, 可选) — 表示句子开头的特殊标记。将与 self.bos_tokenself.bos_token_id 关联。
  • eos_token (strtokenizers.AddedToken, 可选) — 表示句子结束的特殊标记。将与 self.eos_tokenself.eos_token_id 关联。
  • unk_token (strtokenizers.AddedToken, 可选) — 一个表示词汇表外词的特殊标记。将与 self.unk_tokenself.unk_token_id 关联。
  • sep_token (strtokenizers.AddedToken, 可选) — 用于分隔同一输入中的两个不同句子的特殊标记(例如BERT使用)。将关联到 self.sep_tokenself.sep_token_id.
  • pad_token (strtokenizers.AddedToken, 可选) — 用于使令牌数组在批处理时大小相同的特殊令牌。随后将被注意力机制或损失计算忽略。将与 self.pad_tokenself.pad_token_id 关联。
  • cls_token (strtokenizers.AddedToken, 可选) — 一个表示输入类别的特殊标记(例如由BERT使用)。将与 self.cls_tokenself.cls_token_id 关联。
  • mask_token (strtokenizers.AddedToken, 可选) — 一个特殊的标记,表示一个被掩码的标记(用于掩码语言建模预训练目标,如BERT)。将与 self.mask_tokenself.mask_token_id 关联。
  • additional_special_tokens (元组或列表,元素类型为 strtokenizers.AddedToken, 可选) — 一个包含额外特殊标记的元组或列表。将它们添加到这里以确保在解码时,当 skip_special_tokens 设置为 True 时,它们会被跳过。如果它们不是词汇表的一部分,它们将被添加到词汇表的末尾。
  • clean_up_tokenization_spaces (bool, 可选, 默认为 True) — 模型是否应该清理在分词过程中添加的空格,这些空格是在拆分输入文本时添加的。
  • split_special_tokens (bool, optional, defaults to False) — 是否在分词过程中拆分特殊标记。传递此参数将影响分词器的内部状态。默认行为是不拆分特殊标记。这意味着如果 bos_token,那么 tokenizer.tokenize("") = [']。否则,如果 split_special_tokens=True,那么 tokenizer.tokenize("") 将返回 ['<','s', '>'].

所有慢速分词器的基类。

继承自 PreTrainedTokenizerBase

处理所有与分词和特殊标记相关的共享方法,以及下载/缓存/加载预训练分词器的方法,以及向词汇表中添加标记的方法。

该类还以统一的方式包含所有分词器上添加的标记,因此我们不必处理各种底层字典结构(BPE、sentencepiece等)的特定词汇扩展方法。

类属性(由派生类覆盖)

  • vocab_files_names (Dict[str, str]) — 一个字典,其键为模型所需的每个词汇文件的__init__关键字名称,关联的值为保存相关文件的文件名(字符串)。
  • pretrained_vocab_files_map (Dict[str, Dict[str, str]]) — 一个字典的字典,其中高级键是模型所需的每个词汇表文件的__init__关键字名称,低级键是预训练模型的short-cut-names,关联值是相关预训练词汇表文件的url
  • model_input_names (List[str]) — 模型前向传递中期望的输入列表。
  • padding_side (str) — 模型应用填充的默认边。 应为 'right''left'
  • truncation_side (str) — 模型应用截断的默认侧。应为 'right''left'

__call__

< >

( text: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None text_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 is_split_into_words: bool = False pad_to_multiple_of: typing.Optional[int] = None padding_side: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool = False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True **kwargs ) BatchEncoding

参数

  • text (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_target (str, List[str], List[List[str]], optional) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair_target (str, List[str], List[List[str]], 可选) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • add_special_tokens (bool, optional, 默认为 True) — 是否在编码序列时添加特殊标记。这将使用底层的 PretrainedTokenizerBase.build_inputs_with_special_tokens 函数,该函数定义了哪些标记会自动添加到输入ID中。如果您想自动添加 boseos 标记,这将非常有用。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — Activates and controls padding. Accepts the following values:
    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • stride (int, 可选, 默认为 0) — 如果与 max_length 一起设置为一个数字,当 return_overflowing_tokens=True 时返回的溢出标记将包含来自截断序列末尾的一些标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • is_split_into_words (bool, 可选, 默认为 False) — 输入是否已经预分词(例如,分割成单词)。如果设置为 True,分词器会假设输入已经分割成单词(例如,通过空格分割),然后进行分词。这对于NER或分词分类非常有用。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。需要激活padding。 这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • padding_side (str, optional) — 模型应应用填充的一侧。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • return_token_type_ids (bool, optional) — Whether to return token type IDs. If left to the default, will return the token type IDs according to the specific tokenizer’s default, defined by the return_outputs attribute.

    什么是token type IDs?

  • return_attention_mask (bool, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer’s default, defined by the return_outputs attribute.

    什么是注意力掩码?

  • return_overflowing_tokens (bool, optional, defaults to False) — 是否返回溢出的标记序列。如果提供了一对输入ID序列(或一批对)并且使用了truncation_strategy = longest_firstTrue,则会引发错误而不是返回溢出的标记。
  • return_special_tokens_mask (bool, optional, defaults to False) — 是否返回特殊令牌掩码信息。
  • return_offsets_mapping (bool, optional, defaults to False) — Whether or not to return (char_start, char_end) for each token.

    这仅在继承自PreTrainedTokenizerFast的快速分词器上可用,如果使用Python的分词器,此方法将引发NotImplementedError

  • return_length (bool, optional, defaults to False) — 是否返回编码输入的长度。
  • verbose (bool, optional, defaults to True) — 是否打印更多信息和警告。
  • **kwargs — 传递给 self.tokenize() 方法

返回

BatchEncoding

一个包含以下字段的BatchEncoding

  • input_ids — 要输入模型的令牌ID列表。

    什么是输入ID?

  • token_type_ids — 要输入模型的令牌类型ID列表(当return_token_type_ids=True或 如果“token_type_ids”self.model_input_names中)。

    什么是令牌类型ID?

  • attention_mask — 指定模型应关注哪些令牌的索引列表(当 return_attention_mask=True或如果“attention_mask”self.model_input_names中)。

    什么是注意力掩码?

  • overflowing_tokens — 溢出令牌序列列表(当指定了max_lengthreturn_overflowing_tokens=True)。

  • num_truncated_tokens — 截断的令牌数量(当指定了max_lengthreturn_overflowing_tokens=True)。

  • special_tokens_mask — 0和1的列表,1表示添加的特殊令牌,0表示 常规序列令牌(当add_special_tokens=Truereturn_special_tokens_mask=True)。

  • length — 输入的长度(当return_length=True

主要方法,用于将一个或多个序列或一个或多个序列对进行标记化并准备供模型使用。

add_tokens

< >

( new_tokens: typing.Union[str, tokenizers.AddedToken, typing.List[typing.Union[str, tokenizers.AddedToken]]] special_tokens: bool = False ) int

参数

  • new_tokens (str, tokenizers.AddedTokenstrtokenizers.AddedToken 的列表) — 只有在词汇表中不存在的标记才会被添加。tokenizers.AddedToken 包装了一个字符串标记,让你可以个性化其行为:这个标记是否应该只匹配一个单词,这个标记是否应该去除左侧所有可能的空白,这个标记是否应该去除右侧所有可能的空白,等等。
  • special_tokens (bool, optional, defaults to False) — Can be used to specify if the token is a special token. This mostly change the normalization behavior (special tokens like CLS or [MASK] are usually not lower-cased for instance).

    查看 HuggingFace tokenizers 库中 tokenizers.AddedToken 的详细信息。

返回

int

添加到词汇表中的标记数量。

向分词器类添加一系列新标记。如果新标记不在词汇表中,它们将被添加到词汇表中,索引从当前词汇表的长度开始,并在应用分词算法之前被隔离。因此,添加的标记和分词算法词汇表中的标记不会以相同的方式处理。

注意,当向词汇表中添加新标记时,您应确保同时调整模型的标记嵌入矩阵的大小,以便其嵌入矩阵与分词器匹配。

为了做到这一点,请使用resize_token_embeddings()方法。

示例:

# Let's see how to increase the vocabulary of Bert model and tokenizer
tokenizer = BertTokenizerFast.from_pretrained("google-bert/bert-base-uncased")
model = BertModel.from_pretrained("google-bert/bert-base-uncased")

num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
print("We have added", num_added_toks, "tokens")
# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
model.resize_token_embeddings(len(tokenizer))

add_special_tokens

< >

( special_tokens_dict: typing.Dict[str, typing.Union[str, tokenizers.AddedToken]] replace_additional_special_tokens = True ) int

参数

  • special_tokens_dict (dictionary str to str or tokenizers.AddedToken) — Keys should be in the list of predefined special attributes: [bos_token, eos_token, unk_token, sep_token, pad_token, cls_token, mask_token, additional_special_tokens].

    只有当词汇表中不存在该标记时,才会添加标记(通过检查标记器是否为其分配unk_token的索引来测试)。

  • replace_additional_special_tokens (bool, optional,, defaults to True) — If True, the existing list of additional special tokens will be replaced by the list provided in special_tokens_dict. Otherwise, self._special_tokens_map["additional_special_tokens"] is just extended. In the former case, the tokens will NOT be removed from the tokenizer’s full vocabulary - they are only being flagged as non-special tokens. Remember, this only affects which tokens are skipped during decoding, not the added_tokens_encoder and added_tokens_decoder. This means that the previous additional_special_tokens are still added tokens, and will not be split by the model.

返回

int

添加到词汇表中的标记数量。

向编码器添加一个特殊标记(如eos、pad、cls等)的字典,并将它们链接到类属性。如果特殊标记不在词汇表中,它们将被添加到词汇表中(从当前词汇表的最后一个索引开始索引)。

当向词汇表中添加新标记时,您应确保同时调整模型的标记嵌入矩阵的大小,以便其嵌入矩阵与分词器匹配。

为了做到这一点,请使用resize_token_embeddings()方法。

使用 add_special_tokens 将确保您的特殊令牌可以以多种方式使用:

  • 在解码时可以使用skip_special_tokens = True跳过特殊标记。
  • 特殊标记由分词器仔细处理(它们永远不会被分割),类似于AddedTokens
  • 你可以轻松地使用像tokenizer.cls_token这样的tokenizer类属性来引用特殊标记。这使得开发与模型无关的训练和微调脚本变得容易。

在可能的情况下,特殊标记已经为提供的预训练模型注册(例如 BertTokenizercls_token 已经注册为 :obj’[CLS]’,XLM 的标记也注册为 '')。

示例:

# Let's see how to add a new classification token to GPT-2
tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
model = GPT2Model.from_pretrained("openai-community/gpt2")

special_tokens_dict = {"cls_token": "<CLS>"}

num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
print("We have added", num_added_toks, "tokens")
# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
model.resize_token_embeddings(len(tokenizer))

assert tokenizer.cls_token == "<CLS>"

apply_chat_template

< >

( conversation: typing.Union[typing.List[typing.Dict[str, str]], typing.List[typing.List[typing.Dict[str, str]]]] tools: typing.Optional[typing.List[typing.Dict]] = None documents: typing.Optional[typing.List[typing.Dict[str, str]]] = None chat_template: typing.Optional[str] = None add_generation_prompt: bool = False continue_final_message: bool = False tokenize: bool = True padding: bool = False truncation: bool = False max_length: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_dict: bool = False return_assistant_tokens_mask: bool = False tokenizer_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **kwargs ) Union[List[int], Dict]

参数

  • 对话 (Union[List[Dict[str, str]], List[List[Dict[str, str]]]]) — 一个包含“role”和“content”键的字典列表,表示到目前为止的聊天历史。
  • 工具 (List[Dict], 可选) — 模型可以访问的工具(可调用函数)列表。如果模板不支持函数调用,此参数将无效。每个工具应作为JSON Schema传递,提供工具的名称、描述和参数类型。有关更多信息,请参阅我们的 聊天模板指南
  • 文档 (List[Dict[str, str]], 可选) — 一个字典列表,表示如果模型执行RAG(检索增强生成)时将可以访问的文档。如果模板不支持RAG,此参数将无效。我们建议每个文档应为一个包含“title”和“text”键的字典。请参阅聊天模板指南的RAG部分,了解如何通过聊天模板传递文档的示例。
  • chat_template (str, optional) — 用于此转换的Jinja模板。通常不需要向此参数传递任何内容,因为默认情况下将使用模型的模板。
  • add_generation_prompt (bool, 可选) — 如果设置此参数,将在格式化输出中附加一个提示,该提示包含指示助手消息开始的标记。这在您希望从模型生成响应时非常有用。 请注意,此参数将传递给聊天模板,因此模板必须支持此参数才能使其生效。
  • continue_final_message (bool, optional) — 如果设置了这个参数,聊天将被格式化,使得聊天中的最后一条消息是开放式的,没有任何EOS标记。模型将继续这条消息,而不是开始一条新的消息。这允许你“预填充”模型的部分响应。不能与add_generation_prompt同时使用。
  • tokenize (bool, 默认为 True) — 是否对输出进行分词。如果为 False,输出将是一个字符串。
  • padding (bool, 默认为 False) — 是否将序列填充到最大长度。如果 tokenize 为 False,则无效。
  • 截断 (bool, 默认为 False) — 是否在最大长度处截断序列。如果 tokenize 为 False,则无效。
  • max_length (int, 可选) — 用于填充或截断的最大长度(以令牌为单位)。如果tokenize为False,则无效。如果未指定,将使用tokenizer的max_length属性作为默认值。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回特定框架的张量。如果 tokenize 为 False,则无效。可接受 的值为:
    • 'tf': 返回 TensorFlow tf.Tensor 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 NumPy np.ndarray 对象。
    • 'jax': 返回 JAX jnp.ndarray 对象。
  • return_dict (bool, 默认为 False) — 是否返回一个带有命名输出的字典。如果 tokenize 为 False,则无效。
  • tokenizer_kwargs (Dict[str -- Any], 可选): 传递给分词器的额外参数。
  • return_assistant_tokens_mask (bool, 默认为 False) — 是否返回助手生成令牌的掩码。对于由助手生成的令牌, 掩码将包含1。对于用户和系统令牌,掩码将包含0。 此功能仅适用于通过 {% generation %} 关键字支持它的聊天模板。
  • **kwargs — 传递给模板渲染器的额外kwargs。可以通过聊天模板访问。

返回

Union[List[int], Dict]

表示到目前为止的标记化聊天的标记ID列表,包括控制标记。此输出可以直接或通过generate()等方法传递给模型。如果设置了return_dict,将返回一个标记器输出的字典。

将包含"role""content"键的字典列表转换为令牌ID列表。此方法旨在与聊天模型一起使用,并将读取分词器的chat_template属性以确定转换时使用的格式和控制令牌。

batch_decode

< >

( sequences: typing.Union[typing.List[int], typing.List[typing.List[int]], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')] skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None **kwargs ) List[str]

参数

  • sequences (Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]) — 标记化输入ID的列表。可以使用__call__方法获取。
  • skip_special_tokens (bool, optional, defaults to False) — 是否在解码过程中移除特殊标记。
  • clean_up_tokenization_spaces (bool, optional) — 是否清理分词后的空格。如果为None,将默认为 self.clean_up_tokenization_spaces.
  • kwargs (额外的关键字参数,可选) — 将被传递给底层模型的特定解码方法。

返回

List[str]

解码后的句子列表。

通过调用decode将token id的列表列表转换为字符串列表。

解码

< >

( token_ids: typing.Union[int, typing.List[int], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')] skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None **kwargs ) str

参数

  • token_ids (Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]) — 标记化的输入ID列表。可以使用__call__方法获取。
  • skip_special_tokens (bool, optional, defaults to False) — 是否在解码过程中移除特殊标记。
  • clean_up_tokenization_spaces (bool, optional) — 是否清理分词空格。如果为None,将默认为 self.clean_up_tokenization_spaces.
  • kwargs(额外的关键字参数,可选)— 将被传递给底层模型的特定解码方法。

返回

str

解码后的句子。

使用分词器和词汇表将字符串中的ID序列转换为文本,可选择移除特殊标记并清理分词空格。

类似于执行 self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))

编码

< >

( text: typing.Union[str, typing.List[str], typing.List[int]] text_pair: typing.Union[str, typing.List[str], typing.List[int], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 padding_side: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None **kwargs ) List[int], torch.Tensor, tf.Tensornp.ndarray

参数

  • 文本 (str, List[str]List[int]) — 要编码的第一个序列。这可以是一个字符串,一个字符串列表(使用tokenize方法进行分词)或一个整数列表(使用convert_tokens_to_ids方法进行分词后的字符串ID)。
  • text_pair (str, List[str]List[int], 可选) — 可选的第二个序列进行编码。这可以是一个字符串,一个字符串列表(使用tokenize方法进行标记化的字符串)或一个整数列表(使用convert_tokens_to_ids方法进行标记化的字符串ID)。
  • add_special_tokens (bool, 可选, 默认为 True) — 是否在编码序列时添加特殊标记。这将使用底层的 PretrainedTokenizerBase.build_inputs_with_special_tokens 函数,该函数定义了哪些标记会自动添加到输入ID中。如果您想自动添加 boseos 标记,这将非常有用。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — 激活并控制填充。接受以下值:
    • True'longest': 填充到批次中最长的序列(如果只提供一个序列,则不进行填充)。
    • 'max_length': 填充到由参数 max_length 指定的最大长度,或者如果未提供该参数,则填充到模型可接受的最大输入长度。
    • False'do_not_pad' (默认): 不进行填充(即,可以输出具有不同长度序列的批次)。
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • stride (int, 可选, 默认为 0) — 如果与 max_length 一起设置为一个数字,当 return_overflowing_tokens=True 时返回的溢出标记将包含来自截断序列末尾的一些标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • is_split_into_words (bool, 可选, 默认为 False) — 输入是否已经预分词(例如,分割成单词)。如果设置为 True,分词器会假设输入已经分割成单词(例如,通过空格分割),然后进行分词。这对于NER或分词分类非常有用。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。需要激活padding。 这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • padding_side (str, optional) — 模型应在哪一侧应用填充。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • **kwargs — 传递给 .tokenize() 方法。

返回

List[int], torch.Tensor, tf.Tensornp.ndarray

文本的分词ID。

使用分词器和词汇表将字符串转换为ID序列(整数)。

与执行 self.convert_tokens_to_ids(self.tokenize(text)) 相同。

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, 可选) — 是否使用临时目录来存储推送到 Hub 之前保存的文件。 如果没有名为 repo_id 的目录,则默认为 True,否则为 False
  • commit_message (str, optional) — 推送时提交的消息。默认为 "Upload tokenizer".
  • 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 AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")

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

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

convert_ids_to_tokens

< >

( ids: typing.Union[int, typing.List[int]] skip_special_tokens: bool = False ) strList[str]

参数

  • ids (intList[int]) — 要转换为标记的标记ID(或标记ID列表)。
  • skip_special_tokens (bool, optional, defaults to False) — 是否在解码过程中移除特殊标记。

返回

strList[str]

解码后的令牌。

使用词汇表和添加的标记,将单个索引或索引序列转换为标记或标记序列。

convert_tokens_to_ids

< >

( tokens: typing.Union[str, typing.List[str]] ) intList[int]

参数

  • tokens (strList[str]) — 一个或多个要转换为token id(s)的token(s)。

返回

intList[int]

令牌ID或令牌ID列表。

使用词汇表将令牌字符串(或令牌序列)转换为单个整数ID(或ID序列)。

get_added_vocab

< >

( ) Dict[str, int]

返回

Dict[str, int]

添加的令牌。

返回词汇表中添加的标记作为标记到索引的字典。结果可能与快速调用不同,因为目前我们总是添加标记,即使它们已经在词汇表中。这是我们应该改变的地方。

num_special_tokens_to_add

< >

( pair: bool = False ) int

参数

  • pair (bool, 可选, 默认为 False) — 是否应在序列对或单个序列的情况下计算添加的标记数量。

返回

int

添加到序列中的特殊标记数量。

返回使用特殊标记编码序列时添加的标记数量。

这编码了一个虚拟输入并检查添加的标记数量,因此效率不高。不要将其放入训练循环中。

prepare_for_tokenization

< >

( text: str is_split_into_words: bool = False **kwargs ) Tuple[str, Dict[str, Any]]

参数

  • text (str) — 要准备的文本.
  • is_split_into_words (bool, 可选, 默认为 False) — 输入是否已经预分词(例如,分割成单词)。如果设置为 True,分词器会假设输入已经分割成单词(例如,通过空格分割),然后进行分词。这对于NER或分词分类非常有用。
  • kwargs (Dict[str, Any], 可选) — 用于分词的关键字参数。

返回

Tuple[str, Dict[str, Any]]

准备好的文本和未使用的kwargs。

在标记化之前执行任何必要的转换。

此方法应从kwargs中弹出参数并返回剩余的kwargs。我们在编码过程结束时测试kwargs,以确保所有参数都已被使用。

tokenize

< >

( text: str **kwargs ) List[str]

参数

  • 文本 (str) — 要编码的序列。
  • **kwargs (额外的关键字参数) — 传递给模型特定的 prepare_for_tokenization 预处理方法。

返回

List[str]

令牌列表。

使用分词器将字符串转换为一系列标记。

将文本分割为基于单词的词汇表中的单词或基于子词的词汇表中的子词(BPE/SentencePieces/WordPieces)。处理添加的标记。

PreTrainedTokenizerFast

PreTrainedTokenizerFast 依赖于 tokenizers 库。从 🤗 tokenizers 库中获取的 tokenizers 可以非常简单地加载到 🤗 transformers 中。查看 使用 🤗 tokenizers 中的 tokenizers 页面以了解如何实现这一点。

transformers.PreTrainedTokenizerFast

< >

( *args **kwargs )

参数

  • model_max_length (int, optional) — 变压器模型输入的最大长度(以令牌数计)。当使用from_pretrained()加载分词器时,这将设置为存储在max_model_input_sizes中的关联模型的值(见上文)。如果未提供值,则默认为VERY_LARGE_INTEGER (int(1e30))。
  • padding_side (str, 可选) — 模型应在哪一侧应用填充。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • truncation_side (str, optional) — 模型应在哪一侧应用截断。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • chat_template (str, 可选) — 一个Jinja模板字符串,用于格式化聊天消息列表。有关完整描述,请参见 https://huggingface.co/docs/transformers/chat_templating.
  • model_input_names (List[string], 可选) — 模型前向传递接受的输入列表(如 "token_type_ids""attention_mask")。默认值从同名的类属性中选取。
  • bos_token (strtokenizers.AddedToken, 可选) — 表示句子开头的特殊标记。将与 self.bos_tokenself.bos_token_id 相关联。
  • eos_token (strtokenizers.AddedToken, 可选) — 表示句子结束的特殊标记。将与 self.eos_tokenself.eos_token_id 关联。
  • unk_token (strtokenizers.AddedToken, 可选) — 一个表示词汇表外词的特殊标记。将与 self.unk_tokenself.unk_token_id 关联。
  • sep_token (strtokenizers.AddedToken, 可选) — 用于分隔同一输入中的两个不同句子的特殊标记(例如BERT使用)。将关联到 self.sep_tokenself.sep_token_id.
  • pad_token (strtokenizers.AddedToken, 可选) — 用于使令牌数组在批处理时大小相同的特殊令牌。随后将被注意力机制或损失计算忽略。将与 self.pad_tokenself.pad_token_id 关联。
  • cls_token (strtokenizers.AddedToken, 可选) — 一个表示输入类别的特殊标记(例如BERT使用)。将与 self.cls_tokenself.cls_token_id 关联。
  • mask_token (strtokenizers.AddedToken, 可选) — 一个特殊的标记,表示一个被掩码的标记(用于掩码语言建模预训练目标,如BERT)。将与 self.mask_tokenself.mask_token_id 关联。
  • additional_special_tokens (元组或列表,元素类型为 strtokenizers.AddedToken, 可选) — 一个元组或列表,包含额外的特殊标记。将它们添加到这里,以确保在解码时,当 skip_special_tokens 设置为 True 时,它们会被跳过。如果它们不是词汇表的一部分,它们将被添加到词汇表的末尾。
  • clean_up_tokenization_spaces (bool, 可选, 默认为 True) — 模型是否应该清理在分词过程中添加的空格,这些空格是在拆分输入文本时添加的。
  • split_special_tokens (bool, 可选, 默认为 False) — 是否在分词过程中拆分特殊标记。传递此参数将影响分词器的内部状态。默认行为是不拆分特殊标记。这意味着如果 bos_token,那么 tokenizer.tokenize("") = [']。否则,如果 split_special_tokens=True,那么 tokenizer.tokenize("") 将返回 ['<','s', '>'].
  • tokenizer_object (tokenizers.Tokenizer) — 一个来自🤗 tokenizers的tokenizers.Tokenizer对象,用于实例化。有关更多信息,请参见使用🤗 tokenizers的tokenizers.
  • tokenizer_file (str) — 一个指向本地JSON文件的路径,该文件表示之前从🤗 tokenizers序列化的tokenizers.Tokenizer对象。

所有快速分词器的基类(封装了HuggingFace分词器库)。

继承自 PreTrainedTokenizerBase

处理所有用于分词和特殊标记的共享方法,以及下载/缓存/加载预训练分词器的方法,以及向词汇表中添加标记的方法。

这个类还以统一的方式包含了所有分词器上添加的标记,因此我们不需要处理各种底层字典结构(BPE、sentencepiece等)的特定词汇增强方法。

类属性(由派生类覆盖)

  • vocab_files_names (Dict[str, str]) — 一个字典,其键为模型所需的每个词汇文件的__init__关键字名称,关联的值为保存相关文件的文件名(字符串)。
  • pretrained_vocab_files_map (Dict[str, Dict[str, str]]) — 一个字典的字典,其中高级键是模型所需的每个词汇表文件的__init__关键字名称,低级键是预训练模型的short-cut-names,关联值是相关预训练词汇表文件的url
  • model_input_names (List[str]) — 模型前向传递中期望的输入列表。
  • padding_side (str) — 模型应用填充的默认边。 应为 'right''left'
  • truncation_side (str) — 模型应用截断的默认侧。应为 'right''left'

__call__

< >

( text: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None text_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 is_split_into_words: bool = False pad_to_multiple_of: typing.Optional[int] = None padding_side: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool = False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True **kwargs ) BatchEncoding

参数

  • text (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_target (str, List[str], List[List[str]], optional) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair_target (str, List[str], List[List[str]], optional) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置is_split_into_words=True(以消除与序列批次的歧义)。
  • add_special_tokens (bool, optional, 默认为 True) — 是否在编码序列时添加特殊标记。这将使用底层的 PretrainedTokenizerBase.build_inputs_with_special_tokens 函数,该函数定义了哪些标记会自动添加到输入ID中。如果你想自动添加 boseos 标记,这将非常有用。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — Activates and controls padding. Accepts the following values:
    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • stride (int, 可选, 默认为 0) — 如果与 max_length 一起设置为一个数字,当 return_overflowing_tokens=True 时返回的溢出标记将包含来自截断序列末尾的一些标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • is_split_into_words (bool, optional, defaults to False) — 输入是否已经预分词(例如,分割成单词)。如果设置为True,分词器会假设输入已经分割成单词(例如,通过空格分割),然后进行分词。这对于NER或分词分类非常有用。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。需要激活padding。 这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • padding_side (str, optional) — 模型应在哪一侧应用填充。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • return_token_type_ids (bool, optional) — Whether to return token type IDs. If left to the default, will return the token type IDs according to the specific tokenizer’s default, defined by the return_outputs attribute.

    什么是token type IDs?

  • return_attention_mask (bool, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer’s default, defined by the return_outputs attribute.

    什么是注意力掩码?

  • return_overflowing_tokens (bool, 可选, 默认为 False) — 是否返回溢出的标记序列。如果提供了一对输入ID序列(或一批对),并且使用了 truncation_strategy = longest_firstTrue,则会引发错误,而不是返回溢出的标记。
  • return_special_tokens_mask (bool, optional, defaults to False) — 是否返回特殊令牌掩码信息。
  • return_offsets_mapping (bool, optional, defaults to False) — Whether or not to return (char_start, char_end) for each token.

    这仅在继承自PreTrainedTokenizerFast的快速分词器上可用,如果使用Python的分词器,此方法将引发NotImplementedError

  • return_length (bool, optional, defaults to False) — 是否返回编码输入的长度。
  • verbose (bool, optional, defaults to True) — 是否打印更多信息和警告。
  • **kwargs — 传递给 self.tokenize() 方法

返回

BatchEncoding

一个包含以下字段的BatchEncoding

  • input_ids — 要输入模型的令牌ID列表。

    什么是输入ID?

  • token_type_ids — 要输入模型的令牌类型ID列表(当return_token_type_ids=True或 如果“token_type_ids”self.model_input_names中)。

    什么是令牌类型ID?

  • attention_mask — 指定模型应关注哪些令牌的索引列表(当 return_attention_mask=True或如果“attention_mask”self.model_input_names中)。

    什么是注意力掩码?

  • overflowing_tokens — 溢出令牌序列列表(当指定了max_lengthreturn_overflowing_tokens=True)。

  • num_truncated_tokens — 截断的令牌数量(当指定了max_lengthreturn_overflowing_tokens=True)。

  • special_tokens_mask — 0和1的列表,1表示添加的特殊令牌,0表示 常规序列令牌(当add_special_tokens=Truereturn_special_tokens_mask=True)。

  • length — 输入的长度(当return_length=True

主要方法,用于将一个或多个序列或一个或多个序列对进行标记化并准备供模型使用。

add_tokens

< >

( new_tokens: typing.Union[str, tokenizers.AddedToken, typing.List[typing.Union[str, tokenizers.AddedToken]]] special_tokens: bool = False ) int

参数

  • new_tokens (str, tokenizers.AddedTokenstrtokenizers.AddedToken 的列表) — 只有在词汇表中不存在的标记才会被添加。tokenizers.AddedToken 包装了一个字符串标记,让你可以个性化其行为:这个标记是否应该只匹配一个单词,这个标记是否应该去除左侧所有可能的空白,这个标记是否应该去除右侧所有可能的空白,等等。
  • special_tokens (bool, optional, defaults to False) — Can be used to specify if the token is a special token. This mostly change the normalization behavior (special tokens like CLS or [MASK] are usually not lower-cased for instance).

    查看 HuggingFace tokenizers 库中 tokenizers.AddedToken 的详细信息。

返回

int

添加到词汇表中的标记数量。

向分词器类添加一系列新标记。如果新标记不在词汇表中,它们将被添加到词汇表中,索引从当前词汇表的长度开始,并在应用分词算法之前被隔离。因此,添加的标记和分词算法词汇表中的标记不会以相同的方式处理。

注意,当向词汇表中添加新标记时,您应确保同时调整模型的标记嵌入矩阵的大小,以便其嵌入矩阵与分词器匹配。

为了做到这一点,请使用resize_token_embeddings()方法。

示例:

# Let's see how to increase the vocabulary of Bert model and tokenizer
tokenizer = BertTokenizerFast.from_pretrained("google-bert/bert-base-uncased")
model = BertModel.from_pretrained("google-bert/bert-base-uncased")

num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
print("We have added", num_added_toks, "tokens")
# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
model.resize_token_embeddings(len(tokenizer))

add_special_tokens

< >

( special_tokens_dict: typing.Dict[str, typing.Union[str, tokenizers.AddedToken]] replace_additional_special_tokens = True ) int

参数

  • special_tokens_dict (dictionary str to str or tokenizers.AddedToken) — Keys should be in the list of predefined special attributes: [bos_token, eos_token, unk_token, sep_token, pad_token, cls_token, mask_token, additional_special_tokens].

    只有当词汇表中不存在该标记时,才会添加标记(通过检查标记器是否为其分配unk_token的索引来测试)。

  • replace_additional_special_tokens (bool, optional,, defaults to True) — If True, the existing list of additional special tokens will be replaced by the list provided in special_tokens_dict. Otherwise, self._special_tokens_map["additional_special_tokens"] is just extended. In the former case, the tokens will NOT be removed from the tokenizer’s full vocabulary - they are only being flagged as non-special tokens. Remember, this only affects which tokens are skipped during decoding, not the added_tokens_encoder and added_tokens_decoder. This means that the previous additional_special_tokens are still added tokens, and will not be split by the model.

返回

int

添加到词汇表中的标记数量。

向编码器添加一个特殊标记(如eos、pad、cls等)的字典,并将它们链接到类属性。如果特殊标记不在词汇表中,它们将被添加到词汇表中(从当前词汇表的最后一个索引开始索引)。

当向词汇表中添加新标记时,您应确保同时调整模型的标记嵌入矩阵的大小,以便其嵌入矩阵与分词器匹配。

为了做到这一点,请使用resize_token_embeddings()方法。

使用 add_special_tokens 将确保您的特殊令牌可以以多种方式使用:

  • 在解码时可以使用skip_special_tokens = True跳过特殊标记。
  • 特殊标记由分词器仔细处理(它们永远不会被分割),类似于AddedTokens
  • 你可以轻松地使用像tokenizer.cls_token这样的tokenizer类属性来引用特殊标记。这使得开发与模型无关的训练和微调脚本变得容易。

在可能的情况下,特殊标记已经为提供的预训练模型注册(例如 BertTokenizercls_token 已经注册为 :obj’[CLS]’,XLM 的标记也注册为 '')。

示例:

# Let's see how to add a new classification token to GPT-2
tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
model = GPT2Model.from_pretrained("openai-community/gpt2")

special_tokens_dict = {"cls_token": "<CLS>"}

num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
print("We have added", num_added_toks, "tokens")
# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
model.resize_token_embeddings(len(tokenizer))

assert tokenizer.cls_token == "<CLS>"

apply_chat_template

< >

( conversation: typing.Union[typing.List[typing.Dict[str, str]], typing.List[typing.List[typing.Dict[str, str]]]] tools: typing.Optional[typing.List[typing.Dict]] = None documents: typing.Optional[typing.List[typing.Dict[str, str]]] = None chat_template: typing.Optional[str] = None add_generation_prompt: bool = False continue_final_message: bool = False tokenize: bool = True padding: bool = False truncation: bool = False max_length: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_dict: bool = False return_assistant_tokens_mask: bool = False tokenizer_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **kwargs ) Union[List[int], Dict]

参数

  • 对话 (Union[List[Dict[str, str]], List[List[Dict[str, str]]]]) — 一个包含“role”和“content”键的字典列表,表示到目前为止的聊天历史记录。
  • 工具 (List[Dict], 可选) — 一个工具(可调用函数)的列表,这些工具将可供模型访问。如果模板不支持函数调用,此参数将无效。每个工具应作为JSON Schema传递,提供工具的名称、描述和参数类型。有关更多信息,请参阅我们的 聊天模板指南
  • 文档 (List[Dict[str, str]], 可选) — 一个字典列表,表示如果模型执行RAG(检索增强生成)时将可以访问的文档。如果模板不支持RAG,此参数将无效。我们建议每个文档应为一个包含“title”和“text”键的字典。请参阅聊天模板指南的RAG部分,了解如何使用聊天模板传递文档的示例。
  • chat_template (str, optional) — 用于此转换的Jinja模板。通常不需要向此参数传递任何内容,因为默认情况下将使用模型的模板。
  • add_generation_prompt (bool, 可选) — 如果设置此参数,将在格式化输出中附加一个包含指示助手消息开始的标记的提示。这在您希望从模型生成响应时非常有用。 请注意,此参数将传递给聊天模板,因此模板必须支持此参数才能使其生效。
  • continue_final_message (bool, optional) — 如果设置了这个参数,聊天将被格式化,使得聊天中的最后一条消息是开放式的,没有任何EOS标记。模型将继续这条消息,而不是开始一条新的消息。这允许你“预填充”模型的部分响应。不能与add_generation_prompt同时使用。
  • tokenize (bool, 默认为 True) — 是否对输出进行分词。如果为 False,输出将是一个字符串。
  • padding (bool, 默认为 False) — 是否将序列填充到最大长度。如果 tokenize 为 False,则无效。
  • 截断 (bool, 默认为 False) — 是否在最大长度处截断序列。如果 tokenize 为 False,则无效。
  • max_length (int, 可选) — 用于填充或截断的最大长度(以令牌为单位)。如果 tokenize 为 False,则无效。如果 未指定,将使用分词器的 max_length 属性作为默认值。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回特定框架的张量。如果 tokenize 为 False,则无效。可接受 的值为:
    • 'tf': 返回 TensorFlow tf.Tensor 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 NumPy np.ndarray 对象。
    • 'jax': 返回 JAX jnp.ndarray 对象。
  • return_dict (bool, 默认为 False) — 是否返回一个带有命名输出的字典。如果 tokenize 为 False,则此参数无效。
  • tokenizer_kwargs (Dict[str -- Any], optional): 传递给分词器的额外参数。
  • return_assistant_tokens_mask (bool, 默认为 False) — 是否返回助手生成令牌的掩码。对于由助手生成的令牌, 掩码将包含1。对于用户和系统令牌,掩码将包含0。 此功能仅适用于通过 {% generation %} 关键字支持它的聊天模板。
  • **kwargs — 传递给模板渲染器的额外kwargs。可以通过聊天模板访问。

返回

Union[List[int], Dict]

表示到目前为止的标记化聊天的标记ID列表,包括控制标记。此输出可以直接或通过generate()等方法传递给模型。如果设置了return_dict,将返回一个标记器输出的字典。

将包含"role""content"键的字典列表转换为令牌ID列表。此方法旨在与聊天模型一起使用,并将读取分词器的chat_template属性以确定转换时使用的格式和控制令牌。

batch_decode

< >

( sequences: typing.Union[typing.List[int], typing.List[typing.List[int]], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')] skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None **kwargs ) List[str]

参数

  • sequences (Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]) — 标记化输入ID的列表。可以使用__call__方法获取。
  • skip_special_tokens (bool, optional, defaults to False) — 是否在解码过程中移除特殊标记。
  • clean_up_tokenization_spaces (bool, optional) — 是否清理分词空格。如果为None,将默认为 self.clean_up_tokenization_spaces.
  • kwargs(额外的关键字参数,可选)— 将被传递给底层模型的特定解码方法。

返回

List[str]

解码后的句子列表。

通过调用decode将token id的列表列表转换为字符串列表。

解码

< >

( token_ids: typing.Union[int, typing.List[int], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')] skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None **kwargs ) str

参数

  • token_ids (Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]) — 标记化输入ID的列表。可以使用__call__方法获取。
  • skip_special_tokens (bool, 可选, 默认为 False) — 是否在解码过程中移除特殊标记。
  • clean_up_tokenization_spaces (bool, optional) — 是否清理分词空格。如果为None,将默认为 self.clean_up_tokenization_spaces.
  • kwargs(额外的关键字参数,可选)— 将被传递给底层模型的特定解码方法。

返回

str

解码后的句子。

使用分词器和词汇表将字符串中的ID序列转换为文本,可选择移除特殊标记并清理分词空格。

类似于执行 self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))

编码

< >

( text: typing.Union[str, typing.List[str], typing.List[int]] text_pair: typing.Union[str, typing.List[str], typing.List[int], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 padding_side: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None **kwargs ) List[int], torch.Tensor, tf.Tensornp.ndarray

参数

  • text (str, List[str] or List[int]) — 要编码的第一个序列。这可以是一个字符串,一个字符串列表(使用tokenize方法进行标记化的字符串)或一个整数列表(使用convert_tokens_to_ids方法进行标记化的字符串ID)。
  • text_pair (str, List[str]List[int], 可选) — 可选的第二个序列进行编码。这可以是一个字符串,一个字符串列表(使用tokenize方法进行标记化的字符串)或一个整数列表(使用convert_tokens_to_ids方法进行标记化的字符串ID)。
  • add_special_tokens (bool, optional, defaults to True) — 是否在编码序列时添加特殊标记。这将使用底层的 PretrainedTokenizerBase.build_inputs_with_special_tokens 函数,该函数定义了哪些标记会自动添加到输入ID中。如果您想自动添加 boseos 标记,这将非常有用。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — Activates and controls padding. Accepts the following values:
    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • stride (int, 可选, 默认为 0) — 如果设置为一个数字并与 max_length 一起使用,当 return_overflowing_tokens=True 时返回的溢出标记将包含一些来自截断序列末尾的标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • is_split_into_words (bool, 可选, 默认为 False) — 输入是否已经预分词(例如,分割成单词)。如果设置为 True,分词器会假设输入已经分割成单词(例如,通过空格分割),然后进行分词。这对于NER或分词分类非常有用。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。需要激活padding。 这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • padding_side (str, 可选) — 模型应在哪一侧应用填充。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • **kwargs — 传递给 .tokenize() 方法。

返回

List[int], torch.Tensor, tf.Tensornp.ndarray

文本的分词ID。

使用分词器和词汇表将字符串转换为ID序列(整数)。

与执行 self.convert_tokens_to_ids(self.tokenize(text)) 相同。

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 tokenizer".
  • 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 AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")

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

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

convert_ids_to_tokens

< >

( ids: typing.Union[int, typing.List[int]] skip_special_tokens: bool = False ) strList[str]

参数

  • ids (intList[int]) — 要转换为标记的标记ID(或标记ID列表)。
  • skip_special_tokens (bool, optional, defaults to False) — 是否在解码过程中移除特殊标记。

返回

strList[str]

解码后的令牌。

使用词汇表和添加的标记,将单个索引或索引序列转换为标记或标记序列。

convert_tokens_to_ids

< >

( tokens: typing.Union[str, typing.Iterable[str]] ) intList[int]

参数

  • tokens (strIterable[str]) — 一个或多个要转换为token id的token(s)。

返回

intList[int]

令牌ID或令牌ID列表。

使用词汇表将标记字符串(或标记序列)转换为单个整数ID(或ID的可迭代对象)。

get_added_vocab

< >

( ) Dict[str, int]

返回

Dict[str, int]

添加的令牌。

返回词汇表中添加的标记作为标记到索引的字典。

num_special_tokens_to_add

< >

( pair: bool = False ) int

参数

  • pair (bool, 可选, 默认为 False) — 在序列对或单个序列的情况下,是否应计算添加的标记数量。

返回

int

添加到序列中的特殊标记数量。

返回使用特殊标记编码序列时添加的标记数量。

这编码了一个虚拟输入并检查添加的标记数量,因此效率不高。不要将其放入训练循环中。

set_truncation_and_padding

< >

( padding_strategy: PaddingStrategy truncation_strategy: TruncationStrategy max_length: int stride: int pad_to_multiple_of: typing.Optional[int] padding_side: typing.Optional[bool] )

参数

  • padding_strategy (PaddingStrategy) — 将应用于输入的填充类型
  • truncation_strategy (TruncationStrategy) — 将应用于输入的截断类型
  • max_length (int) — 序列的最大长度。
  • stride (int) — 处理溢出时使用的步长。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • padding_side (str, optional) — 模型应应用填充的一侧。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。

定义快速分词器的截断和填充策略(由HuggingFace分词器库提供),并在之后恢复分词器设置。

提供的分词器在管理部分之前没有填充/截断策略。如果你的分词器之前设置了填充/截断策略,那么在退出管理部分时,它将被重置为无填充/截断。

train_new_from_iterator

< >

( text_iterator vocab_size length = None new_special_tokens = None special_tokens_map = None **kwargs ) PreTrainedTokenizerFast

参数

  • text_iterator (生成器 of List[str]) — 训练语料库。应该是一个文本批次的生成器,例如,如果你将所有内容都存储在内存中,可以是一个文本列表的列表。
  • vocab_size (int) — 你想要为你的分词器设置的词汇表大小。
  • length (int, optional) — 迭代器中序列的总数。这用于提供有意义的进度跟踪
  • new_special_tokens (list of str or AddedToken, optional) — 一个要添加到您正在训练的标记器中的新特殊标记列表。
  • special_tokens_map (Dict[str, str], optional) — 如果你想重命名此分词器使用的一些特殊标记,请在此参数中传递旧特殊标记名称到新特殊标记名称的映射。
  • kwargs (Dict[str, Any], optional) — 从🤗 Tokenizers库传递给训练器的额外关键字参数。

返回

PreTrainedTokenizerFast

一个与原始类型相同的新分词器,训练于 text_iterator

使用与当前相同的默认设置(在特殊标记或标记化管道方面)在新语料库上训练一个标记器。

BatchEncoding

transformers.BatchEncoding

< >

( 数据: typing.Optional[typing.Dict[str, typing.Any]] = None 编码: typing.Union[tokenizers.Encoding, typing.Sequence[tokenizers.Encoding], NoneType] = None 张量类型: typing.Union[NoneType, str, transformers.utils.generic.TensorType] = None 预置批次轴: bool = False 序列数量: typing.Optional[int] = None )

参数

  • data (dict, 可选) — 由 __call__/encode_plus/batch_encode_plus 方法返回的列表/数组/张量的字典 (‘input_ids’, ‘attention_mask’, 等).
  • encoding (tokenizers.EncodingSequence[tokenizers.Encoding], 可选) — 如果分词器是一个快速分词器,它输出额外的信息,如从单词/字符空间到标记空间的映射,tokenizers.Encoding 实例或实例列表(用于批处理)将保存这些信息。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在这里提供一个tensor_type,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。
  • prepend_batch_axis (bool, 可选, 默认为 False) — 是否在转换为张量时添加批次轴(参见上面的 tensor_type)。请注意,如果设置了参数 tensor_type,此参数才会生效,否则无效.
  • n_sequences (Optional[int], 可选) — 你可以在这里提供一个tensor_type,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。

保存call()encode_plus()batch_encode_plus()方法的输出(如tokens、attention_masks等)。

这个类是从Python字典派生出来的,可以像字典一样使用。此外,这个类还提供了一些实用方法,用于将单词/字符空间映射到标记空间。

char_to_token

< >

( batch_or_char_index: int char_index: typing.Optional[int] = None sequence_index: int = 0 ) int

参数

  • batch_or_char_index (int) — 批次中序列的索引。如果批次只包含一个序列,这可以是序列中单词的索引
  • char_index (int, optional) — 如果在 batch_or_token_index 中提供了批次索引,这可以是序列中单词的索引。
  • sequence_index (int, 可选, 默认为 0) — 如果批次中编码了一对序列,这可以用来指定提供的字符索引属于这对序列中的哪个序列(0 或 1)。

返回

int

标记的索引,如果字符索引指的是仅包含空格的标记并且使用trim_offsets=True修剪了空格,则为None。

获取批次序列中原始字符串中字符的编码输出中的标记索引。

可以这样调用:

  • self.char_to_token(char_index) 如果批次大小为1
  • self.char_to_token(batch_index, char_index) 如果批量大小大于或等于1

当输入序列以预分词的序列形式提供时(即单词由用户定义),此方法特别适用。在这种情况下,它可以轻松地将编码的标记与提供的分词单词关联起来。

char_to_word

< >

( batch_or_char_index: int char_index: typing.Optional[int] = None sequence_index: int = 0 ) intList[int]

参数

  • batch_or_char_index (int) — 批次中序列的索引。如果批次只包含一个序列,这可以是原始字符串中字符的索引。
  • char_index (int, optional) — 如果在 batch_or_token_index 中提供了批次索引,这可以是原始字符串中字符的索引。
  • sequence_index (int, 可选, 默认为 0) — 如果批次中编码了一对序列,这可以用来指定提供的字符索引属于这对序列中的哪个序列(0 或 1)。

返回

intList[int]

关联编码标记的索引或索引列表。

获取批次序列的原始字符串中字符对应的原始字符串中的单词。

可以这样调用:

  • self.char_to_word(char_index) 如果批次大小为1
  • self.char_to_word(batch_index, char_index) 如果批量大小大于1

当输入序列以预分词的序列形式提供时(即单词由用户定义),此方法特别适用。在这种情况下,它可以轻松地将编码的标记与提供的分词单词关联起来。

convert_to_tensors

< >

( tensor_type: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None prepend_batch_axis: bool = False )

参数

  • tensor_type (strTensorType, 可选) — 使用的张量类型。如果是 str,应该是枚举 TensorType 的值之一。如果是 None,则不进行任何修改。
  • prepend_batch_axis (int, 可选, 默认为 False) — 是否在转换过程中添加批次维度。

将内部内容转换为张量。

sequence_ids

< >

( batch_index: int = 0 ) List[Optional[int]]

参数

  • batch_index (int, optional, defaults to 0) — 批次中要访问的索引。

返回

List[Optional[int]]

一个列表,指示每个标记对应的序列ID。由标记器添加的特殊标记被映射到None,其他标记被映射到它们对应序列的索引。

返回一个列表,将标记映射到其原始句子的ID:

  • None 用于在序列周围或之间添加的特殊标记,
  • 0 用于与第一个序列中的单词对应的标记,
  • 1 用于表示当一对序列被联合编码时,对应于第二个序列中的单词的标记。

< >

( 设备: typing.Union[str, ForwardRef('torch.device')] ) BatchEncoding

参数

  • device (str or torch.device) — 将张量放置的设备。

返回

BatchEncoding

修改后的相同实例。

通过调用 v.to(device) 将所有值发送到设备(仅限 PyTorch)。

token_to_chars

< >

( batch_or_token_index: int token_index: typing.Optional[int] = None ) CharSpan

参数

  • batch_or_token_index (int) — 批次中序列的索引。如果批次只包含一个序列,这可以是序列中令牌的索引。
  • token_index (int, optional) — 如果在 batch_or_token_index 中提供了批次索引,这可以是序列中标记或标记的索引。

返回

CharSpan

原始字符串中的字符范围,如果标记(例如 , )不对应于原始字符串中的任何字符,则为 None。

获取批次序列中编码标记对应的字符跨度。

字符跨度以CharSpan的形式返回,包含以下内容:

  • start — 与标记关联的原始字符串中第一个字符的索引。
  • end — 与标记关联的原始字符串中最后一个字符之后的字符的索引。

可以这样调用:

  • self.token_to_chars(token_index) 如果批次大小为1
  • self.token_to_chars(batch_index, token_index) 如果批量大小大于或等于1

token_to_sequence

< >

( batch_or_token_index: int token_index: typing.Optional[int] = None ) int

参数

  • batch_or_token_index (int) — 批次中序列的索引。如果批次只包含一个序列,这可以是序列中令牌的索引。
  • token_index (int, optional) — 如果在 batch_or_token_index 中提供了批次索引,这可以是序列中令牌的索引。

返回

int

输入序列中单词的索引。

获取由给定令牌表示的序列的索引。在一般使用情况下,此方法返回0表示单个序列或一对序列中的第一个序列,返回1表示一对序列中的第二个序列

可以这样调用:

  • self.token_to_sequence(token_index) 如果批次大小为1
  • self.token_to_sequence(batch_index, token_index) 如果批量大小大于1

当输入序列以预分词的序列形式提供时(即,单词由用户定义),此方法特别适用。在这种情况下,它可以轻松地将编码的标记与提供的分词单词关联起来。

token_to_word

< >

( batch_or_token_index: int token_index: typing.Optional[int] = None ) int

参数

  • batch_or_token_index (int) — 批次中序列的索引。如果批次只包含一个序列,这可以是序列中令牌的索引。
  • token_index (int, optional) — 如果在 batch_or_token_index 中提供了批次索引,这可以是序列中令牌的索引。

返回

int

输入序列中单词的索引。

获取批次序列中与编码令牌对应的单词的索引(即包含该令牌的单词)。

可以这样调用:

  • self.token_to_word(token_index) 如果批量大小为1
  • self.token_to_word(batch_index, token_index) 如果批量大小大于1

当输入序列以预分词的序列形式提供时(即,单词由用户定义),此方法特别适用。在这种情况下,它可以轻松地将编码后的标记与提供的分词单词关联起来。

tokens

< >

( batch_index: int = 0 ) List[str]

参数

  • batch_index (int, optional, defaults to 0) — 批次中要访问的索引。

返回

List[str]

该索引处的令牌列表。

返回给定批次索引处的标记列表(输入字符串在单词/子词分割后且转换为整数索引之前的子部分)(仅适用于快速分词器的输出)。

word_ids

< >

( batch_index: int = 0 ) List[Optional[int]]

参数

  • batch_index (int, optional, 默认为 0) — 批次中要访问的索引。

返回

List[Optional[int]]

一个列表,指示每个标记对应的单词。由标记器添加的特殊标记被映射到None,其他标记被映射到它们对应单词的索引(如果它们是该单词的一部分,则多个标记将映射到相同的单词索引)。

返回一个列表,将标记映射到初始句子中的实际单词,适用于快速标记器。

word_to_chars

< >

( batch_or_word_index: int word_index: typing.Optional[int] = None sequence_index: int = 0 ) CharSpanList[CharSpan]

参数

  • batch_or_word_index (int) — 批次中序列的索引。如果批次只包含一个序列,这可以是序列中单词的索引
  • word_index (int, optional) — 如果在 batch_or_token_index 中提供了批次索引,这可以是序列中单词的索引。
  • sequence_index (int, optional, defaults to 0) — 如果批次中编码了一对序列,这可以用来指定提供的单词索引属于这对序列中的哪个序列(0 或 1)。

返回

CharSpanList[CharSpan]

字符串中相关字符或字符的跨度。CharSpan 是NamedTuple,包含:

  • start: 原始字符串中与标记关联的第一个字符的索引
  • end: 原始字符串中与标记关联的最后一个字符的下一个字符的索引

获取批次序列中给定单词对应的原始字符串中的字符跨度。

字符跨度以CharSpan NamedTuple的形式返回,包含以下内容:

  • start: 原始字符串中第一个字符的索引
  • end: 原始字符串中最后一个字符之后的字符的索引

可以这样调用:

  • self.word_to_chars(word_index) 如果批量大小为1
  • self.word_to_chars(batch_index, word_index) 如果批量大小大于或等于1

word_to_tokens

< >

( batch_or_word_index: int word_index: typing.Optional[int] = None sequence_index: int = 0 ) (TokenSpan, 可选)

参数

  • batch_or_word_index (int) — 批次中序列的索引。如果批次只包含一个序列,这可以是序列中单词的索引。
  • word_index (int, 可选) — 如果在 batch_or_token_index 中提供了批次索引,这可以是序列中单词的索引。
  • sequence_index (int, 可选, 默认为 0) — 如果批次中编码了一对序列,这可以用来指定提供的单词索引属于这对序列中的哪个序列(0 或 1)。

返回

(TokenSpan, 可选)

编码序列中的标记范围。如果没有标记对应单词,则返回 None。这种情况尤其可能发生在标记是用于格式化标记化的特殊标记时。例如,当我们在标记化的最开始时添加一个类标记。

获取批次序列中单词对应的编码标记跨度。

Token spans 以 TokenSpan 的形式返回,包含以下内容:

  • start — 第一个标记的索引。
  • end — 最后一个标记之后的标记的索引。

可以这样调用:

  • self.word_to_tokens(word_index, sequence_index: int = 0) 如果批次大小为1
  • self.word_to_tokens(batch_index, word_index, sequence_index: int = 0) 如果批量大小大于或等于1

当输入序列以预分词的序列形式提供时(即单词由用户定义),此方法特别适用。在这种情况下,它可以轻松地将编码的标记与提供的分词单词关联起来。

单词

< >

( batch_index: int = 0 ) List[Optional[int]]

参数

  • batch_index (int, optional, defaults to 0) — 批次中要访问的索引。

返回

List[Optional[int]]

一个列表,指示每个标记对应的单词。由标记器添加的特殊标记被映射到None,其他标记被映射到它们对应单词的索引(如果它们是该单词的一部分,则多个标记将映射到相同的单词索引)。

返回一个列表,将标记映射到初始句子中的实际单词,适用于快速标记器。

< > Update on GitHub