sentence transformers compat

#6
by michaelfeil - opened
No description provided.

This makes the model compatible with sentence_transformers by telling the package to perform "pooling_mode_mean_tokens" after the model, and optional normalize
Example:
https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/tree/main

tested via

import torch.nn.functional as F

from torch import Tensor
from transformers import AutoTokenizer, AutoModel
import numpy as np

def average_pool(last_hidden_states: Tensor,
                 attention_mask: Tensor) -> Tensor:
    last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
    return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]


# Each input text should start with "query: " or "passage: ".
# For tasks other than retrieval, you can simply use the "query: " prefix.
input_texts = ['query: how much protein should a female eat',
               'query: summit define',
               "passage: As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
               "passage: Definition of summit for English Language Learners. : 1  the highest point of a mountain : the top of a mountain. : 2  the highest level. : 3  a meeting or series of meetings between the leaders of two or more governments."]

tokenizer = AutoTokenizer.from_pretrained('intfloat/e5-small')
model = AutoModel.from_pretrained('intfloat/e5-small')

# Tokenize the input texts
batch_dict = tokenizer(input_texts, max_length=512, padding=True, truncation=True, return_tensors='pt')

outputs = model(**batch_dict)
embeddings = average_pool(outputs.last_hidden_state, batch_dict['attention_mask'])

# (Optionally) normalize embeddings
embeddings_norm = F.normalize(embeddings, p=2, dim=1)
scores = (embeddings_norm[:2] @ embeddings_norm[2:].T) * 100

embeddings_norm = embeddings_norm.detach().numpy()

from sentence_transformers import SentenceTransformer
model = SentenceTransformer('./e5-small')
embeddings_norm2 = model.encode(input_texts, normalize_embeddings=True)

np.testing.assert_allclose(embeddings_norm, embeddings_norm2, atol=1e-7)
michaelfeil changed pull request status to open
intfloat changed pull request status to merged

Sign up or log in to comment