Sub topic 9
Transformer-based spaCy pipelines
This chapter assumes you can run the pretrained spaCy NER pipeline from earlier in the tutorial and that you know how subword tokenization splits words into pieces. You should also know roughly what a transformer encoder does. Here you will see how spaCy wraps a transformer so that you keep the Doc and ents interface. You will also see where the pieces sit in the pipeline and what the cost is.
What changes and what stays the same
A transformer-based spaCy pipeline replaces the small convolutional word-vector layer with a pretrained transformer such as RoBERTa. Your code stays almost the same. You still call nlp(text), and you still read doc.ents, ent.label_ and ent.start_char. The model behind it is different.
The Hugging Face token-classification pipeline needs the subword and label handling you saw in earlier chapters. A spaCy transformer pipeline handles that for you. It tokenizes with spaCy's rules, runs the transformer's own tokenizer on the text, and keeps the alignment between the two.
The pretrained English package is en_core_web_trf. Install it with python -m spacy download en_core_web_trf. It needs the spacy-transformers package, which you can install with pip install "spacy[transformers]".
import spacy
nlp = spacy.load("en_core_web_trf")
doc = nlp("Satya Nadella leads Microsoft from Redmond.")
print([(ent.text, ent.label_) for ent in doc.ents])The output has the same shape as with en_core_web_sm. Only the accuracy and the speed differ.
How the pipeline is organized
Run print(nlp.pipe_names) on the loaded pipeline. You will see a transformer component first, followed by components such as tagger, parser, attribute_ruler, lemmatizer and ner. The exact list depends on the package version.
The transformer component runs the pretrained encoder once per document. It stores the result on the Doc. The ner component does not run its own encoder. It reads the stored vectors through a listener and applies a small prediction layer on top.
This design has two consequences:
- The transformer cost is paid once. Adding another component that listens to the same transformer adds little extra compute.
- Components are coupled. If you retrain the transformer with only NER, the tagger and parser that listen to it may get worse. Later in this chapter you will see how to protect them.
Inspecting what the transformer produced
You can look at the stored output. This is useful for debugging alignment problems.
import spacy
nlp = spacy.load("en_core_web_trf")
doc = nlp("Hugging Face is based in New York City.")
print(nlp.pipe_names)
trf = doc._.trf_data
print(trf.wordpieces.strings[0])
print(trf.tensors[0].shape)
print(len(doc), "spaCy tokens")The wordpiece list is longer than the spaCy token list, and it includes special tokens at the start and end. The tensor has one row per wordpiece. The pipeline pools or aligns those rows back to spaCy tokens before the ner component predicts. The first dimension of the tensor counts the spans the document was split into, which the next section explains.
Long documents and strided spans
A transformer has a fixed maximum input length, 512 wordpieces for RoBERTa-base. Real documents are often longer. The transformer component splits a Doc into overlapping windows, runs each window, and merges the outputs. The default en_core_web_trf configuration uses a strided span getter with a window of 128 wordpieces and a stride of 96. Each token therefore appears in at least one window with context on both sides.
Two points follow from this:
- Entities near a window edge see less context than entities in the middle. Overlap reduces this effect and does not remove it.
- Smaller windows lower memory use. They also lower the context available to the model.
You can see the settings in the pipeline config:
import spacy
nlp = spacy.load("en_core_web_trf")
print(nlp.config["components"]["transformer"]["model"]["get_spans"])Speed, memory and hardware
Transformer pipelines are slower than en_core_web_sm, often by an order of magnitude on CPU. A GPU closes most of that gap. Ask spaCy to use one before loading the pipeline:
import spacy
spacy.prefer_gpu() # returns False and stays on CPU if no GPU is found
nlp = spacy.load("en_core_web_trf")
texts = ["Apple is looking at buying a U.K. startup."] * 1000
for doc in nlp.pipe(texts, batch_size=64):
passUse nlp.pipe rather than calling nlp in a loop. Batching lets the transformer process several documents at once. On a GPU, a batch size that is too large can run out of memory. If you see out-of-memory errors, lower batch_size.
| Property | `en_core_web_sm` | `en_core_web_trf` |
|---|---|---|
| Encoder | Small CNN with static features | Pretrained transformer (RoBERTa-base) |
| Speed on CPU | Fast | Slow |
| Typical NER accuracy | Lower | Higher |
| Context across a sentence | Limited | Strong |
| Download and memory size | Small | Large |
| GPU helps | Little | A lot |
Training your own transformer-based NER
The spaCy training workflow from the previous chapter works the same way. You change one option when you create the config. The --optimize accuracy setting picks a transformer-based architecture. --optimize efficiency picks the small, fast one.
python -m spacy init config config.cfg --lang en --pipeline ner --optimize accuracy
python -m spacy train config.cfg --output ./output --paths.train ./train.spacy --paths.dev ./dev.spacy --gpu-id 0The --gpu-id 0 flag trains on the first GPU. Training a transformer on CPU is possible and very slow.
The generated config contains a transformer section. These are the settings you are most likely to change:
[components.transformer.model]
@architectures = "spacy-transformers.TransformerModel.v3"
name = "roberta-base"
[components.transformer.model.get_spans]
@span_getters = "spacy-transformers.strided_spans.v1"
window = 128
stride = 96The name value is any Hugging Face model name that works with the AutoModel classes. Choose a model that matches your language. For a language other than English, use --lang with the right code and a multilingual or language-specific checkpoint. Check that the config you generate names the checkpoint you expect before you start a long run.
Protecting other components
If you start from en_core_web_trf and want to add or retrain only NER, you can freeze the other components and let the pipeline source them. In the config, use frozen_components and annotating_components in the [training] section:
- A frozen component is not updated during training.
- An annotating component still runs during training, so that later components can use its output.
When the transformer itself is updated by only one component's loss, the frozen components that listen to the same transformer can drift. The safe option is to give the new NER component its own transformer. Components with their own transformer copy do not drift, and memory use goes up.
Common errors
ModuleNotFoundErroror an unknown componenttransformer. Thespacy-transformerspackage is missing or its version does not match your spaCy version. Installspacy[transformers]in the same environment as spaCy.- Out-of-memory on GPU. Lower
batch_sizeinnlp.pipe, or lower the window size inget_spansfor training. A shortermax_lengthfor documents also helps. - Loading a model trained with a different spaCy version. Pipelines warn when versions differ. Retrain, or install the package version that matches your spaCy minor version.
- Unexpectedly slow runs. Check that you are on a GPU with
spacy.prefer_gpu()and that you usenlp.pipe. Usenlp.select_pipes(enable=["transformer", "ner"])as a context manager to run only what you need. Thenercomponent needs thetransformercomponent to be enabled.
import spacy
nlp = spacy.load("en_core_web_trf")
with nlp.select_pipes(enable=["transformer", "ner"]):
doc = nlp("Marie Curie won the Nobel Prize in Paris.")
print([(e.text, e.label_) for e in doc.ents])When to choose it
Pick a transformer-based spaCy pipeline when you want the spaCy interface and higher accuracy. It fits cases where an entity's label depends on context, such as telling a person from an organization with the same name. Pick the small pipeline when you need speed, run on CPU only, or process very large volumes. Pick the Hugging Face fine-tuning route from the next chapter when you need a specific checkpoint or full control over the training loop, or when your labels do not suit spaCy's span handling.
Exercise
You load encoreweb_trf and run it on 10,000 short texts with a for loop that calls nlp(text) once per text. It is slow on a GPU. Name two changes that should help and explain why.
Show answer
Use nlp.pipe(texts, batchsize=...) so the transformer processes several documents per forward pass, which uses the GPU better than one document at a time. Also call spacy.prefergpu() before spacy.load so the model runs on the GPU. Disabling components you do not need, with nlp.select_pipes, helps further, but the ner component still needs the transformer enabled.
Exercise
A document has 2,000 wordpieces. The transformer accepts at most 512. How does the spaCy transformer component handle it, and what is the risk for entities near the edge of a window?
Show answer
It splits the Doc into overlapping windows with a strided span getter (128 wordpieces with stride 96 by default), runs the transformer on each window and merges the output per token. An entity near a window edge sees less surrounding context, so predictions there can be less reliable. The overlap reduces this effect but does not remove it.