This is the
BAAI/BGE-M3 inference model converted to ONNX format and can be used with Optimum ONNX Runtime with CPU acceleration. This model outputs all 3 embedding types (Dense, Sparse, ColBERT).
No ONNX optimizations are applied to this model. If you want to apply optimizations, use the export script included in this repo to generate a version of ONNX model with optimizations.
Some of the code is adapted from
aapot/bge-m3-onnx. The model in this repo inherits from
PretrainedModel and the ONNX model can be downloaded from Huggingface Hub and used directly with the
model.from_pretrained() method.
1from collections import defaultdict
2from typing import Any
3
4import numpy as np
5from optimum.onnxruntime import ORTModelForCustomTasks
6from transformers import AutoTokenizer
7
8# Download ONNX model from Huggingface Hub
9onnx_model = ORTModelForCustomTasks.from_pretrained("philipchung/bge-m3-onnx")
10tokenizer = AutoTokenizer.from_pretrained("philipchung/bge-m3-onnx")
11# Inference forward pass
12sentences = ["First test sentence.", "Second test sentence"]
13inputs = tokenizer(
14 sentences,
15 padding="longest",
16 return_tensors="np",
17)
18outputs = onnx_model.forward(**inputs)
19
20def process_token_weights(
21 token_weights: np.ndarray, input_ids: list
22) -> defaultdict[Any, int]:
23 """Convert sparse token weights into dictionary of token indices and corresponding weights.
24
25 Function is taken from the original FlagEmbedding.bge_m3.BGEM3FlagModel from the
26 _process_token_weights() function defined within the encode() method.
27 """
28 # convert to dict
29 result = defaultdict(int)
30 unused_tokens = set(
31 [
32 tokenizer.cls_token_id,
33 tokenizer.eos_token_id,
34 tokenizer.pad_token_id,
35 tokenizer.unk_token_id,
36 ]
37 )
38 for w, idx in zip(token_weights, input_ids, strict=False):
39 if idx not in unused_tokens and w > 0:
40 idx = str(idx)
41 # w = int(w)
42 if w > result[idx]:
43 result[idx] = w
44 return result
45
46# Each sentence results in a dict[str, list]float] | dict[str, float] | list[list[float]]] which corresponds to a dict with dense, sparse, and colbert embeddings.
47embeddings_list = []
48for input_ids, dense_vec, sparse_vec, colbert_vec in zip(
49 inputs["input_ids"],
50 outputs["dense_vecs"],
51 outputs["sparse_vecs"],
52 outputs["colbert_vecs"],
53 strict=False,
54):
55 # Convert token weights into dictionary of token indices and corresponding weights
56 token_weights = sparse_vec.astype(float).squeeze(-1)
57 sparse_embeddings = process_token_weights(
58 token_weights,
59 input_ids.tolist(),
60 )
61 multivector_embedding = {
62 "dense": dense_vec.astype(float).tolist(), # (1024)
63 "sparse": dict(sparse_embeddings), # dict[token_index, weight]
64 "colbert": colbert_vec.astype(float).tolist(), # (token len, 1024)
65 }
66 embeddings_list.append(multivector_embedding)