2020-07-29 09:36:42 +00:00
---
title: Transformer
teaser: Pipeline component for multi-task learning with transformer models
tag: class
source: github.com/explosion/spacy-transformers/blob/master/spacy_transformers/pipeline_component.py
new: 3
api_base_class: /api/pipe
api_string_name: transformer
---
> #### Installation
>
> ```bash
2020-10-08 08:58:50 +00:00
> $ pip install -U %%SPACY_PKG_NAME[transformers] %%SPACY_PKG_FLAGS
2020-07-29 09:36:42 +00:00
> ```
< Infobox title = "Important note" variant = "warning" >
This component is available via the extension package
[`spacy-transformers` ](https://github.com/explosion/spacy-transformers ). It
exposes the component via entry points, so if you have the package installed,
using `factory = "transformer"` in your
[training config ](/usage/training#config ) or `nlp.add_pipe("transformer")` will
work out-of-the-box.
< / Infobox >
2020-08-27 07:43:32 +00:00
This pipeline component lets you use transformer models in your pipeline. It
supports all models that are available via the
2020-08-09 22:42:26 +00:00
[HuggingFace `transformers` ](https://huggingface.co/transformers ) library.
Usually you will connect subsequent components to the shared transformer using
2020-08-26 11:31:01 +00:00
the [TransformerListener ](/api/architectures#TransformerListener ) layer. This
2020-08-09 22:42:26 +00:00
works similarly to spaCy's [Tok2Vec ](/api/tok2vec ) component and
2020-09-12 15:05:10 +00:00
[Tok2VecListener ](/api/architectures/#Tok2VecListener ) sublayer.
2020-08-09 22:01:38 +00:00
2020-08-31 12:40:55 +00:00
The component assigns the output of the transformer to the `Doc` 's extension
attributes. We also calculate an alignment between the word-piece tokens and the
spaCy tokenization, so that we can use the last hidden states to set the
`Doc.tensor` attribute. When multiple word-piece tokens align to the same spaCy
token, the spaCy token receives the sum of their values. To access the values,
2021-09-01 10:09:39 +00:00
you can use the custom [`Doc._.trf_data` ](#assigned-attributes ) attribute. The
2020-08-31 12:40:55 +00:00
package also adds the function registries [`@span_getters` ](#span_getters ) and
[`@annotation_setters` ](#annotation_setters ) with several built-in registered
functions. For more details, see the
[usage documentation ](/usage/embeddings-transformers ).
2020-07-29 09:36:42 +00:00
2021-09-01 10:09:39 +00:00
## Assigned Attributes {#assigned-attributes}
The component sets the following
[custom extension attribute ](/usage/processing-pipeline#custom-components-attributes ):
| Location | Value |
| ---------------- | ------------------------------------------------------------------------ |
| `Doc._.trf_data` | Transformer tokens and outputs for the `Doc` object. ~~TransformerData~~ |
2020-07-29 09:36:42 +00:00
## Config and implementation {#config}
The default config is defined by the pipeline component factory and describes
how the component should be configured. You can override its settings via the
`config` argument on [`nlp.add_pipe` ](/api/language#add_pipe ) or in your
[`config.cfg` for training ](/usage/training#config ). See the
2020-08-27 17:24:44 +00:00
[model architectures ](/api/architectures#transformers ) documentation for details
on the transformer architectures and their arguments and hyperparameters.
2020-07-29 09:36:42 +00:00
> #### Example
>
> ```python
2021-01-21 15:18:03 +00:00
> from spacy_transformers import Transformer
> from spacy_transformers.pipeline_component import DEFAULT_CONFIG
2020-07-29 09:36:42 +00:00
>
2021-01-21 15:18:03 +00:00
> nlp.add_pipe("transformer", config=DEFAULT_CONFIG["transformer"])
2020-07-29 09:36:42 +00:00
> ```
2020-11-19 13:11:38 +00:00
| Setting | Description |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `max_batch_items` | Maximum size of a padded batch. Defaults to `4096` . ~~int~~ |
| `set_extra_annotations` | Function that takes a batch of `Doc` objects and transformer outputs to set additional annotations on the `Doc` . The `Doc._.trf_data` attribute is set prior to calling the callback. Defaults to `null_annotation_setter` (no additional annotations). ~~Callable[[List[Doc], FullTransformerBatch], None]~~ |
| `model` | The Thinc [`Model` ](https://thinc.ai/docs/api-model ) wrapping the transformer. Defaults to [TransformerModel ](/api/architectures#TransformerModel ). ~~Model[List[Doc], FullTransformerBatch]~~ |
2020-07-29 09:36:42 +00:00
```python
https://github.com/explosion/spacy-transformers/blob/master/spacy_transformers/pipeline_component.py
```
## Transformer.\_\_init\_\_ {#init tag="method"}
> #### Example
>
> ```python
> # Construction via add_pipe with default model
> trf = nlp.add_pipe("transformer")
>
2020-07-29 13:14:07 +00:00
> # Construction via add_pipe with custom config
> config = {
> "model": {
2021-10-18 12:15:06 +00:00
> "@architectures": "spacy-transformers.TransformerModel.v3",
2020-07-29 13:14:07 +00:00
> "name": "bert-base-uncased",
2021-10-18 12:15:06 +00:00
> "tokenizer_config": {"use_fast": True},
> "transformer_config": {"output_attentions": True},
> "mixed_precision": True,
> "grad_scaler_config": {"init_scale": 32768}
2020-07-29 13:14:07 +00:00
> }
> }
2020-07-29 09:36:42 +00:00
> trf = nlp.add_pipe("transformer", config=config)
>
> # Construction from class
> from spacy_transformers import Transformer
> trf = Transformer(nlp.vocab, model)
> ```
2020-08-09 22:01:38 +00:00
Construct a `Transformer` component. One or more subsequent spaCy components can
use the transformer outputs as features in its model, with gradients
backpropagated to the single shared weights. The activations from the
2021-09-01 10:09:39 +00:00
transformer are saved in the [`Doc._.trf_data` ](#assigned-attributes ) extension
2020-08-31 12:40:55 +00:00
attribute. You can also provide a callback to set additional annotations. In
your application, you would normally use a shortcut for this and instantiate the
component using its string name and [`nlp.add_pipe` ](/api/language#create_pipe ).
2020-08-27 17:24:44 +00:00
2020-09-09 08:31:03 +00:00
| Name | Description |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `vocab` | The shared vocabulary. ~~Vocab~~ |
| `model` | The Thinc [`Model` ](https://thinc.ai/docs/api-model ) wrapping the transformer. Usually you will want to use the [TransformerModel ](/api/architectures#TransformerModel ) layer for this. ~~Model[List[Doc], FullTransformerBatch]~~ |
| `set_extra_annotations` | Function that takes a batch of `Doc` objects and transformer outputs and stores the annotations on the `Doc` . The `Doc._.trf_data` attribute is set prior to calling the callback. By default, no additional annotations are set. ~~Callable[[List[Doc], FullTransformerBatch], None]~~ |
| _keyword-only_ | |
| `name` | String name of the component instance. Used to add entries to the `losses` during training. ~~str~~ |
| `max_batch_items` | Maximum size of a padded batch. Defaults to `128*32` . ~~int~~ |
2020-07-29 09:36:42 +00:00
2020-07-29 13:14:07 +00:00
## Transformer.\_\_call\_\_ {#call tag="method"}
Apply the pipe to one document. The document is modified in place, and returned.
This usually happens under the hood when the `nlp` object is called on a text
and all pipeline components are applied to the `Doc` in order. Both
[`__call__` ](/api/transformer#call ) and [`pipe` ](/api/transformer#pipe ) delegate
to the [`predict` ](/api/transformer#predict ) and
[`set_annotations` ](/api/transformer#set_annotations ) methods.
> #### Example
>
> ```python
> doc = nlp("This is a sentence.")
> trf = nlp.add_pipe("transformer")
> # This usually happens under the hood
> processed = transformer(doc)
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | -------------------------------- |
| `doc` | The document to process. ~~Doc~~ |
| **RETURNS** | The processed document. ~~Doc~~ |
2020-07-29 13:14:07 +00:00
## Transformer.pipe {#pipe tag="method"}
Apply the pipe to a stream of documents. This usually happens under the hood
when the `nlp` object is called on a text and all pipeline components are
applied to the `Doc` in order. Both [`__call__` ](/api/transformer#call ) and
[`pipe` ](/api/transformer#pipe ) delegate to the
[`predict` ](/api/transformer#predict ) and
[`set_annotations` ](/api/transformer#set_annotations ) methods.
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
> for doc in trf.pipe(docs, batch_size=50):
> pass
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------------- | ------------------------------------------------------------- |
| `stream` | A stream of documents. ~~Iterable[Doc]~~ |
| _keyword-only_ | |
| `batch_size` | The number of documents to buffer. Defaults to `128` . ~~int~~ |
| **YIELDS** | The processed documents in order. ~~Doc~~ |
2020-07-29 13:14:07 +00:00
2020-09-28 19:35:09 +00:00
## Transformer.initialize {#initialize tag="method"}
2020-07-29 13:14:07 +00:00
2020-08-11 18:57:23 +00:00
Initialize the component for training and return an
[`Optimizer` ](https://thinc.ai/docs/api-optimizers ). `get_examples` should be a
2022-08-03 14:53:02 +00:00
function that returns an iterable of [`Example` ](/api/example ) objects. **At
least one example should be supplied.** The data examples are used to
**initialize the model** of the component and can either be the full training
data or a representative sample. Initialization includes validating the network,
2020-08-11 18:57:23 +00:00
[inferring missing shapes ](https://thinc.ai/docs/usage-models#validation ) and
2020-09-29 14:59:21 +00:00
setting up the label scheme based on the data. This method is typically called
by [`Language.initialize` ](/api/language#initialize ).
2020-07-29 13:14:07 +00:00
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
2022-08-03 14:53:02 +00:00
> trf.initialize(lambda: examples, nlp=nlp)
2020-07-29 13:14:07 +00:00
> ```
2022-08-03 14:53:02 +00:00
| Name | Description |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get_examples` | Function that returns gold-standard annotations in the form of [`Example` ](/api/example ) objects. Must contain at least one `Example` . ~~Callable[[], Iterable[Example]]~~ |
| _keyword-only_ | |
| `nlp` | The current `nlp` object. Defaults to `None` . ~~Optional[Language]~~ |
2020-07-29 13:14:07 +00:00
## Transformer.predict {#predict tag="method"}
2020-09-28 14:50:15 +00:00
Apply the component's model to a batch of [`Doc` ](/api/doc ) objects without
2020-08-10 11:45:22 +00:00
modifying them.
2020-07-29 13:14:07 +00:00
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
> scores = trf.predict([doc1, doc2])
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ------------------------------------------- |
| `docs` | The documents to predict. ~~Iterable[Doc]~~ |
| **RETURNS** | The model's prediction for each document. |
2020-07-29 13:14:07 +00:00
## Transformer.set_annotations {#set_annotations tag="method"}
2020-09-28 14:50:15 +00:00
Assign the extracted features to the `Doc` objects. By default, the
2020-08-09 22:01:38 +00:00
[`TransformerData` ](/api/transformer#transformerdata ) object is written to the
2021-09-01 10:09:39 +00:00
[`Doc._.trf_data` ](#assigned-attributes ) attribute. Your `set_extra_annotations`
2020-08-31 12:40:55 +00:00
callback is then called, if provided.
2020-07-29 13:14:07 +00:00
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
> scores = trf.predict(docs)
> trf.set_annotations(docs, scores)
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------- | ----------------------------------------------------- |
| `docs` | The documents to modify. ~~Iterable[Doc]~~ |
| `scores` | The scores to set, produced by `Transformer.predict` . |
2020-07-29 13:14:07 +00:00
## Transformer.update {#update tag="method"}
2020-08-09 22:01:38 +00:00
Prepare for an update to the transformer. Like the [`Tok2Vec` ](/api/tok2vec )
component, the `Transformer` component is unusual in that it does not receive
"gold standard" annotations to calculate a weight update. The optimal output of
the transformer data is unknown – it's a hidden layer inside the network that is
updated by backpropagating from output layers.
The `Transformer` component therefore does **not** perform a weight update
during its own `update` method. Instead, it runs its transformer model and
communicates the output and the backpropagation callback to any **downstream
components** that have been connected to it via the
2020-08-26 11:31:01 +00:00
[TransformerListener ](/api/architectures#TransformerListener ) sublayer. If there
2020-08-09 22:01:38 +00:00
are multiple listeners, the last layer will actually backprop to the transformer
and call the optimizer, while the others simply increment the gradients.
2020-07-29 13:14:07 +00:00
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
2020-09-28 19:35:09 +00:00
> optimizer = nlp.initialize()
2020-07-29 13:14:07 +00:00
> losses = trf.update(examples, sgd=optimizer)
> ```
2021-04-26 14:53:53 +00:00
| Name | Description |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `examples` | A batch of [`Example` ](/api/example ) objects. Only the [`Example.predicted` ](/api/example#predicted ) `Doc` object is used, the reference `Doc` is ignored. ~~Iterable[Example]~~ |
| _keyword-only_ | |
| `drop` | The dropout rate. ~~float~~ |
| `sgd` | An optimizer. Will be created via [`create_optimizer` ](#create_optimizer ) if not set. ~~Optional[Optimizer]~~ |
| `losses` | Optional record of the loss during training. Updated using the component name as the key. ~~Optional[Dict[str, float]]~~ |
| **RETURNS** | The updated `losses` dictionary. ~~Dict[str, float]~~ |
2020-07-29 13:14:07 +00:00
## Transformer.create_optimizer {#create_optimizer tag="method"}
Create an optimizer for the pipeline component.
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
> optimizer = trf.create_optimizer()
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ---------------------------- |
| **RETURNS** | The optimizer. ~~Optimizer~~ |
2020-07-29 13:14:07 +00:00
## Transformer.use_params {#use_params tag="method, contextmanager"}
2020-09-28 14:50:15 +00:00
Modify the pipe's model to use the given parameter values. At the end of the
2020-07-29 13:14:07 +00:00
context, the original parameters are restored.
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
> with trf.use_params(optimizer.averages):
> trf.to_disk("/best_model")
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------- | -------------------------------------------------- |
| `params` | The parameter values to use in the model. ~~dict~~ |
2020-07-29 13:14:07 +00:00
## Transformer.to_disk {#to_disk tag="method"}
Serialize the pipe to disk.
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
> trf.to_disk("/path/to/transformer")
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `path` | A 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]~~ |
| _keyword-only_ | |
| `exclude` | String names of [serialization fields ](#serialization-fields ) to exclude. ~~Iterable[str]~~ |
2020-07-29 13:14:07 +00:00
## Transformer.from_disk {#from_disk tag="method"}
Load the pipe from disk. Modifies the object in place and returns it.
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
> trf.from_disk("/path/to/transformer")
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------------- | ----------------------------------------------------------------------------------------------- |
| `path` | A path to a directory. Paths may be either strings or `Path` -like objects. ~~Union[str, Path]~~ |
| _keyword-only_ | |
| `exclude` | String names of [serialization fields ](#serialization-fields ) to exclude. ~~Iterable[str]~~ |
| **RETURNS** | The modified `Transformer` object. ~~Transformer~~ |
2020-07-29 13:14:07 +00:00
## Transformer.to_bytes {#to_bytes tag="method"}
> #### Example
>
> ```python
> trf = nlp.add_pipe("transformer")
> trf_bytes = trf.to_bytes()
> ```
Serialize the pipe to a bytestring.
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------------- | ------------------------------------------------------------------------------------------- |
| _keyword-only_ | |
| `exclude` | String names of [serialization fields ](#serialization-fields ) to exclude. ~~Iterable[str]~~ |
| **RETURNS** | The serialized form of the `Transformer` object. ~~bytes~~ |
2020-07-29 13:14:07 +00:00
## Transformer.from_bytes {#from_bytes tag="method"}
Load the pipe from a bytestring. Modifies the object in place and returns it.
> #### Example
>
> ```python
> trf_bytes = trf.to_bytes()
> trf = nlp.add_pipe("transformer")
> trf.from_bytes(trf_bytes)
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------------- | ------------------------------------------------------------------------------------------- |
| `bytes_data` | The data to load from. ~~bytes~~ |
| _keyword-only_ | |
| `exclude` | String names of [serialization fields ](#serialization-fields ) to exclude. ~~Iterable[str]~~ |
| **RETURNS** | The `Transformer` object. ~~Transformer~~ |
2020-07-29 13:14:07 +00:00
## Serialization fields {#serialization-fields}
During serialization, spaCy will export several data fields used to restore
different aspects of the object. If needed, you can exclude them from
serialization by passing in the string names via the `exclude` argument.
> #### Example
>
> ```python
> data = trf.to_disk("/path", exclude=["vocab"])
> ```
| Name | Description |
| ------- | -------------------------------------------------------------- |
| `vocab` | The shared [`Vocab` ](/api/vocab ). |
| `cfg` | The config file. You usually don't want to exclude this. |
| `model` | The binary model data. You usually don't want to exclude this. |
2020-07-29 09:36:42 +00:00
## TransformerData {#transformerdata tag="dataclass"}
2020-08-16 13:56:32 +00:00
Transformer tokens and outputs for one `Doc` object. The transformer models
return tensors that refer to a whole padded batch of documents. These tensors
are wrapped into the
[FullTransformerBatch ](/api/transformer#fulltransformerbatch ) object. The
`FullTransformerBatch` then splits out the per-document data, which is handled
2020-08-27 17:24:44 +00:00
by this class. Instances of this class are typically assigned to the
2021-09-01 10:09:39 +00:00
[`Doc._.trf_data` ](/api/transformer#assigned-attributes ) extension attribute.
2020-08-16 13:56:32 +00:00
2021-10-18 12:16:58 +00:00
| Name | Description |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tokens` | A slice of the tokens data produced by the tokenizer. This may have several fields, including the token IDs, the texts and the attention mask. See the [`transformers.BatchEncoding` ](https://huggingface.co/transformers/main_classes/tokenizer.html#transformers.BatchEncoding ) object for details. ~~dict~~ |
| `model_output` | The model output from the transformer model, determined by the model and transformer config. New in `spacy-transformers` v1.1.0. ~~transformers.file_utils.ModelOutput~~ |
| `tensors` | The `model_output` in the earlier `transformers` tuple format converted using [`ModelOutput.to_tuple()` ](https://huggingface.co/transformers/main_classes/output.html#transformers.file_utils.ModelOutput.to_tuple ). Returns `Tuple` instead of `List` as of `spacy-transformers` v1.1.0. ~~Tuple[Union[FloatsXd, List[FloatsXd]]]~~ |
| `align` | Alignment from the `Doc` 's tokenization to the wordpieces. This is a ragged array, where `align.lengths[i]` indicates the number of wordpiece tokens that token `i` aligns against. The actual indices are provided at `align[i].dataXd` . ~~Ragged~~ |
| `width` | The width of the last hidden layer. ~~int~~ |
2020-07-29 13:14:07 +00:00
### TransformerData.empty {#transformerdata-emoty tag="classmethod"}
2020-08-16 13:56:32 +00:00
Create an empty `TransformerData` container.
2020-07-29 13:14:07 +00:00
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ---------------------------------- |
| **RETURNS** | The container. ~~TransformerData~~ |
2020-07-29 13:14:07 +00:00
2021-10-18 12:16:58 +00:00
< Accordion title = "Previous versions of TransformerData" spaced >
In `spacy-transformers` v1.0, the model output is stored in
`TransformerData.tensors` as `List[Union[FloatsXd]]` and only includes the
activations for the `Doc` from the transformer. Usually the last tensor that is
3-dimensional will be the most important, as that will provide the final hidden
state. Generally activations that are 2-dimensional will be attention weights.
Details of this variable will differ depending on the underlying transformer
model.
< / Accordion >
2020-07-29 09:36:42 +00:00
## FullTransformerBatch {#fulltransformerbatch tag="dataclass"}
2020-08-16 13:56:32 +00:00
Holds a batch of input and output objects for a transformer model. The data can
then be split to a list of [`TransformerData` ](/api/transformer#transformerdata )
objects to associate the outputs to each [`Doc` ](/api/doc ) in the batch.
2020-07-29 13:14:07 +00:00
2021-10-18 12:16:58 +00:00
| Name | Description |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `spans` | The batch of input spans. The outer list refers to the Doc objects in the batch, and the inner list are the spans for that `Doc` . Note that spans are allowed to overlap or exclude tokens, but each `Span` can only refer to one `Doc` (by definition). This means that within a `Doc` , the regions of the output tensors that correspond to each `Span` may overlap or have gaps, but for each `Doc` , there is a non-overlapping contiguous slice of the outputs. ~~List[List[Span]]~~ |
| `tokens` | The output of the tokenizer. ~~transformers.BatchEncoding~~ |
| `model_output` | The model output from the transformer model, determined by the model and transformer config. New in `spacy-transformers` v1.1.0. ~~transformers.file_utils.ModelOutput~~ |
| `tensors` | The `model_output` in the earlier `transformers` tuple format converted using [`ModelOutput.to_tuple()` ](https://huggingface.co/transformers/main_classes/output.html#transformers.file_utils.ModelOutput.to_tuple ). Returns `Tuple` instead of `List` as of `spacy-transformers` v1.1.0. ~~Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]~~ |
| `align` | Alignment from the spaCy tokenization to the wordpieces. This is a ragged array, where `align.lengths[i]` indicates the number of wordpiece tokens that token `i` aligns against. The actual indices are provided at `align[i].dataXd` . ~~Ragged~~ |
| `doc_data` | The outputs, split per `Doc` object. ~~List[TransformerData]~~ |
2020-07-29 13:14:07 +00:00
### FullTransformerBatch.unsplit_by_doc {#fulltransformerbatch-unsplit_by_doc tag="method"}
2020-08-16 13:56:32 +00:00
Return a new `FullTransformerBatch` from a split batch of activations, using the
current object's spans, tokens and alignment. This is used during the backward
pass, in order to construct the gradients to pass back into the transformer
model.
2020-07-29 13:14:07 +00:00
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | -------------------------------------------------------- |
| `arrays` | The split batch of activations. ~~List[List[Floats3d]]~~ |
| **RETURNS** | The transformer batch. ~~FullTransformerBatch~~ |
2020-07-29 13:14:07 +00:00
### FullTransformerBatch.split_by_doc {#fulltransformerbatch-split_by_doc tag="method"}
Split a `TransformerData` object that represents a batch into a list with one
`TransformerData` per `Doc` .
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ------------------------------------------ |
| **RETURNS** | The split batch. ~~List[TransformerData]~~ |
2020-07-29 13:14:07 +00:00
2021-10-18 12:16:58 +00:00
< Accordion title = "Previous versions of FullTransformerBatch" spaced >
In `spacy-transformers` v1.0, the model output is stored in
`FullTransformerBatch.tensors` as `List[torch.Tensor]` .
< / Accordion >
2020-08-09 22:42:26 +00:00
## Span getters {#span_getters source="github.com/explosion/spacy-transformers/blob/master/spacy_transformers/span_getters.py"}
2020-07-29 16:44:10 +00:00
Span getters are functions that take a batch of [`Doc` ](/api/doc ) objects and
2020-09-28 14:50:15 +00:00
return a lists of [`Span` ](/api/span ) objects for each doc to be processed by
the transformer. This is used to manage long documents by cutting them into
2020-08-09 22:01:38 +00:00
smaller sequences before running the transformer. The spans are allowed to
2020-09-28 14:50:15 +00:00
overlap, and you can also omit sections of the `Doc` if they are not relevant.
2020-08-09 22:01:38 +00:00
2020-08-09 22:42:26 +00:00
Span getters can be referenced in the `[components.transformer.model.get_spans]`
block of the config to customize the sequences processed by the transformer. You
2020-08-27 17:24:44 +00:00
can also register
[custom span getters ](/usage/embeddings-transformers#transformers-training-custom-settings )
using the `@spacy.registry.span_getters` decorator.
2020-07-29 16:44:10 +00:00
> #### Example
>
> ```python
2020-09-03 15:37:06 +00:00
> @spacy.registry.span_getters("custom_sent_spans")
2020-07-29 16:44:10 +00:00
> def configure_get_sent_spans() -> Callable:
> def get_sent_spans(docs: Iterable[Doc]) -> List[List[Span]]:
> return [list(doc.sents) for doc in docs]
>
> return get_sent_spans
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ------------------------------------------------------------- |
| `docs` | A batch of `Doc` objects. ~~Iterable[Doc]~~ |
| **RETURNS** | The spans to process by the transformer. ~~List[List[Span]]~~ |
2020-07-29 16:44:10 +00:00
2020-08-09 22:42:26 +00:00
### doc_spans.v1 {#doc_spans tag="registered function"}
2020-07-29 16:44:10 +00:00
2020-08-09 22:42:26 +00:00
> #### Example config
>
> ```ini
> [transformer.model.get_spans]
2020-09-03 15:37:06 +00:00
> @span_getters = "spacy-transformers.doc_spans.v1"
2020-08-09 22:42:26 +00:00
> ```
Create a span getter that uses the whole document as its spans. This is the best
approach if your [`Doc` ](/api/doc ) objects already refer to relatively short
texts.
### sent_spans.v1 {#sent_spans tag="registered function"}
> #### Example config
>
> ```ini
> [transformer.model.get_spans]
2020-09-03 15:37:06 +00:00
> @span_getters = "spacy-transformers.sent_spans.v1"
2020-08-09 22:42:26 +00:00
> ```
Create a span getter that uses sentence boundary markers to extract the spans.
This requires sentence boundaries to be set (e.g. by the
[`Sentencizer` ](/api/sentencizer )), and may result in somewhat uneven batches,
depending on the sentence lengths. However, it does provide the transformer with
more meaningful windows to attend over.
2021-04-26 14:53:53 +00:00
To set sentence boundaries with the `sentencizer` during training, add a
`sentencizer` to the beginning of the pipeline and include it in
[`[training.annotating_components]`](/usage/training#annotating-components) to
have it set the sentence boundaries before the `transformer` component runs.
2020-08-09 22:42:26 +00:00
### strided_spans.v1 {#strided_spans tag="registered function"}
> #### Example config
>
> ```ini
> [transformer.model.get_spans]
2020-09-03 15:37:06 +00:00
> @span_getters = "spacy-transformers.strided_spans.v1"
2020-08-09 22:42:26 +00:00
> window = 128
> stride = 96
> ```
Create a span getter for strided spans. If you set the `window` and `stride` to
the same value, the spans will cover each token once. Setting `stride` lower
than `window` will allow for an overlap, so that some tokens are counted twice.
This can be desirable, because it allows all tokens to have both a left and
right context.
2020-07-31 15:02:54 +00:00
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------- | ------------------------ |
| `window` | The window size. ~~int~~ |
| `stride` | The stride size. ~~int~~ |
2020-07-29 16:44:10 +00:00
## Annotation setters {#annotation_setters tag="registered functions" source="github.com/explosion/spacy-transformers/blob/master/spacy_transformers/annotation_setters.py"}
2020-08-27 07:43:32 +00:00
Annotation setters are functions that take a batch of `Doc` objects and a
2020-08-31 12:40:55 +00:00
[`FullTransformerBatch` ](/api/transformer#fulltransformerbatch ) and can set
additional annotations on the `Doc` , e.g. to set custom or built-in attributes.
You can register custom annotation setters using the
`@registry.annotation_setters` decorator.
2020-07-29 16:44:10 +00:00
> #### Example
>
> ```python
2020-08-31 12:40:55 +00:00
> @registry.annotation_setters("spacy-transformers.null_annotation_setter.v1")
> def configure_null_annotation_setter() -> Callable:
2020-07-29 16:44:10 +00:00
> def setter(docs: List[Doc], trf_data: FullTransformerBatch) -> None:
2020-08-31 12:40:55 +00:00
> pass
2020-07-29 16:44:10 +00:00
>
2020-08-31 12:46:00 +00:00
> return setter
2020-07-29 16:44:10 +00:00
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ---------- | ------------------------------------------------------------- |
| `docs` | A batch of `Doc` objects. ~~List[Doc]~~ |
| `trf_data` | The transformers data for the batch. ~~FullTransformerBatch~~ |
2020-07-29 16:44:10 +00:00
The following built-in functions are available:
2020-08-31 12:40:55 +00:00
| Name | Description |
| ---------------------------------------------- | ------------------------------------- |
| `spacy-transformers.null_annotation_setter.v1` | Don't set any additional annotations. |