Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix paraphrase minilm #436

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open

Fix paraphrase minilm #436

wants to merge 12 commits into from

Conversation

hh-space-invader
Copy link
Contributor

import torch
import numpy as np
from transformers import AutoTokenizer, AutoModel
from sentence_transformers import SentenceTransformer

from fastembed import TextEmbedding


model_name = 'sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2'
docs = ["hello world", "flag embedding"]

model = SentenceTransformer(model_name)
st_embeddings = model.encode(docs)
rounded_st_embeddings = np.array([[round(value, 4) for value in embedding[:5]] for embedding in st_embeddings])
print(f"st_embeddings: {rounded_st_embeddings}")

# Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)

# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)

# Tokenize sentences
encoded_input = tokenizer(docs, padding=True, truncation=True, return_tensors='pt')

# Compute token embeddings
with torch.no_grad():
    model_output = model(**encoded_input)

# Perform pooling. In this case, max pooling.
hf_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
rounded_hf_embeddings = np.array([[round(value, 4) for value in embedding[:5]] for embedding in np.array(hf_embeddings)])
print(f"hf_embeddings: {rounded_hf_embeddings}")

model = TextEmbedding(model_name, cache_dir="models")
fe_embeddings = np.array(list(model.embed(documents=docs)))
rounded_fe_embeddings = np.array([[round(value, 4) for value in embedding[:5]] for embedding in np.array(fe_embeddings)])
print(f"fe_embeddings: {rounded_fe_embeddings}")

print(np.allclose(
    a=rounded_st_embeddings,
    b=rounded_hf_embeddings,
    atol=1e-3 # taken from test file
))

print(np.allclose(
    a=rounded_st_embeddings,
    b=rounded_fe_embeddings,
    atol=1e-3 # taken from test file
))

All Submissions:

ref: #368

  • Have you followed the guidelines in our Contributing document?
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?

New Feature Submissions:

  • Does your submission pass the existing tests?
  • Have you added tests for your feature?
  • Have you installed pre-commit with pip3 install pre-commit and set up hooks with pre-commit install?

New models submission:

  • Have you added an explanation of why it's important to include this model?
  • Have you added tests for the new model? Were canonical values for tests computed via the original model?
  • Have you added the code snippet for how canonical values were computed?
  • Have you successfully ran tests with your changes locally?

@joein
Copy link
Member

joein commented Jan 10, 2025

We need to add a warning that the model has been updated, something similar to the one we're showing when users use splade with incorrect spelling

Copy link
Member

@joein joein left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please upload notebooks to reproduce canonical vectors to the dedicated repo?

@@ -12,7 +12,6 @@ keywords = ["vector", "embedding", "neural", "search", "qdrant", "sentence-trans

[tool.poetry.dependencies]
python = ">=3.9.0"
onnx = ">=1.15.0"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should not be in this PR

@@ -62,6 +63,14 @@ def __init__(
**kwargs,
):
super().__init__(model_name, cache_dir, threads, **kwargs)
if model_name == "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2":
warnings.warn(
"The model 'sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2' has been updated to include a mean pooling layer. "
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please add fastembed version in which it's gonna changed? (0.5.2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants