处理器
在Transformers库中,Processors可以指两种不同的东西:
多模态处理器
任何多模态模型都需要一个对象来编码或解码包含多种模态(如文本、视觉和音频)的数据。这是通过称为处理器的对象来处理的,这些处理器将两个或多个处理对象(如用于文本模态的分词器、用于视觉的图像处理器和用于音频的特征提取器)组合在一起。
这些处理器继承自以下实现了保存和加载功能的基类:
这是一个用于为所有处理器类提供保存/加载功能的混入。
apply_chat_template
< source >( conversation: typing.List[typing.Dict[str, str]] chat_template: typing.Optional[str] = None tokenize: bool = False **kwargs )
类似于分词器上的apply_chat_template
方法,此方法将Jinja模板应用于输入对话,将其转换为单个可标记的字符串。
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 上的模型仓库中的预训练特征提取器的 模型 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 ) → List[str]
对vlm的输出进行后处理以解码文本。
将可选的位置参数与处理器类中optional_call_args
中的相应名称按传递给处理器调用的顺序进行匹配。
请注意,这应该仅在具有特殊参数的处理器中的__call__
方法中使用。特殊参数是指那些不是text
、images
、audio
,也不是videos
,同时也不会传递给分词器、图像处理器等的参数。此类处理器的示例包括:
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,
)
push_to_hub
< source >( repo_id: str use_temp_dir: typing.Optional[bool] = None commit_message: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None max_shard_size: typing.Union[int, str, NoneType] = '5GB' create_pr: bool = False safe_serialization: bool = True revision: str = None commit_description: str = None tags: typing.Optional[typing.List[str]] = None **deprecated_kwargs )
参数
- repo_id (
str
) — 您想要推送处理器的仓库名称。当推送到特定组织时,它应包含您的组织名称。 - use_temp_dir (
bool
, optional) — 是否使用临时目录来存储推送到 Hub 之前保存的文件。 如果没有名为repo_id
的目录,则默认为True
,否则为False
。 - commit_message (
str
, 可选) — 推送时提交的消息。默认为"Upload processor"
. - private (
bool
, 可选) — 是否将仓库设为私有。如果为None
(默认值),仓库将为公开,除非组织的默认设置为私有。如果仓库已存在,则忽略此值。 - token (
bool
或str
, 可选) — 用于远程文件的HTTP承载授权的令牌。如果为True
,将使用运行huggingface-cli login
时生成的令牌(存储在~/.huggingface
中)。如果未指定repo_url
,则默认为True
。 - max_shard_size (
int
或str
, 可选, 默认为"5GB"
) — 仅适用于模型。分片前的检查点的最大大小。分片后的检查点大小将小于此大小。如果以字符串形式表示,需要是数字后跟单位(如"5MB"
)。我们将其默认设置为"5GB"
,以便用户可以在免费层级的Google Colab实例上轻松加载模型,而不会出现CPU内存不足的问题。 - create_pr (
bool
, 可选, 默认为False
) — 是否创建一个带有上传文件的PR或直接提交。 - safe_serialization (
bool
, optional, defaults toTrue
) — 是否将模型权重转换为safetensors格式以实现更安全的序列化。 - revision (
str
, optional) — 将上传的文件推送到的分支. - commit_description (
str
, optional) — 将要创建的提交的描述 - 标签 (
List[str]
, 可选) — 推送到Hub的标签列表。
将处理器文件上传到 🤗 模型中心。
示例:
from transformers import 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' )
使用给定的自动类注册此类。这应该仅用于自定义特征提取器,因为库中的特征提取器已经通过AutoProcessor
进行了映射。
此API是实验性的,在接下来的版本中可能会有一些轻微的破坏性更改。
save_pretrained
< source >( 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数据集不同。此方法将示例转换为正确的格式。
类 transformers.InputExample
< source >( guid: str text_a: str text_b: typing.Optional[str] = None label: typing.Optional[str] = None )
用于简单序列分类的单个训练/测试示例。
将此实例序列化为JSON字符串。
类 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)是一个评估模型在各种现有自然语言理解任务中表现的基准。它与论文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 >( 示例: typing.Union[typing.List[transformers.data.processors.utils.InputExample], ForwardRef('tf.data.Dataset')] 分词器: PreTrainedTokenizer 最大长度: typing.Optional[int] = None 任务 = None 标签列表 = None 输出模式 = 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版本。
获取开发示例
< source >( data_dir filename = 无 )
返回数据目录中的评估示例。
get_examples_from_dataset
< source >( 数据集 评估 = 否 )
使用TFDS数据集创建一个SquadExample
列表。
获取训练示例
< source >( data_dir filename = 无 )
从数据目录返回训练示例。
此外,可以使用以下方法将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 )
参数
- 示例 —
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脚本中给出。
< > Update on GitHub