Skip to main content

Hugging Face Transformers Tutorial for NLP in Python — Part 1: Install Transformers and Run Your First Pipeline

· 30 min read
Jagdish Kumawat
Founder @ Dewiride

Hugging Face Transformers gives you thousands of pretrained language models and a few lines of Python to use them. In this first part you install Transformers and PyTorch, run your first pipeline on your computer's GPU, and build the first version of a project the whole series grows: a router that reads a customer's support message and decides what it's about.

This is Part 1 of a 12-part series.

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

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

What You'll Have at the End of the Series​

Each part teaches one piece of the Transformers library, in depth, and uses it in the same project. By the end of Part 12 you'll know how to:

  • run pretrained models with pipelines, on a GPU or a CPU (this part and Part 2);
  • turn text into model inputs with tokenizers, and read a model's raw outputs (Parts 3 and 4);
  • prepare your own data with the datasets library (Part 5);
  • fine-tune a model on your own labels with the Trainer, and measure how good it is (Parts 6 to 8);
  • share a model on the Hugging Face Hub (Part 9);
  • make it fast and serve it as a web API (Parts 10 and 11);
  • run it safely in production, with a checklist (Part 12).

Everything runs on your own computer, with free, open-source software. A second series, later, does the same for large language models: text generation, chat and fine-tuning them.

What Hugging Face Transformers Is​

Three names come up all the time:

NameWhat it is
Hugging Face HubA website, huggingface.co, that hosts models and datasets anyone can download, each with a page that says what it does and under which license
TransformersThe Python library that downloads models from the Hub and runs them, with the same code for every model
PyTorchThe deep-learning framework Transformers uses to do the maths, on the CPU or a GPU

The models are pretrained. The Transformers glossary defines a pretrained model as one "that has been pretrained on some data (for instance all of Wikipedia)": it has already learned how language works from huge amounts of text, so you can use it as it is, or teach it your task with fewer examples than training a model from scratch would need.

Encoders and Decoders​

Most models you'll meet belong to one of three families:

FamilyWhat it doesUsed for
Encoder models, such as BERTRead a whole text at once and "transform them into a condensed numerical representation called an embedding"Classifying text, finding names in it, answering questions from it
Decoder models, such as GPTRead text in order and "predict the next word"Generating text: chat, summaries, code
Encoder-decoder models, such as BART and T5An encoder reads the input, then a decoder writes the outputTranslating and summarizing, and the zero-shot model this part uses

The quotes are from the Transformers glossary. This series is about understanding and classifying text: the model you'll fine-tune from Part 6 is an encoder. The second series is about decoders.

What a Pipeline Does​

A pipeline is the quickest way to use a model. The glossary describes it as "a series of steps that are executed in a specific order to preprocess and transform data and return a prediction from a model":

You give it text and get back an answer such as POSITIVE with a score. Parts 3 and 4 open the box and run each step yourself.

The Example Project​

The series is about Transformers, not about one app, so the project grows behind the parts. It's a support-message router: a customer writes "my new card hasn't arrived", and the router says which topic, or intent, the message is about, so it can go to the right team, with a confidence score.

  • This part: a first router that needs no training. It uses zero-shot classification, which scores a message against labels you choose on the spot, and five intents.
  • Later parts: the router learns from banking77, a public dataset of 13,083 real customer-support messages in 77 intents, licensed CC BY 4.0, published by PolyAI. You'll fine-tune ModernBERT, an encoder model, on it, and compare it with this part's zero-shot router.

Versions Used​

ToolVersion
Python3.14.10
uv0.13.10
Transformers5.24.1
PyTorch2.15.0
huggingface_hub2.5.0
tokenizers0.23.3
Git2.56.1

The outputs were captured on a Mac with an Apple M1 Pro, whose GPU PyTorch uses through MPS. On Windows and Linux, the commands are the same.

Why Python 3.14 and Not 3.15​

Python 3.15 is the newest release, but the Hugging Face stack doesn't fully support it yet. Transformers 5.24.1 and the datasets library, which Part 5 uses, both list Python up to 3.14, and on 3.15, datasets' parallel processing fails with AttributeError: 'code' object has no attribute 'co_lnotab'. Fixed: AttributeError: 'code' object has no attribute 'co_lnotab' shows the failure and why. So the project uses Python 3.14.

What This Part Costs​

Nothing. Transformers, PyTorch and uv are free, open-source software, the two models this part downloads are free to use (Apache-2.0 and MIT licenses), and everything runs on your own computer. You don't need a Hugging Face account. You need about 3 GB of disk space: 0.8 GB for the project's packages and 1.9 GB for the models.

Prerequisites​

  • uv, which creates Python projects and installs packages. It also downloads Python 3.14 if your computer doesn't have it. Check uv:
Terminal
uv --version
Output
uv 0.13.10 (e3e7c1eac 2026-11-24 aarch64-apple-darwin)
  • Git, to commit the project. Check it:
Terminal
git --version
Output
git version 2.56.1
  • An internet connection, for the packages and the models.

Every command on this page works the same in Terminal (macOS), PowerShell (Windows) and Linux shells.

Step 1: Create the Project​

Terminal
uv init --package --name support-intent-router --python 3.14 dewiride-support-intent-router
Output
Initialized project `support-intent-router` at `/Users/you/source/dewiride-support-intent-router`

The terminal after uv init: Initialized project support-intent-router at /Users/you/source/dewiride-support-intent-router.

PartWhat it does
--packageMakes an installable project, with its code in a src/ folder
--name support-intent-routerThe project's name; its Python package becomes support_intent_router
--python 3.14Uses Python 3.14 and records it in .python-version
dewiride-support-intent-routerThe folder to create

How to Create a Python Project with uv explains every uv init option. uv also made the folder a Git repository. Move into it and name its branch main:

Terminal
cd dewiride-support-intent-router
git branch -m main

Step 2: Add Transformers and PyTorch​

Terminal
uv add transformers torch
Output
Using CPython 3.14.10
Creating virtual environment at: .venv
Resolved 60 packages in 3.10s
Built support-intent-router @ file:///Users/you/source/dewiride-support-intent-router
Prepared 39 packages in 21.46s
Installed 39 packages in 322ms
+ annotated-doc==0.0.7
+ annotated-types==0.8.0
+ anyio==4.16.0
+ click==8.5.1
+ filelock==4.3.2
+ fsspec==2026.9.0
+ h11==0.16.0
+ hf-xet==1.8.0
+ httpcore2==2.17.0
+ httpx2==2.17.0
+ huggingface-hub==2.5.0
+ idna==3.20
+ jinja2==3.1.6
+ markdown-it-py==4.3.0
+ markupsafe==3.0.4
+ mdurl==0.1.2
+ mpmath==1.3.0
+ networkx==3.7
+ numpy==2.5.5
+ packaging==26.4
+ pydantic==2.14.4
+ pydantic-core==2.50.5
+ pygments==2.21.0
+ pyyaml==6.0.4
+ regex==2026.11.30
+ rich==15.0.0
+ safetensors==0.8.0
+ setuptools==84.2.1
+ shellingham==1.5.4
+ support-intent-router==0.1.0 (from file:///Users/you/source/dewiride-support-intent-router)
+ sympy==1.14.0
+ tokenizers==0.23.3
+ torch==2.15.0
+ tqdm==4.70.1
+ transformers==5.24.1
+ truststore==0.10.5
+ typer==0.29.3
+ typing-extensions==4.16.0
+ typing-inspection==0.4.5

The terminal after uv add transformers torch: uv used CPython 3.14.10, created .venv, resolved 60 packages and installed 39, among them huggingface-hub 2.5.0, safetensors 0.8.0, tokenizers 0.23.3, torch 2.15.0 and transformers 5.24.1.

uv created the project's environment and installed both libraries with everything they need. Three of those packages do important work behind the scenes:

PackageWhat it does
huggingface-hubDownloads models from the Hub and keeps them in a local cache, so each is downloaded only once
tokenizersTurns text into the numbers a model reads, fast
safetensorsLoads model weights from .safetensors files, a format that can't run hidden code when it's opened

How to Add a Package to a Python Project with uv covers uv add in detail.

On Windows with an NVIDIA GPU: this command installs PyTorch from PyPI, and uv's PyTorch guide explains that PyPI "hosts CPU-only wheels for Windows and macOS, and GPU-accelerated wheels on Linux". On a Mac, the build still uses Apple's GPU. On Windows, follow that guide to install a CUDA build, or everything in this series runs on the CPU (slower, but it works).

Step 3: Check the Versions and the GPU​

Terminal
uv run python -c "import transformers, torch; print(transformers.__version__, torch.__version__)"
uv run python -c "import torch; print('Apple GPU (MPS):', torch.backends.mps.is_available()); print('NVIDIA GPU (CUDA):', torch.cuda.is_available())"
Output
5.24.1 2.15.0
Apple GPU (MPS): True
NVIDIA GPU (CUDA): False

The terminal after the two checks: 5.24.1 2.15.0, then Apple GPU (MPS): True and NVIDIA GPU (CUDA): False.

Transformers 5.24.1 and PyTorch 2.15.0 are installed, and PyTorch can use this Mac's GPU. On a PC with a working NVIDIA GPU and a CUDA build of PyTorch, the NVIDIA line would say True and the Apple line False. How to Check Whether PyTorch Can Use a GPU goes further.

Step 4: Run Your First Pipeline​

The Transformers installation guide checks an install with a one-line sentiment-analysis pipeline. Run it in the project:

Terminal
uv run python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))"
Output
W1201 05:05:58.723000 54420 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
[transformers] No model was supplied, defaulted to distilbert/distilbert-base-uncased-finetuned-sst-2-english and revision 714eb0f.
Using a pipeline without specifying a model name and revision in production is not recommended.
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%|█████████████████████████████████████████████████| 629/629 [00:00<00:00, 4.59MB/s]
model.safetensors: downloading bytes: ██████████████████████████████████████████| 250MB, 8.84MB/s
model.safetensors: reconstructing file: 100%|██████████████████████████| 268MB / 268MB, 16.5MB/s
Loading weights: 100%|██████████████████████████████████████████| 104/104 [00:00<00:00, 9626.12it/s]
tokenizer_config.json: 100%|██████████████████████████████████████| 48.0/48.0 [00:00<00:00, 151kB/s]
vocab.txt: 100%|█████████████████████████████████████████████████| 232k/232k [00:00<00:00, 3.07MB/s]
[{'label': 'POSITIVE', 'score': 0.999839186668396}]

The terminal after the first pipeline: a macOS note from PyTorch, the No model was supplied warning, the Hub's unauthenticated-requests warning, the model's files downloading, and the result: the label POSITIVE with the score 0.999839186668396.

The last line is the answer: POSITIVE, with a score of 0.9998, the model's confidence. Everything above it happened on the way, and it's worth reading once:

LineWhat it means
NOTE: Redirects are currently not supported in MacOs.A note from PyTorch on a Mac. Transformers 5.24 loads a part of PyTorch that prints it when imported. It changes nothing. Transformers' development branch no longer triggers it, so it should disappear in a later release
No model was supplied, defaulted to distilbert/distilbert-base-uncased-finetuned-sst-2-english and revision 714eb0f.You asked for a task, not a model, so Transformers used its default model for that task. Step 6 names the model itself, the way to fix this; Fixed: "No model was supplied, defaulted to …" explains it in full
Warning: You are sending unauthenticated requests to the HF Hub.A notice from the Hub: you downloaded without an account, which works, with lower rate limits. Part 9 signs in
config.json, model.safetensors, …The model's files downloading: its configuration, its 268 MB of weights and its tokenizer
Loading weightsThe weights loading into memory

How to Run Sentiment Analysis with a Hugging Face Pipeline shows this task with a named model and several texts.

Step 5: Run It Again​

Terminal
uv run python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))"
Output
W1201 05:06:34.459000 55094 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
[transformers] No model was supplied, defaulted to distilbert/distilbert-base-uncased-finetuned-sst-2-english and revision 714eb0f.
Using a pipeline without specifying a model name and revision in production is not recommended.
Loading weights: 100%|█████████████████████████████████████████| 104/104 [00:00<00:00, 13711.18it/s]
[{'label': 'POSITIVE', 'score': 0.999839186668396}]

The terminal after the second run: the same notes and warning, Loading weights, and the same result, with no downloads.

No downloads this time: the model came from the Hugging Face cache on your disk, and the answer is identical, to the last digit. The Hub's warning didn't appear either: the default model is pinned to a commit, and with that commit's files already in the cache, Transformers had no reason to contact the Hub.

Step 6: Write the Router​

Now the project's own code. The router uses zero-shot classification: for each intent you list, the model judges whether the message is about it, and the best-scoring intent wins. No training is needed. Create src/support_intent_router/router.py, piece by piece.

First, the model, pinned to one exact version, and the intents:

src/support_intent_router/router.py (top)
"""Route a customer support message to the intent it is about."""

from dataclasses import dataclass

from transformers import pipeline
from transformers.pipelines import Pipeline

# A zero-shot classification model (MIT licence). Pinning the commit means every run
# uses exactly the same weights, even if the model's owner updates it on the Hub.
MODEL = "facebook/bart-large-mnli"
REVISION = "d7645e127eaf1aefc7862fd59a17a5aa8558b8ce"

# The intents the router can choose from, written the way a person would say them.
INTENTS = (
"card arrival",
"lost or stolen card",
"refund not showing up",
"exchange rate",
"transfer not received by recipient",
)
NameWhat it is
MODELfacebook/bart-large-mnli, the model Transformers itself uses for zero-shot classification, trained to judge whether one sentence follows from another
REVISIONThe model's commit on the Hub. Naming a model and its revision is what Step 4's warning asked for. How to Pin a Hugging Face Model to an Exact Revision shows how to find it
INTENTSFive intents, taken from banking77's own intent names and written as plain words

Next, the shape of an answer:

src/support_intent_router/router.py (continued)
@dataclass(frozen=True)
class Route:
"""The intent chosen for a message, and the score of every intent."""

intent: str
confidence: float
scores: dict[str, float]

A Route holds the winning intent, its score, and the score of every intent, so you can see how close the race was. frozen=True makes it read-only once created.

Then the two functions:

src/support_intent_router/router.py (continued)
def load_router() -> Pipeline:
"""Load the zero-shot classification pipeline (downloads the model the first time)."""
return pipeline("zero-shot-classification", model=MODEL, revision=REVISION)


def route(router: Pipeline, message: str) -> Route:
"""Score the message against every intent and pick the most likely one."""
result = router(message, candidate_labels=list(INTENTS))
scores = dict(zip(result["labels"], result["scores"], strict=True))
return Route(intent=result["labels"][0], confidence=result["scores"][0], scores=scores)
  • load_router() builds the pipeline. Loading a model takes a few seconds, so it's a separate function: a program that routes many messages loads the model once.
  • route() asks the pipeline to score the message against the intents. The pipeline returns the labels sorted from best to worst with their scores; zip(..., strict=True) pairs them up and fails loudly if the two lists ever differ in length.

The complete file:

src/support_intent_router/router.py
"""Route a customer support message to the intent it is about."""

from dataclasses import dataclass

from transformers import pipeline
from transformers.pipelines import Pipeline

# A zero-shot classification model (MIT licence). Pinning the commit means every run
# uses exactly the same weights, even if the model's owner updates it on the Hub.
MODEL = "facebook/bart-large-mnli"
REVISION = "d7645e127eaf1aefc7862fd59a17a5aa8558b8ce"

# The intents the router can choose from, written the way a person would say them.
INTENTS = (
"card arrival",
"lost or stolen card",
"refund not showing up",
"exchange rate",
"transfer not received by recipient",
)


@dataclass(frozen=True)
class Route:
"""The intent chosen for a message, and the score of every intent."""

intent: str
confidence: float
scores: dict[str, float]


def load_router() -> Pipeline:
"""Load the zero-shot classification pipeline (downloads the model the first time)."""
return pipeline("zero-shot-classification", model=MODEL, revision=REVISION)


def route(router: Pipeline, message: str) -> Route:
"""Score the message against every intent and pick the most likely one."""
result = router(message, candidate_labels=list(INTENTS))
scores = dict(zip(result["labels"], result["scores"], strict=True))
return Route(intent=result["labels"][0], confidence=result["scores"][0], scores=scores)

The complete router.py in a macOS-style code window: the bart-large-mnli model pinned to a commit, five intents, a frozen Route data class with intent, confidence and scores, load_router() building a zero-shot-classification pipeline, and route() scoring a message against the intents.

How to Classify Text into Your Own Labels with Zero-Shot Classification explains zero-shot classification and its options on a simpler example.

Step 7: Add the route-message Command​

A command reads the message from the terminal and prints the answer. Create src/support_intent_router/cli.py:

src/support_intent_router/cli.py
"""The `route-message` command: print the intent of one customer message."""

import argparse


def non_empty(text: str) -> str:
"""Accept a message only if it has some text in it."""
message = text.strip()
if not message:
raise argparse.ArgumentTypeError("the message is empty")
return message


def main() -> None:
parser = argparse.ArgumentParser(description="Route a customer support message to its intent.")
parser.add_argument("message", type=non_empty, help="the customer's message, in quotes")
args = parser.parse_args()

# Imported only after the arguments are checked: loading PyTorch and Transformers takes
# a few seconds, and --help or a mistyped command shouldn't have to wait for it.
from support_intent_router.router import load_router, route

result = route(load_router(), args.message)

print(f"Intent: {result.intent}")
print(f"Confidence: {result.confidence:.2f}")
print()
print("All intents:")
for intent, score in result.scores.items():
print(f" {intent:<36} {score:.2f}")

The cli.py file in a macOS-style code window: a non_empty check for the message, an argparse parser with one message argument, the router imported inside main after the arguments are checked, and the result printed as the intent, its confidence and every intent's score.

  • non_empty rejects a message that's empty or only spaces, with a clear error instead of a meaningless answer.
  • The import inside main() is deliberate. Importing Transformers loads PyTorch, which takes a few seconds. Checking the arguments first means --help and mistakes answer at once.

uv init also put a sample main() in src/support_intent_router/__init__.py. Replace that file's contents with a description of the package:

src/support_intent_router/__init__.py
"""Route customer support messages to their intent with Hugging Face Transformers."""

Then register the command. Open pyproject.toml, give the project a description, and replace its [project.scripts] table, so the file reads:

pyproject.toml
[project]
name = "support-intent-router"
version = "0.1.0"
description = "Route customer support messages to their intent with Hugging Face Transformers."
readme = "README.md"
authors = [
{ name = "Your Name", email = "you@example.com" }
]
requires-python = ">=3.14"
dependencies = [
"torch>=2.15.0",
"transformers>=5.24.1",
]

[project.scripts]
route-message = "support_intent_router.cli:main"

[build-system]
requires = ["uv_build>=0.13.10,<0.14.0"]
build-backend = "uv_build"

The complete pyproject.toml in a macOS-style code window, with the project's description, Python 3.14 or newer, torch and transformers as dependencies, and the route-message command pointing at support_intent_router.cli.

authors shows the name and email from your Git settings. How to Add a Command to a Python Project with [project.scripts] explains the route-message = "support_intent_router.cli:main" line.

The command was called route at first. But macOS, Linux and Windows already have a route command, for network routing, and run outside the project, uv run route started that one instead. A name no other program uses avoids it; Fixed: "route: bad keyword" When uv run route Runs the System Command shows what happened.

Step 8: Route Your First Message​

Terminal
uv run route-message "I ordered a new card two weeks ago and it still hasn't arrived"
Output
Built support-intent-router @ file:///Users/you/source/dewiride-support-intent-router
Uninstalled 1 package in 0.94ms
Installed 1 package in 2ms
W1201 05:10:32.491000 60339 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.15k/1.15k [00:00<00:00, 335kB/s]
model.safetensors: downloading bytes: ██████████████████████████████████████████| 1.09GB, 7.94MB/s
model.safetensors: reconstructing file: 100%|██████████████████████████| 1.63GB / 1.63GB, 39.3MB/s
Loading weights: 100%|██████████████████████████████████████████| 515/515 [00:00<00:00, 6627.37it/s]
tokenizer_config.json: 100%|██████████████████████████████████████| 26.0/26.0 [00:00<00:00, 136kB/s]
vocab.json: 100%|████████████████████████████████████████████████| 899k/899k [00:00<00:00, 4.92MB/s]
merges.txt: 100%|████████████████████████████████████████████████| 456k/456k [00:00<00:00, 16.2MB/s]
tokenizer.json: 100%|██████████████████████████████████████████| 1.36M/1.36M [00:00<00:00, 14.6MB/s]
Intent: transfer not received by recipient
Confidence: 0.72

All intents:
transfer not received by recipient 0.72
card arrival 0.11
refund not showing up 0.11
lost or stolen card 0.05
exchange rate 0.02

The terminal after the first uv run route-message: uv rebuilt the project, the macOS note and the Hub warning, the 1.63 GB model downloading, then Intent: transfer not received by recipient with confidence 0.72, and card arrival at 0.11.

uv rebuilt the project first, because pyproject.toml changed, which installed the route-message command. Then the router downloaded bart-large-mnli, 1.63 GB, and answered.

And the answer is wrong. The message is plainly about a card that hasn't arrived, yet the router chose transfer not received by recipient, and with confidence 0.72. card arrival came second, at only 0.11. A confidence score is the model's own opinion, not a guarantee.

That's the honest starting point. The zero-shot model was never taught what these five intents mean in banking: for each one, it only judges whether a sentence such as "This example is card arrival." follows from the message, and here it judged the wrong one more likely. Part 2 measures how often zero-shot gets banking77 messages right, and from Part 6 on, you'll train a model on real examples of each intent. This message is the one to beat.

Step 9: Try a Second Message and the Checks​

A message about currency:

Terminal
uv run route-message "Why did I get such a bad rate when I paid in euros?"
Output
W1201 05:12:38.779000 62710 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|█████████████████████████████████████████| 515/515 [00:00<00:00, 11047.41it/s]
Intent: exchange rate
Confidence: 0.85

All intents:
exchange rate 0.85
card arrival 0.07
transfer not received by recipient 0.06
refund not showing up 0.01
lost or stolen card 0.01

The terminal after the second uv run route-message: Intent: exchange rate with confidence 0.85, ahead of card arrival at 0.07.

This one is right: exchange rate, with 0.85. No download either: the model came from the cache. Now an empty message, and the help:

Terminal
uv run route-message " "
uv run route-message --help
Output
usage: route-message [-h] message
route-message: error: argument message: the message is empty
usage: route-message [-h] message

Route a customer support message to its intent.

positional arguments:
message the customer's message, in quotes

options:
-h, --help show this help message and exit

The terminal after the two checks: route-message: error: argument message: the message is empty, then the usage and help text of the route-message command.

Both answered at once, without loading PyTorch, thanks to the import inside main().

Step 10: Check Where the Router Runs​

Terminal
uv run python -c "from support_intent_router.router import load_router; print(load_router().device)"
Output
W1201 05:08:45.844000 58046 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|██████████████████████████████████████████| 515/515 [00:00<00:00, 8654.60it/s]
mps:0

The terminal after printing the router's device: mps:0.

mps:0: the pipeline put the model on the Mac's GPU by itself. When you don't set a device, a pipeline uses the first accelerator it finds, CUDA, MPS or another, and the CPU only when there's none. How to Choose the Device a Hugging Face Pipeline Runs On shows how to choose.

Step 11: See What Was Downloaded​

The hf command came with huggingface-hub. It lists the Hugging Face cache:

Terminal
uv run hf cache ls
Output
ID SIZE LAST_ACCESSED LAST_MODIFIED REFS
---------------------------------------------------------------- ------ ----------------- ----------------- -------
model/distilbert/distilbert-base-uncased-finetuned-sst-2-english 268.1M 6 minutes ago 13 minutes ago 714eb0f
model/facebook/bart-large-mnli 1.6G a few seconds ago a few seconds ago

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

The terminal after uv run hf cache ls: distilbert-base-uncased-finetuned-sst-2-english at 268.1M with the ref 714eb0f, and facebook/bart-large-mnli at 1.6G, 1.9G on disk in total.

Both models live in the cache, ~/.cache/huggingface/hub (on Windows, C:\Users\<you>\.cache\huggingface\hub), not in the project. Every project on your computer shares them, so each model is downloaded once. The guides on listing the cache, moving it with HF_HOME and using it offline go further.

Step 12: Check the Model's License​

Before you build on a model, check that you may. Open huggingface.co/facebook/bart-large-mnli: the license is the last tag under the model's name.

The top of the facebook/bart-large-mnli model page: the model's name and tags for Zero-Shot Classification, Transformers, PyTorch, JAX, Rust, Safetensors, multi_nli, bart, text-classification and two arxiv papers, ending with License: mit.

License: mit. The MIT license allows commercial use. The sentiment model from Step 4 is under Apache-2.0, which does too. How to Check a Model's License on the Hugging Face Hub shows what else the page and the hf command tell you.

Step 13: Commit the Project​

Terminal
git status
Output
On branch main

No commits yet

Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
.python-version
README.md
pyproject.toml
src/
uv.lock

nothing added to commit but untracked files present (use "git add" to track)

The model files aren't there: they're in the cache, not the project. uv's .gitignore keeps .venv out too. Commit the rest:

Terminal
git add .
git commit -m "Route support messages with a zero-shot pipeline"
Output
[main (root-commit) 44c9817] Route support messages with a zero-shot pipeline
8 files changed, 1147 insertions(+)
create mode 100644 .gitignore
create mode 100644 .python-version
create mode 100644 README.md
create mode 100644 pyproject.toml
create mode 100644 src/support_intent_router/__init__.py
create mode 100644 src/support_intent_router/cli.py
create mode 100644 src/support_intent_router/router.py
create mode 100644 uv.lock

The terminal after git commit: the root commit on main, Route support messages with a zero-shot pipeline, with 8 files: .gitignore, .python-version, README.md, pyproject.toml, the package's init.py, cli.py and router.py, and uv.lock.

How to Create a Git Repository and Make Your First Commit covers git add and git commit.

Your Project Now Looks Like This​

dewiride-support-intent-router/
dewiride-support-intent-router/
├── .gitignore
├── .python-version
├── README.md
├── pyproject.toml
├── src/
│ └── support_intent_router/
│ ├── __init__.py
│ ├── cli.py
│ └── router.py
└── uv.lock

.venv exists too, but Git ignores it, and the models sit in the Hugging Face cache.

Telemetry: What Hugging Face Sends​

The huggingface_hub documentation says: "By default, some data is collected by HF libraries (transformers, datasets, gradio,..) to monitor usage, debug issues and help prioritize features." To turn it off, set HF_HUB_DISABLE_TELEMETRY=1 before running your programs. How to Turn Off Hugging Face Telemetry shows how, and how to check it.

Common Mistakes​

MistakeWhat happensDo this instead
Creating the project on Python 3.15The datasets library's parallel processing fails in Part 5 with AttributeError: 'code' object has no attribute 'co_lnotab'Use --python 3.14
Calling pipeline("sentiment-analysis") without a modelNo model was supplied, defaulted to …, and a model you didn't chooseName the model and its revision, as router.py does
Trusting a high confidencetransfer not received by recipient won with 0.72 and was wrongCheck results on messages you know the answer to; Part 7 measures it properly
Running the command without quotes around the messageThe shell splits the message into separate words: error: unrecognized arguments: lost my cardPut the message in quotes

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
Warning: You are sending unauthenticated requests to the HF Hub.Downloading without a Hugging Face accountNothing for now; Part 9 signs in
route-message: error: argument message: the message is emptyThe message was empty or only spacesType a message between the quotes
error: Failed to spawn: route-messageYou ran it outside the project folder, where uv can't find the project's commandscd into dewiride-support-intent-router first
The first run seems stuckThe 1.63 GB model is downloadingWait; later runs use the cache

FAQ​

Do I need a GPU?​

No. Everything in this series also runs on the CPU, more slowly. Parts 6 and 10 say how long each takes on a CPU.

Why did the second message load faster?​

The first run downloaded the model; the second loaded it from the cache. Loading still takes a few seconds, because the model has to be read into memory each time the command runs. Part 11 keeps it loaded in a server.

Why does transformers env say NA for my Mac's GPU?​

Its accelerator check doesn't include Apple's MPS yet, so it prints NA even when PyTorch uses the GPU. I reported it to Transformers as issue #51548. Step 10's mps:0 is the reliable check.

Clean Up​

Nothing runs in the background, so there's nothing to stop. Keep the project and the cached models: Part 2 uses both.

If you need the disk space back before then, uv run hf cache rm model/facebook/bart-large-mnli deletes the larger model from the cache. It asks before deleting, and the router downloads it again the next time it runs. How to Delete a Model from Your Hugging Face Cache with hf cache rm shows each step.

Conclusion​

You installed Transformers 5.24.1 and PyTorch 2.15.0 into a Python 3.14 project, ran your first pipeline on the Mac's GPU, and built a router that sends support messages to one of five intents, with a pinned model and a route-message command. It got the currency message right and the card message wrong, which is exactly why the rest of the series exists.

In Part 2 you'll use pipelines for the other common language tasks, and measure the zero-shot router on real banking77 messages, all 77 intents of them.

Additional Resources​


Next → Part 2: Use Pipelines for Common NLP Tasks (coming soon)