Sub topic 12
Alternative: Embedding Similarity with a Bi-Encoder
This chapter assumes you have run the zero-shot pipeline from earlier chapters. You should know what an NLI model does with a premise and a hypothesis, and be comfortable with basic Python and NumPy-style vectors. You do not need to know how sentence embeddings are trained.
Why look for an alternative
The NLI approach is accurate for many tasks, but it has a cost. For every candidate label, the pipeline runs a full forward pass of a large cross-encoder (the model reads the text and the hypothesis together). With 3 labels you pay for 3 passes per text. With 50 labels you pay for 50.
Embedding similarity avoids this. It uses a different kind of model, called a bi-encoder, and a different way of scoring. The text is encoded once and each label is encoded once. After that, scoring is just vector arithmetic.
This chapter covers how that works, how to run it, where it is weaker than NLI, and how to fix some of its common problems.
Cross-encoders and bi-encoders
The two model types differ in where the text and the label meet.
- A cross-encoder takes both inputs in one sequence, such as
premise [SEP] hypothesis. Attention can compare every word of the text with every word of the hypothesis. The NLI modelfacebook/bart-large-mnliworks this way. - A bi-encoder encodes each input separately into a fixed-size vector called an embedding. The two inputs never see each other. You compare the finished vectors with a similarity function.
A sentence embedding model is trained so that sentences with similar meaning land close together in vector space. That is the property zero-shot classification needs. If "I was charged twice for my subscription" lies near the vector for "billing", the label is a good match.
Cosine similarity
The usual way to compare two embeddings is cosine similarity. It is the cosine of the angle between the vectors:
cos(a, b) = (a · b) / (‖a‖ ‖b‖)
The value lies between -1 and 1. A higher value means the vectors point in more similar directions. Cosine similarity ignores vector length, so it measures direction (meaning) and not magnitude.
Two points matter when you read the numbers:
- Cosine scores are not probabilities. They do not sum to 1, and 0.4 does not mean "40% likely".
- The scale depends on the model. One model may give 0.6 for a clear match, and another may give 0.35 for the same pair. You cannot reuse a threshold across models.
Running it
The code below embeds the text and the label names, then picks the label with the highest cosine similarity.
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2")
text = "I was charged twice for my subscription this month."
labels = ["billing", "technical support", "sales"]
text_vec = model.encode(text, convert_to_tensor=True)
label_vecs = model.encode(labels, convert_to_tensor=True)
scores = util.cos_sim(text_vec, label_vecs)[0]
print(labels[int(scores.argmax())])Install the library first with pip install sentence-transformers. The model all-MiniLM-L6-v2 is small (about 22 million parameters) and runs comfortably on a CPU. The first call downloads the weights.
Here is what each step does:
model.encode(text, ...)returns one vector for the text.model.encode(labels, ...)takes a list and returns a matrix with one row per label.util.cos_sim(text_vec, label_vecs)returns a matrix of shape(1, 3). Taking[0]gives the three scores.argmaxfinds the index of the best score, and that index selects the label.
For this example the expected output is billing, though the exact scores depend on the model version.
Ranking all labels and scoring many texts
The first example prints only the winner. In practice you often want the full ranking, and you want to classify many texts at once. encode accepts a list of texts and processes them in batches.
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2")
labels = ["billing", "technical support", "sales"]
texts = [
"I was charged twice for my subscription this month.",
"The app freezes every time I open the settings page.",
"Do you offer a discount for annual plans?",
]
label_vecs = model.encode(labels, convert_to_tensor=True)
text_vecs = model.encode(texts, convert_to_tensor=True, batch_size=32)
scores = util.cos_sim(text_vecs, label_vecs) # shape: (3 texts, 3 labels)
for text, row in zip(texts, scores):
ranked = sorted(zip(labels, row.tolist()), key=lambda p: p[1], reverse=True)
print(text)
for label, score in ranked:
print(f" {label}: {score:.3f}")Notice that label_vecs is computed once, outside any loop. This is the main efficiency gain. If you classify a million texts against the same label set, you embed the labels a single time. Each text needs one encoder pass, no matter how many labels you have. You can also store the text embeddings and reuse them when the label set changes.
Comparing cost with NLI
| Property | NLI cross-encoder | Bi-encoder similarity |
|---|---|---|
| Passes per text | One per label | One |
| Cost grows with number of labels | Yes, linearly | Almost not at all |
| Label embeddings reusable | No | Yes |
| Text embeddings reusable | No | Yes |
| Typical model size | Hundreds of millions of parameters | Tens of millions |
| Score meaning | Entailment probability | Cosine similarity, not a probability |
| Reads text and label together | Yes | No |
| Handles negation and fine distinctions | Better | Weaker |
The trade-off is accuracy against cost. A cross-encoder can notice that "I never got charged" is not about a billing error. A bi-encoder tends to place that sentence near "billing" because the topic words match, even though the meaning is different.
Making label text work better
With NLI you tune a hypothesis template. With a bi-encoder you tune the text that you embed for each label. A single bare word is often a weak query. Embedding models are trained on sentences and short passages, so a richer description usually lands closer to the texts you want.
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2")
text = "The app crashes when I try to update my payment method."
variants = {
"bare word": ["billing", "technical support", "sales"],
"descriptive": [
"a question about billing, charges, invoices or refunds",
"a report of a bug, crash or technical problem",
"a question about prices, plans or buying a product",
],
}
names = ["billing", "technical support", "sales"]
text_vec = model.encode(text, convert_to_tensor=True)
for style, label_texts in variants.items():
vecs = model.encode(label_texts, convert_to_tensor=True)
scores = util.cos_sim(text_vec, vecs)[0]
best = names[int(scores.argmax())]
print(f"{style}: {best} {[round(s, 3) for s in scores.tolist()]}")This message mixes two topics: a crash (technical) and a payment method (billing). Compare the two variants on your own machine. Descriptive labels often separate the classes more clearly, but this is not guaranteed. Always test both on labeled examples, as the evaluation chapter describes.
Useful techniques for label text:
- Describe the class, listing the typical words or situations it covers.
- Average several phrasings. Embed three or four descriptions per label and average the vectors. This reduces the effect of one unlucky wording.
- Add example sentences. If you have even a handful of real examples per class, embed them and compare against their mean. At that point you are moving toward few-shot classification, which is a natural next step.
- Keep the phrasing parallel across labels, so one label is not favored by being longer or more specific.
Here is the averaging technique:
import torch
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2")
label_descriptions = {
"billing": [
"I was charged the wrong amount.",
"I need a refund for my invoice.",
"My payment failed.",
],
"technical support": [
"The app crashes on startup.",
"I cannot log in to my account.",
"The page will not load.",
],
"sales": [
"How much does the premium plan cost?",
"Do you offer discounts for teams?",
"I want to buy a license.",
],
}
names = list(label_descriptions)
label_vecs = torch.stack([
model.encode(descs, convert_to_tensor=True).mean(dim=0)
for descs in label_descriptions.values()
])
text_vec = model.encode("Can I get a refund for last month?", convert_to_tensor=True)
scores = util.cos_sim(text_vec, label_vecs)[0]
print(names[int(scores.argmax())])Choosing an embedding model
Not every embedding model suits this job. Keep these points in mind:
- Use a model trained for sentence similarity. Models in the
sentence-transformersfamily are designed for this. A raw BERT encoder with mean pooling gives poor similarity scores because it was never trained to place similar sentences close together. - Match the language. An English-only model will do badly on German text. Use a multilingual model such as
paraphrase-multilingual-MiniLM-L12-v2for mixed or non-English data. - Check the maximum sequence length.
all-MiniLM-L6-v2truncates input at 256 word pieces by default. Long documents lose their ends silently. Split long texts into chunks and combine the scores. - Check instruction conventions. Some embedding models expect a prefix, such as
query:or a task instruction, before the input. Read the model card. Leaving the prefix out can reduce quality without raising an error.
Thresholds and multi-label output
The NLI pipeline gives you a probability per label, so thresholding is direct. With cosine similarity you must choose your own scheme.
- Single label with abstention: take the top label, but return "unknown" if its score is below a threshold. Also consider the margin between the top two scores. A small margin means the model is unsure.
- Multi-label: return every label with a score above a threshold. Because scores are not probabilities, calibrate the threshold on labeled data.
- Softmax with temperature: if you want values that sum to 1, apply softmax to the scores multiplied by a scale factor, for example 20. This gives a relative ranking, not a calibrated probability.
import torch
def classify(scores, labels, min_score=0.30, min_margin=0.05):
"""Return a label, or None when the evidence is weak or ambiguous."""
top = torch.topk(scores, k=2)
best, second = top.values.tolist()
if best < min_score or (best - second) < min_margin:
return None
return labels[int(top.indices[0])]
scores = torch.tensor([0.52, 0.31, 0.12])
print(classify(scores, ["billing", "technical support", "sales"]))The values 0.30 and 0.05 are placeholders. Pick them by sweeping candidates on a labeled sample and checking the trade-off between coverage (how many texts get a label) and accuracy on the texts that do.
Failure modes
- Topic over meaning. Embeddings capture what a text is about, so they confuse texts that share vocabulary but differ in intent. "How do I cancel my order?" and "Why was my order not canceled?" sit close together.
- Negation. "The app does not crash" may score near "technical support".
- Label imbalance in the space. Some labels sit in dense regions of the vector space and attract many texts. Check the confusion matrix for one label that absorbs the others.
- Very short or abstract labels. A label such as "other" has no meaningful position. Do not include catch-all labels. Use a threshold to abstain instead.
- Anisotropy and scale. Scores for different label sets are not comparable. Re-tune thresholds whenever you change the model or label wording.
When to prefer each approach
Use bi-encoder similarity when you have many labels, a large volume of text, tight latency or cost limits, or a need to reuse embeddings for search and clustering. Use NLI when you have few labels, need better handling of negation and nuance, and can afford extra compute. When accuracy matters and you have even a few hundred labeled examples, the later chapter on choosing an approach explains why fine-tuning can beat both.
Exercise
You must classify 2 million support tickets into 120 categories with a small CPU budget. Your NLI model is too slow. Describe how a bi-encoder reduces the work, and name one accuracy risk you should check before deploying.
Show answer
The NLI model needs 120 forward passes per ticket, about 240 million in total. A bi-encoder embeds the 120 labels once, then embeds each ticket once (2 million passes) and computes cosine similarity against the stored label matrix, which is cheap matrix arithmetic. One risk is that embeddings match on topic and miss intent or negation, so similar categories get confused. Check this on a labeled sample with accuracy, macro F1 and a confusion matrix, and tune label wording and the abstain threshold before deploying.
Exercise
Your cosine scores for a text are 0.41, 0.39 and 0.08. A colleague says "the model is 41% sure it is billing." What is wrong with this statement, and what would you do with this prediction?
Show answer
Cosine similarity is not a probability, so 0.41 does not mean 41% confidence, and the scale differs between models. The top two scores are also very close (margin 0.02), which suggests ambiguity. Use a margin rule or threshold, tuned on labeled data, to abstain or send the text for review, or treat it as multi-label if both categories apply.