Transformers 文档

分词器工具

用于分词器的工具

本页面列出了分词器使用的所有实用函数,主要是实现了PreTrainedTokenizerPreTrainedTokenizerFast之间共同方法的类PreTrainedTokenizerBase以及混入类SpecialTokensMixin

大多数这些内容只有在您研究库中的分词器代码时才有用。

PreTrainedTokenizerBase

transformers.PreTrainedTokenizerBase

< >

( **kwargs )

参数

  • model_max_length (int, 可选) — 变压器模型输入的最大长度(以令牌数计)。当使用from_pretrained()加载分词器时,这将设置为存储在max_model_input_sizes中的关联模型的值(见上文)。如果未提供值,则默认为VERY_LARGE_INTEGER (int(1e30))。
  • padding_side (str, optional) — 模型应应用填充的一侧。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • truncation_side (str, 可选) — 模型应在哪一侧应用截断。应在['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', '>'].

PreTrainedTokenizerPreTrainedTokenizerFast 的基类。

处理这两个类的共享(主要是样板)方法。

类属性(由派生类覆盖)

  • 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, 可选, 默认为 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, optional, 默认为 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, 可选, 默认为 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_length并且 return_overflowing_tokens=True)。

  • num_truncated_tokens — 截断的令牌数量(当指定了max_length并且 return_overflowing_tokens=True)。

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

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

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

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], 可选): 传递给分词器的额外参数。
  • return_assistant_tokens_mask (bool, 默认为 False) — 是否返回助手生成令牌的掩码。对于由助手生成的令牌, 掩码将包含1。对于用户和系统令牌,掩码将包含0。 此功能仅适用于通过 {% generation %} 关键字支持它的聊天模板。
  • **kwargs — 传递给模板渲染器的额外kwargs。可以通过聊天模板访问。

返回

Union[List[int], Dict]

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

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

as_target_tokenizer

< >

( )

暂时设置用于编码目标的标记器。对于与序列到序列模型相关的标记器非常有用,这些模型需要对标签进行稍微不同的处理。

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]

参数

  • 序列 (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, 可选) — 是否清理分词空格。如果为None,将默认为 self.clean_up_tokenization_spaces.
  • kwargs(额外的关键字参数,可选)— 将被传递给底层模型的特定解码方法。

返回

List[str]

解码后的句子列表。

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

batch_encode_plus

< >

( batch_text_or_text_pairs: typing.Union[typing.List[str], typing.List[typing.Tuple[str, str]], typing.List[typing.List[str]], typing.List[typing.Tuple[typing.List[str], typing.List[str]]], typing.List[typing.List[int]], typing.List[typing.Tuple[typing.List[int], typing.List[int]]]] 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 split_special_tokens: bool = False **kwargs ) BatchEncoding

参数

  • batch_text_or_text_pairs (List[str], List[Tuple[str, str]], List[List[str]], List[Tuple[List[str], List[str]]], 对于非快速分词器,还包括 List[List[int]], List[Tuple[List[int], List[int]]]) — 要编码的序列或序列对的批次。这可以是字符串/字符串序列/整数序列的列表,或者是字符串/字符串序列/整数序列对的列表(详见 encode_plus)。
  • 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, 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_length并且 return_overflowing_tokens=True)。

  • num_truncated_tokens — 截断的令牌数量(当指定了max_length并且 return_overflowing_tokens=True)。

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

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

对一系列序列或一系列序列对进行标记化处理,并为模型做准备。

此方法已弃用,应改用__call__

build_inputs_with_special_tokens

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 第一个标记化的序列.
  • token_ids_1 (List[int], optional) — 第二个标记化序列.

返回

List[int]

带有特殊标记的模型输入。

通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。

此实现不添加特殊标记,此方法应在子类中被重写。

清理标记化

< >

( out_string: str ) str

参数

  • out_string (str) — 要清理的文本。

返回

str

清理后的字符串。

清理简单的英文分词伪影列表,如标点符号前的空格和缩写形式。

convert_tokens_to_string

< >

( tokens: typing.List[str] ) str

参数

  • tokens (List[str]) — 要连接成字符串的标记。

返回

str

连接的令牌。

将一系列标记转换为单个字符串。最简单的方法是" ".join(tokens),但我们通常希望同时去除子词标记化的痕迹。

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 第一个标记化的序列.
  • token_ids_1 (List[int], optional) — 第二个标记化序列。

返回

List[int]

令牌类型ID。

创建与传递的序列相对应的令牌类型ID。什么是令牌类型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, 默认为 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)) 相同。

encode_plus

< >

( 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 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[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) — 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 (str or TensorType, 可选) — 如果设置,将返回张量而不是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) — 是否返回溢出的token序列。如果提供了一对输入id序列(或一批对),并且使用了truncation_strategy = longest_firstTrue,则会引发错误,而不是返回溢出的token。
  • 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_length并且 return_overflowing_tokens=True)。

  • num_truncated_tokens — 截断的令牌数量(当指定了max_length并且 return_overflowing_tokens=True)。

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

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

对序列或序列对进行标记化并准备供模型使用。

此方法已弃用,应改用__call__

from_pretrained

< >

( pretrained_model_name_or_path: typing.Union[str, os.PathLike] *init_inputs 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' trust_remote_code = False **kwargs )

参数

  • pretrained_model_name_or_path (str or os.PathLike) — Can be either:
    • A string, the model id of a predefined tokenizer hosted inside a model repo on huggingface.co.
    • A path to a directory containing vocabulary files required by the tokenizer, for instance saved using the save_pretrained() method, e.g., ./my_model_directory/.
    • (Deprecated, not applicable to all derived classes) A path or url to a single saved vocabulary file (if and only if the tokenizer only requires a single vocabulary file like Bert or XLNet), e.g., ./my_model_directory/vocab.txt.
  • 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 中)。
  • local_files_only (bool, 可选, 默认为 False) — 是否仅依赖本地文件而不尝试下载任何文件。
  • revision (str, optional, defaults to "main") — 使用的特定模型版本。它可以是分支名称、标签名称或提交ID,因为我们使用基于git的系统在huggingface.co上存储模型和其他工件,所以revision可以是git允许的任何标识符。
  • 子文件夹 (str, 可选) — 如果相关文件位于 huggingface.co 上的模型仓库的子文件夹中(例如 facebook/rag-token-base),请在此处指定它。
  • inputs (额外的位置参数, 可选) — 将被传递给 Tokenizer 的 __init__ 方法.
  • trust_remote_code (bool, 可选, 默认为 False) — 是否允许在Hub上使用自定义模型文件定义的模型。此选项应仅对您信任的仓库设置为True,并且您已阅读其代码,因为它将在您的本地机器上执行Hub上的代码。
  • kwargs(额外的关键字参数,可选)— 将被传递给Tokenizer的__init__方法。可用于设置特殊标记,如bos_tokeneos_tokenunk_tokensep_tokenpad_tokencls_tokenmask_tokenadditional_special_tokens。有关更多详细信息,请参阅__init__中的参数。

从预定义的tokenizer实例化一个PreTrainedTokenizerBase(或其派生类)。

当您想要使用私有模型时,需要传递token=True

示例:

# We can't instantiate directly the base class *PreTrainedTokenizerBase* so let's show our examples on a derived class: BertTokenizer
# Download vocabulary from huggingface.co and cache.
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")

# Download vocabulary from huggingface.co (user-uploaded) and cache.
tokenizer = BertTokenizer.from_pretrained("dbmdz/bert-base-german-cased")

# If vocabulary files are in a directory (e.g. tokenizer was saved using *save_pretrained('./test/saved_model/')*)
tokenizer = BertTokenizer.from_pretrained("./test/saved_model/")

# If the tokenizer uses a single vocabulary file, you can point directly to this file
tokenizer = BertTokenizer.from_pretrained("./test/saved_model/my_vocab.txt")

# You can link tokens to special vocabulary when instantiating
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased", unk_token="<unk>")
# You should be sure '<unk>' is in the vocabulary when doing that.
# Otherwise use tokenizer.add_special_tokens({'unk_token': '<unk>'}) instead)
assert tokenizer.unk_token == "<unk>"

get_chat_template

< >

( chat_template: typing.Optional[str] = None tools: typing.Optional[typing.List[typing.Dict]] = None ) str

参数

  • chat_template (str, optional) — 用于此转换的Jinja模板或模板名称。 通常不需要向此参数传递任何内容, 因为默认情况下将使用模型的模板。
  • 工具 (List[Dict], 可选) — 一个工具(可调用函数)的列表,这些工具将可供模型访问。如果模板不支持函数调用,此参数将无效。每个工具应作为JSON Schema传递,提供工具的名称、描述和参数类型。有关更多信息,请参阅我们的 聊天模板指南

返回

str

聊天模板字符串。

检索用于标记化聊天消息的聊天模板字符串。此模板由apply_chat_template方法内部使用,也可以外部使用以检索模型的聊天模板,以便更好地进行生成跟踪。

get_special_tokens_mask

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) 一个在范围 [0, 1] 内的整数列表

参数

  • token_ids_0 (List[int]) — 第一个序列的ID列表。
  • token_ids_1 (List[int], optional) — 第二个序列的ID列表。
  • already_has_special_tokens (bool, optional, defaults to False) — 是否已经为模型格式化了带有特殊标记的标记列表。

返回

一个在范围 [0, 1] 内的整数列表

1 表示特殊标记,0 表示序列标记。

从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_modelencode_plus方法添加特殊标记时,会调用此方法。

get_vocab

< >

( ) Dict[str, int]

返回

Dict[str, int]

词汇表。

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

tokenizer.get_vocab()[token] 等同于 tokenizer.convert_tokens_to_ids(token)token 在词汇表中时。

pad

< >

( encoded_inputs: typing.Union[transformers.tokenization_utils_base.BatchEncoding, typing.List[transformers.tokenization_utils_base.BatchEncoding], typing.Dict[str, typing.List[int]], typing.Dict[str, typing.List[typing.List[int]]], typing.List[typing.Dict[str, typing.List[int]]]] padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = True max_length: typing.Optional[int] = None pad_to_multiple_of: typing.Optional[int] = None padding_side: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None verbose: bool = True )

参数

  • encoded_inputs (BatchEncoding, list of BatchEncoding, Dict[str, List[int]], Dict[str, List[List[int]] or List[Dict[str, List[int]]]) — Tokenized inputs. Can represent one input (BatchEncoding or Dict[str, List[int]]) or a batch of tokenized inputs (list of BatchEncoding, Dict[str, List[List[int]]] or List[Dict[str, List[int]]]) so you can use this method during preprocessing as well as in a PyTorch Dataloader collate function.

    你可以使用张量(numpy数组、PyTorch张量或TensorFlow张量)代替List[int],请参阅上面的注释了解返回类型。

  • padding (bool, str or PaddingStrategy, optional, defaults to True) — Select a strategy to pad the returned sequences (according to the model’s padding side and padding index) among:
    • 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).
  • max_length (int, optional) — 返回列表的最大长度以及可选的填充长度(见上文)。
  • pad_to_multiple_of (int, optional) — If set will pad the sequence to a multiple of the provided value.

    这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Core特别有用。

  • padding_side (str, optional) — 模型应在哪一侧应用填充。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • 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_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • verbose (bool, 可选, 默认为 True) — 是否打印更多信息和警告。

将单个编码输入或一批编码输入填充到预定义长度或批次中的最大序列长度。

填充侧(左/右)填充标记ID在标记器级别定义(使用self.padding_sideself.pad_token_idself.pad_token_type_id)。

请注意,使用快速分词器时,使用__call__方法比使用一个方法来编码文本然后再调用pad方法以获得填充编码要快。

如果传递的encoded_inputs是numpy数组、PyTorch张量或TensorFlow张量的字典,结果将使用相同的类型,除非你通过return_tensors提供了不同的张量类型。在PyTorch张量的情况下,你将失去张量的特定设备信息。

prepare_for_model

< >

( ids: typing.List[int] pair_ids: typing.Optional[typing.List[int]] = 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 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 prepend_batch_axis: bool = False **kwargs ) BatchEncoding

参数

  • ids (List[int]) — 第一个序列的标记化输入ID。可以通过链接tokenizeconvert_tokens_to_ids方法从字符串中获取。
  • pair_ids (List[int], 可选) — 第二序列的分词输入ID。可以通过链接tokenizeconvert_tokens_to_ids方法从字符串中获取。
  • 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 对象。
  • 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, 可选, 默认为 False) — 是否返回编码输入的长度.
  • verbose (bool, 可选, 默认为 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_length并且 return_overflowing_tokens=True)。

  • num_truncated_tokens — 截断的令牌数量(当指定了max_length并且 return_overflowing_tokens=True)。

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

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

准备一系列输入ID,或一对输入ID序列,以便模型可以使用它。它添加特殊标记,如果序列溢出则截断序列,同时考虑到特殊标记,并管理一个移动窗口(用户定义的步幅)来处理溢出的标记。请注意,对于pair_ids不等于Nonetruncation_strategy = longest_firstTrue的情况,无法返回溢出的标记。这样的参数组合将引发错误。

prepare_seq2seq_batch

< >

( src_texts: typing.List[str] tgt_texts: typing.Optional[typing.List[str]] = None max_length: typing.Optional[int] = None max_target_length: typing.Optional[int] = None padding: str = 'longest' return_tensors: str = None truncation: bool = True **kwargs ) BatchEncoding

参数

  • src_texts (List[str]) — 要摘要的文档列表或源语言文本列表。
  • tgt_texts (list, optional) — 摘要或目标语言文本的列表。
  • max_length (int, optional) — 控制编码器输入的最大长度(要摘要的文档或源语言文本)。如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度将被停用。
  • max_target_length (int, optional) — 控制解码器输入(目标语言文本或摘要)的最大长度。如果未设置或设置为None,将使用max_length的值。
  • 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).
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • truncation (bool, str or TruncationStrategy, optional, defaults to True) — 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).
  • **kwargs — 传递给 self.__call__ 的额外关键字参数。

返回

BatchEncoding

一个 BatchEncoding 包含以下字段:

  • input_ids — 要输入到编码器的标记ID列表。
  • attention_mask — 指定模型应关注哪些标记的索引列表。
  • labels — tgt_texts的标记ID列表。

完整的键集 [input_ids, attention_mask, labels],只有在传递了tgt_texts时才会返回。 否则,只有input_ids和attention_mask会被返回。

准备模型输入以进行翻译。为了获得最佳性能,请一次翻译一个句子。

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, 可选) — 推送时提交的消息。默认为 "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")

register_for_auto_class

< >

( auto_class = 'AutoTokenizer' )

参数

  • auto_class (strtype, 可选, 默认为 "AutoTokenizer") — 用于注册此新分词器的自动类。

将此类注册到给定的自动类中。这仅应用于自定义分词器,因为库中的分词器已经通过AutoTokenizer进行了映射。

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

save_pretrained

< >

( save_directory: typing.Union[str, os.PathLike] legacy_format: typing.Optional[bool] = None filename_prefix: typing.Optional[str] = None push_to_hub: bool = False **kwargs ) 一个由 str 组成的元组

参数

  • save_directory (str or os.PathLike) — 保存分词器的目录路径。
  • legacy_format (bool, optional) — Only applicable for a fast tokenizer. If unset (default), will save the tokenizer in the unified JSON format as well as in legacy format if it exists, i.e. with tokenizer specific vocabulary and a separate added_tokens files.

    如果False,将仅以统一的JSON格式保存分词器。此格式与“慢速”分词器(不由tokenizers库支持)不兼容,因此分词器将无法在相应的“慢速”分词器中加载。

    如果 True,将以旧格式保存分词器。如果“慢”分词器不存在,则会引发值错误。

  • filename_prefix (str, optional) — 一个前缀,用于添加到由分词器保存的文件名中。
  • push_to_hub (bool, optional, defaults to False) — 是否在保存后将模型推送到 Hugging Face 模型中心。您可以使用 repo_id 指定要推送到的仓库(默认为您命名空间中 save_directory 的名称)。
  • kwargs (Dict[str, Any], 可选) — 传递给 push_to_hub() 方法的额外关键字参数。

返回

一个由str组成的元组

文件已保存。

保存完整的tokenizer状态。

此方法确保可以使用~tokenization_utils_base.PreTrainedTokenizer.from_pretrained类方法重新加载完整的tokenizer。

警告,None 这不会保存您在实例化后可能对分词器应用的修改(例如,在创建后修改 tokenizer.do_lower_case)。

保存词汇表

< >

( save_directory: str filename_prefix: typing.Optional[str] = None ) Tuple(str)

参数

  • save_directory (str) — 保存词汇表的目录。
  • filename_prefix (str, optional) — 一个可选的前缀,用于添加到保存文件的名称中。

返回

Tuple(str)

保存文件的路径。

仅保存分词器的词汇表(词汇表 + 添加的标记)。

此方法不会保存分词器的配置和特殊标记映射。使用 _save_pretrained() 来保存分词器的整个状态。

tokenize

< >

( text: str pair: typing.Optional[str] = None add_special_tokens: bool = False **kwargs ) List[str]

参数

  • text (str) — 要编码的序列。
  • pair (str, optional) — 与第一个序列一起编码的第二个序列。
  • add_special_tokens (bool, optional, defaults to False) — 是否添加与相应模型相关的特殊标记。
  • kwargs (额外的关键字参数,可选) — 将被传递给底层模型的特定编码方法。详情请参见 call()

返回

List[str]

令牌列表。

将字符串转换为一系列标记,并用unk_token替换未知标记。

truncate_sequences

< >

( ids: typing.List[int] pair_ids: typing.Optional[typing.List[int]] = None num_tokens_to_remove: int = 0 truncation_strategy: typing.Union[str, transformers.tokenization_utils_base.TruncationStrategy] = 'longest_first' stride: int = 0 ) Tuple[List[int], List[int], List[int]]

参数

  • ids (List[int]) — 第一个序列的标记化输入ID。可以通过链接tokenizeconvert_tokens_to_ids方法从字符串中获取。
  • pair_ids (List[int], 可选) — 第二个序列的标记化输入ID。可以通过链接tokenizeconvert_tokens_to_ids方法从字符串中获取。
  • num_tokens_to_remove (int, optional, defaults to 0) — 使用截断策略移除的令牌数量。
  • truncation_strategy (str or TruncationStrategy, optional, defaults to 'longest_first') — The strategy to follow for truncation. Can be:
    • '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.
    • 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • stride (int, 可选, 默认为 0) — 如果设置为正数,返回的溢出标记将包含一些来自主序列的标记。此参数的值定义了额外标记的数量。

返回

Tuple[List[int], List[int], List[int]]

被截断的ids,被截断的pair_ids以及溢出的令牌列表。注意:如果提供了一对序列(或一批对),longest_first策略将返回空的溢出令牌列表。

根据策略就地截断序列对。

SpecialTokensMixin

transformers.SpecialTokensMixin

< >

( verbose = False **kwargs )

参数

  • bos_token (strtokenizers.AddedToken, 可选) — 表示句子开头的特殊标记。
  • eos_token (str or tokenizers.AddedToken, optional) — 表示句子结束的特殊标记。
  • unk_token (strtokenizers.AddedToken, 可选) — 一个表示词汇表外词汇的特殊标记。
  • sep_token (strtokenizers.AddedToken, 可选) — 用于分隔同一输入中的两个不同句子的特殊标记(例如BERT使用)。
  • pad_token (strtokenizers.AddedToken, 可选) — 用于使令牌数组在批处理时大小相同的特殊令牌。随后将被注意力机制或损失计算忽略。
  • cls_token (strtokenizers.AddedToken, 可选) — 表示输入类别的特殊标记(例如BERT使用)。
  • mask_token (strtokenizers.AddedToken, 可选) — 一个特殊的标记,表示一个被掩码的标记(用于掩码语言建模预训练目标,如 BERT)。
  • additional_special_tokens (元组或列表,元素类型为 strtokenizers.AddedToken, 可选) — 一个元组或列表,包含额外的标记,这些标记将被标记为 special,意味着如果 skip_special_tokens 设置为 True,它们将在解码时被跳过。

PreTrainedTokenizerPreTrainedTokenizerFast派生的mixin,用于处理与特殊标记相关的特定行为。特别是,此类持有可以直接以模型无关的方式访问这些特殊标记的属性,并允许设置和更新特殊标记。

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>"

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))

sanitize_special_tokens

< >

( )

sanitize_special_tokens 现已弃用,为了向后兼容而保留,并将在 transformers v5 中移除。

枚举和命名元组

transformers.tokenization_utils_base.TruncationStrategy

< >

( value names = 无 module = 无 qualname = 无 type = 无 start = 1 )

truncation 参数在 PreTrainedTokenizerBase.call() 中的可能值。在 IDE 中用于自动补全。

transformers.CharSpan

< >

( 开始: int 结束: int )

参数

  • start (int) — 原始字符串中第一个字符的索引。
  • end (int) — 原始字符串中最后一个字符之后的字符索引。

原始字符串中的字符跨度。

transformers.TokenSpan

< >

( 开始: int 结束: int )

参数

  • start (int) — 跨度中第一个标记的索引。
  • end (int) — 跨度中最后一个标记之后的标记的索引。

编码字符串中的令牌跨度(令牌列表)。

< > Update on GitHub