Views
No views yet
sentence-transformers/all-mpnet-base-v2convert.py script.transformerssentence-transformers/all-mpnet-base-v2 except using ORTModelForFeatureExtraction from optimum.pip install optimum[onnxruntime]1from transformers import AutoTokenizer
2from optimum.onnxruntime import ORTModelForFeatureExtraction
3import torch
4import torch.nn.functional as F
5
6# Mean Pooling - Take attention mask into account for correct averaging
7def mean_pooling(model_output, attention_mask):
8 token_embeddings = model_output[0] #First element of model_output contains all token embeddings
9 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
10 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
11
12
13# Sentences we want sentence embeddings for
14sentences = ['This is an example sentence', 'Each sentence is converted']
15
16# Load model from HuggingFace Hub
17tokenizer = AutoTokenizer.from_pretrained('yilunzhang/all-mpnet-base-v2-onnx')
18model = ORTModelForFeatureExtraction.from_pretrained('yilunzhang/all-mpnet-base-v2-onnx')
19
20# Tokenize sentences
21encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
22
23# Compute token embeddings
24with torch.no_grad():
25 model_output = model(**encoded_input)
26
27# Perform pooling
28sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
29
30# Normalize embeddings
31sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
32
33print("Sentence embeddings:")
34print(sentence_embeddings)