Views
No views yet
1from huggingface_hub import snapshot_download
2
3snapshot_download(repo_id="philipp-zettl/BAAI-bge-m3-ONNX")
4
5from optimum.onnxruntime import ORTModelForFeatureExtraction
6from transformers import AutoTokenizer
7
8tokenizer = AutoTokenizer.from_pretrained("philipp-zettl/BAAI-bge-m3-ONNX")
9model = ORTModelForFeatureExtraction.from_pretrained("philipp-zettl/BAAI-bge-m3-ONNX")1import torch
2import torch.nn.functional as F
3from sklearn.metrics.pairwise import cosine_similarity
4
5
6def mean_pooling(model_output, attention_mask):
7 token_embeddings = model_output[0]
8 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
9 return (
10 torch.sum(token_embeddings * input_mask_expanded, 1)
11 / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
12 )
13
14
15def embed(text):
16 encoded_input = tokenizer([text], padding=True, truncation=True, max_length=512, return_tensors='pt')
17 model_output = model(**encoded_input)
18
19 sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
20 return F.normalize(sentence_embeddings, p=2, dim=1)
21
22
23# from https://en.wikipedia.org/wiki/Artificial_intelligence
24document_embedding = embed('''
25Artificial intelligence (AI), in its broadest sense, is intelligence exhibited by machines, particularly computer systems.
26It is a field of research in computer science that develops and studies methods and software that enable machines to perceive their
27environment and use learning and intelligence to take actions that maximize their chances of achieving defined goals.[1]
28Such machines may be called AIs.
29''')
30cosine_similarity(
31 document_embedding,
32 embed('A text about technology')
33)