Vui Seng Chua
commited on
Commit
•
949837c
1
Parent(s):
769e2c6
add config.py converter.py to scripts
Browse files- scripts/config.py +267 -0
- scripts/converter.py +473 -0
scripts/config.py
ADDED
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import (
|
2 |
+
StoppingCriteria,
|
3 |
+
StoppingCriteriaList,
|
4 |
+
)
|
5 |
+
import torch
|
6 |
+
|
7 |
+
DEFAULT_SYSTEM_PROMPT = """\
|
8 |
+
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
9 |
+
If a question does not make any sense or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\
|
10 |
+
"""
|
11 |
+
|
12 |
+
DEFAULT_SYSTEM_PROMPT_CHINESE = """\
|
13 |
+
你是一个乐于助人、尊重他人以及诚实可靠的助手。在安全的情况下,始终尽可能有帮助地回答。 您的回答不应包含任何有害、不道德、种族主义、性别歧视、有毒、危险或非法的内容。请确保您的回答在社会上是公正的和积极的。
|
14 |
+
如果一个问题没有任何意义或与事实不符,请解释原因,而不是回答错误的问题。如果您不知道问题的答案,请不要分享虚假信息。另外,答案请使用中文。\
|
15 |
+
"""
|
16 |
+
|
17 |
+
DEFAULT_SYSTEM_PROMPT_JAPANESE = """\
|
18 |
+
あなたは親切で、礼儀正しく、誠実なアシスタントです。 常に安全を保ちながら、できるだけ役立つように答えてください。 回答には、有害、非倫理的、人種差別的、性差別的、有毒、危険、または違法なコンテンツを含めてはいけません。 回答は社会的に偏見がなく、本質的に前向きなものであることを確認してください。
|
19 |
+
質問が意味をなさない場合、または事実に一貫性がない場合は、正しくないことに答えるのではなく、その理由を説明してください。 質問の答えがわからない場合は、誤った情報を共有しないでください。\
|
20 |
+
"""
|
21 |
+
|
22 |
+
DEFAULT_RAG_PROMPT = """\
|
23 |
+
You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\
|
24 |
+
"""
|
25 |
+
|
26 |
+
DEFAULT_RAG_PROMPT_CHINESE = """\
|
27 |
+
基于以下已知信息,请简洁并专业地回答用户的问题。如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息"。不允许在答案中添加编造成分。另外,答案请使用中文。\
|
28 |
+
"""
|
29 |
+
|
30 |
+
|
31 |
+
def red_pijama_partial_text_processor(partial_text, new_text):
|
32 |
+
if new_text == "<":
|
33 |
+
return partial_text
|
34 |
+
|
35 |
+
partial_text += new_text
|
36 |
+
return partial_text.split("<bot>:")[-1]
|
37 |
+
|
38 |
+
|
39 |
+
def llama_partial_text_processor(partial_text, new_text):
|
40 |
+
new_text = new_text.replace("[INST]", "").replace("[/INST]", "")
|
41 |
+
partial_text += new_text
|
42 |
+
return partial_text
|
43 |
+
|
44 |
+
|
45 |
+
def chatglm_partial_text_processor(partial_text, new_text):
|
46 |
+
new_text = new_text.strip()
|
47 |
+
new_text = new_text.replace("[[训练时间]]", "2023年")
|
48 |
+
partial_text += new_text
|
49 |
+
return partial_text
|
50 |
+
|
51 |
+
|
52 |
+
def youri_partial_text_processor(partial_text, new_text):
|
53 |
+
new_text = new_text.replace("システム:", "")
|
54 |
+
partial_text += new_text
|
55 |
+
return partial_text
|
56 |
+
|
57 |
+
|
58 |
+
SUPPORTED_LLM_MODELS = {
|
59 |
+
"tiny-llama-1b-chat": {
|
60 |
+
"model_id": "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
|
61 |
+
"remote": False,
|
62 |
+
"start_message": f"<|system|>\n{DEFAULT_SYSTEM_PROMPT}</s>\n",
|
63 |
+
"history_template": "<|user|>\n{user}</s> \n<|assistant|>\n{assistant}</s> \n",
|
64 |
+
"current_message_template": "<|user|>\n{user}</s> \n<|assistant|>\n{assistant}",
|
65 |
+
"prompt_template": f"""<|system|> {DEFAULT_RAG_PROMPT }</s>"""
|
66 |
+
+ """
|
67 |
+
<|user|>
|
68 |
+
Question: {question}
|
69 |
+
Context: {context}
|
70 |
+
Answer: </s>
|
71 |
+
<|assistant|>""",
|
72 |
+
},
|
73 |
+
"minicpm-2b-dpo": {
|
74 |
+
"model_id": "openbmb/MiniCPM-2B-dpo-fp16",
|
75 |
+
"remote_code": True,
|
76 |
+
"remote": False,
|
77 |
+
"start_message": f"<|system|>\n{DEFAULT_SYSTEM_PROMPT}</s>\n",
|
78 |
+
"history_template": "<|user|>\n{user}</s> \n<|assistant|>\n{assistant}</s> \n",
|
79 |
+
"current_message_template": "<|user|>\n{user}</s> \n<|assistant|>\n{assistant}",
|
80 |
+
"stop_tokens": ["<|user|>", "<|assistant|>"],
|
81 |
+
"prompt_template": f"""<|system|> {DEFAULT_RAG_PROMPT }</s>"""
|
82 |
+
+ """
|
83 |
+
<|user|>
|
84 |
+
Question: {question}
|
85 |
+
Context: {context}
|
86 |
+
Answer: </s>
|
87 |
+
<|assistant|>""",
|
88 |
+
},
|
89 |
+
"gemma-2b-it": {
|
90 |
+
"model_id": "google/gemma-2b-it",
|
91 |
+
"remote": True,
|
92 |
+
"start_message": DEFAULT_SYSTEM_PROMPT + ", ",
|
93 |
+
"history_template": "<start_of_turn>user{user}<end_of_turn><start_of_turn>model{assistant}<end_of_turn>",
|
94 |
+
"current_message_template": "<start_of_turn>user{user}<end_of_turn><start_of_turn>model{assistant}",
|
95 |
+
"prompt_template": f"""{DEFAULT_RAG_PROMPT},"""+"""<start_of_turn>user{question}<end_of_turn><start_of_turn>context{context}<end_of_turn><start_of_turn>model"""
|
96 |
+
},
|
97 |
+
"red-pajama-3b-chat": {
|
98 |
+
"model_id": "togethercomputer/RedPajama-INCITE-Chat-3B-v1",
|
99 |
+
"remote": False,
|
100 |
+
"start_message": "",
|
101 |
+
"history_template": "\n<human>:{user}\n<bot>:{assistant}",
|
102 |
+
"stop_tokens": [29, 0],
|
103 |
+
"partial_text_processor": red_pijama_partial_text_processor,
|
104 |
+
"current_message_template": "\n<human>:{user}\n<bot>:{assistant}",
|
105 |
+
"prompt_template": f"""{DEFAULT_RAG_PROMPT }"""
|
106 |
+
+ """
|
107 |
+
<human>: Question: {question}
|
108 |
+
Context: {context}
|
109 |
+
Answer: <bot>""",
|
110 |
+
},
|
111 |
+
"gemma-7b-it": {
|
112 |
+
"model_id": "google/gemma-7b-it",
|
113 |
+
"remote": True,
|
114 |
+
"start_message": DEFAULT_SYSTEM_PROMPT + ", ",
|
115 |
+
"history_template": "<start_of_turn>user{user}<end_of_turn><start_of_turn>model{assistant}<end_of_turn>",
|
116 |
+
"current_message_template": "<start_of_turn>user{user}<end_of_turn><start_of_turn>model{assistant}",
|
117 |
+
"prompt_template": f"""{DEFAULT_RAG_PROMPT},"""+"""<start_of_turn>user{question}<end_of_turn><start_of_turn>context{context}<end_of_turn><start_of_turn>model"""
|
118 |
+
},
|
119 |
+
"llama-2-chat-7b": {
|
120 |
+
"model_id": "meta-llama/Llama-2-7b-chat-hf",
|
121 |
+
"remote": False,
|
122 |
+
"start_message": f"<s>[INST] <<SYS>>\n{DEFAULT_SYSTEM_PROMPT }\n<</SYS>>\n\n",
|
123 |
+
"history_template": "{user}[/INST]{assistant}</s><s>[INST]",
|
124 |
+
"current_message_template": "{user} [/INST]{assistant}",
|
125 |
+
"tokenizer_kwargs": {"add_special_tokens": False},
|
126 |
+
"partial_text_processor": llama_partial_text_processor,
|
127 |
+
"prompt_template": f"""[INST]Human: <<SYS>> {DEFAULT_RAG_PROMPT }<</SYS>>"""
|
128 |
+
+ """
|
129 |
+
Question: {question}
|
130 |
+
Context: {context}
|
131 |
+
Answer: [/INST]""",
|
132 |
+
},
|
133 |
+
"mpt-7b-chat": {
|
134 |
+
"model_id": "mosaicml/mpt-7b-chat",
|
135 |
+
"remote": True,
|
136 |
+
"start_message": f"<|im_start|>system\n {DEFAULT_SYSTEM_PROMPT }<|im_end|>",
|
137 |
+
"history_template": "<|im_start|>user\n{user}<im_end><|im_start|>assistant\n{assistant}<|im_end|>",
|
138 |
+
"current_message_template": '"<|im_start|>user\n{user}<im_end><|im_start|>assistant\n{assistant}',
|
139 |
+
"stop_tokens": ["<|im_end|>", "<|endoftext|>"],
|
140 |
+
"prompt_template": f"""<|im_start|>system
|
141 |
+
{DEFAULT_RAG_PROMPT }<|im_end|>"""
|
142 |
+
+ """
|
143 |
+
<|im_start|>user
|
144 |
+
Question: {question}
|
145 |
+
Context: {context}
|
146 |
+
Answer: <im_end><|im_start|>assistant""",
|
147 |
+
},
|
148 |
+
"qwen1.5-7b-chat": {
|
149 |
+
"model_id": "Qwen/Qwen1.5-7B-Chat",
|
150 |
+
"remote": False,
|
151 |
+
"start_message": f"<|im_start|>system\n {DEFAULT_SYSTEM_PROMPT_CHINESE }<|im_end|>",
|
152 |
+
"history_template": "<|im_start|>user\n{user}<im_end><|im_start|>assistant\n{assistant}<|im_end|>",
|
153 |
+
"current_message_template": '"<|im_start|>user\n{user}<im_end><|im_start|>assistant\n{assistant}',
|
154 |
+
"stop_tokens": ["<|im_end|>", "<|endoftext|>"],
|
155 |
+
"prompt_template": f"""<|im_start|>system
|
156 |
+
{DEFAULT_RAG_PROMPT_CHINESE }<|im_end|>"""
|
157 |
+
+ """
|
158 |
+
<|im_start|>user
|
159 |
+
问题: {question}
|
160 |
+
已知内容: {context}
|
161 |
+
回答: <|im_end|><|im_start|>assistant""",
|
162 |
+
},
|
163 |
+
"chatglm3-6b": {
|
164 |
+
"model_id": "THUDM/chatglm3-6b",
|
165 |
+
"remote": True,
|
166 |
+
"start_message": f"{DEFAULT_SYSTEM_PROMPT_CHINESE }",
|
167 |
+
"roles": ["system", "user", "assistant"],
|
168 |
+
"tokenizer_kwargs": {"add_special_tokens": False},
|
169 |
+
"stop_tokens": [2, 64795, 64797],
|
170 |
+
"prompt_template": f"""{DEFAULT_RAG_PROMPT_CHINESE }"""
|
171 |
+
+ """
|
172 |
+
问题: {question}
|
173 |
+
已知内容: {context}
|
174 |
+
回答:
|
175 |
+
""",
|
176 |
+
},
|
177 |
+
"mistral-7b": {
|
178 |
+
"model_id": "mistralai/Mistral-7B-v0.1",
|
179 |
+
"remote": False,
|
180 |
+
"start_message": f"<s>[INST] <<SYS>>\n{DEFAULT_SYSTEM_PROMPT }\n<</SYS>>\n\n",
|
181 |
+
"history_template": "{user}[/INST]{assistant}</s><s>[INST]",
|
182 |
+
"current_message_template": "{user} [/INST]{assistant}",
|
183 |
+
"tokenizer_kwargs": {"add_special_tokens": False},
|
184 |
+
"partial_text_processor": llama_partial_text_processor,
|
185 |
+
"prompt_template": f"""<s> [INST] {DEFAULT_RAG_PROMPT } [/INST] </s>"""
|
186 |
+
+ """
|
187 |
+
[INST] Question: {question}
|
188 |
+
Context: {context}
|
189 |
+
Answer: [/INST]""",
|
190 |
+
},
|
191 |
+
"zephyr-7b-beta": {
|
192 |
+
"model_id": "HuggingFaceH4/zephyr-7b-beta",
|
193 |
+
"remote": False,
|
194 |
+
"start_message": f"<|system|>\n{DEFAULT_SYSTEM_PROMPT}</s>\n",
|
195 |
+
"history_template": "<|user|>\n{user}</s> \n<|assistant|>\n{assistant}</s> \n",
|
196 |
+
"current_message_template": "<|user|>\n{user}</s> \n<|assistant|>\n{assistant}",
|
197 |
+
"prompt_template": f"""<|system|> {DEFAULT_RAG_PROMPT }</s>"""
|
198 |
+
+ """
|
199 |
+
<|user|>
|
200 |
+
Question: {question}
|
201 |
+
Context: {context}
|
202 |
+
Answer: </s>
|
203 |
+
<|assistant|>""",
|
204 |
+
},
|
205 |
+
"neural-chat-7b-v3-1": {
|
206 |
+
"model_id": "Intel/neural-chat-7b-v3-3",
|
207 |
+
"remote": False,
|
208 |
+
"start_message": f"<s>[INST] <<SYS>>\n{DEFAULT_SYSTEM_PROMPT }\n<</SYS>>\n\n",
|
209 |
+
"history_template": "{user}[/INST]{assistant}</s><s>[INST]",
|
210 |
+
"current_message_template": "{user} [/INST]{assistant}",
|
211 |
+
"tokenizer_kwargs": {"add_special_tokens": False},
|
212 |
+
"partial_text_processor": llama_partial_text_processor,
|
213 |
+
"prompt_template": f"""<s> [INST] {DEFAULT_RAG_PROMPT } [/INST] </s>"""
|
214 |
+
+ """
|
215 |
+
[INST] Question: {question}
|
216 |
+
Context: {context}
|
217 |
+
Answer: [/INST]""",
|
218 |
+
},
|
219 |
+
"notus-7b-v1": {
|
220 |
+
"model_id": "argilla/notus-7b-v1",
|
221 |
+
"remote": False,
|
222 |
+
"start_message": f"<|system|>\n{DEFAULT_SYSTEM_PROMPT}</s>\n",
|
223 |
+
"history_template": "<|user|>\n{user}</s> \n<|assistant|>\n{assistant}</s> \n",
|
224 |
+
"current_message_template": "<|user|>\n{user}</s> \n<|assistant|>\n{assistant}",
|
225 |
+
"prompt_template": f"""<|system|> {DEFAULT_RAG_PROMPT }</s>"""
|
226 |
+
+ """
|
227 |
+
<|user|>
|
228 |
+
Question: {question}
|
229 |
+
Context: {context}
|
230 |
+
Answer: </s>
|
231 |
+
<|assistant|>""",
|
232 |
+
},
|
233 |
+
"youri-7b-chat": {
|
234 |
+
"model_id": "rinna/youri-7b-chat",
|
235 |
+
"remote": False,
|
236 |
+
"start_message": f"設定: {DEFAULT_SYSTEM_PROMPT_JAPANESE}\n",
|
237 |
+
"history_template": "ユーザー: {user}\nシステム: {assistant}\n",
|
238 |
+
"current_message_template": "ユーザー: {user}\nシステム: {assistant}",
|
239 |
+
"tokenizer_kwargs": {"add_special_tokens": False},
|
240 |
+
"partial_text_processor": youri_partial_text_processor,
|
241 |
+
},
|
242 |
+
"baichuan2-7b-chat": {
|
243 |
+
"model_id": "baichuan-inc/Baichuan2-7B-Chat",
|
244 |
+
"remote": True,
|
245 |
+
"start_message": f"{DEFAULT_SYSTEM_PROMPT_CHINESE }",
|
246 |
+
"roles": [195, 196],
|
247 |
+
"tokenizer_kwargs": {"add_special_tokens": False},
|
248 |
+
"stop_tokens": [2],
|
249 |
+
"prompt_template": f"""{DEFAULT_RAG_PROMPT_CHINESE }"""
|
250 |
+
+ """
|
251 |
+
问题: {question}
|
252 |
+
已知内容: {context}
|
253 |
+
回答:
|
254 |
+
""",
|
255 |
+
},
|
256 |
+
}
|
257 |
+
|
258 |
+
SUPPORTED_EMBEDDING_MODELS = {
|
259 |
+
"all-mpnet-base-v2": {
|
260 |
+
"model_id": "sentence-transformers/all-mpnet-base-v2",
|
261 |
+
"do_norm": True,
|
262 |
+
},
|
263 |
+
"text2vec-large-chinese": {
|
264 |
+
"model_id": "GanymedeNil/text2vec-large-chinese",
|
265 |
+
"do_norm": False,
|
266 |
+
},
|
267 |
+
}
|
scripts/converter.py
ADDED
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import wraps
|
2 |
+
import warnings
|
3 |
+
import torch
|
4 |
+
import openvino as ov
|
5 |
+
from pathlib import Path
|
6 |
+
from typing import Tuple, Optional
|
7 |
+
import types
|
8 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
9 |
+
|
10 |
+
try:
|
11 |
+
from optimum.exporters.openvino.stateful import make_stateful
|
12 |
+
from optimum.exporters.openvino.stateful import fuse_cache_reorder
|
13 |
+
except ImportError:
|
14 |
+
warnings.warn("We recommend to update optimum-intel for getting optimal performance")
|
15 |
+
make_stateful = None
|
16 |
+
fuse_cache_reorder = None
|
17 |
+
|
18 |
+
|
19 |
+
def register_configs():
|
20 |
+
from optimum.exporters.tasks import TasksManager
|
21 |
+
TasksManager._SUPPORTED_MODEL_TYPE["minicpm"] = TasksManager._SUPPORTED_MODEL_TYPE["llama"]
|
22 |
+
TasksManager._SUPPORTED_MODEL_TYPE["qwen2"] = TasksManager._SUPPORTED_MODEL_TYPE["llama"]
|
23 |
+
|
24 |
+
def patch_stateful(ov_model, model_type):
|
25 |
+
key_value_input_names = [
|
26 |
+
key.get_any_name() for key in ov_model.inputs if any("key_values" in key_name for key_name in key.get_names())
|
27 |
+
]
|
28 |
+
key_value_output_names = [
|
29 |
+
key.get_any_name() for key in ov_model.outputs if any("present" in key_name for key_name in key.get_names())
|
30 |
+
]
|
31 |
+
not_kv_inputs = [
|
32 |
+
input for input in ov_model.inputs if not any(name in key_value_input_names for name in input.get_names())
|
33 |
+
]
|
34 |
+
if not key_value_input_names or not key_value_output_names:
|
35 |
+
return
|
36 |
+
batch_dim = 1 if model_type == "chatglm" else 0
|
37 |
+
num_attention_heads = 1
|
38 |
+
|
39 |
+
fuse_cache_reorder(ov_model, not_kv_inputs, key_value_input_names, batch_dim)
|
40 |
+
make_stateful(
|
41 |
+
ov_model, not_kv_inputs, key_value_input_names, key_value_output_names, batch_dim, num_attention_heads, None
|
42 |
+
)
|
43 |
+
|
44 |
+
|
45 |
+
|
46 |
+
def flattenize_inputs(inputs):
|
47 |
+
"""
|
48 |
+
Helper function for making nested inputs flattens
|
49 |
+
"""
|
50 |
+
flatten_inputs = []
|
51 |
+
for input_data in inputs:
|
52 |
+
if input_data is None:
|
53 |
+
continue
|
54 |
+
if isinstance(input_data, (list, tuple)):
|
55 |
+
flatten_inputs.extend(flattenize_inputs(input_data))
|
56 |
+
else:
|
57 |
+
flatten_inputs.append(input_data)
|
58 |
+
return flatten_inputs
|
59 |
+
|
60 |
+
|
61 |
+
def cleanup_torchscript_cache():
|
62 |
+
"""
|
63 |
+
Helper for removing cached model representation
|
64 |
+
"""
|
65 |
+
torch._C._jit_clear_class_registry()
|
66 |
+
torch.jit._recursive.concrete_type_store = torch.jit._recursive.ConcreteTypeStore()
|
67 |
+
torch.jit._state._clear_class_state()
|
68 |
+
|
69 |
+
|
70 |
+
def convert_mpt(pt_model: torch.nn.Module, model_path: Path):
|
71 |
+
"""
|
72 |
+
MPT model conversion function
|
73 |
+
|
74 |
+
Params:
|
75 |
+
pt_model: PyTorch model
|
76 |
+
model_path: path for saving model
|
77 |
+
Returns:
|
78 |
+
None
|
79 |
+
"""
|
80 |
+
ov_out_path = Path(model_path) / "openvino_model.xml"
|
81 |
+
pt_model.config.save_pretrained(ov_out_path.parent)
|
82 |
+
pt_model.config.use_cache = True
|
83 |
+
outs = pt_model(
|
84 |
+
input_ids=torch.ones((1, 10), dtype=torch.long),
|
85 |
+
attention_mask=torch.ones((1, 10), dtype=torch.long),
|
86 |
+
)
|
87 |
+
inputs = ["input_ids"]
|
88 |
+
outputs = ["logits"]
|
89 |
+
|
90 |
+
dynamic_shapes = {"input_ids": {0: "batch_size", 1: "seq_len"}, "attention_mask": {0: "batch_size", 1: "seq_len"}}
|
91 |
+
for idx in range(len(outs.past_key_values)):
|
92 |
+
inputs.extend([f"past_key_values.{idx}.key", f"past_key_values.{idx}.value"])
|
93 |
+
dynamic_shapes[inputs[-1]] = {0: "batch_size", 2: "past_sequence + sequence"}
|
94 |
+
dynamic_shapes[inputs[-2]] = {0: "batch_size", 3: "past_sequence + sequence"}
|
95 |
+
outputs.extend([f"present.{idx}.key", f"present.{idx}.value"])
|
96 |
+
|
97 |
+
inputs.append("attention_mask")
|
98 |
+
dummy_inputs = {
|
99 |
+
"input_ids": torch.ones((1, 2), dtype=torch.long),
|
100 |
+
"past_key_values": outs.past_key_values,
|
101 |
+
"attention_mask": torch.ones((1, 12), dtype=torch.long),
|
102 |
+
}
|
103 |
+
pt_model.config.torchscript = True
|
104 |
+
orig_forward = pt_model.forward
|
105 |
+
|
106 |
+
@wraps(orig_forward)
|
107 |
+
def ts_patched_forward(
|
108 |
+
input_ids: torch.Tensor,
|
109 |
+
past_key_values: Tuple[Tuple[torch.Tensor]],
|
110 |
+
attention_mask: torch.Tensor,
|
111 |
+
):
|
112 |
+
pkv_list = list(past_key_values)
|
113 |
+
outs = orig_forward(
|
114 |
+
input_ids=input_ids, past_key_values=pkv_list, attention_mask=attention_mask
|
115 |
+
)
|
116 |
+
return (outs.logits, tuple(outs.past_key_values))
|
117 |
+
|
118 |
+
pt_model.forward = ts_patched_forward
|
119 |
+
ov_model = ov.convert_model(pt_model, example_input=dummy_inputs)
|
120 |
+
pt_model.forward = orig_forward
|
121 |
+
for inp_name, m_input, input_data in zip(
|
122 |
+
inputs, ov_model.inputs, flattenize_inputs(dummy_inputs.values())
|
123 |
+
):
|
124 |
+
input_node = m_input.get_node()
|
125 |
+
if input_node.element_type == ov.Type.dynamic:
|
126 |
+
m_input.get_node().set_element_type(ov.Type.f32)
|
127 |
+
shape = list(input_data.shape)
|
128 |
+
if inp_name in dynamic_shapes:
|
129 |
+
for k in dynamic_shapes[inp_name]:
|
130 |
+
shape[k] = -1
|
131 |
+
input_node.set_partial_shape(ov.PartialShape(shape))
|
132 |
+
m_input.get_tensor().set_names({inp_name})
|
133 |
+
|
134 |
+
for out, out_name in zip(ov_model.outputs, outputs):
|
135 |
+
out.get_tensor().set_names({out_name})
|
136 |
+
|
137 |
+
ov_model.validate_nodes_and_infer_types()
|
138 |
+
if make_stateful is not None:
|
139 |
+
patch_stateful(ov_model, "mpt")
|
140 |
+
ov.save_model(ov_model, ov_out_path)
|
141 |
+
del ov_model
|
142 |
+
cleanup_torchscript_cache()
|
143 |
+
del pt_model
|
144 |
+
|
145 |
+
|
146 |
+
def convert_baichuan(pt_model: torch.nn.Module, model_path: Path):
|
147 |
+
"""
|
148 |
+
Baichuan model conversion function
|
149 |
+
Params:
|
150 |
+
pt_model: PyTorch model
|
151 |
+
model_path: path for saving model
|
152 |
+
Returns:
|
153 |
+
None
|
154 |
+
"""
|
155 |
+
ov_out_path = Path(model_path) / "openvino_model.xml"
|
156 |
+
pt_model.config.save_pretrained(ov_out_path.parent)
|
157 |
+
pt_model.config.use_cache = True
|
158 |
+
outs = pt_model(
|
159 |
+
input_ids=torch.ones((1, 10), dtype=torch.long),
|
160 |
+
attention_mask=torch.ones((1, 10), dtype=torch.long),
|
161 |
+
)
|
162 |
+
inputs = ["input_ids", "attention_mask"]
|
163 |
+
outputs = ["logits"]
|
164 |
+
|
165 |
+
dynamic_shapes = {
|
166 |
+
"input_ids": {0: "batch_size", 1: "seq_len"},
|
167 |
+
"attention_mask": {0: "batch_size", 1: "seq_len"},
|
168 |
+
}
|
169 |
+
for idx in range(len(outs.past_key_values)):
|
170 |
+
inputs.extend([f"past_key_values.{idx}.key", f"past_key_values.{idx}.value"])
|
171 |
+
dynamic_shapes[inputs[-1]] = {0: "batch_size", 2: "past_sequence + sequence"}
|
172 |
+
dynamic_shapes[inputs[-2]] = {0: "batch_size", 2: "past_sequence + sequence"}
|
173 |
+
outputs.extend([f"present.{idx}.key", f"present.{idx}.value"])
|
174 |
+
|
175 |
+
dummy_inputs = {
|
176 |
+
"input_ids": torch.ones((1, 2), dtype=torch.long),
|
177 |
+
"attention_mask": torch.ones((1, 12), dtype=torch.long),
|
178 |
+
"past_key_values": outs.past_key_values,
|
179 |
+
}
|
180 |
+
pt_model.config.torchscript = True
|
181 |
+
ov_model = ov.convert_model(pt_model, example_input=dummy_inputs)
|
182 |
+
for inp_name, m_input, input_data in zip(
|
183 |
+
inputs, ov_model.inputs, flattenize_inputs(dummy_inputs.values())
|
184 |
+
):
|
185 |
+
input_node = m_input.get_node()
|
186 |
+
if input_node.element_type == ov.Type.dynamic:
|
187 |
+
m_input.get_node().set_element_type(ov.Type.f32)
|
188 |
+
shape = list(input_data.shape)
|
189 |
+
if inp_name in dynamic_shapes:
|
190 |
+
for k in dynamic_shapes[inp_name]:
|
191 |
+
shape[k] = -1
|
192 |
+
input_node.set_partial_shape(ov.PartialShape(shape))
|
193 |
+
m_input.get_tensor().set_names({inp_name})
|
194 |
+
|
195 |
+
for out, out_name in zip(ov_model.outputs, outputs):
|
196 |
+
out.get_tensor().set_names({out_name})
|
197 |
+
|
198 |
+
ov_model.validate_nodes_and_infer_types()
|
199 |
+
if make_stateful is not None:
|
200 |
+
patch_stateful(ov_model, "baichuan")
|
201 |
+
ov.save_model(ov_model, ov_out_path)
|
202 |
+
del ov_model
|
203 |
+
cleanup_torchscript_cache()
|
204 |
+
del pt_model
|
205 |
+
|
206 |
+
|
207 |
+
@torch.jit.script_if_tracing
|
208 |
+
def _chatglm2_get_context_layer(query_layer: torch.Tensor, key_layer: torch.Tensor, value_layer: torch.Tensor):
|
209 |
+
mask = torch.zeros((query_layer.shape[-2], key_layer.shape[-2]), dtype=query_layer.dtype)
|
210 |
+
if query_layer.shape[2] == key_layer.shape[2]:
|
211 |
+
tmp_mask = torch.ones((query_layer.shape[-2], key_layer.shape[-2]), dtype=torch.bool).triu(diagonal=1)
|
212 |
+
mask.masked_fill_(tmp_mask, float("-inf"))
|
213 |
+
|
214 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer, attn_mask=mask)
|
215 |
+
return context_layer
|
216 |
+
|
217 |
+
|
218 |
+
def _core_attention_forward(self, query_layer, key_layer, value_layer, attention_mask):
|
219 |
+
query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]
|
220 |
+
if attention_mask is None:
|
221 |
+
context_layer = _chatglm2_get_context_layer(query_layer, key_layer, value_layer)
|
222 |
+
else:
|
223 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(
|
224 |
+
query_layer, key_layer, value_layer, attention_mask
|
225 |
+
)
|
226 |
+
context_layer = context_layer.permute(2, 0, 1, 3)
|
227 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
|
228 |
+
context_layer = context_layer.reshape(*new_context_layer_shape)
|
229 |
+
|
230 |
+
return context_layer
|
231 |
+
|
232 |
+
|
233 |
+
@torch.jit.script_if_tracing
|
234 |
+
def _get_chatglm_attention_mask(input_ids, past_key):
|
235 |
+
mask = torch.zeros((input_ids.shape[1], past_key.shape[0] + input_ids.shape[1]), dtype=past_key.dtype)
|
236 |
+
if past_key.shape[0] == 0:
|
237 |
+
tmp_mask = torch.ones((input_ids.shape[1], past_key.shape[0] + input_ids.shape[1]), dtype=torch.bool).triu(diagonal=1)
|
238 |
+
mask.masked_fill_(tmp_mask, float("-inf"))
|
239 |
+
return mask
|
240 |
+
|
241 |
+
|
242 |
+
def _chatglm_transformer_forward(
|
243 |
+
self,
|
244 |
+
input_ids,
|
245 |
+
position_ids: Optional[torch.Tensor] = None,
|
246 |
+
attention_mask: Optional[torch.BoolTensor] = None,
|
247 |
+
full_attention_mask: Optional[torch.BoolTensor] = None,
|
248 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
249 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
250 |
+
use_cache: Optional[bool] = None,
|
251 |
+
output_hidden_states: Optional[bool] = None,
|
252 |
+
return_dict: Optional[bool] = None
|
253 |
+
):
|
254 |
+
output_hidden_states = (
|
255 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
256 |
+
)
|
257 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
258 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
259 |
+
|
260 |
+
batch_size, seq_length = input_ids.shape
|
261 |
+
|
262 |
+
if inputs_embeds is None:
|
263 |
+
inputs_embeds = self.embedding(input_ids)
|
264 |
+
|
265 |
+
if self.pre_seq_len is not None:
|
266 |
+
if past_key_values is None:
|
267 |
+
past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
|
268 |
+
dtype=inputs_embeds.dtype)
|
269 |
+
if attention_mask is not None:
|
270 |
+
attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)), attention_mask], dim=-1)
|
271 |
+
|
272 |
+
if full_attention_mask is None:
|
273 |
+
if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
|
274 |
+
full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
|
275 |
+
elif past_key_values is not None:
|
276 |
+
full_attention_mask = torch.ones(batch_size, seq_length, seq_length,
|
277 |
+
device=input_ids.device,
|
278 |
+
dtype=torch.float) * float("-inf")
|
279 |
+
full_attention_mask.triu_(diagonal=1)
|
280 |
+
past_length = 0
|
281 |
+
if past_key_values:
|
282 |
+
past_length = past_key_values[0][0].shape[0]
|
283 |
+
if past_length:
|
284 |
+
full_attention_mask = torch.cat((torch.zeros(batch_size, seq_length, past_length,
|
285 |
+
device=input_ids.device), full_attention_mask), dim=-1)
|
286 |
+
full_attention_mask.unsqueeze_(1)
|
287 |
+
|
288 |
+
# Rotary positional embeddings
|
289 |
+
rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
|
290 |
+
if position_ids is not None:
|
291 |
+
rotary_pos_emb = rotary_pos_emb[position_ids]
|
292 |
+
else:
|
293 |
+
rotary_pos_emb = rotary_pos_emb[None, :seq_length]
|
294 |
+
rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
|
295 |
+
|
296 |
+
# Run encoder.
|
297 |
+
hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
|
298 |
+
inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
|
299 |
+
kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
|
300 |
+
)
|
301 |
+
|
302 |
+
if not return_dict:
|
303 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
|
304 |
+
|
305 |
+
return BaseModelOutputWithPast(
|
306 |
+
last_hidden_state=hidden_states,
|
307 |
+
past_key_values=presents,
|
308 |
+
hidden_states=all_hidden_states,
|
309 |
+
attentions=all_self_attentions,
|
310 |
+
)
|
311 |
+
|
312 |
+
|
313 |
+
def _patch_chatglm_forward(model: "PreTrainedModel"):
|
314 |
+
model.transformer.forward = types.MethodType(_chatglm_transformer_forward, model.transformer)
|
315 |
+
for block in model.transformer.encoder.layers:
|
316 |
+
block.self_attention.core_attention.forward = types.MethodType(
|
317 |
+
_core_attention_forward, block.self_attention.core_attention
|
318 |
+
)
|
319 |
+
|
320 |
+
|
321 |
+
def convert_chatglm(pt_model: torch.nn.Module, model_path: Path):
|
322 |
+
"""
|
323 |
+
ChatGLM model conversion function
|
324 |
+
|
325 |
+
Params:
|
326 |
+
pt_model: PyTorch model
|
327 |
+
model_path: path for saving model
|
328 |
+
Returns:
|
329 |
+
None
|
330 |
+
"""
|
331 |
+
_patch_chatglm_forward(pt_model)
|
332 |
+
ov_out_path = Path(model_path) / "openvino_model.xml"
|
333 |
+
pt_model.config.save_pretrained(ov_out_path.parent)
|
334 |
+
pt_model.config.use_cache = True
|
335 |
+
outs = pt_model(
|
336 |
+
input_ids=torch.ones((1, 10), dtype=torch.long),
|
337 |
+
position_ids=torch.arange(0, 10, dtype=torch.long),
|
338 |
+
)
|
339 |
+
inputs = ["input_ids"]
|
340 |
+
outputs = ["logits"]
|
341 |
+
|
342 |
+
dynamic_shapes = {
|
343 |
+
"input_ids": {0: "batch_size", 1: "seq_len"},
|
344 |
+
"position_ids": {0: "batch_size", 1: "seq_len"},
|
345 |
+
"attention_mask": {0: "batch_size", 1: "seq_len"},
|
346 |
+
}
|
347 |
+
inputs += ["position_ids", "attention_mask"]
|
348 |
+
for idx in range(len(outs.past_key_values)):
|
349 |
+
inputs.extend([f"past_key_values.{idx}.key", f"past_key_values.{idx}.value"])
|
350 |
+
dynamic_shapes[inputs[-1]] = {0: "past_sequence + sequence", 1: "batch_size"}
|
351 |
+
dynamic_shapes[inputs[-2]] = {0: "past_sequence + sequence", 1: "batch_size"}
|
352 |
+
outputs.extend([f"present.{idx}.key", f"present.{idx}.value"])
|
353 |
+
|
354 |
+
dummy_inputs = {
|
355 |
+
"input_ids": torch.ones((1, 1), dtype=torch.long),
|
356 |
+
"position_ids": torch.tensor([[10]], dtype=torch.long),
|
357 |
+
"attention_mask": torch.ones((1, 11), dtype=torch.long),
|
358 |
+
"past_key_values": outs.past_key_values,
|
359 |
+
}
|
360 |
+
pt_model.config.torchscript = True
|
361 |
+
ov_model = ov.convert_model(pt_model, example_input=dummy_inputs)
|
362 |
+
for inp_name, m_input, input_data in zip(
|
363 |
+
inputs, ov_model.inputs, flattenize_inputs(dummy_inputs.values())
|
364 |
+
):
|
365 |
+
input_node = m_input.get_node()
|
366 |
+
if input_node.element_type == ov.Type.dynamic:
|
367 |
+
m_input.get_node().set_element_type(ov.Type.f32)
|
368 |
+
shape = list(input_data.shape)
|
369 |
+
if inp_name in dynamic_shapes:
|
370 |
+
for k in dynamic_shapes[inp_name]:
|
371 |
+
shape[k] = -1
|
372 |
+
input_node.set_partial_shape(ov.PartialShape(shape))
|
373 |
+
m_input.get_tensor().set_names({inp_name})
|
374 |
+
|
375 |
+
for out, out_name in zip(ov_model.outputs, outputs):
|
376 |
+
out.get_tensor().set_names({out_name})
|
377 |
+
|
378 |
+
ov_model.validate_nodes_and_infer_types()
|
379 |
+
if make_stateful is not None:
|
380 |
+
patch_stateful(ov_model, "chatglm")
|
381 |
+
ov.save_model(ov_model, ov_out_path)
|
382 |
+
del ov_model
|
383 |
+
cleanup_torchscript_cache()
|
384 |
+
del pt_model
|
385 |
+
|
386 |
+
def convert_gemma(pt_model: torch.nn.Module, model_path: Path):
|
387 |
+
"""
|
388 |
+
Gamma model conversion function
|
389 |
+
|
390 |
+
Params:
|
391 |
+
pt_model: PyTorch model
|
392 |
+
model_path: path for saving model
|
393 |
+
Returns:
|
394 |
+
None
|
395 |
+
"""
|
396 |
+
ov_out_path = Path(model_path) / "openvino_model.xml"
|
397 |
+
pt_model.config.save_pretrained(ov_out_path.parent)
|
398 |
+
pt_model.config.use_cache = True
|
399 |
+
outs = pt_model(input_ids=torch.ones((2, 10), dtype=torch.long))
|
400 |
+
inputs = ["input_ids"]
|
401 |
+
outputs = ["logits"]
|
402 |
+
|
403 |
+
dynamic_shapes = {
|
404 |
+
"input_ids": {0: "batch_size", 1: "seq_len"},
|
405 |
+
"attention_mask": {0: "batch_size", 1: "seq_len"},
|
406 |
+
"position_ids": {0: "batch_size", 1: "seq_len"},
|
407 |
+
}
|
408 |
+
inputs += ["attention_mask", "position_ids"]
|
409 |
+
for idx in range(len(outs.past_key_values)):
|
410 |
+
inputs.extend([f"past_key_values.{idx}.key", f"past_key_values.{idx}.value"])
|
411 |
+
dynamic_shapes[inputs[-1]] = {0: "batch_size", 2: "past_sequence + sequence"}
|
412 |
+
dynamic_shapes[inputs[-2]] = {0: "batch_size", 2: "past_sequence + sequence"}
|
413 |
+
outputs.extend([f"present.{idx}.key", f"present.{idx}.value"])
|
414 |
+
|
415 |
+
dummy_inputs = {
|
416 |
+
"input_ids": torch.ones((2, 2), dtype=torch.long),
|
417 |
+
"attention_mask": torch.ones((2, 12), dtype=torch.long),
|
418 |
+
"position_ids": torch.tensor([[10, 11], [10, 11]], dtype=torch.long),
|
419 |
+
"past_key_values": outs.past_key_values,
|
420 |
+
}
|
421 |
+
pt_model.config.torchscript = True
|
422 |
+
ov_model = ov.convert_model(pt_model, example_input=dummy_inputs)
|
423 |
+
for inp_name, m_input, input_data in zip(
|
424 |
+
inputs, ov_model.inputs, flattenize_inputs(dummy_inputs.values())
|
425 |
+
):
|
426 |
+
input_node = m_input.get_node()
|
427 |
+
if input_node.element_type == ov.Type.dynamic:
|
428 |
+
m_input.get_node().set_element_type(ov.Type.f32)
|
429 |
+
shape = list(input_data.shape)
|
430 |
+
if inp_name in dynamic_shapes:
|
431 |
+
for k in dynamic_shapes[inp_name]:
|
432 |
+
shape[k] = -1
|
433 |
+
input_node.set_partial_shape(ov.PartialShape(shape))
|
434 |
+
m_input.get_tensor().set_names({inp_name})
|
435 |
+
|
436 |
+
for out, out_name in zip(ov_model.outputs, outputs):
|
437 |
+
out.get_tensor().set_names({out_name})
|
438 |
+
|
439 |
+
ov_model.validate_nodes_and_infer_types()
|
440 |
+
if make_stateful is not None:
|
441 |
+
patch_stateful(ov_model, "gemma")
|
442 |
+
ov.save_model(ov_model, ov_out_path)
|
443 |
+
del ov_model
|
444 |
+
cleanup_torchscript_cache()
|
445 |
+
del pt_model
|
446 |
+
|
447 |
+
|
448 |
+
|
449 |
+
def convert_mpnet(pt_model: torch.nn.Module, model_path: Path):
|
450 |
+
ov_out_path = Path(model_path) / "openvino_model.xml"
|
451 |
+
dummy_inputs = {"input_ids": torch.ones((1, 10), dtype=torch.long), "attention_mask": torch.ones(
|
452 |
+
(1, 10), dtype=torch.long)}
|
453 |
+
ov_model = ov.convert_model(pt_model, example_input=dummy_inputs)
|
454 |
+
ov.save_model(ov_model, ov_out_path)
|
455 |
+
|
456 |
+
def convert_bert(pt_model: torch.nn.Module, model_path: Path):
|
457 |
+
ov_out_path = Path(model_path) / "openvino_model.xml"
|
458 |
+
dummy_inputs = {"input_ids": torch.ones((1, 10), dtype=torch.long), "attention_mask": torch.ones(
|
459 |
+
(1, 10), dtype=torch.long), "token_type_ids": torch.zeros((1, 10), dtype=torch.long)}
|
460 |
+
ov_model = ov.convert_model(pt_model, example_input=dummy_inputs)
|
461 |
+
ov.save_model(ov_model, ov_out_path)
|
462 |
+
|
463 |
+
|
464 |
+
converters = {
|
465 |
+
# LLM models
|
466 |
+
"mpt": convert_mpt,
|
467 |
+
"chatglm3": convert_chatglm,
|
468 |
+
"baichuan2": convert_baichuan,
|
469 |
+
"gemma": convert_gemma,
|
470 |
+
# embedding models
|
471 |
+
"all-mpnet-base-v2": convert_mpnet,
|
472 |
+
"text2vec-large-chinese": convert_bert,
|
473 |
+
}
|