Sub topic 13
Pipeline components, nlp.pipe, and disabling
This chapter assumes you can load a spaCy pipeline, read token attributes such as pos_, dep_, and lemma_, and run Python from a script or notebook. You should also know that en_core_web_sm has been installed with python -m spacy download en_core_web_sm. Here you will see which components produce which attributes, how to process many texts efficiently, and how to turn off the parts you do not need.
What a pipeline is made of
A spaCy pipeline is an ordered list of components. When you call nlp(text), the tokenizer first splits the text into tokens and builds a Doc. Each component then receives that Doc, adds annotations to it, and passes it on. The order matters, because some components read what earlier ones wrote.
You can list the active components with nlp.pipe_names. For the small English pipeline the list usually looks like this: tok2vec, tagger, parser, attribute_ruler, lemmatizer, ner. The exact names and order can differ between model versions, so print them for your own installation instead of assuming.
| Component | What it writes | Depends on |
|---|---|---|
| `tok2vec` | Shared vector representations of tokens | Tokenizer only |
| `tagger` | `tag_` and the first guess at `pos_` | `tok2vec` |
| `parser` | `dep_`, `head`, sentence boundaries | `tok2vec` |
| `attribute_ruler` | Rule-based fixes to `pos_`, morphology, and other attributes | `tagger` |
| `lemmatizer` | `lemma_` | `pos_` from the tagger and attribute ruler |
| `ner` | `ent_type_` and `ent_iob_` (named entities) | `tok2vec` |
The tokenizer is not in nlp.pipe_names. It always runs, and you cannot disable it the way you disable a component.
Why components depend on each other
Two dependencies cause most surprises.
- The lemmatizer uses part-of-speech tags. In English, the rule-based lemmatizer chooses its rules by
pos_. If the tagger or attribute ruler is missing, lemmas can be wrong or empty. - Several components may share a
tok2veclayer. The tagger, parser, and NER in the small pipeline listen to the sharedtok2vecoutput. Removingtok2vecwhile keeping a component that listens to it breaks the pipeline.
Because of this, "disable what I don't need" is only safe when you know what the remaining components need. Test the result on a sample sentence after every change.
Processing many texts with nlp.pipe
Calling nlp(text) in a loop works, but it processes one text at a time. nlp.pipe(texts) takes an iterable of texts and streams Doc objects back. It groups the texts into batches, which lets the statistical models do their work more efficiently, and it does not hold every Doc in memory at once.
import spacy
nlp = spacy.load("en_core_web_sm")
texts = [
"The cat sat on the mat.",
"Dogs chase balls in the park.",
"The committee approved the new budget.",
]
for doc in nlp.pipe(texts, batch_size=50):
print([(t.text, t.pos_, t.dep_) for t in doc])Three details are worth knowing.
nlp.pipereturns a generator. Nothing is processed until you iterate over it. If you want a list, wrap it inlist(...), but for large corpora iterate and extract what you need.- The
Docobjects come back in the same order as the input texts. batch_sizeis the number of texts per batch. The default is usually fine. Very large values use more memory and rarely help.
Keeping your own data attached to each text
If your texts come with ids or other metadata, pass (text, context) tuples and set as_tuples=True. spaCy returns (doc, context) tuples in the same order.
import spacy
nlp = spacy.load("en_core_web_sm")
records = [
("The engineer fixed the bug.", {"id": 1}),
("Researchers published the dataset.", {"id": 2}),
]
for doc, meta in nlp.pipe(records, as_tuples=True):
print(meta["id"], [t.lemma_ for t in doc])Using several processes
nlp.pipe accepts n_process to spread the work across processes. This can help on large batches of long texts, but it has costs: each process loads its own copy of the model, and results must be sent back between processes. For short texts or small corpora, n_process=1 is often as fast or faster. Measure before you choose a larger value.
import spacy
nlp = spacy.load("en_core_web_sm")
texts = ["The cat sat on the mat."] * 1000
if __name__ == "__main__":
docs = list(nlp.pipe(texts, batch_size=100, n_process=2))
print(len(docs))The if __name__ == "__main__": guard matters in a script because some operating systems start worker processes by importing your file again. Without the guard, that import can start new workers recursively.
Disabling components you do not need
Every component costs time. The parser and NER are usually the most expensive. If your task only needs tokens and part-of-speech tags, you can skip the rest.
There are four related options, and they behave differently.
| Option | Where you use it | Effect |
|---|---|---|
| `disable=[...]` | `spacy.load` | Component is loaded but not run. You can enable it later. |
| `exclude=[...]` | `spacy.load` | Component is not loaded at all. It saves memory and load time. |
| `nlp.select_pipes(disable=[...])` | Context manager or method | Temporarily turns components off, then restores them. |
| `nlp.disable_pipe("name")` | Method on `nlp` | Turns one component off until you call `enable_pipe`. |
Loading without the named entity recognizer looks like this:
import spacy
texts = ["The cat sat on the mat.", "Dogs chase balls in the park."]
nlp = spacy.load("en_core_web_sm", disable=["ner"])
print(nlp.pipe_names)
for doc in nlp.pipe(texts, batch_size=50):
print([(t.text, t.pos_, t.dep_) for t in doc])nlp.pipe_names now lacks ner. The ents of each Doc will be empty, but everything else still works.
Temporary changes with select_pipes
When you want a different configuration for one block of work, use select_pipes as a context manager. The components return when the block ends, even if an error occurs.
import spacy
nlp = spacy.load("en_core_web_sm")
print("before:", nlp.pipe_names)
with nlp.select_pipes(disable=["parser", "ner"]):
print("inside:", nlp.pipe_names)
doc = nlp("The quick brown fox jumps over the lazy dog.")
print([(t.text, t.pos_) for t in doc])
print("after:", nlp.pipe_names)What breaks when you disable the parser
This is the common mistake for readers of this tutorial. The parser writes dep_, head, and the sentence boundaries. If you disable it, three things change.
token.dep_is an empty string for every token.token.headpoints to the token itself, so tree navigation withchildrenandsubtreegives meaningless results.doc.sentsanddoc.noun_chunksfail or raise an error, because sentence boundaries and noun chunks need the parse. The error message mentions that sentence boundaries are not set.
If you disable the parser but still need sentences, add the rule-based sentencizer. It splits on punctuation and does not need a parse.
import spacy
nlp = spacy.load("en_core_web_sm", exclude=["parser", "ner"])
nlp.add_pipe("sentencizer")
print(nlp.pipe_names)
doc = nlp("The cat sat. The dog barked.")
print([s.text for s in doc.sents])Notice that this example uses exclude rather than disable. A component excluded at load time is not loaded, so memory use is lower. A component listed in disable is loaded and can be switched back on.
Choosing a configuration
Pick components by the attributes your code reads. A quick way to decide is to list every attribute your script touches and match it to the table at the top of this chapter.
| Your code reads | Keep these components |
|---|---|
| `text`, `is_alpha`, other tokenizer attributes | None (the tokenizer always runs) |
| `pos_`, `tag_` | `tok2vec`, `tagger`, `attribute_ruler` |
| `lemma_` | The part-of-speech components plus `lemmatizer` |
| `dep_`, `head`, `children`, `subtree`, `sents`, `noun_chunks` | `tok2vec`, `parser` |
| `ents` | `tok2vec`, `ner` |
For the subject-verb-object extraction from earlier chapters, you need pos_ (to find verbs), dep_ and head, and lemma_ if you print lemmas. You can safely drop ner.
Checking what you actually get
After changing a pipeline, confirm that the attributes you rely on are filled in. A short check on one sentence is enough to catch most mistakes.
import spacy
nlp = spacy.load("en_core_web_sm", disable=["ner"])
doc = nlp("The engineer fixed the bug.")
print(nlp.pipe_names)
print(doc.has_annotation("DEP"))
print(doc.has_annotation("TAG"))
print(doc.has_annotation("LEMMA"))
print(doc.ents)Doc.has_annotation returns True when the attribute has been set on the document. After you disable parser, has_annotation("DEP") returns False. This check is cheaper and clearer than discovering a missing parse through an error in the middle of a long job.
Summary of rules
- Print
nlp.pipe_namesto see what runs. Component names and order can vary by model version. - Use
nlp.pipefor more than a handful of texts. Useas_tuples=Trueto carry ids along. - Try
n_processonly after measuring, and protect scripts with the__main__guard. - Use
excludeto save memory,disableto keep a component available, andselect_pipesfor temporary changes. - Keep the parser if you use
dep_,head,sents, ornoun_chunks. Keep the part-of-speech components if you uselemma_. - Check results with
has_annotationafter changing a pipeline.
Exercise
You load spacy.load("en_core_web_sm", disable=["parser"]) and then run [chunk.text for chunk in nlp("The small team wrote a report.").noun_chunks]. What do you expect to happen, and what are two ways to fix it?
Show answer
It raises an error, because noun chunks need the dependency parse and sentence boundaries, and the parser is the component that provides them. One fix is to keep the parser by removing it from the disable list. The other fix applies only to sentence boundaries: add the sentencizer component. That second fix does not restore noun chunks, which still need dep_ and head, so for noun chunks the parser must stay enabled.
Exercise
You have a list of 10,000 review texts, each paired with a review id. You need each review's lemmas and do not need entities. Write the loading line and the loop that prints the id and the lemmas.
Show answer
Load with the entity recognizer disabled and keep the tagger, attribute ruler, and lemmatizer: nlp = spacy.load("encorewebsm", disable=["ner"]) Then pass the (text, id) pairs with astuples=True: for doc, reviewid in nlp.pipe(records, astuples=True): print(reviewid, [t.lemma for t in doc]) Here records is a list of (text, reviewid) tuples. The parser could also be dropped, since lemmas do not need it, but the lemmatizer reads pos, so the tagger and attribute ruler must stay.
Exercise
What is the difference between disable=["ner"] and exclude=["ner"] in spacy.load, and when would you choose each?
Show answer
With disable, the component is loaded into memory but skipped when processing, so you can turn it back on later with nlp.enable_pipe("ner"). With exclude, the component is not loaded at all, which saves memory and load time but means you cannot re-enable it without reloading. Choose disable when you might need the component later in the same program, and exclude when you know you never will.