Sub topic 8
Running a transformer NER model with Hugging Face
This chapter shows how to run a pretrained transformer NER model through the Hugging Face pipeline API. It covers what the raw output looks like, how aggregation turns subword predictions into entities, and the parameters and failure modes you will meet in practice.
It assumes you know the BIO tagging scheme from earlier chapters, have used spaCy's Doc.ents, and have installed packages with pip. You need transformers and a backend such as PyTorch (pip install transformers torch).
What the pipeline does
A transformer NER model is a token classifier. An encoder such as BERT reads the whole sentence and produces one vector per subword token. A linear layer on top maps each vector to scores over the label set, for example B-PER, I-PER, B-ORG, O.
The token-classification pipeline wraps four steps:
- Tokenize the text into subwords and keep character offsets for each one.
- Run the model to get a score for every label at every token.
- Take the highest-scoring label per token.
- Optionally group neighbouring tokens into whole entities (aggregation).
A first run
The model dslim/bert-base-NER is a BERT-base cased model fine-tuned on CoNLL-2003. It predicts four entity types: PER, ORG, LOC and MISC. The first call downloads the weights, so it needs network access.
from transformers import pipeline
ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
aggregation_strategy="simple",
)
for ent in ner("Hugging Face is based in New York City."):
print(ent["entity_group"], ent["word"], round(float(ent["score"]), 3), ent["start"], ent["end"])Each result is a dictionary with these keys:
| Key | Meaning |
|---|---|
| `entity_group` | The entity type with the `B-` and `I-` prefix removed, such as `ORG` |
| `word` | The decoded text of the span |
| `score` | The model's confidence for the span, between 0 and 1 |
| `start`, `end` | Character offsets into the original string |
The offsets use the same convention as spaCy's ent.start_char and ent.end_char. You can slice the input with them: text[ent["start"]:ent["end"]]. Slicing the original text is safer than using word, because word is decoded from tokens and may differ in spacing or casing from the input.
You should see Hugging Face as ORG and New York City as LOC. Exact scores vary slightly by library version, but they are typically above 0.9 for clear cases like these.
Raw output: no aggregation
To see what the model really predicts, turn aggregation off. This is the best way to debug surprising entities.
from transformers import pipeline
raw = pipeline(
"token-classification",
model="dslim/bert-base-NER",
aggregation_strategy="none",
)
for tok in raw("Satya Nadella leads Microsoft from Redmond."):
print(tok["index"], tok["entity"], tok["word"], round(float(tok["score"]), 3), tok["start"], tok["end"])Now you get one dictionary per token that was not labelled O. Two differences matter:
- The key is
entity, notentity_group, and it keeps the BIO prefix, such asB-PERorI-PER. - Rare words are split into pieces. In a WordPiece vocabulary, continuation pieces start with
##, so a name might appear as pieces such asNad,##ella. The split depends on the tokenizer's vocabulary, so look at your own output.
Tokens labelled O are dropped from the output, so the index values you see are not contiguous.
Aggregation strategies
Aggregation groups tokens into entities. It has to solve two problems: joining subwords into words, and joining words into entities. The aggregation_strategy argument controls how it picks one label for a word that has several subword predictions.
| Strategy | Behaviour |
|---|---|
| `none` | No grouping. One dictionary per token. |
| `simple` | Groups adjacent tokens using the BIO tags. Averages the scores. |
| `first` | Uses the label of the first subword for each word. |
| `average` | Averages the label scores across a word's subwords, then takes the best label. |
| `max` | Uses the label of the subword with the highest score. |
simple is a good default for models trained with all-subword labels. If a model was trained with the first-subword-only scheme (covered in the label alignment chapter), later subwords carry arbitrary predictions, and first matches how the model was trained. average and max help when the subwords disagree about the type.
Inspecting the label set
A model's labels live in its config. Check them before you trust the entity types, because different checkpoints use different schemes.
from transformers import AutoConfig
config = AutoConfig.from_pretrained("dslim/bert-base-NER")
for idx, label in sorted(config.id2label.items()):
print(idx, label)This prints nine labels: O, plus B- and I- for each of MISC, PER, ORG and LOC. A model trained on CoNLL-2003 has no DATE, MONEY or PRODUCT type, unlike spaCy's OntoNotes-trained English models. Running the same sentence through both can give different spans and different labels, and neither is wrong. The label schemes differ.
Useful pipeline arguments
Pass these when you build the pipeline, or in the call where noted.
from transformers import pipeline
ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
aggregation_strategy="simple",
device=-1, # -1 for CPU; 0 for the first GPU
batch_size=8,
)
texts = [
"Angela Merkel visited Paris.",
"Toyota opened a plant in Texas.",
"The Nile flows through Egypt.",
]
for text, ents in zip(texts, ner(texts)):
print(text)
for e in ents:
print(" ", e["entity_group"], text[e["start"]:e["end"]], round(float(e["score"]), 2))Passing a list returns a list of results, one list of entities per input text, in the same order. The batch_size argument controls how many inputs run through the model together. It speeds up GPU inference but can slow down CPU runs or increase memory use, so measure on your hardware. If you only have one very long input, batch_size does nothing.
Edge cases and failure modes
Input length. BERT-style encoders accept at most 512 tokens. Longer text is a problem. Depending on the version and settings, the pipeline either raises an error or truncates, and truncation means entities after the cutoff are silently lost. For long documents, either split the text into sentences or paragraphs yourself and shift the offsets back, or use the pipeline's stride argument with an aggregation strategy other than none. With stride, the pipeline splits the text into overlapping windows and merges the results. Check that the entity count from a long test document matches what you expect.
Casing. Cased models such as bert-base-NER use capitalization as a strong signal. Text in all lowercase or all uppercase, such as tweets or headlines, often yields fewer or wrong entities. Test on text that looks like your real data.
Boundary errors. A model may predict I-ORG right after O, with no B-ORG first. The aggregation step has its own rule for this and may start a new group. Do not assume the groups always match a clean BIO sequence. If you evaluate the output, convert it carefully.
Confidence is not calibration. The score is a softmax probability, and it tends to be high even for wrong predictions on out-of-domain text. Use it for ranking and for thresholds you have validated, not as a probability of being correct.
Domain shift. A news-trained model does poorly on medical notes, code or chat messages. Fixing that means fine-tuning on your own labels, which later chapters cover.
How this compares with spaCy
Both tools produce spans with character offsets, but they differ in what you get back.
| Aspect | Hugging Face pipeline | spaCy pipeline |
|---|---|---|
| Output | List of dictionaries | `Doc` with `Span` objects in `doc.ents` |
| Tokenization | Subwords from the model's tokenizer | spaCy's rule-based word tokenizer |
| Other annotations | None | Sentences, tags, dependencies, and more |
| Model choice | Thousands of checkpoints on the Hub | A smaller set of packaged pipelines |
| Rules | You write them yourself | `EntityRuler` is built in |
A common pattern is to use the Hugging Face model for its accuracy and then convert its dictionaries into spaCy spans with doc.char_span(start, end, label=...), so the rest of your code can use one interface. char_span returns None when offsets do not align with spaCy token boundaries, so handle that case.
Exercise
You run a Hugging Face NER pipeline with aggregationstrategy="none" and see a token with entity "I-ORG" and word "##ella", but with aggregationstrategy="simple" you get a single PER entity "Satya Nadella". Name two reasons the raw output looks different, and say which output you would use to find out why a name was split into the wrong type.
Show answer
First, "none" returns one dictionary per subword token and keeps the B-/I- prefixes, while "simple" merges adjacent tokens into one entity group and strips the prefixes. Second, "none" shows each subword's own predicted label, so one piece can carry a different type from the rest of the name, such as I-ORG inside a name that is mostly PER, and the aggregation step then resolves or splits these. To debug a wrong type or a wrong split, use the "none" output, because it shows each token's label and score before any merging.
Exercise
A news article of 3,000 words returns far fewer entities than you expect, all from the first part of the text. What is the likely cause, and what are two ways to fix it?
Show answer
The encoder accepts at most 512 tokens, so the text beyond that limit was truncated and never labelled. Fix it by splitting the article into sentences or paragraphs and adding each chunk's start offset back to the entity offsets, or by passing the pipeline's stride argument with an aggregation strategy other than "none" so it processes overlapping windows and merges the results.