JeremyHibiki
commited on
Upload convert.py
Browse files- convert.py +130 -0
convert.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import os
|
4 |
+
from collections import OrderedDict
|
5 |
+
from pathlib import Path
|
6 |
+
from typing import Dict
|
7 |
+
|
8 |
+
import torch
|
9 |
+
from huggingface_hub import snapshot_download
|
10 |
+
from optimum.exporters.onnx import export
|
11 |
+
from optimum.exporters.onnx.model_configs import XLMRobertaOnnxConfig
|
12 |
+
from optimum.onnxruntime import ORTModelForCustomTasks, ORTOptimizer
|
13 |
+
from optimum.onnxruntime.configuration import AutoOptimizationConfig
|
14 |
+
from torch import Tensor
|
15 |
+
from transformers import AutoConfig, AutoModel, PretrainedConfig, PreTrainedModel, XLMRobertaConfig
|
16 |
+
|
17 |
+
|
18 |
+
class BGEM3InferenceModel(PreTrainedModel):
|
19 |
+
config_class = XLMRobertaConfig
|
20 |
+
base_model_prefix = "BGEM3InferenceModel"
|
21 |
+
model_tags = ["BAAI/bge-m3"]
|
22 |
+
|
23 |
+
def __init__(self, model_name: str = "BAAI/bge-m3"):
|
24 |
+
super().__init__(PretrainedConfig())
|
25 |
+
|
26 |
+
model_name = snapshot_download(repo_id=model_name)
|
27 |
+
|
28 |
+
self.config = AutoConfig.from_pretrained(model_name)
|
29 |
+
self.model = AutoModel.from_pretrained(model_name)
|
30 |
+
|
31 |
+
self.sparse_linear = torch.nn.Linear(
|
32 |
+
in_features=self.model.config.hidden_size,
|
33 |
+
out_features=1,
|
34 |
+
)
|
35 |
+
sparse_state_dict = torch.load(os.path.join(model_name, "sparse_linear.pt"), map_location="cpu")
|
36 |
+
self.sparse_linear.load_state_dict(sparse_state_dict)
|
37 |
+
|
38 |
+
self.colbert_linear = torch.nn.Linear(
|
39 |
+
in_features=self.model.config.hidden_size,
|
40 |
+
out_features=self.model.config.hidden_size,
|
41 |
+
)
|
42 |
+
colbert_state_dict = torch.load(os.path.join(model_name, "colbert_linear.pt"), map_location="cpu")
|
43 |
+
self.colbert_linear.load_state_dict(colbert_state_dict)
|
44 |
+
|
45 |
+
def dense_embedding(self, last_hidden_state: Tensor) -> Tensor:
|
46 |
+
return last_hidden_state[:, 0]
|
47 |
+
|
48 |
+
def sparse_embedding(self, last_hidden_state: Tensor) -> Tensor:
|
49 |
+
with torch.no_grad():
|
50 |
+
return torch.relu(self.sparse_linear(last_hidden_state))
|
51 |
+
|
52 |
+
def colbert_embedding(self, last_hidden_state: Tensor, attention_mask: Tensor) -> Tensor:
|
53 |
+
with torch.no_grad():
|
54 |
+
colbert_vecs = self.colbert_linear(last_hidden_state[:, 1:])
|
55 |
+
return colbert_vecs * attention_mask[:, 1:][:, :, None].float()
|
56 |
+
|
57 |
+
def forward(self, input_ids: Tensor, attention_mask: Tensor) -> Dict[str, Tensor]:
|
58 |
+
with torch.no_grad():
|
59 |
+
last_hidden_state = self.model(
|
60 |
+
input_ids=input_ids, attention_mask=attention_mask, return_dict=True
|
61 |
+
).last_hidden_state
|
62 |
+
|
63 |
+
output = {}
|
64 |
+
dense_vecs = self.dense_embedding(last_hidden_state)
|
65 |
+
output["dense_vecs"] = torch.nn.functional.normalize(dense_vecs, dim=-1)
|
66 |
+
|
67 |
+
sparse_vecs = self.sparse_embedding(last_hidden_state)
|
68 |
+
output["sparse_vecs"] = sparse_vecs
|
69 |
+
|
70 |
+
colbert_vecs = self.colbert_embedding(last_hidden_state, attention_mask)
|
71 |
+
output["colbert_vecs"] = torch.nn.functional.normalize(colbert_vecs, dim=-1)
|
72 |
+
|
73 |
+
return output
|
74 |
+
|
75 |
+
|
76 |
+
class BGEM3OnnxConfig(XLMRobertaOnnxConfig):
|
77 |
+
@property
|
78 |
+
def outputs(self) -> Dict[str, Dict[int, str]]:
|
79 |
+
return OrderedDict(
|
80 |
+
{
|
81 |
+
"dense_vecs": {0: "batch_size", 1: "embedding"},
|
82 |
+
"sparse_vecs": {0: "batch_size", 1: "token", 2: "weight"},
|
83 |
+
"colbert_vecs": {0: "batch_size", 1: "token", 2: "embedding"},
|
84 |
+
}
|
85 |
+
)
|
86 |
+
|
87 |
+
|
88 |
+
def main(output: str, device: str = "cuda", optimize: str = "O4"):
|
89 |
+
# 加载模型
|
90 |
+
model = BGEM3InferenceModel()
|
91 |
+
model.save_pretrained(output)
|
92 |
+
|
93 |
+
# 配置
|
94 |
+
bgem3_onnx_config = BGEM3OnnxConfig(model.config)
|
95 |
+
|
96 |
+
# 导出
|
97 |
+
export(
|
98 |
+
model,
|
99 |
+
output=Path(output) / "model.onnx",
|
100 |
+
config=bgem3_onnx_config,
|
101 |
+
opset=bgem3_onnx_config.DEFAULT_ONNX_OPSET,
|
102 |
+
device=device,
|
103 |
+
)
|
104 |
+
|
105 |
+
optimizer = ORTOptimizer.from_pretrained(output, file_names=["model.onnx"])
|
106 |
+
optimization_config = AutoOptimizationConfig.with_optimization_level(optimization_level=optimize)
|
107 |
+
optimization_config.disable_shape_inference = True
|
108 |
+
if optimize == "O4":
|
109 |
+
optimization_config.optimize_for_gpu = True
|
110 |
+
optimization_config.fp16 = True
|
111 |
+
optimization_config.optimization_level = 99
|
112 |
+
optimizer.optimize(save_dir=output, optimization_config=optimization_config, file_suffix="")
|
113 |
+
|
114 |
+
ORTModelForCustomTasks.from_pretrained(
|
115 |
+
output,
|
116 |
+
provider="CUDAExecutionProvider" if device == "cuda" else "CPUExecutionProvider",
|
117 |
+
)
|
118 |
+
|
119 |
+
|
120 |
+
if __name__ == "__main__":
|
121 |
+
import argparse
|
122 |
+
|
123 |
+
parser = argparse.ArgumentParser()
|
124 |
+
parser.add_argument("--output", type=str)
|
125 |
+
parser.add_argument("--device", type=str, choices=["cuda", "cpu"], default="cuda")
|
126 |
+
parser.add_argument("--optimize", type=str, choices=["O1", "O2", "O3", "O4"], default="O4")
|
127 |
+
parser.add_argument("--push_to_hub", action="store_true", default=False)
|
128 |
+
parser.add_argument("--push_to_hub_repo_id", type=str, default="JeremyHibiki/bge-m3-onnx")
|
129 |
+
args = parser.parse_args()
|
130 |
+
main(args.output, args.device, args.optimize)
|