205 points · by tosh · 2y ago · 70 comments
One issue I’ve run into is that they produce a very good ranking, but the actual cosine similarity scores appear to be meaningless. (E.g., “chocolate chip cookies” and “PLS6;YJBXSRF&/” could have a similarity of 0.8.) Consequently, I’ve had a hard time selecting sensible cutoff values to balance recall and precision. Has anyone found a good approach to this?
In my experience there are two paths forward, the one I recommend is to train an MLP classifier on the embeddings to produce a binary classification (ie similar or not). The advantage is that you no longer need to set a numeric threshold on a distance metric, however you will need labeled training data to define what is “similar” in the context of your use case.
The other path is to calculate the statistics of pair-wise distances for every record in some unlabeled dataset you have, and use the resulting distribution to inform choice of threshold. This will at least give you an estimate of what % of records will be classified as similar for a given threshold value.
In our cases, < 100 labels on modern models (per task) goes far. We can do better, but more useful problems to solve. Impressive how far these have come!
However, if you use a "two towers" approach and have several additional MLP layers on top of each embedding separately, and then a dense MLP on the concatenations of each tower, the individual tower MLP layers are an embedding transformation, and will improve retrieval.
Like this:
Final MLP
/ \
QP MLP DP MLP
| |
QE DE
Now, you can apply the document preprocessor ("DP MLP") to your document embeddings ("DE") before storing them in the vector database, and apply the query preprocessor ("QP MLP") to your query embeddings ("QE") before querying your vector database.This should improve the precision and recall of your vector retrieval step beyond using e.g. raw LLM embeddings. Even better is for the final layer to just be cosine similarity, maximum inner product, or L2 distance, rather than having an MLP so you can just use a raw threshold (it's at least worth trying).
If you train a binary classifier on the embeddings, have you found that the resulting probabilities are also good for ranking? Or do you stick with a distance measure for that?
Any paper or other source about this approach?
I tried out your example using the following code:
from sentence_transformers import SentenceTransformer
import scipy.spatial as ssp
model = SentenceTransformer("all-mpnet-base-v2")
A = model.encode(['chocolate chip cookies','PLS6;YJBXSRF&/'])
CosineDistance = ssp.distance.cosine(A[0],A[1])
Where `CosineDistance == 0.953`This means the model is actually working quite well, were these to be similar to each other we'd expect CosineDistance to be much closer to 0.
The other comments about such distances being useful for relative comparisons also apply: I've used SentenceTransformers quite successfully for nearest-neighbor searches.
https://github.com/Dicklesworthstone/fast_vector_similarity
pip install fast_vector_similarity
On one hand it's super impressive what you can get out of these embeddings. On the other I'm with you that there seems to be a missing piece to make them work great.
An additional MLP or Siamese Network works really well but it seems like there should be something easier and unsupervised given your set of vectorized samples.
Thinking out loud, could PCA help with this by centering the data and removing dimensions that mostly model noise?
I should have clarified that it really depends on the model. I have had this problem to a greater extent with the GTE and BGE embeddings. But I use them anyway, because they’re so strong overall.
PCA is an interesting idea, and worth looking at.
GTE comes to mind. You can try the demo widget on HuggingFace and see this: https://huggingface.co/thenlper/gte-large
As an example, against “Chocolate chip cookies”, “Oreos” has a cosine similarity of .808, while “Bubonic plague” is at .709.
So of course I want to reach to blame that here.
I'm doing a cross-platform app pipeline that basically search API => get pages => embed => run against prompt, so unfortunately I don't have much more insight.
MiniLM V3 is good enough, the nearest constraint at this point is more "will I download all 10 search results in time?" than "am I grabbing the absolutely best passages?" -- good on you for legitimately testing those things.
edit: actually, I do have one more thought: sometimes I end up with embeddings for the last part of a web page that match ~anything. i.e. imagine i have a 1005 word web page and split it into 250 word chunks to embed. Then I'll have 4 "full" vectors, and one that represents just 5 words. That 5 word tends to match almost ~anything, i.e. I'll see ones from previous search queries match the current search query. Maybe you're seeing noise because its just 3-5 words? But then again, you were probably just illustrating without splatting in huge chunks of texts.
This is obviously quite significant given how important sentence embedding models are.
I would recommend against merging (averaging, etc.) the embeddings (unless you want a blurry idea of what your document contains), as well as feeding very large pieces of text to the embedder (some models have massive context lengths, but the result is similarly vague).
Sounds right, I've heard this from multiple sources. That's why I'm leaning towards just embedding the keywords.
I've found LASER[1] which originally had the idea to embed all languages in the same vector space, though it's a bit harder to use than models available through SentenceTransformers. LASER2 stuck with this approach, but LASER3 switched to language-specific models. However, I haven't found benchmarks for these models, and they were released about 2 years ago.
Another alternative would be to translate everything before embedding, which would introduce some amount of error, though maybe it wouldn't be significant.
For good old embedding models (eg. GLoVe), you have a few choices:
1. LASER as you mentioned. The performance tends to suck though.
2. Language prediction + one embedding model per supported language. Libraries like whichlang make this nice, and MUSE has embedding modes aligned per language for 100ish languages.
Fastembed is a good library for this.
Note that for most people, 32 dimension glove is all they need if you benchmark it.
As the length of the text you're embedding goes up, or as the specificity goes up (eg. You have only medical documents and want difference between them) you'll need richer embeddings (more dimensions, or a transformer model, or both)
People never benchmark their embeddings and I find it incredible how they end up with needlessly overenginneered systems.
For the normal user that just wants something across languages, the minilm-paraphrase-multilingual in the OP library is great.
Of you want better than that (either bigger model, or specifically for a subset of languages, etc.) then you need to think about your task, priorities, target languages, etc.
Currently I'm working on an old fashioned search engine (tf-if + keyword expansion). Apparently that can work better than vector databases in some cases:
Could someone more knowledgeable suggest when it would make sense to use the SentenceTransformers library vs for instance relying on the OpenAI API to get embeddings for a sentence?
I presume if your customers are enterprise companies then you may opt to use this library vs sending their data to OpenAI etc.
And you can get more customisation/fine-tuning from this library too.
The main reason to use one of those providers is if you want something that performs well out of the box without doing any work and you don't mind paying for it. Those companies like OpenAI, Cohere and others, already did they work to make those models work well on various domains. They may also use larger models that are not as easy to deal with yourself. (although as I mentioned previously, a small embeddings model fine-tuned on your task is likely to perform as well as a much bigger general model)
There isn't a single usecase where they're better than the free models, and they're slower, needlessly large, and outrageously expensive for what they are.
Now it depends un specific usecase (domain, language, length of texts)
You feed in the paragraph ID(yes just an integer of the para where the word was) via its own layer along with the word to CBOW/SkipGram set up. Then throw away that part after training. Then, during inference, you attach a new randmly initialized layer for where that old layer was and "re-train" just that part before generating the embedding for words.
Probably historic reasons, anyway solid 9/10 API.
>tfw it's 2024 and we just accept that the context "falls out" of the model if we push it beyond it's regular context length
So everyone forgot that we can put large N number of tokens into small N number of embeddings because???
is the feature more of "reliable and accurate without hallucination" than LLM?
where are you using it? text interface?