Views
No views yet
transformers>=4.37.0, or you might encounter the following error:KeyError: 'Qwen2.5'1from sentence_transformers import SentenceTransformer
2import torch
3
4# 1. Load a pretrained Sentence Transformer model
5model = SentenceTransformer("ssmits/Qwen2.5-7B-embed-base") # device = "cpu" when <= 24 GB VRAM
6
7# The sentences to encode
8sentences = [
9 "The weather is lovely today.",
10 "It's so sunny outside!",
11 "He drove to the stadium.",
12]
13
14# 2. Calculate embeddings by calling model.encode()
15embeddings = model.encode(sentences)
16print(embeddings.shape)
17# (3, 3584)
18
19# 3. Calculate the embedding similarities
20# Assuming embeddings is a numpy array, convert it to a torch tensor
21embeddings_tensor = torch.tensor(embeddings)
22
23# Using torch to compute cosine similarity matrix
24similarities = torch.nn.functional.cosine_similarity(embeddings_tensor.unsqueeze(0), embeddings_tensor.unsqueeze(1), dim=2)
25
26print(similarities)
27# tensor([[1.0000, 0.8608, 0.6609],
28# [0.8608, 1.0000, 0.7046],
29# [0.6609, 0.7046, 1.0000]])1from transformers import AutoTokenizer, AutoModel
2import torch
3
4#Mean Pooling - Take attention mask into account for correct averaging
5def mean_pooling(model_output, attention_mask):
6 token_embeddings = model_output[0] #First element of model_output contains all token embeddings
7 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
8 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
9
10# Sentences we want sentence embeddings for
11sentences = ['This is an example sentence', 'Each sentence is converted']
12
13# Load model from HuggingFace Hub
14tokenizer = AutoTokenizer.from_pretrained('ssmits/Qwen2.5-7B-Instruct-embed-base')
15model = AutoModel.from_pretrained('ssmits/Qwen2.5-7B-Instruct-embed-base') # device = "cpu" when <= 24 GB VRAM
16
17# Tokenize sentences
18encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
19
20# Compute token embeddings
21with torch.no_grad():
22 model_output = model(**encoded_input)
23
24# Perform pooling. In this case, mean pooling.
25sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
26
27print("Sentence embeddings:")
28print(sentence_embeddings)1from transformers import AutoModel
2from torch.nn import DataParallel
3
4model = AutoModel.from_pretrained("ssmits/Qwen2.5-7B-Instruct-embed-base")
5for module_key, module in model._modules.items():
6 model._modules[module_key] = DataParallel(module)