Views
No views yet
1from optimum.onnxruntime import ORTModelForFeatureExtraction
2from transformers import AutoTokenizer
3
4from transformers import Pipeline
5import torch.nn.functional as F
6import torch
7
8# copied from the model card
9def mean_pooling(model_output, attention_mask):
10 token_embeddings = model_output[0] #First element of model_output contains all token embeddings
11 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
12 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
13
14
15class SentenceEmbeddingPipeline(Pipeline):
16 def _sanitize_parameters(self, **kwargs):
17 # we don't have any hyperameters to sanitize
18 preprocess_kwargs = {}
19 return preprocess_kwargs, {}, {}
20
21 def preprocess(self, inputs):
22 encoded_inputs = self.tokenizer(inputs, padding=True, truncation=True, return_tensors='pt')
23 return encoded_inputs
24
25 def _forward(self, model_inputs):
26 outputs = self.model(**model_inputs)
27 return {"outputs": outputs, "attention_mask": model_inputs["attention_mask"]}
28
29 def postprocess(self, model_outputs):
30 # Perform pooling
31 sentence_embeddings = mean_pooling(model_outputs["outputs"], model_outputs['attention_mask'])
32 # Normalize embeddings
33 sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
34 return sentence_embeddings
35
36# load optimized model
37model_name = "rawsh/multi-qa-MiniLM-distill-onnx-L6-cos-v1"
38model = ORTModelForFeatureExtraction.from_pretrained(model_name, file_name="model_quantized.onnx")
39
40# create optimized pipeline
41tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
42optimized_emb = SentenceEmbeddingPipeline(model=model, tokenizer=tokenizer)
43pred1 = optimized_emb("Hello world!")
44pred2 = optimized_emb("I hate everything.")
45
46print(pred1[0].dot(pred2[0]))pip install -U sentence-transformers1from sentence_transformers import SentenceTransformer, util
2
3query = "How many people live in London?"
4docs = ["Around 9 Million people live in London", "London is known for its financial district"]
5
6#Load the model
7model = SentenceTransformer('sentence-transformers/multi-qa-MiniLM-L6-cos-v1')
8
9#Encode query and documents
10query_emb = model.encode(query)
11doc_emb = model.encode(docs)
12
13#Compute dot score between query and all document embeddings
14scores = util.dot_score(query_emb, doc_emb)[0].cpu().tolist()
15
16#Combine docs & scores
17doc_score_pairs = list(zip(docs, scores))
18
19#Sort by decreasing score
20doc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True)
21
22#Output passages & scores
23for doc, score in doc_score_pairs:
24 print(score, doc)1from transformers import AutoTokenizer, AutoModel
2import torch
3import torch.nn.functional as F
4
5#Mean Pooling - Take average of all tokens
6def mean_pooling(model_output, attention_mask):
7 token_embeddings = model_output.last_hidden_state
8 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
9 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
10
11
12#Encode text
13def encode(texts):
14 # Tokenize sentences
15 encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors='pt')
16
17 # Compute token embeddings
18 with torch.no_grad():
19 model_output = model(**encoded_input, return_dict=True)
20
21 # Perform pooling
22 embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
23
24 # Normalize embeddings
25 embeddings = F.normalize(embeddings, p=2, dim=1)
26
27 return embeddings
28
29
30# Sentences we want sentence embeddings for
31query = "How many people live in London?"
32docs = ["Around 9 Million people live in London", "London is known for its financial district"]
33
34# Load model from HuggingFace Hub
35tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/multi-qa-MiniLM-L6-cos-v1")
36model = AutoModel.from_pretrained("sentence-transformers/multi-qa-MiniLM-L6-cos-v1")
37
38#Encode query and docs
39query_emb = encode(query)
40doc_emb = encode(docs)
41
42#Compute dot score between query and all document embeddings
43scores = torch.mm(query_emb, doc_emb.transpose(0, 1))[0].cpu().tolist()
44
45#Combine docs & scores
46doc_score_pairs = list(zip(docs, scores))
47
48#Sort by decreasing score
49doc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True)
50
51#Output passages & scores
52for doc, score in doc_score_pairs:
53 print(score, doc)1from transformers import AutoTokenizer, TFAutoModel
2import tensorflow as tf
3
4#Mean Pooling - Take attention mask into account for correct averaging
5def mean_pooling(model_output, attention_mask):
6 token_embeddings = model_output.last_hidden_state
7 input_mask_expanded = tf.cast(tf.tile(tf.expand_dims(attention_mask, -1), [1, 1, token_embeddings.shape[-1]]), tf.float32)
8 return tf.math.reduce_sum(token_embeddings * input_mask_expanded, 1) / tf.math.maximum(tf.math.reduce_sum(input_mask_expanded, 1), 1e-9)
9
10
11#Encode text
12def encode(texts):
13 # Tokenize sentences
14 encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors='tf')
15
16 # Compute token embeddings
17 model_output = model(**encoded_input, return_dict=True)
18
19 # Perform pooling
20 embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
21
22 # Normalize embeddings
23 embeddings = tf.math.l2_normalize(embeddings, axis=1)
24
25 return embeddings
26
27
28# Sentences we want sentence embeddings for
29query = "How many people live in London?"
30docs = ["Around 9 Million people live in London", "London is known for its financial district"]
31
32# Load model from HuggingFace Hub
33tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/multi-qa-MiniLM-L6-cos-v1")
34model = TFAutoModel.from_pretrained("sentence-transformers/multi-qa-MiniLM-L6-cos-v1")
35
36#Encode query and docs
37query_emb = encode(query)
38doc_emb = encode(docs)
39
40#Compute dot score between query and all document embeddings
41scores = (query_emb @ tf.transpose(doc_emb))[0].numpy().tolist()
42
43#Combine docs & scores
44doc_score_pairs = list(zip(docs, scores))
45
46#Sort by decreasing score
47doc_score_pairs = sorted(doc_score_pairs, key=lambda x: x[1], reverse=True)
48
49#Output passages & scores
50for doc, score in doc_score_pairs:
51 print(score, doc)| Setting | Value |
|---|---|
| Dimensions | 384 |
| Produces normalized embeddings | Yes |
| Pooling-Method | Mean pooling |
| Suitable score functions | dot-product (util.dot_score), cosine-similarity (util.cos_sim), or euclidean distance |
sentence-transformers, this model produces normalized embeddings with length 1. In that case, dot-product and cosine-similarity are equivalent. dot-product is preferred as it is faster. Euclidean distance is proportional to dot-product and can also be used.train_script.py.nreimers/MiniLM-L6-H384-uncased model. Please refer to the model card for more detailed information about the pre-training procedure.data_config.json file.| Dataset | Number of training tuples |
|---|---|
| WikiAnswers Duplicate question pairs from WikiAnswers | 77,427,422 |
| PAQ Automatically generated (Question, Paragraph) pairs for each paragraph in Wikipedia | 64,371,441 |
| Stack Exchange (Title, Body) pairs from all StackExchanges | 25,316,456 |
| Stack Exchange (Title, Answer) pairs from all StackExchanges | 21,396,559 |
| MS MARCO Triplets (query, answer, hard_negative) for 500k queries from Bing search engine | 17,579,773 |
| GOOAQ: Open Question Answering with Diverse Answer Types (query, answer) pairs for 3M Google queries and Google featured snippet | 3,012,496 |
| Amazon-QA (Question, Answer) pairs from Amazon product pages | 2,448,839 |
| Yahoo Answers (Title, Answer) pairs from Yahoo Answers | 1,198,260 |
| Yahoo Answers (Question, Answer) pairs from Yahoo Answers | 681,164 |
| Yahoo Answers (Title, Question) pairs from Yahoo Answers | 659,896 |
| SearchQA (Question, Answer) pairs for 140k questions, each with Top5 Google snippets on that question | 582,261 |
| ELI5 (Question, Answer) pairs from Reddit ELI5 (explainlikeimfive) | 325,475 |
| Stack Exchange Duplicate questions pairs (titles) | 304,525 |
| Quora Question Triplets (Question, Duplicate_Question, Hard_Negative) triplets for Quora Questions Pairs dataset | 103,663 |
| Natural Questions (NQ) (Question, Paragraph) pairs for 100k real Google queries with relevant Wikipedia paragraph | 100,231 |
| SQuAD2.0 (Question, Paragraph) pairs from SQuAD2.0 dataset | 87,599 |
| TriviaQA (Question, Evidence) pairs | 73,346 |
| Total | 214,988,242 |