Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 5 of 13
Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
Run two pretrained Hugging Face models on six support messages with no training: a sentiment pipeline that calls a polite password question NEGATIVE at 0.9996, and an embedding model that ranks messages by meaning with 384-number vectors.
What you will learn
- Read a Hugging Face model name and model card before you use the model
- Run a sentiment classifier with pipeline() in a few lines, with no training
- Turn sentences into 384-number embeddings with AutoTokenizer, AutoModel and mean pooling
- Decide when to use a pretrained model as-is, fine-tune it or train from scratch
Before you start
- Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
- Basic Python
Say you need a chef for your restaurant. You could find a child and train them for years. Or you hire someone who has already spent those years in kitchens. You don't get every meal they ever cooked, you get what they learned.
Hugging Face is the hiring board. People publish trained models there, and you can download them and run them on a plain CPU. Somebody else has already done the expensive training. But a hired chef still has habits from the last job, so you taste the food first. Hold on to that.
In this article we run two pretrained models on six short support messages: one reads the mood of a message, one turns a sentence into numbers.
The six messages
"""Six short ticket messages used by all the examples."""
MESSAGES = [
"I was charged twice for my order and nobody has answered my emails. This is unacceptable!",
"Hi, could you tell me how to reset my password? I forgot it after the holiday.",
"Thank you so much, the new dashboard is fantastic and your support team was very helpful.",
"Please refund my last payment. The product did not match the description.",
"The app crashes every time I open the settings page on my phone.",
"My package was supposed to arrive last week and the tracking has not moved in six days.",
]
That's messages.py. An angry billing message, a calm password question, praise, a refund request, a crash report and a shipping delay. The project needs only torch and transformers.
A name, a card, two parts
Every model on Hugging Face has a name with two parts: the publisher, a slash, then the model. The sentiment model we'll use is:
distilbert/distilbert-base-uncased-finetuned-sst-2-english
A long name, but it tells you a lot: a DistilBERT model, fine-tuned on SST-2 (a dataset of movie-review sentences), in English. Its page, the model card, says what it learned from and which labels it knows. Read that first.
What comes down is two things. A tokenizer turns text into numbers. The weights are the numbers the model learned. After the first download they stay on your disk, so the next run is quick.
One pipeline, six answers
Here's 01_sentiment.py:
"""Reuse a trained sentiment model: no training, just download and call."""
import warnings
from transformers import logging, pipeline
from messages import MESSAGES
warnings.filterwarnings("ignore")
logging.set_verbosity_error()
classifier = pipeline(
"sentiment-analysis",
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
)
for text, result in zip(MESSAGES, classifier(MESSAGES)):
print(f"{result['label']:<8} {result['score']:.4f} {text[:60]}")
We import pipeline from transformers, name the job ("sentiment-analysis") and the model. That's the whole setup, with no training at all. Then we call it on the list, and each message comes back with a label and a score.
NEGATIVE 0.9998 I was charged twice for my order and nobody has answered my
NEGATIVE 0.9996 Hi, could you tell me how to reset my password? I forgot it
POSITIVE 0.9999 Thank you so much, the new dashboard is fantastic and your s
NEGATIVE 0.9998 Please refund my last payment. The product did not match the
NEGATIVE 0.9996 The app crashes every time I open the settings page on my ph
NEGATIVE 0.9990 My package was supposed to arrive last week and the tracking
Taste the food: a calm question, marked negative
"I was charged twice", NEGATIVE at 0.9998. Fair enough. "Thank you so much", POSITIVE at 0.9999. Also fair.
Now look at the second line. Hi, could you tell me how to reset my password? That's a calm, polite question, and the model says NEGATIVE, 0.9996.
This model has only two labels, and it learned from movie reviews. It has no way to say "neutral". And a high score is not the same as being right: 0.9996 is how sure the model is, not how often it's correct on your messages.
A sentence becomes numbers
The second model doesn't give a label. It gives a list of numbers, an embedding. A sentence goes in, and 384 numbers come out. Think of it as a spot on a map: sentences that mean similar things land close together. To compare two of them we use cosine similarity, which measures how closely they point the same way: near 1 is close, near 0 is unrelated. You saw this with single words in Embeddings: Words as Vectors. Here a pretrained model does it for whole sentences.
Here's 02_embeddings.py. This time we load the tokenizer and the model ourselves:
"""Turn sentences into vectors with a pretrained model and rank messages by similarity."""
import warnings
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoTokenizer, logging
from messages import MESSAGES
warnings.filterwarnings("ignore")
logging.set_verbosity_error()
NAME = "sentence-transformers/all-MiniLM-L6-v2"
tokenizer = AutoTokenizer.from_pretrained(NAME)
model = AutoModel.from_pretrained(NAME)
def embed(texts):
batch = tokenizer(texts, padding=True, truncation=True, return_tensors="pt")
with torch.no_grad():
hidden = model(**batch).last_hidden_state # one vector per token
mask = batch["attention_mask"].unsqueeze(-1)
pooled = (hidden * mask).sum(1) / mask.sum(1) # mean pooling: one vector per sentence
return F.normalize(pooled, dim=1)
query = "I was charged twice"
scores = (embed([query]) @ embed(MESSAGES).T)[0] # cosine similarity
print(f"query: {query!r} (vector size {embed([query]).shape[1]})")
for rank, i in enumerate(scores.argsort(descending=True).tolist(), start=1):
print(f"{rank}. {scores[i]:.3f} {MESSAGES[i][:60]}")
AutoTokenizerandAutoModelload the right classes for whatever model name you give them.padding=Truemakes the six messages the same length so they fit in one batch; theattention_maskmarks which positions are real words and which are padding.- The model gives one vector per token. Averaging them, while ignoring the padding, gives one vector per sentence. That's mean pooling.
F.normalizemakes every vector length 1, so a dot product (@) is the cosine similarity. The same trick is in Similarity Search.
query: 'I was charged twice' (vector size 384)
1. 0.545 I was charged twice for my order and nobody has answered my
2. 0.291 Please refund my last payment. The product did not match the
3. 0.234 Hi, could you tell me how to reset my password? I forgot it
4. 0.191 My package was supposed to arrive last week and the tracking
5. 0.139 The app crashes every time I open the settings page on my ph
6. -0.018 Thank you so much, the new dashboard is fantastic and your s
The top result is the message that says it, 0.545. Second is Please refund my last payment, 0.291. It shares almost no words with the query, but it's about money. That's meaning, not keyword matching. Third is the password question at 0.234: it's simply the nearest of what's left, so don't read every position in the ranking as meaning. This is one query on six messages, not a search evaluation.
When is a pretrained model enough?
03_when_to_train.py prints a small decision table. These are rules of thumb written by hand, not measurements:
Choice When Example Cost
----------------------------------------------------------------------------------------------------------------------------
Use as-is The task matches what the model learned Sentiment of English reviews Minutes
Fine-tune Same kind of task, but your data is different Your tickets, your own labels Hours, a few hundred examples
Train from scratch Nothing similar exists, and you have lots of data A new kind of sensor signal Days or more, large data
Our password mistake tells us where we stand. Support tickets aren't movie reviews, so we're in the fine-tune row. Start pretrained, check it on your own data, and move down this list only if you have to. Before you fine-tune, read When NOT to Fine-Tune. And to load a text generator and run it yourself, see Loading a Model and Running Inference.
Common mistakes
- Skipping the model card. It tells you the labels and the training data. This model has no "neutral" label at all.
- Reading the score as accuracy. NEGATIVE 0.9996 on a polite question is confident and wrong.
- Averaging token vectors without the mask. Padding positions would drag the sentence vector around.
- Forgetting to normalise. Without
F.normalize, the dot product is not the cosine similarity. - Expecting identical scores everywhere. Scores can differ slightly on another machine; the labels and the ranking order should match.
Quick recap
| Step | Code | What we saw |
|---|---|---|
| Choose | publisher/model + model card | Two labels, learned from movie reviews |
| Classify | pipeline("sentiment-analysis", model=...) | 5 NEGATIVE, 1 POSITIVE; the password question NEGATIVE 0.9996 |
| Embed | AutoTokenizer, AutoModel, mean pooling | 384 numbers per sentence |
| Rank | F.normalize then @ | Refund request second at 0.291, by meaning |
Try it yourself
Add a message of your own to messages.py, something mixed like "The app is great but it crashed twice today". Run 01_sentiment.py and see what it says. Then make it the query in 02_embeddings.py and read its nearest neighbour.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
Next →Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.