Transformers 文档
处理器
并获得增强的文档体验
开始使用
处理器
在 Transformers 库中,“处理器”可以指代两种不同的事物
多模态处理器
任何多模态模型都需要一个对象来编码或解码组合了多种模态的数据(包括文本、视觉和音频)。这由称为“处理器”的对象处理,这些处理器将两个或多个处理对象组合在一起,例如分词器(用于文本模态)、图像处理器(用于视觉)和特征提取器(用于音频)。
这些处理器继承自以下基类,该基类实现了保存和加载功能
这是一个混入类,用于为所有处理器类提供保存/加载功能。
apply_chat_template
< source >( conversation: typing.Union[typing.List[typing.Dict[str, str]], typing.List[typing.List[typing.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”, “image”: “https://www.ilankelman.org/stopsigns/australia.jpg”}, {“type”: “text”, “text”: “Please describe this image in detail.”}, ], }, ]
from_args_and_dict
< source >( args processor_dict: typing.Dict[str, typing.Any] **kwargs ) → ~processing_utils.ProcessingMixin
从 Python 参数字典实例化 ~processing_utils.ProcessingMixin
类型。
from_pretrained
< source >( pretrained_model_name_or_path: typing.Union[str, os.PathLike] cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[str, bool, NoneType] = None revision: str = 'main' **kwargs )
参数
- pretrained_model_name_or_path (
str
或os.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
< source >( 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
< source >( generated_outputs skip_special_tokens = True **kwargs ) → List[str]
参数
- generated_outputs (
torch.Tensor
或np.ndarray
) — 模型generate
函数的输出。输出应为形状为(batch_size, sequence_length)
或(sequence_length,)
的张量。 - skip_special_tokens (
bool
, 可选, 默认为True
) — 是否移除输出中的特殊 token。传递给 tokenizer 的batch_decode
方法的参数。 - **kwargs — 要传递给 tokenizer 的
batch_decode method
的其他参数。
返回值
List[str]
解码后的文本。
后处理 vlm 的输出以解码文本。
将可选的位置参数与其在处理器类中的 optional_call_args
中的对应名称匹配,按照它们传递给处理器调用的顺序排列。
请注意,这应仅在具有特殊参数的处理器的 __call__
方法中使用。特殊参数是不属于 text
、images
、audio
或 videos
,但也不传递给 tokenizer、图像处理器等的参数。此类处理器的示例包括:
CLIPSegProcessor
LayoutLMv2Processor
OwlViTProcessor
另请注意,现在不推荐通过位置传递给处理器调用,并且将来版本中将不允许这样做。我们仅为了向后兼容性而保留此功能。
示例:假设处理器类具有 optional_call_args = ["arg_name_1", "arg_name_2"]
。
我们定义调用方法为:
def __call__(
self,
text: str,
images: Optional[ImageInput] = None,
*arg,
audio=None,
videos=None,
)
然后,如果我们像这样调用处理器:
images = [...]
processor("What is common in these images?", images, arg_value_1, arg_value_2)
self._merge_kwargs
push_to_hub
< source >( repo_id: str use_temp_dir: typing.Optional[bool] = None commit_message: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None max_shard_size: typing.Union[int, str, NoneType] = '5GB' create_pr: bool = False safe_serialization: bool = True revision: str = None commit_description: str = None tags: typing.Optional[typing.List[str]] = None **deprecated_kwargs )
参数
- repo_id (
str
) — 您想要将处理器推送到的仓库的名称。当推送到给定的组织时,它应该包含您的组织名称。 - use_temp_dir (
bool
, 可选) — 是否使用临时目录来存储在推送到 Hub 之前保存的文件。如果不存在像repo_id
这样的目录,则默认为True
,否则为False
。 - commit_message (
str
, 可选) — 推送时提交的消息。默认为"Upload processor"
。 - private (
bool
, 可选) — 是否将仓库设为私有。如果为None
(默认),则仓库将是公开的,除非组织的默认设置为私有。如果仓库已存在,则忽略此值。 - token (
bool
或str
, 可选) — 用作远程文件的 HTTP bearer 授权的 token。如果为True
,将使用运行huggingface-cli login
时生成的 token (存储在~/.huggingface
中)。如果未指定repo_url
,则默认为True
。 - max_shard_size (
int
或str
, 可选, 默认为"5GB"
) — 仅适用于模型。分片之前的检查点最大大小。然后,检查点分片的大小将小于此大小。如果表示为字符串,则需要是数字后跟单位(例如"5MB"
)。我们将其默认为"5GB"
,以便用户可以在免费层的 Google Colab 实例上轻松加载模型,而不会出现任何 CPU OOM 问题。 - create_pr (
bool
, 可选, 默认为False
) — 是否创建包含上传文件的 PR 或直接提交。 - safe_serialization (
bool
, 可选, 默认为True
) — 是否将模型权重转换为 safetensors 格式以实现更安全的序列化。 - revision (
str
, 可选) — 要将上传的文件推送到的分支。 - commit_description (
str
, 可选) — 将要创建的提交的描述 - tags (
List[str]
, 可选) — 要推送到 Hub 的标签列表。
将处理器文件上传到 🤗 Model 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
< source >( auto_class = 'AutoProcessor' )
将此类注册到给定的 auto class。这应该仅用于自定义特征提取器,因为库中的特征提取器已与 AutoProcessor
映射。
此 API 是实验性的,并且在接下来的版本中可能会有一些小的重大更改。
save_pretrained
< source >( save_directory push_to_hub: bool = False **kwargs )
参数
- save_directory (
str
或os.PathLike
) — 将在其中保存特征提取器 JSON 文件和 tokenizer 文件的目录(如果目录不存在,则将创建目录)。 - push_to_hub (
bool
, 可选, 默认为False
) — 是否在保存模型后将其推送到 Hugging Face 模型 Hub。您可以使用repo_id
指定要推送到的仓库(默认为您命名空间中save_directory
的名称)。 - kwargs (
Dict[str, Any]
, 可选) — 传递给 push_to_hub() 方法的其他关键字参数。
将此处理器的属性(特征提取器、tokenizer...)保存在指定目录中,以便可以使用 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: typing.List[int] attention_mask: typing.Optional[typing.List[int]] = None token_type_ids: typing.Optional[typing.List[int]] = None label: typing.Union[int, float, NoneType] = None )
一组数据特征。属性名称与模型的相应输入名称相同。
将此实例序列化为 JSON 字符串。
GLUE
通用语言理解评估 (GLUE) 是一个基准,用于评估模型在各种现有 NLU 任务中的性能。它与论文 GLUE:自然语言理解的多任务基准和分析平台 一起发布
此库总共托管了 10 个用于以下任务的处理器:MRPC、MNLI、MNLI(不匹配)、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[typing.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 — 多处理线程。
将示例列表转换为可以直接作为模型输入的功能列表。它依赖于模型,并利用 tokenizer 的许多功能来创建模型的输入。
示例
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 上更新