Views
No views yet
bgem3_model.py and re-run the ONNX export with export_onnx.py script.export_onnx.py with appropriate optimization argument.pip install onnxruntime==1.17.0pip install transformers==4.37.21import onnxruntime as ort
2from transformers import AutoTokenizer
3
4tokenizer = AutoTokenizer.from_pretrained("BAAI/bge-m3")
5ort_session = ort.InferenceSession("model.onnx")
6
7inputs = tokenizer("BGE M3 is an embedding model supporting dense retrieval, lexical matching and multi-vector interaction.", padding="longest", return_tensors="np")
8inputs_onnx = {k: ort.OrtValue.ortvalue_from_numpy(v) for k, v in inputs.items()}
9
10outputs = ort_session.run(None, inputs_onnx)1from collections import defaultdict
2
3
4def process_token_weights(token_weights: np.ndarray, input_ids: list):
5 # conver to dict
6 result = defaultdict(int)
7 unused_tokens = set(
8 [
9 tokenizer.cls_token_id,
10 tokenizer.eos_token_id,
11 tokenizer.pad_token_id,
12 tokenizer.unk_token_id,
13 ]
14 )
15 for w, idx in zip(token_weights, input_ids):
16 if idx not in unused_tokens and w > 0:
17 idx = str(idx)
18 # w = int(w)
19 if w > result[idx]:
20 result[idx] = w
21 return result
22
23
24token_weights = outputs[1].squeeze(-1)
25lexical_weights = list(
26 map(process_token_weights, token_weights, inputs["input_ids"].tolist())
27)bgem3_model.py file and with the provided export_onnx.py ONNX weight export script which leverages HF Optimum.
If needed, you can modify the bgem3_model.py model configuration to for example remove embedding normalization or to not output all three embedding representations. If you modify the number of output representations, you need to also modify the ONNX output config BGEM3OnnxConfig in export_onnx.py.pip install -r requirements.txtpython export_onnx.py --output . --opset 17 --device cpu --optimize O2