Transformers 文档
处理器
并获得增强的文档体验
开始使用
处理器
在 Transformers 库中,处理器(Processors)可能指两种不同的东西:
多模态处理器
任何多模态模型都需要一个对象来编码或解码组合了多种模态(文本、视觉、音频)的数据。这由称为处理器的对象处理,这些对象组合了两个或多个处理对象,例如分词器(用于文本模态)、图像处理器(用于视觉)和特征提取器(用于音频)。
这些处理器继承自以下基类,该基类实现了保存和加载功能:
这是一个混入(mixin),用于为所有处理器类提供保存/加载功能。
apply_chat_template
< 源 >( conversation: typing.Union[list[dict[str, str]], list[list[dict[str, str]]]] chat_template: typing.Optional[str] = None **kwargs: typing_extensions.Unpack[transformers.processing_utils.AllKwargsForChatTemplate] )
与分词器上的 `apply_chat_template` 方法类似,此方法将 Jinja 模板应用于输入对话,将其转换为单个可分词的字符串。
输入应为以下格式,其中每条消息内容是一个列表,包含文本以及可选的图像或视频输入。也可以提供图像、视频、URL 或本地路径,当 `return_dict=True` 时,这些将被用于形成 `pixel_values`。如果未提供,将只获得格式化的文本,或可选的分词后的文本。
conversation = [ { “role”: “user”, “content”: [ {“type”: “image”, “url”: “https://www.ilankelman.org/stopsigns/australia.jpg”}, {“type”: “text”, “text”: “请详细描述这张图片。”}, ], }, ]
检查传入参数的类是否与预期的 transformers 类匹配。如果预期类与实际类之间出现意外不匹配,则会引发错误。否则,返回正确检索到的类。
from_args_and_dict
< 源 >( args processor_dict: dict **kwargs ) → ~processing_utils.ProcessingMixin
从一个 Python 参数字典实例化 `~processing_utils.ProcessingMixin` 类型的对象。
from_pretrained
< 源 >( pretrained_model_name_or_path: typing.Union[str, os.PathLike] cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[str, bool, NoneType] = None revision: str = 'main' **kwargs )
参数
- pretrained_model_name_or_path (
str
oros.PathLike
) — 这可以是以下之一:- 一个字符串,即托管在 huggingface.co 模型仓库中的预训练 feature_extractor 的 *模型 id*。
- 一个包含使用 save_pretrained() 方法保存的特征提取器文件的 *目录* 的路径,例如,`./my_model_directory/`。
- 一个已保存的特征提取器 JSON *文件* 的路径或 URL,例如,`./my_model_directory/preprocessor_config.json`。
- **kwargs — 传递给 from_pretrained() 和 `~tokenization_utils_base.PreTrainedTokenizer.from_pretrained` 的附加关键字参数。
实例化与预训练模型关联的处理器。
此类方法仅调用特征提取器的 from_pretrained()、图像处理器的 ImageProcessingMixin 和分词器的 `~tokenization_utils_base.PreTrainedTokenizer.from_pretrained` 方法。请参阅上述方法的文档字符串以获取更多信息。
get_processor_dict
< 源 >( pretrained_model_name_or_path: typing.Union[str, os.PathLike] **kwargs ) → tuple[Dict, Dict]
从一个 `pretrained_model_name_or_path` 解析出一个参数字典,用于使用 `from_args_and_dict` 实例化一个 `~processing_utils.ProcessingMixin` 类型的处理器。
post_process_image_text_to_text
< 源 >( generated_outputs skip_special_tokens = True **kwargs ) → list[str]
后处理视觉语言模型(VLM)的输出以解码文本。
将可选的位置参数与处理器类中的 `optional_call_args` 中的相应名称按它们传递给处理器调用的顺序进行匹配。
请注意,这只应在具有特殊参数的处理器的 `__call__` 方法中使用。特殊参数是指既不是 `text`、`images`、`audio`、`videos`,也不是传递给分词器、图像处理器等的参数。这类处理器的例子有:
CLIPSegProcessor
LayoutLMv2Processor
OwlViTProcessor
另请注意,通过位置向处理器调用传递参数现已弃用,并将在未来版本中被禁止。我们保留此功能仅为向后兼容。
例如:假设处理器类有 `optional_call_args = ["arg_name_1", "arg_name_2"]`。
我们定义 call 方法如下:
def __call__(
self,
text: str,
images: Optional[ImageInput] = None,
*arg,
audio=None,
videos=None,
)
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[str, int, NoneType] = '5GB' create_pr: bool = False safe_serialization: bool = True revision: typing.Optional[str] = None commit_description: typing.Optional[str] = None tags: typing.Optional[list[str]] = None **deprecated_kwargs )
参数
- repo_id (
str
) — 您想要将处理器推送到的仓库名称。当推送到特定组织时,它应包含您的组织名称。 - use_temp_dir (
bool
, 可选) — 是否使用临时目录来存储推送到 Hub 之前保存的文件。如果没有名为 `repo_id` 的目录,则默认为 `True`,否则为 `False`。 - commit_message (
str
, 可选) — 推送时提交的消息。将默认为 `"Upload processor"`。 - private (
bool
, 可选) — 是否将仓库设为私有。如果为 `None` (默认),除非组织的默认设置为私有,否则仓库将为公开。如果仓库已存在,则忽略此值。 - token (
bool
orstr
, 可选) — 用于远程文件 HTTP 持有者授权的令牌。如果为 `True`,将使用运行 `huggingface-cli login` 时生成的令牌 (存储在 `~/.huggingface` 中)。如果未指定 `repo_url`,则默认为 `True`。 - max_shard_size (
int
orstr
, 可选, 默认为"5GB"
) — 仅适用于模型。在分片前检查点的最大大小。检查点分片的大小将小于此大小。如果表示为字符串,需要是数字后跟一个单位 (如 `"5MB"`)。我们将其默认为 `"5GB"`,以便用户可以轻松在免费的 Google Colab 实例上加载模型,而不会出现 CPU 内存不足的问题。 - create_pr (
bool
, 可选, 默认为False
) — 是为上传的文件创建一个拉取请求(PR)还是直接提交。 - safe_serialization (
bool
, 可选, 默认为True
) — 是否将模型权重转换为 safetensors 格式以实现更安全的序列化。 - revision (
str
, 可选) — 推送上传文件到的分支。 - commit_description (
str
, 可选) — 将要创建的提交的描述 - tags (
list[str]
, 可选) — 要推送到 Hub 的标签列表。
将处理器文件上传到 🤗 模型中心。
示例
from transformers import AutoProcessor
processor = AutoProcessor.from_pretrained("google-bert/bert-base-cased")
# Push the processor to your namespace with the name "my-finetuned-bert".
processor.push_to_hub("my-finetuned-bert")
# Push the processor to an organization with the name "my-finetuned-bert".
processor.push_to_hub("huggingface/my-finetuned-bert")
register_for_auto_class
< 源 >( auto_class = 'AutoProcessor' )
向给定的自动类注册此类。这只应用于自定义特征提取器,因为库中的特征提取器已经与 `AutoProcessor` 映射。
save_pretrained
< 源 >( save_directory push_to_hub: bool = False **kwargs )
参数
- save_directory (
str
oros.PathLike
) — 将保存特征提取器 JSON 文件和分词器文件的目录(如果不存在,将创建该目录)。 - push_to_hub (
bool
, 可选, 默认为False
) — 是否在保存模型后将其推送到 Hugging Face 模型中心。您可以使用 `repo_id` 指定要推送到的仓库(将默认为您命名空间中 `save_directory` 的名称)。 - kwargs (
dict[str, Any]
, 可选) — 传递给 push_to_hub() 方法的附加关键字参数。
将此处理器(特征提取器、分词器…)的属性保存在指定目录中,以便可以使用 from_pretrained() 方法重新加载。
这个类方法只是简单地调用 save_pretrained() 和 save_pretrained()。有关更多信息,请参阅上述方法的文档字符串。
将此实例序列化为 Python 字典。
to_json_file
< source >( json_file_path: typing.Union[str, os.PathLike] )
将此实例保存到 JSON 文件。
将此实例序列化为 JSON 字符串。
已弃用的处理器
所有处理器都遵循相同的架构,即 DataProcessor 的架构。处理器返回一个 InputExample 列表。这些 InputExample 可以被转换为 InputFeatures,以便输入到模型中。
序列分类数据集的数据转换器基类。
获取开发集的一组 InputExample。
get_example_from_tensor_dict
< source >( tensor_dict )
从带有 tensorflow 张量的字典中获取示例。
获取此数据集的标签列表。
获取测试集的一组 InputExample。
获取训练集的一组 InputExample。
一些 tensorflow_datasets 数据集的格式与 GLUE 数据集的格式不同。此方法将示例转换为正确的格式。
class transformers.InputExample
< source >( guid: str text_a: str text_b: typing.Optional[str] = None label: typing.Optional[str] = None )
用于简单序列分类的单个训练/测试示例。
将此实例序列化为 JSON 字符串。
class transformers.InputFeatures
< source >( input_ids: list attention_mask: typing.Optional[list[int]] = None token_type_ids: typing.Optional[list[int]] = None label: typing.Union[int, float, NoneType] = None )
一组数据特征。属性名称与模型的相应输入名称相同。
将此实例序列化为 JSON 字符串。
GLUE
通用语言理解评估(GLUE)是一个基准测试,用于评估模型在各种现有 NLU 任务上的性能。它与论文 GLUE: A multi-task benchmark and analysis platform for natural language understanding 一同发布。
该库共托管了 10 个用于以下任务的处理器:MRPC、MNLI、MNLI (mismatched)、CoLA、SST2、STSB、QQP、QNLI、RTE 和 WNLI。
这些处理器是
~data.processors.utils.MrpcProcessor
~data.processors.utils.MnliProcessor
~data.processors.utils.MnliMismatchedProcessor
~data.processors.utils.Sst2Processor
~data.processors.utils.StsbProcessor
~data.processors.utils.QqpProcessor
~data.processors.utils.QnliProcessor
~data.processors.utils.RteProcessor
~data.processors.utils.WnliProcessor
此外,以下方法可用于从数据文件中加载值,并将其转换为 InputExample 列表。
transformers.glue_convert_examples_to_features
< source >( examples: typing.Union[list[transformers.data.processors.utils.InputExample], ForwardRef('tf.data.Dataset')] tokenizer: PreTrainedTokenizer max_length: typing.Optional[int] = None task = None label_list = None output_mode = None )
将数据文件加载到 `InputFeatures` 列表中
XNLI
跨语言 NLI 语料库 (XNLI) 是一个评估跨语言文本表示质量的基准测试。XNLI 是一个基于 MultiNLI 的众包数据集:为 15 种不同语言(包括高资源语言如英语和低资源语言如斯瓦希里语)的文本对标注了文本蕴含注释。
它与论文 XNLI: Evaluating Cross-lingual Sentence Representations 一同发布。
此库托管了用于加载 XNLI 数据的处理器。
~data.processors.utils.XnliProcessor
请注意,由于测试集上提供了真实标签,评估是在测试集上进行的。
在 run_xnli.py 脚本中给出了使用这些处理器的示例。
SQuAD
斯坦福问答数据集 (SQuAD) 是一个评估模型问答性能的基准测试。有两个版本可用,v1.1 和 v2.0。第一个版本 (v1.1) 与论文 SQuAD: 100,000+ Questions for Machine Comprehension of Text 一同发布。第二个版本 (v2.0) 与论文 Know What You Don’t Know: Unanswerable Questions for SQuAD 一同发布。
这个库为这两个版本中的每一个都提供了一个处理器。
处理器
这些处理器是
~data.processors.utils.SquadV1Processor
~data.processors.utils.SquadV2Processor
它们都继承自抽象类 ~data.processors.utils.SquadProcessor
用于 SQuAD 数据集的处理器。由 SquadV1Processor 和 SquadV2Processor 覆盖,分别用于 SQuAD 的 1.1 版本和 2.0 版本。
get_dev_examples
< source >( data_dir filename = None )
从数据目录返回评估示例。
get_examples_from_dataset
< source >( dataset evaluate = False )
使用 TFDS 数据集创建 `SquadExample` 列表。
get_train_examples
< source >( data_dir filename = None )
从数据目录返回训练示例。
此外,可以使用以下方法将 SQuAD 示例转换为可作为模型输入的 `~data.processors.utils.SquadFeatures`。
transformers.squad_convert_examples_to_features
< source >( examples tokenizer max_seq_length doc_stride max_query_length is_training padding_strategy = 'max_length' return_dataset = False threads = 1 tqdm_enabled = True )
参数
- examples — `SquadExample` 的列表
- tokenizer — 一个 PreTrainedTokenizer 的子类的实例
- max_seq_length — 输入的最大序列长度。
- doc_stride — 当上下文过长并被分割成多个特征时使用的步长。
- max_query_length — 查询的最大长度。
- is_training — 是为模型评估还是模型训练创建特征。
- padding_strategy — 默认为“max_length”。使用哪种填充策略。
- return_dataset — 默认为 False。可以是 'pt' 或 'tf'。如果为 'pt':返回一个 torch.data.TensorDataset,如果为 'tf':返回一个 tf.data.Dataset。
- threads — 多处理线程。
将样本列表转换为可直接作为模型输入的特征列表。它依赖于具体模型,并利用分词器的许多功能来创建模型的输入。
示例
processor = SquadV2Processor()
examples = processor.get_dev_examples(data_dir)
features = squad_convert_examples_to_features(
examples=examples,
tokenizer=tokenizer,
max_seq_length=args.max_seq_length,
doc_stride=args.doc_stride,
max_query_length=args.max_query_length,
is_training=not evaluate,
)
这些处理器以及上述方法既可以用于包含数据的文件,也可以与 tensorflow_datasets 包一起使用。下面给出了一些示例。
用法示例
这是一个使用处理器和转换方法处理数据文件的示例
# Loading a V2 processor
processor = SquadV2Processor()
examples = processor.get_dev_examples(squad_v2_data_dir)
# Loading a V1 processor
processor = SquadV1Processor()
examples = processor.get_dev_examples(squad_v1_data_dir)
features = squad_convert_examples_to_features(
examples=examples,
tokenizer=tokenizer,
max_seq_length=max_seq_length,
doc_stride=args.doc_stride,
max_query_length=max_query_length,
is_training=not evaluate,
)
使用 tensorflow_datasets 和使用数据文件一样简单
# tensorflow_datasets only handle Squad V1.
tfds_examples = tfds.load("squad")
examples = SquadV1Processor().get_examples_from_dataset(tfds_examples, evaluate=evaluate)
features = squad_convert_examples_to_features(
examples=examples,
tokenizer=tokenizer,
max_seq_length=max_seq_length,
doc_stride=args.doc_stride,
max_query_length=max_query_length,
is_training=not evaluate,
)
另一个使用这些处理器的示例在 run_squad.py 脚本中给出。
< > 在 GitHub 上更新