Skip to main content

Hugging Face Transformers Tutorial for NLP in Python — Part 2: Use Pipelines for Common NLP Tasks

· 40 min read
Jagdish Kumawat
Founder @ Dewiride

Pipelines can do much more than Part 1's zero-shot classification. In this part you run the other language tasks of Transformers 5 on real support messages: you choose a model on the Hugging Face Hub, pick out the names in a message, score how a customer feels, fill in a missing word and compare what messages mean, and you fix each warning and error the tasks throw along the way.

This is Part 2 of a 13-part series.

  1. Part 1: Install Transformers and Run Your First Pipeline
  2. Part 2: Use Pipelines for Common NLP Tasks (you are here)
  3. Part 3: Run a Pipeline on a Whole Dataset (coming soon)
  4. Part 4: Tokenizers: Turn Text into Model Inputs (coming soon)
  5. Part 5: Load Models with the Auto Classes (coming soon)
  6. Part 6: Load and Prepare Datasets for Fine-Tuning (coming soon)
  7. Part 7: Fine-Tune a Text Classifier with the Trainer (coming soon)
  8. Part 8: Evaluate a Fine-Tuned Classifier (coming soon)
  9. Part 9: Callbacks, Early Stopping and Hyperparameter Search (coming soon)
  10. Part 10: Share Models on the Hugging Face Hub (coming soon)
  11. Part 11: Make Transformers Inference Faster (coming soon)
  12. Part 12: Serve a Transformers Model as a REST API (coming soon)
  13. Part 13: Production Checklist and Recap (coming soon)

Every command and output on this page is real, captured while building the project.

What This Part Covers​

Part 1 used one task, zero-shot classification, inside the router. This part tries the other common language tasks on the kind of messages the router reads, one short script each, and ends by working out which task the router really needs:

StepTaskThe question it answersModel
1Every taskWhich model should I use?Found on the Hub
2 and 3Token classification (NER)Which words are names of people, places or organizations?dslim/bert-base-NER
4 and 5Text classificationWhich label fits the whole message, and how sure is the model?The sentiment model from Part 1
6Fill-maskWhich word fits the gap?answerdotai/ModernBERT-base
7Feature extractionWhich messages mean nearly the same thing?sentence-transformers/all-MiniLM-L6-v2 and ModernBERT-base

The router itself doesn't change in this part. The scripts go in a playground folder that you delete at the end.

The Language Tasks in Transformers 5​

Pipelines also handle audio, images and documents. These are the tasks for text in Transformers 5.24.1; two of them also accept a second name:

TaskOther nameWhat it returnsWhere this series uses it
text-classificationsentiment-analysisOne label for a whole text, from the labels its model was trained onPart 1's first pipeline, Steps 4 and 5, and the router once it's fine-tuned in Part 7
zero-shot-classificationOne label for a whole text, from labels you choose when you run itThe router, since Part 1
token-classificationnerA label for each token, such as the names in a textSteps 2 and 3
fill-maskThe words that best fill a gapStep 6
feature-extractionNumbers that stand for the meaning of each tokenStep 7
text-generationNew text, such as the answer in a chatThe second series
table-question-answeringAnswers to questions about a tableNot used

Four text tasks from Transformers 4 are gone: Transformers 5 removed question-answering, summarization, translation and text2text-generation. Asking for one raises a KeyError that says: "Use the text-generation pipeline with a chat model instead." Fixed: "KeyError: The task question-answering has been removed from transformers" and Fixed: "KeyError: The task summarization has been removed from transformers" show the error and do both tasks with a small chat model.

Versions Used​

The project from Part 1, unchanged: Python 3.14.10, uv 0.13.10, Transformers 5.24.1 and PyTorch 2.15.0. The outputs were captured on a Mac with an Apple M1 Pro; on Windows and Linux, the commands are the same.

What This Part Costs​

Nothing. The three new models are free to use, commercially too: dslim/bert-base-NER is under the MIT license, and ModernBERT-base and all-MiniLM-L6-v2 under Apache-2.0. The sentiment model is already in your cache from Part 1. The new downloads need about 1.1 GB of disk space, 433 MB, 599 MB and 91 MB, and Clean Up deletes the ones later parts don't use.

Prerequisites​

  • The project from Part 1, dewiride-support-intent-router. Run every command in this part inside its folder.
  • About 1.1 GB of free disk space and an internet connection, for the three new models.

Step 1: Find a Model for the Task​

Every pipeline needs a model trained for its task. Each task has a default model, but Part 1 named its own, to choose the license and the exact version. That matters here: the default model for named entity recognition (NER), dbmdz/bert-large-cased-finetuned-conll03-english, is a 1.3 GB download whose Hub page states no license. So find one on the Hub. Open huggingface.co/models in your browser; you don't need an account.

Choose the task. On the left, click the Tasks tab, and under Natural Language Processing, click Token Classification: NER gives a label to each token, so it's a token-classification task.

The Natural Language Processing tasks on the Hugging Face Models page, with Token Classification selected among Text Classification, Table Question Answering, Question Answering, Zero-Shot Classification, Translation, Summarization, Feature Extraction, Text Generation, Fill-Mask, Sentence Similarity and Text Ranking.

Narrow the list. Type ner in the Filter by name box above the list, and change Sort, on the right, from Trending to Most downloads. 888 models matched when I did it, and dslim/bert-base-NER came first, with 1.03M downloads. 0.1B on its card means about 0.1 billion parameters, the numbers the model learned: a small model. How to Find a Model for a Task on the Hugging Face Hub also filters by license and shows what else a model's page tells you.

The Models page filtered to Token Classification and the name ner, sorted by most downloads: 888 models, led by dslim/bert-base-NER with 0.1B parameters and 1.03M downloads, then Babelscape/wikineural-multilingual-ner and two OpenMed models.

Open the model. Click dslim/bert-base-NER. The tags under its name say what it is: a Token Classification model that runs with Transformers and PyTorch, trained on the conll2003 dataset, in English, and License: mit, which allows commercial use. The scripts below pin the model to its newest commit, d1a3e8f13f8c3566299d95fcfc9a8d2382a9affc, the way Part 1 pinned its models; How to Pin a Hugging Face Model to an Exact Revision shows where to find it.

The tags at the top of the dslim/bert-base-NER page: Token Classification, Transformers, PyTorch, TensorFlow, JAX, ONNX, Safetensors, conll2003, English, bert, Eval Results (legacy), arxiv:1810.04805 and License: mit.

Read what it finds. The model card's description says it "has been trained to recognize four types of entities: location (LOC), organizations (ORG), person (PER) and Miscellaneous (MISC)".

The Model description section of the dslim/bert-base-NER card: a fine-tuned BERT model for Named Entity Recognition, trained to recognize location (LOC), organizations (ORG), person (PER) and Miscellaneous (MISC), fine-tuned from bert-base-cased on the English CoNLL-2003 dataset.

Further down, the card is honest about its limits: "This model is limited by its training dataset of entity-annotated news articles from a specific span of time. This may not generalize well for all use cases in different domains." Support messages aren't news articles, so check its answers on your own messages, as the next step does.

Read its labels. The card's table lists the nine labels the model gives a token: O for a token outside any name, then a B- and an I- label for each of the four kinds of names.

The table of labels on the dslim/bert-base-NER card: O for outside of a named entity, then B-MISC, I-MISC, B-PER, I-PER, B-ORG, I-ORG, B-LOC and I-LOC, where each B- label is described as the beginning of an entity right after another entity of the same kind.

The table describes B- the older way, as the start of a name "right after another" name of the same kind. Step 2 shows what this model really does with it.

Step 2: Tag Every Name in a Support Message​

Customers write names in their messages: their own, the person they sent money to, a city. First, make the folder for this part's scripts, inside the project folder:

Terminal
mkdir playground

mkdir makes a folder, the same way in PowerShell. Keeping the scripts inside the project lets uv run run them with the project's packages, Transformers and PyTorch.

Create playground/ner_tokens.py:

playground/ner_tokens.py
"""Tag every name, place and organization in a support message, token by token."""

from transformers import pipeline

ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
revision="d1a3e8f13f8c3566299d95fcfc9a8d2382a9affc",
)

message = (
"Hi, this is Priya Ramanathan. I sent 250 euros to my brother Daniel "
"in Madrid on Monday and he still hasn't got it."
)

for token in ner(message):
print(f"{token['word']:<8} {token['entity']:<6} {token['score']:.3f}")
  • "token-classification" is the task. "ner" works too: it's the task's other name.
  • message is one long text written over two lines: Python joins two strings that stand next to each other inside the round brackets.
  • ner(message) returns one dictionary for each token it tagged. The loop prints three of its keys: the token (word), its label (entity) and how sure the model is of the label (score, from 0 to 1). :<8 pads the token to 8 characters so the columns line up, and .3f shows the score with three decimals.

Run it:

Terminal
uv run python playground/ner_tokens.py
Output
W1204 10:50:52.672000 30317 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
config.json: 100%|█████████████████████████████████████████████████| 829/829 [00:00<00:00, 7.27MB/s]
model.safetensors: downloading bytes: ██████████████████████████████████████████| 411MB, 9.23MB/s
model.safetensors: reconstructing file: 100%|██████████████████████████| 433MB / 433MB, 25.9MB/s
Loading weights: 100%|█████████████████████████████████████████| 199/199 [00:00<00:00, 14953.36it/s]
[transformers] BertForTokenClassification LOAD REPORT from: dslim/bert-base-NER
Key | Status | Details
-------------------------+------------+--------
bert.pooler.dense.bias | UNEXPECTED |
bert.pooler.dense.weight | UNEXPECTED |

Notes:
- UNEXPECTED: can be ignored when loading from different task/architecture; not ok if you expect identical arch.
tokenizer_config.json: 100%|██████████████████████████████████████| 59.0/59.0 [00:00<00:00, 375kB/s]
vocab.txt: 100%|█████████████████████████████████████████████████| 213k/213k [00:00<00:00, 3.02MB/s]
added_tokens.json: 100%|█████████████████████████████████████████| 2.00/2.00 [00:00<00:00, 7.94kB/s]
special_tokens_map.json: 100%|██████████████████████████████████████| 112/112 [00:00<00:00, 349kB/s]
P B-PER 0.999
##riya B-PER 0.902
Rama I-PER 0.998
##nath I-PER 0.987
Daniel B-PER 0.999
Madrid B-LOC 1.000

The terminal after uv run python playground/ner_tokens.py: the model downloading, a BertForTokenClassification LOAD REPORT with two UNEXPECTED pooler weights, then six tagged tokens: P B-PER, ##riya B-PER, Rama I-PER, ##nath I-PER, Daniel B-PER and Madrid B-LOC.

From the top:

  • The NOTE line is the same harmless note from PyTorch on a Mac as in Part 1. Fixed: "NOTE: Redirects are currently not supported in MacOs." shows where it comes from.
  • The downloads. The first run downloads the model, 433 MB, and its tokenizer's files, with the same notice about unauthenticated requests as in Part 1. Later runs load them from the cache.
  • The LOAD REPORT is a warning, not an error. The model's file holds a part called the pooler, which a token classifier doesn't use, so Transformers leaves it out and lists its two weights as UNEXPECTED. Its own note says that "can be ignored when loading from different task/architecture". Fixed: "BertForTokenClassification LOAD REPORT from: dslim/bert-base-NER" explains it and how to hide it.
  • The tokens. B- marks the first token of a name and I- a token that continues it; PER is a person and LOC a location. "Daniel" and "Madrid" follow no other name, yet both got B-: this model starts every name with B-, not only one right after another name.
  • The ## pieces. The model's vocabulary has no single token for "Priya" or "Ramanathan", so its tokenizer split them into pieces. ## means "glued to the token before". Part 4 shows how tokenizers split words.
  • What's missing. "250 euros" and "Monday" aren't any of the four kinds of names. The model labels such tokens O, and the pipeline leaves O tokens out.

Two things are wrong. ##riya got B-PER, as if a second person started in the middle of "Priya". And "Ramanathan" is cut short: the model labelled the end of the word O. The card warned about the first: "the model occassionally tags subword tokens as entities and post-processing of results may be necessary to handle those cases."

Step 3: Group the Tokens into Whole Names​

A list of word pieces is hard to use. The pipeline can join them into whole names with aggregation_strategy. Try two strategies on the same message: the loop runs the pipeline once with "simple" and once with "first".

playground/ner_entities.py (the loop)
for strategy in ("simple", "first"):
print(f'aggregation_strategy="{strategy}"')
for entity in ner(message, aggregation_strategy=strategy):
print(
f" {entity['word']:<16} {entity['entity_group']:<4} {entity['score']:.3f}"
)

With a strategy, each result is a whole name. Its kind is in entity_group, without the B- or I-. The complete file, playground/ner_entities.py:

playground/ner_entities.py
"""Group the tagged tokens of a support message into whole names and places."""

from transformers import pipeline

ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
revision="d1a3e8f13f8c3566299d95fcfc9a8d2382a9affc",
)

message = (
"Hi, this is Priya Ramanathan. I sent 250 euros to my brother Daniel "
"in Madrid on Monday and he still hasn't got it."
)

for strategy in ("simple", "first"):
print(f'aggregation_strategy="{strategy}"')
for entity in ner(message, aggregation_strategy=strategy):
print(
f" {entity['word']:<16} {entity['entity_group']:<4} {entity['score']:.3f}"
)

The ner_entities.py script in a macOS-style code window: a token-classification pipeline with dslim/bert-base-NER pinned to a commit, the support message about Priya Ramanathan, Daniel and Madrid, and a loop that runs the pipeline with aggregation_strategy simple and then first, printing each name, its kind and its score.

Terminal
uv run python playground/ner_entities.py
Output
W1204 10:51:44.584000 31422 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|█████████████████████████████████████████| 199/199 [00:00<00:00, 12193.63it/s]
[transformers] BertForTokenClassification LOAD REPORT from: dslim/bert-base-NER
Key | Status | Details
-------------------------+------------+--------
bert.pooler.dense.bias | UNEXPECTED |
bert.pooler.dense.weight | UNEXPECTED |

Notes:
- UNEXPECTED: can be ignored when loading from different task/architecture; not ok if you expect identical arch.
aggregation_strategy="simple"
P PER 0.999
##riya Ramanath PER 0.962
Daniel PER 0.999
Madrid LOC 1.000
aggregation_strategy="first"
Priya Ramanathan PER 0.999
Daniel PER 0.999
Madrid LOC 1.000

The terminal after uv run python playground/ner_entities.py: with aggregation_strategy simple, P and ##riya Ramanath as two people, then Daniel and Madrid; with first, Priya Ramanathan as one person, then Daniel and Madrid.

  • "simple" joins each B- token with the I- tokens after it. Because ##riya started with B-, one customer became two people, P and ##riya Ramanath, both wrong.
  • "first" works on whole words: each word takes the label of its first token. "Priya" takes B-PER from P and "Ramanathan" takes I-PER from Rama, so the two words make one person, and the pipeline joins the pieces back into whole words, the untagged end of "Ramanathan" included.

The documentation marks "first", "average" and "max" as working "only on word based models": models whose tokens follow the spaces between words, as BERT's do. For a BERT model like this one, use a word-level strategy. How to Find Names, Places and Organizations in Text with a Hugging Face NER Pipeline compares all five strategies, and Fixed: Hugging Face NER Pipeline Splits a Name into Pieces Like "##ka" shows the same split on another name.

note

NER found the names, but it can't tell the router what a message is about: it labels words, not whole messages.

Step 4: Classify Whole Messages​

Text classification gives one label to a whole message. Part 1's first pipeline did this with one sentence; here, three support messages go in together, and the second call asks for every label's score. Create playground/classify.py:

playground/classify.py
"""Classify support messages as positive or negative, with every label's score."""

from transformers import pipeline

classifier = pipeline(
"text-classification",
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
revision="714eb0fa89d2f80546fda750413ed43d93601a13",
)

messages = [
"Thanks, the money arrived in minutes!",
"This is the third time my card payment failed. I'm furious.",
"How do I change my PIN?",
]

print(classifier(messages))
print(classifier(messages, top_k=None))
  • classifier(messages) takes the whole list and returns one result per message, in the same order.
  • top_k=None asks for every label instead of only the best one. A number, such as top_k=2, would return that many.
Terminal
uv run python playground/classify.py
Output
W1204 10:51:49.522000 31507 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|██████████████████████████████████████████| 104/104 [00:00<00:00, 8102.23it/s]
[{'label': 'POSITIVE', 'score': 0.998742401599884}, {'label': 'NEGATIVE', 'score': 0.9989423155784607}, {'label': 'NEGATIVE', 'score': 0.9990561604499817}]
[[{'label': 'POSITIVE', 'score': 0.998742401599884}, {'label': 'NEGATIVE', 'score': 0.00125756801571697}], [{'label': 'NEGATIVE', 'score': 0.9989423155784607}, {'label': 'POSITIVE', 'score': 0.0010577546199783683}], [{'label': 'NEGATIVE', 'score': 0.9990561604499817}, {'label': 'POSITIVE', 'score': 0.0009438989218324423}]]

The terminal after uv run python playground/classify.py: first a list of three results, POSITIVE 0.9987, NEGATIVE 0.9989 and NEGATIVE 0.9991; then the same three messages with both labels each, POSITIVE and NEGATIVE, the best one first.

There's no download: the model has been in your cache since Part 1.

  • The first line holds one dictionary per message: the best label and its score.
  • The second line, with top_k=None, holds a list per message, with both of the model's labels, best first. Each message's two scores add up to 1.

The first two answers are right. The third isn't: "How do I change my PIN?" is a neutral question, and the model called it NEGATIVE with a score of 0.999. The model was fine-tuned on SST-2, as its card says, and its only labels are POSITIVE and NEGATIVE, so it has to choose one of them. A score says how sure the model is between its own labels, not whether either label fits. Part 1's router works the same way: it always picks one of its intents.

Older examples ask for every score with return_all_scores=True. Transformers 5 ignores it and returns only the best label, without a warning: use top_k=None, as Fixed: return_all_scores=True Returns Only One Label in Transformers 5 shows. How to Get the Score of Every Label from a Hugging Face Text Classification Pipeline uses top_k on a model with six labels.

Step 5: Classify a Message Longer Than the Model Can Read​

A customer might paste a whole conversation into one message. To try a really long one, the script below builds a complaint from one sentence repeated 40 times. Create playground/long_message.py:

playground/long_message.py
"""Classify a very long support message."""

from transformers import pipeline

classifier = pipeline(
"text-classification",
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
revision="714eb0fa89d2f80546fda750413ed43d93601a13",
)

# A long complaint: the same sentence 40 times.
sentence = "My card payment failed again and I am really not happy about how this has been handled."
message = " ".join([sentence] * 40)

print(classifier(message))

[sentence] * 40 makes a list that holds the sentence 40 times, and " ".join(...) joins its items into one text, with a space between them.

Terminal
uv run python playground/long_message.py
Output (start and end)
W1204 10:51:54.532000 31580 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|█████████████████████████████████████████| 104/104 [00:00<00:00, 27608.08it/s]
[transformers] Token indices sequence length is longer than the specified maximum sequence length for this model (722 > 512). Running this sequence through the model will result in indexing errors
Traceback (most recent call last):
File "/Users/you/source/dewiride-support-intent-router/playground/long_message.py", line 15, in <module>
print(classifier(message))
~~~~~~~~~~^^^^^^^^^
...
embeddings = inputs_embeds + position_embeddings # (bs, max_seq_length, dim)
~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
RuntimeError: The size of tensor a (722) must match the size of tensor b (512) at non-singleton dimension 1

The terminal after uv run python playground/long_message.py: the warning Token indices sequence length is longer than the specified maximum sequence length for this model (722 > 512), then a traceback from print(classifier(message)) on line 15, ending in RuntimeError: The size of tensor a (722) must match the size of tensor b (512) at non-singleton dimension 1.

The ... stands for the middle of the traceback: calls inside Transformers and PyTorch.

  • The warning. The tokenizer turned the message into 722 tokens, more than this model's limit of 512, and warned that running it "will result in indexing errors".
  • The error. To know the order of the words, the model adds a position vector to each token, and it has only 512 of them. Adding 512 position vectors to 722 tokens fails: that's the RuntimeError on the last line.

Fixed: "RuntimeError: The size of tensor a (802) must match the size of tensor b (512) at non-singleton dimension 1" shows the same error with another text's length, on the GPU and on the CPU. The fix is to let the tokenizer cut the text to the length the model accepts. Replace the last line of playground/long_message.py with:

playground/long_message.py (last line)
print(classifier(message, truncation=True))

The text-classification pipeline passes truncation=True on to its tokenizer. With no length given, the tokenizer cuts the text to the maximum the model accepts, 512 tokens.

Terminal
uv run python playground/long_message.py
Output
W1204 10:51:59.377000 31669 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|█████████████████████████████████████████| 104/104 [00:00<00:00, 23184.03it/s]
[{'label': 'NEGATIVE', 'score': 0.9997748732566833}]

The terminal after running the script again with truncation=True: no warning and no error, and the result NEGATIVE with a score of 0.9998.

NEGATIVE with 0.9998, and no warning. But the model read only the first 512 tokens. Here that's harmless, because the message repeats itself; in a real message, everything after that point is ignored. Part 4 measures how long banking77's messages really are.

Step 6: Fill In a Missing Word with ModernBERT​

ModernBERT-base is the model this series fine-tunes from Part 7 on. Before fine-tuning, it can do one task, and its card names it: "Since ModernBERT is a Masked Language Model (MLM), you can use the fill-mask pipeline". A masked language model learned language by guessing words hidden in sentences. You hide a word by writing ModernBERT's mask token, [MASK], in its place. Create playground/fill_mask.py:

playground/fill_mask.py
"""Ask ModernBERT to fill in the missing word of a support message."""

from transformers import pipeline

fill = pipeline(
"fill-mask",
model="answerdotai/ModernBERT-base",
revision="8949b909ec900327062f0ebf497f51aef5e6f0c8",
)

sentences = [
"My new card still hasn't [MASK].",
"I lost my wallet, so I want to [MASK] my card.",
"How much does it cost to send money [MASK]?",
]

for sentence in sentences:
print(sentence)
for guess in fill(sentence):
print(f" {guess['token_str'].strip():<14} {guess['score']:.3f}")

For each sentence, fill(sentence) returns the five words the model finds most likely, best first. Each guess's token_str comes with the space that goes before the word, so .strip() removes it for printing.

Terminal
uv run python playground/fill_mask.py
Output
W1204 10:52:04.575000 31788 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
config.json: 100%|█████████████████████████████████████████████| 1.19k/1.19k [00:00<00:00, 4.31MB/s]
model.safetensors: downloading bytes: ██████████████████████████████████████████| 569MB, 295kB/s
model.safetensors: reconstructing file: 100%|██████████████████████████| 599MB / 599MB, 4.30MB/s
Loading weights: 100%|██████████████████████████████████████████| 137/137 [00:00<00:00, 5100.93it/s]
tokenizer_config.json: 100%|███████████████████████████████████| 20.8k/20.8k [00:00<00:00, 4.29MB/s]
tokenizer.json: 100%|██████████████████████████████████████████| 2.13M/2.13M [00:00<00:00, 10.5MB/s]
special_tokens_map.json: 100%|█████████████████████████████████████| 694/694 [00:00<00:00, 6.87MB/s]
My new card still hasn't [MASK].
[transformers] Ignoring clean_up_tokenization_spaces=True for BPE tokenizer TokenizersBackend. The clean_up_tokenization post-processing step is designed for WordPiece tokenizers and is destructive for BPE (it strips spaces before punctuation). Set clean_up_tokenization_spaces=False to suppress this warning, or set clean_up_tokenization_spaces_for_bpe_even_though_it_will_corrupt_output=True to force cleanup anyway.
arrived 0.626
worked 0.070
come 0.037
appeared 0.035
shipped 0.030
I lost my wallet, so I want to [MASK] my card.
use 0.194
get 0.110
change 0.094
replace 0.053
return 0.040
How much does it cost to send money [MASK]?
overseas 0.176
abroad 0.145
online 0.142
here 0.087
internationally 0.073

The terminal after uv run python playground/fill_mask.py: the 599 MB model downloading, a warning that begins Ignoring clean_up_tokenization_spaces=True for BPE tokenizer TokenizersBackend, then five guesses per sentence: arrived 0.626 for the card, use 0.194 for the wallet, and overseas 0.176 for sending money.

The guesses make sense: "arrived" for the new card, with 0.626, and "overseas", "abroad" and "internationally" for sending money. ModernBERT wasn't trained on support messages, but it already knows how people write about cards and payments: its card says it was "pre-trained on 2 trillion tokens of English and code data". Fine-tuning builds on that knowledge.

The warning in the middle comes from turning the guessed tokens back into text. ModernBERT's settings ask Transformers to tidy the spaces in that text, a step that, as the warning says, "is designed for WordPiece tokenizers and is destructive for BPE", the kind of tokenizer ModernBERT has. So Transformers skips it, warns, and says how to stop the warning: set clean_up_tokenization_spaces=False. That setting belongs to the tokenizer, so load the tokenizer yourself with it, and hand it to the pipeline:

playground/fill_mask.py (the model and the tokenizer)
from transformers import AutoTokenizer, pipeline

MODEL = "answerdotai/ModernBERT-base"
REVISION = "8949b909ec900327062f0ebf497f51aef5e6f0c8"

# ModernBERT's tokenizer settings ask for a clean-up step that only suits other
# tokenizers. Turning it off stops the warning; the predictions stay the same.
tokenizer = AutoTokenizer.from_pretrained(
MODEL, revision=REVISION, clean_up_tokenization_spaces=False
)
fill = pipeline("fill-mask", model=MODEL, revision=REVISION, tokenizer=tokenizer)
  • AutoTokenizer.from_pretrained loads a model's tokenizer from the Hub, at the same pinned revision, and clean_up_tokenization_spaces=False changes that one setting. Part 4 is all about tokenizers.
  • MODEL and REVISION hold the name and the commit once, because the tokenizer and the pipeline both need them.
  • tokenizer=tokenizer makes the pipeline use this tokenizer instead of loading its own.

Fixed: "Ignoring clean_up_tokenization_spaces=True for BPE tokenizer TokenizersBackend" covers the warning in detail, and How to Predict a Missing Word with a Hugging Face Fill-Mask Pipeline shows the task on a simpler example. The complete playground/fill_mask.py:

playground/fill_mask.py
"""Ask ModernBERT to fill in the missing word of a support message."""

from transformers import AutoTokenizer, pipeline

MODEL = "answerdotai/ModernBERT-base"
REVISION = "8949b909ec900327062f0ebf497f51aef5e6f0c8"

# ModernBERT's tokenizer settings ask for a clean-up step that only suits other
# tokenizers. Turning it off stops the warning; the predictions stay the same.
tokenizer = AutoTokenizer.from_pretrained(
MODEL, revision=REVISION, clean_up_tokenization_spaces=False
)
fill = pipeline("fill-mask", model=MODEL, revision=REVISION, tokenizer=tokenizer)

sentences = [
"My new card still hasn't [MASK].",
"I lost my wallet, so I want to [MASK] my card.",
"How much does it cost to send money [MASK]?",
]

for sentence in sentences:
print(sentence)
for guess in fill(sentence):
print(f" {guess['token_str'].strip():<14} {guess['score']:.3f}")

The complete fill_mask.py in a macOS-style code window: ModernBERT-base's name and pinned revision, its tokenizer loaded with clean_up_tokenization_spaces=False and passed to a fill-mask pipeline, three support sentences with [MASK], and a loop that prints each guess and its score.

Terminal
uv run python playground/fill_mask.py
Output
W1204 10:58:29.635000 71376 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|█████████████████████████████████████████| 137/137 [00:00<00:00, 11170.03it/s]
My new card still hasn't [MASK].
arrived 0.626
worked 0.070
come 0.037
appeared 0.035
shipped 0.030
I lost my wallet, so I want to [MASK] my card.
use 0.194
get 0.110
change 0.094
replace 0.053
return 0.040
How much does it cost to send money [MASK]?
overseas 0.176
abroad 0.145
online 0.142
here 0.087
internationally 0.073

The terminal after running the fixed fill_mask.py: no warning, and the same five guesses and scores for each sentence as before.

The same guesses with the same scores, and no warning: Transformers was already skipping the clean-up, so turning it off removed only the warning.

Step 7: Compare What Messages Mean with Embeddings​

Feature extraction returns the numbers a model computes for each token: hundreds of numbers per token, which together stand for what the token means in its sentence. Averaged over all the tokens, they give one list of numbers for the whole message, its embedding. Messages that mean similar things get embeddings that point in similar directions, and cosine similarity measures how similar the directions are: the closer to 1, the more alike.

The script compares one message with three others, using two models: all-MiniLM-L6-v2, which its card says "maps sentences & paragraphs to a 384 dimensional dense vector space and can be used for tasks like clustering or semantic search", and ModernBERT-base, the model from Step 6. Start playground/embeddings.py with the models and the messages:

playground/embeddings.py (models and messages)
from torch.nn.functional import cosine_similarity
from transformers import pipeline

MODELS = {
"sentence-transformers/all-MiniLM-L6-v2": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
"answerdotai/ModernBERT-base": "8949b909ec900327062f0ebf497f51aef5e6f0c8",
}

message = "My card still hasn't arrived."
others = [
"When will my new card be delivered?",
"I was charged twice for one purchase.",
"How do I change my PIN?",
]

MODELS maps each model's name to its pinned commit. Of the three other messages, the first asks about the same thing in other words, and the other two are about something else.

Next, a function that turns a text into one vector:

playground/embeddings.py (embed)
def embed(extractor, text):
"""One vector for the whole text: the average of its token vectors."""
return extractor(text, return_tensors=True).mean(dim=1)

Then the loop:

playground/embeddings.py (the loop)
for model, revision in MODELS.items():
extractor = pipeline("feature-extraction", model=model, revision=revision)
print(model, extractor(message, return_tensors=True).shape)
vector = embed(extractor, message)
for other in others:
similarity = cosine_similarity(vector, embed(extractor, other))
print(f" {similarity.item():.3f} {other}")

The complete playground/embeddings.py:

playground/embeddings.py
"""Compare the meaning of support messages with embeddings from two models."""

from torch.nn.functional import cosine_similarity
from transformers import pipeline

MODELS = {
"sentence-transformers/all-MiniLM-L6-v2": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
"answerdotai/ModernBERT-base": "8949b909ec900327062f0ebf497f51aef5e6f0c8",
}

message = "My card still hasn't arrived."
others = [
"When will my new card be delivered?",
"I was charged twice for one purchase.",
"How do I change my PIN?",
]


def embed(extractor, text):
"""One vector for the whole text: the average of its token vectors."""
return extractor(text, return_tensors=True).mean(dim=1)


for model, revision in MODELS.items():
extractor = pipeline("feature-extraction", model=model, revision=revision)
print(model, extractor(message, return_tensors=True).shape)
vector = embed(extractor, message)
for other in others:
similarity = cosine_similarity(vector, embed(extractor, other))
print(f" {similarity.item():.3f} {other}")

The complete embeddings.py in a macOS-style code window: two models with pinned commits, a message about a card that hasn't arrived and three others, an embed function that averages the token vectors with mean(dim=1), and a loop that prints each model's tensor shape and the cosine similarity of the message with each other message.

Terminal
uv run python playground/embeddings.py
Output
W1204 10:58:34.933000 74371 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
config.json: 100%|█████████████████████████████████████████████████| 612/612 [00:00<00:00, 5.14MB/s]
model.safetensors: downloading bytes: ██████████████████████████████████████████| 85.0MB, 5.65MB/s
model.safetensors: reconstructing file: 100%|██████████████████████████| 90.9MB / 90.9MB, 7.49MB/s
Loading weights: 100%|█████████████████████████████████████████| 103/103 [00:00<00:00, 11993.71it/s]
tokenizer_config.json: 100%|███████████████████████████████████████| 350/350 [00:00<00:00, 2.64MB/s]
vocab.txt: 100%|█████████████████████████████████████████████████| 232k/232k [00:00<00:00, 3.30MB/s]
tokenizer.json: 100%|████████████████████████████████████████████| 466k/466k [00:00<00:00, 7.76MB/s]
special_tokens_map.json: 100%|██████████████████████████████████████| 112/112 [00:00<00:00, 888kB/s]
sentence-transformers/all-MiniLM-L6-v2 torch.Size([1, 10, 384])
0.672 When will my new card be delivered?
0.333 I was charged twice for one purchase.
0.305 How do I change my PIN?
Loading weights: 100%|██████████████████████████████████████████| 134/134 [00:00<00:00, 1121.22it/s]
[transformers] ModernBertModel LOAD REPORT from: answerdotai/ModernBERT-base
Key | Status | Details
------------------+------------+--------
head.dense.weight | UNEXPECTED |
decoder.bias | UNEXPECTED |
head.norm.weight | UNEXPECTED |

Notes:
- UNEXPECTED: can be ignored when loading from different task/architecture; not ok if you expect identical arch.
answerdotai/ModernBERT-base torch.Size([1, 9, 768])
0.949 When will my new card be delivered?
0.914 I was charged twice for one purchase.
0.928 How do I change my PIN?

The terminal after uv run python playground/embeddings.py: all-MiniLM-L6-v2 downloading, its shape 1, 10, 384 and the scores 0.672 for the delivery question, 0.333 for the double charge and 0.305 for the PIN question; then a ModernBertModel LOAD REPORT, its shape 1, 9, 768 and the scores 0.949, 0.914 and 0.928.

  • all-MiniLM-L6-v2 split the message into 10 tokens of 384 numbers each, torch.Size([1, 10, 384]). Its scores follow the meaning: 0.672 for the delivery question, which asks about the same card, and about 0.3 for the two messages about something else.
  • ModernBERT-base split it into 9 tokens of 768 numbers. Its scores, 0.949, 0.914 and 0.928, are all close to 1, and it rates the PIN question above the double charge: its averaged vectors don't tell these messages apart.
  • The ModernBertModel LOAD REPORT. Feature extraction loads a model without any task on top, and ModernBERT's file holds the fill-mask layers Step 6 used, so their weights go unused: the same kind of report as in Step 2.

The difference is training. all-MiniLM-L6-v2 was fine-tuned on a dataset of 1 billion pairs of sentences to recognize which sentence belongs with which, as its card explains. ModernBERT wasn't, and its card says so: to use it "for downstream tasks like classification, retrieval, or QA, fine-tune it following standard BERT fine-tuning recipes." How to Turn a Sentence into an Embedding with a Hugging Face Feature-Extraction Pipeline and How to Measure How Similar Two Sentences Are with Hugging Face Embeddings show both on their own examples.

Which Task Fits the Router​

The router answers one question for each message: which of the bank's intents is it about? Here's how each task fared on that kind of message:

TaskWhat it did with support messagesFits the router?
Token classificationFound the names and places, once grouped with "first"No: it labels words, not messages
Text classificationOne label per message, but the sentiment model only knows two labels, and called a neutral question NEGATIVEYes, with a model trained on the router's intents
Fill-maskGuessed sensible missing wordsNo, but it shows what ModernBERT knows before fine-tuning
Feature extractionPut messages with the same meaning close together, with the right modelNot by itself: it compares messages, it doesn't label them
Zero-shot classification (Part 1)One intent per message, from labels you choose, with no trainingYes: it's the router today

The router's job is text classification with its own labels. There are two ways to get it. Zero-shot classification needs no training and is what the router uses now; Part 3 measures it on all 77 banking77 intents. Or a model like ModernBERT learns the intents from labelled messages, by fine-tuning, which Parts 6 to 8 do. Step 4 showed why the labels matter: a confident answer from a model trained on other labels is still the wrong answer.

Your Project Now Looks Like This​

dewiride-support-intent-router/
dewiride-support-intent-router/
├── .gitignore
├── .python-version
├── README.md
├── playground/
│ ├── classify.py
│ ├── embeddings.py
│ ├── fill_mask.py
│ ├── long_message.py
│ ├── ner_entities.py
│ └── ner_tokens.py
├── pyproject.toml
├── src/
│ └── support_intent_router/
│ ├── __init__.py
│ ├── cli.py
│ └── router.py
└── uv.lock

Only playground/ is new, and Clean Up deletes it: the router is the same as at the end of Part 1.

Clean Up​

The playground and three of the models aren't needed after this part. Delete them, and keep two models that later parts use: facebook/bart-large-mnli, the router's model, and ModernBERT-base.

First the playground folder, from the project folder:

Terminal
rm -r playground

Then the three models, from the Hugging Face cache. hf cache rm lists what it will delete and asks first; type y and press Enter:

Terminal
uv run hf cache rm model/dslim/bert-base-NER model/distilbert/distilbert-base-uncased-finetuned-sst-2-english model/sentence-transformers/all-MiniLM-L6-v2
Output
About to delete 3 repo(s) totalling 793.1M.
- model/distilbert/distilbert-base-uncased-finetuned-sst-2-english (entire repo)
- model/dslim/bert-base-NER (entire repo)
- model/sentence-transformers/all-MiniLM-L6-v2 (entire repo)
Proceed with deletion? [y/N]: y
✓ Deleted 3 repo(s) and 3 revision(s); freed 793.1M.
repos_deleted: 3
revisions_deleted: 3
freed: 793.1M

Check what's left:

Terminal
uv run hf cache ls
Output
ID SIZE LAST_ACCESSED LAST_MODIFIED REFS
--------------------------------- ------ -------------- ------------- ----
model/answerdotai/ModernBERT-base 600.8M 36 minutes ago 2 hours ago
model/facebook/bart-large-mnli 1.6G 2 hours ago 3 days ago

Found 2 repo(s) for a total of 2 revision(s) and 2.2G on disk.

The terminal after the clean-up: hf cache rm deleting the three models after a y, then hf cache ls listing only answerdotai/ModernBERT-base and facebook/bart-large-mnli.

How to Delete a Model from Your Hugging Face Cache with hf cache rm explains each line. The commands work unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Asking for a removed task, such as pipeline("summarization")KeyError: 'The task summarization has been removed from transformers. …'The text-generation pipeline with a chat model
Grouping a BERT model's tokens with "simple""Priya Ramanathan" came back as two people, P and ##riya Ramanathaggregation_strategy="first"
Copying return_all_scores=True from an older exampleOnly the best label comes back, without a warningtop_k=None
Using a model whose labels don't fit your messages"How do I change my PIN?" came back NEGATIVE with 0.999A model trained on labels that fit, or zero-shot with your own labels
Comparing meanings with a model that wasn't trained for itModernBERT scored all three messages above 0.9A sentence-embedding model such as all-MiniLM-L6-v2

Troubleshooting​

SymptomLikely causeFix
NOTE: Redirects are currently not supported in MacOs.PyTorch on a Mac, triggered by Transformers 5.24's importsNothing: it doesn't affect results
A LOAD REPORT listing UNEXPECTED keysThe model's file holds weights the task doesn't useNothing: it's a warning
Token indices sequence length is longer than the specified maximum sequence length for this model (722 > 512), then RuntimeError: The size of tensor a (722) must match the size of tensor b (512) at non-singleton dimension 1The message has more tokens than the model can readtruncation=True
Ignoring clean_up_tokenization_spaces=True for BPE tokenizer TokenizersBackendModernBERT's tokenizer settingsLoad the tokenizer with clean_up_tokenization_spaces=False, as in Step 6
PipelineException: No mask_token ([MASK]) found on the inputThe sentence doesn't contain the model's mask tokenWrite [MASK] where the word goes. Fixed: "PipelineException: No mask_token ([MASK]) found on the input"
TypeError: list indices must be integers or slices, not str with top_ktop_k=None on a single text returns a list inside a listFixed: "TypeError: list indices must be integers or slices, not str" with a Hugging Face Pipeline's top_k
A script seems stuck on its first runA model is downloadingWait; later runs use the cache

FAQ​

Why not use each task's default model?​

Transformers picks the default, not you: you can't choose its license, its size or its version, and it prints a warning. For NER, the default is a 1.3 GB model whose Hub page states no license. Naming the model and its revision, as every script here does, keeps the results the same on every run.

Why weren't "250 euros" and "Monday" found?​

The model finds only four kinds of names: people, organizations, locations and miscellaneous names. Amounts and dates aren't among them, so it labelled those words O, outside any name.

Did these scripts use the GPU?​

Yes. When you don't give a device, a pipeline uses the first accelerator it finds, as Part 1 showed with mps:0, so every output here came from the Mac's GPU. Without one, the same scripts run on the CPU.

Conclusion​

You chose an NER model on the Hub by its task, downloads and license, grouped its tokens into whole names, got every label's score from a text classifier, read a 722-token message by truncating it, asked ModernBERT for missing words and fixed its warning, and compared messages with embeddings. Each task answered a different question, and the router's question, which intent, is text classification with its own labels.

In Part 3, the zero-shot router meets all 77 banking77 intents, on real messages, and you measure how often it's right.

Additional Resources​


← Previous: Part 1: Install Transformers and Run Your First Pipeline

Next → Part 3: Run a Pipeline on a Whole Dataset (coming soon)