流水线

精选Transformer

classv3.7
String name:curated_transformer
用于与Curated Transformer模型进行多任务学习的流水线组件

该流水线组件允许您在流水线中使用精选的Transformer模型集。spaCy Curated Transformers目前支持以下模型类型:

  • ALBERT
  • BERT
  • CamemBERT
  • RoBERTa
  • XLM-RoBERT

如果你想使用其他类型的模型,可以使用 spacy-transformers,它允许你将所有Hugging Face的transformer模型与spaCy结合使用。

通常您会通过Curated Transformer监听器层之一将下游组件连接到共享的Curated Transformer管道。其工作原理类似于spaCy的Tok2VecTok2VecListener子层。该组件将transformer的输出分配给Doc的扩展属性。要访问这些值,您可以使用自定义的Doc._.trf_data属性。

更多详情,请参阅使用文档

Assigned Attributes

该组件设置了以下 自定义扩展属性

位置
Doc._.trf_dataCurated Transformer outputs for the Doc object. DocTransformerOutput

配置与实现

默认配置由管道组件工厂定义,描述了组件应如何配置。您可以通过nlp.add_pipe中的config参数或在训练用的config.cfg中覆盖其设置。有关精选转换器架构及其参数和超参数的详细信息,请参阅模型架构文档。

设置描述
modelThe Thinc Model wrapping the transformer. Defaults to XlmrTransformer. Model
frozenIf True, the model’s weights are frozen and no backpropagation is performed. bool
all_layer_outputsIf True, the model returns the outputs of all the layers. Otherwise, only the output of the last layer is returned. This must be set to True if any of the pipe’s downstream listeners require the outputs of all transformer layers. bool
explosion/spacy-curated-transformers/main/spacy_curated_transformers/pipeline/transformer.py

CuratedTransformer.__init__ 方法

构建一个CuratedTransformer组件。一个或多个后续的spaCy组件可以在其模型中使用该transformer的输出作为特征,并将梯度反向传播到共享权重中。transformer的激活状态保存在Doc._.trf_data扩展属性中。您还可以提供一个回调函数来设置额外的注释。在您的应用程序中,通常会使用快捷方式并通过其字符串名称和nlp.add_pipe来实例化该组件。

名称描述
vocabThe shared vocabulary. Vocab
modelOne of the supported pre-trained transformer models. Model
仅关键字
nameThe component instance name. str
frozenIf True, the model’s weights are frozen and no backpropagation is performed. bool
all_layer_outputsIf True, the model returns the outputs of all the layers. Otherwise, only the output of the last layer is returned. This must be set to True if any of the pipe’s downstream listeners require the outputs of all transformer layers. bool

CuratedTransformer.__call__ 方法

将管道应用于单个文档。文档会被原地修改并返回。 这通常在调用nlp对象处理文本时自动完成, 所有管道组件会按顺序应用于Doc对象。 __call__pipe方法都会委托给 predictset_annotations方法。

名称描述
docThe document to process. Doc

CuratedTransformer.pipe 方法

将管道应用于文档流。这通常在调用nlp对象处理文本时自动完成,所有流水线组件会按顺序应用于Doc对象。无论是__call__还是pipe方法,最终都会委托给predictset_annotations方法执行。

名称描述
streamA stream of documents. Iterable[Doc]
仅关键字
batch_sizeThe number of documents to buffer. Defaults to 128. int

CuratedTransformer.initialize 方法

初始化组件用于训练并返回一个Optimizerget_examples应为一个返回可迭代Example对象的函数。至少需要提供一个示例。这些数据示例用于初始化组件模型,可以是完整训练数据或代表性样本。初始化过程包括验证网络、推断缺失形状以及根据数据设置标签方案。该方法通常由Language.initialize调用。

名称描述
get_examplesFunction that returns gold-standard annotations in the form of Example objects. Must contain at least one Example. Callable[[], Iterable[Example]]
仅关键字
nlpThe current nlp object. Defaults to None. Optional[Language]
encoder_loaderInitialization callback for the transformer model. Optional[Callable]
piece_loaderInitialization callback for the input piece encoder. Optional[Callable]

CuratedTransformer.predict 方法

在不修改的情况下,将组件的模型应用于一批Doc对象。

名称描述
docsThe documents to predict. Iterable[Doc]

CuratedTransformer.set_annotations 方法

将提取的特征分配给Doc对象。默认情况下,DocTransformerOutput对象会被写入Doc._.trf_data属性。如果提供了set_extra_annotations回调函数,则会调用该函数。

名称描述
docsThe documents to modify. Iterable[Doc]
scoresThe scores to set, produced by CuratedTransformer.predict.

CuratedTransformer.update 方法

准备更新transformer。

Tok2Vec组件类似,CuratedTransformer组件的特殊之处在于它不接收"黄金标准"标注来计算权重更新。transformer数据的最优输出是未知的;它是网络中的一个隐藏层,通过从输出层反向传播来更新。

因此,CuratedTransformer组件在其自身的update方法中不会执行权重更新。相反,它会运行其transformer模型,并通过transformer监听器子层将输出和反向传播回调传递给任何已连接的下游组件。如果存在多个监听器,最后一层实际上会反向传播到transformer并调用优化器,而其他层仅简单地累加梯度。

名称描述
examplesA batch of Example objects. Only the Example.predicted Doc object is used, the reference Doc is ignored. Iterable[Example]
仅关键字
dropThe dropout rate. float
sgdAn optimizer. Will be created via create_optimizer if not set. Optional[Optimizer]
lossesOptional record of the loss during training. Updated using the component name as the key. Optional[Dict[str, float]]

CuratedTransformer.create_optimizer 方法

为管道组件创建一个优化器。

名称描述

CuratedTransformer.use_params 方法上下文管理器

修改管道的模型以使用给定的参数值。在上下文结束时,原始参数将被恢复。

名称描述
paramsThe parameter values to use in the model. dict

CuratedTransformer.to_disk 方法

将管道序列化到磁盘。

名称描述
pathA path to a directory, which will be created if it doesn’t exist. Paths may be either strings or Path-like objects. Union[str,Path]
仅关键字
excludeString names of serialization fields to exclude. Iterable[str]

CuratedTransformer.from_disk 方法

从磁盘加载管道。就地修改对象并返回它。

名称描述
pathA path to a directory. Paths may be either strings or Path-like objects. Union[str,Path]
仅关键字
excludeString names of serialization fields to exclude. Iterable[str]

CuratedTransformer.to_bytes 方法

将管道序列化为字节串。

名称描述
仅关键字
excludeString names of serialization fields to exclude. Iterable[str]

CuratedTransformer.from_bytes 方法

从字节串加载管道。原地修改对象并返回它。

名称描述
bytes_dataThe data to load from. bytes
仅关键字
excludeString names of serialization fields to exclude. Iterable[str]

序列化字段

在序列化过程中,spaCy会导出多个用于恢复对象不同方面的数据字段。如果需要,您可以通过exclude参数传入字符串名称来将它们排除在序列化之外。

名称描述
vocabThe shared Vocab.
cfgThe config file. You usually don’t want to exclude this.
modelThe binary model data. You usually don’t want to exclude this.

DocTransformerOutput 数据类

为单个Doc对象精选的Transformer输出。存储由transformer为每个片段标识符生成的密集表示。片段标识符按词符分组。该类的实例通常会被赋值给Doc._.trf_data扩展属性。

名称描述
all_outputsList of Ragged tensors that correspends to outputs of the different transformer layers. Each tensor element corresponds to a piece identifier’s representation. List[Ragged]
last_layer_onlyIf only the last transformer layer’s outputs are preserved. bool

DocTransformerOutput.embedding_layer 属性

返回transformer嵌入层的输出,如果last_layer_onlyTrue则返回None

名称描述

DocTransformerOutput.last_hidden_layer_state 属性

返回transformer最后一层隐藏层的输出。

名称描述

DocTransformerOutput.all_hidden_layer_states 属性

返回所有transformer层(不包括嵌入层)的输出。

名称描述

DocTransformerOutput.num_outputs 属性

返回存储在DocTransformerOutput实例中的层输出数量(包括嵌入层)。

名称描述

Span Getters

Span获取器是接收一批Doc对象并返回每个文档中待处理Span对象列表的函数。该功能用于通过将长文档切割成较小序列来管理长文档处理,这些Span允许重叠,也可以忽略Doc中不相关的部分。Span获取器可在配置文件的[components.transformer.model.with_spans]模块中引用,以自定义transformer处理的序列。

名称描述
docsA batch of Doc objects. Iterable[Doc]

WithStridedSpans.v1 注册函数

为跨步跨度创建跨度获取器。如果将windowstride设置为相同值,这些跨度将覆盖每个标记一次。将stride设置为小于window将允许重叠,这样某些标记会被计算两次。这可能是可取的,因为它允许所有标记同时拥有左右上下文。

名称描述
windowThe window size. int
strideThe stride size. int

模型加载器

精选Transformer模型在创建管道时会使用默认超参数和随机初始化权重。要将现有预训练模型的权重加载到管道中,可以使用以下加载回调函数之一。预训练模型必须与管道使用的模型具有相同的超参数。

HFTransformerEncoderLoader.v1 registered_function

构建一个回调函数,用于使用来自相应HuggingFace模型的权重初始化受支持的transformer模型。

名称描述
nameName of the HuggingFace model. str
revisionName of the model revision/branch. str

PyTorchCheckpointLoader.v1 registered_function

构建一个回调函数,用于从PyTorch检查点初始化一个支持的transformer模型权重。

名称描述
pathPath to the PyTorch checkpoint. Path

分词器加载器

精选的Transformer模型必须与spaCy管道中匹配的分词器(片段编码器)模型配对使用。与transformer模型一样,分词器在管道创建时使用空词汇表构建 - 在训练/推理使用前需要通过适当的加载器进行初始化。

ByteBPELoader.v1 registered_function

构建一个回调函数,用于初始化Byte-BPE分词编码器模型。

名称描述
vocab_pathPath to the vocabulary file. Path
merges_pathPath to the merges file. Path

CharEncoderLoader.v1 registered_function

构建一个回调函数,用于初始化字符片段编码器模型。

名称描述
pathPath to the serialized character model. Path
bos_piecePiece used as a beginning-of-sentence token. Defaults to "[BOS]". str
eos_piecePiece used as a end-of-sentence token. Defaults to "[EOS]". str
unk_piecePiece used as a stand-in for unknown tokens. Defaults to "[UNK]". str
normalizeUnicode normalization form to use. Defaults to "NFKC". str

HFPieceEncoderLoader.v1 registered_function

构建一个回调函数,用于初始化HuggingFace分词编码器模型。需与HuggingFace模型加载器配合使用。

名称描述
nameName of the HuggingFace model. str
revisionName of the model revision/branch. str

SentencepieceLoader.v1 registered_function

构建一个回调函数,用于初始化SentencePiece分词编码器模型。

名称描述
pathPath to the serialized SentencePiece model. Path

WordpieceLoader.v1 注册函数

构建一个回调函数,用于初始化WordPiece分词编码器模型。

名称描述
pathPath to the serialized WordPiece model. Path

回调函数

gradual_transformer_unfreezing.v1 注册函数

构建一个回调函数,可用于在训练过程中逐步解冻一个或多个Transformer组件的权重。这可用于防止微调期间的灾难性遗忘。

名称描述
target_pipesA dictionary whose keys and values correspond to the names of Transformer components and the training step at which they should be unfrozen respectively. Dict[str, int]