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

Merged
merged 12 commits into from
Jan 27, 2025
Merged

Fix paraphrase minilm #436

merged 12 commits into from
Jan 27, 2025

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?

@joein joein self-requested a review January 20, 2025 09:56
@joein joein force-pushed the fix-paraphrase-minilm branch from 5cc5007 to f06fded Compare January 27, 2025 21:45
@joein joein merged commit c2f6fd1 into main Jan 27, 2025
17 checks passed
@joein joein deleted the fix-paraphrase-minilm branch January 27, 2025 22:27
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