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

Last Token Embedding not matching #2591

Open
akjindal53244 opened this issue Apr 13, 2024 · 4 comments
Open

Last Token Embedding not matching #2591

akjindal53244 opened this issue Apr 13, 2024 · 4 comments

Comments

@akjindal53244
Copy link

akjindal53244 commented Apr 13, 2024

I am using intfloat/e5-mistral-7b-instruct model to get last hidden state for my input and compute cosine similarity.

I am using a toy example provided at: https://huggingface.co/intfloat/e5-mistral-7b-instruct#usage

Method-1

Code ref: https://huggingface.co/intfloat/e5-mistral-7b-instruct#usage

import torch
import torch.nn.functional as F

from torch import Tensor
from transformers import AutoTokenizer, AutoModel


def last_token_pool(last_hidden_states: Tensor,
                 attention_mask: Tensor) -> Tensor:
    left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
    if left_padding:
        return last_hidden_states[:, -1]
    else:
        sequence_lengths = attention_mask.sum(dim=1) - 1
        batch_size = last_hidden_states.shape[0]
        return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]


def get_detailed_instruct(task_description: str, query: str) -> str:
    return f'Instruct: {task_description}\nQuery: {query}'


# Each query must come with a one-sentence instruction that describes the task
task = 'Given a web search query, retrieve relevant passages that answer the query'
queries = [
    get_detailed_instruct(task, 'how much protein should a female eat'),
    get_detailed_instruct(task, 'summit define')
]
# No need to add instruction for retrieval documents
documents = [
    "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.",
    "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."
]
input_texts = queries + documents

tokenizer = AutoTokenizer.from_pretrained('intfloat/e5-mistral-7b-instruct')
model = AutoModel.from_pretrained('intfloat/e5-mistral-7b-instruct')

max_length = 4096
# Tokenize the input texts
batch_dict = tokenizer(input_texts, max_length=max_length - 1, return_attention_mask=False, padding=False, truncation=True)
# append eos_token_id to every input_ids
batch_dict['input_ids'] = [input_ids + [tokenizer.eos_token_id] for input_ids in batch_dict['input_ids']]
batch_dict = tokenizer.pad(batch_dict, padding=True, return_attention_mask=True, return_tensors='pt')

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

# normalize embeddings
embeddings = F.normalize(embeddings, p=2, dim=1)
scores = (embeddings[:2] @ embeddings[2:].T)
print(scores.tolist())

Output:
[[0.8291366100311279, 0.4797157943248749], [0.46951112151145935, 0.8174349665641785]]

Method-2

Here is my code using SentenceTransformers library:

from sentence_transformers import SentenceTransformer, models

emb_model_name = 'intfloat/e5-mistral-7b-instruct'

word_embedding_model = models.Transformer(model_name_or_path=emb_model_name)
last_token_pooling_model = models.Pooling(4096, pooling_mode = "lasttoken")

model = SentenceTransformer(modules=[word_embedding_model, last_token_pooling_model])

embeddings = model.encode(input_texts, normalize_embeddings=True, convert_to_numpy = True)
similarites = (embeddings[:2] @ embeddings[2:].T)
print(similarites.tolist())

Output:
[[0.5713191032409668, 0.20948277413845062], [0.3217913508415222, 0.5535271167755127]]

Output of both should match but looks like I am missing something obvious. Any help is appreciated!

@akjindal53244 akjindal53244 changed the title Last Token Embedding not matching with Last Token Embedding not matching Apr 13, 2024
@tomaarsen
Copy link
Collaborator

Hello!

If I remember correctly, https://huggingface.co/intfloat/e5-mistral-7b-instruct is not compatible with Sentence Transformers out of the box due to its left-sided tokenizer. The Sentence Transformers Pooler isn't expecting such a tokenizer, so it incorrectly picks the "last" token.
With other words, it's best to stick to the usage in the README until there's left-sided tokenizer support in Sentence Transformers. Apologies for the inconvenience.

  • Tom Aarsen

@satyamk7054
Copy link
Contributor

@akjindal53244 You need to pass add_eos_token=True when creating the sentence-transformers model

word_embedding_model = Transformer(model_name_or_path="intfloat/e5-mistral-7b-instruct", tokenizer_args={"add_eos_token": True})
last_token_pooling_model = Pooling(4096, pooling_mode="lasttoken")
model = SentenceTransformer(modules=[word_embedding_model, last_token_pooling_model], device="cpu")

embeddings = model.encode(input_texts, normalize_embeddings=True, device="cpu")
similarities = (embeddings[:2] @ embeddings[2:].T)
print(similarities)

Output:

[[0.82913667 0.4797157 ]
 [0.4695111  0.81743485]]

@tomaarsen
Copy link
Collaborator

Oh, wow! Great job. Do you think we should make a pull request on https://huggingface.co/intfloat/e5-mistral-7b-instruct to add "add_eos_token": true in the tokenizer_config.json?

Then the transformers-based usage snippet can be simplified and we can integrate Sentence Transformers out of the box!

cc @intfloat as this might interest you

  • Tom Aarsen

@akjindal53244
Copy link
Author

Hi @tomaarsen @satyamk7054 , coincidentally, I was also able to get it working after few hours of opening the issue.

I was able to trace the issue by comparing input_ids being passed to the model in both codebases and found missing eos token when using SentenceTransformers and added that through tokenizer_args argument. Next, added lasttoken as pooling mechanism. Both these fixed combined reproduced the expected output!

Here is my code:

def load_e5_model(max_seq_length):
    # Critical: E5-Mistral adds EOS token explicitly.
    tokenizer_args = {
        "add_eos_token": True
    }
    emb_dim = 4096

    word_embedding_model = models.Transformer(model_name_or_path=emb_model_name, tokenizer_args = tokenizer_args, max_seq_length=max_seq_length)
    # Important: E5-Mistral uses last token embedding
    last_token_pooling_model = models.Pooling(emb_dim, pooling_mode = "lasttoken")

    model = SentenceTransformer(modules=[word_embedding_model, last_token_pooling_model])
    return model

To load the model: model = load_e5_model(max_seq_length)

We should add these changes to the repo as the model is widely used :)

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

No branches or pull requests

3 participants