Debian Codegraph @

generate/whispercpp/convert-pt-to-ggml.py

raw symbols SCIP
1 # Convert Whisper transformer model from PyTorch to ggml format
2 #
3 # Usage: python convert-pt-to-ggml.py ~/.cache/whisper/medium.pt ~/path/to/repo/whisper/ ./models/whisper-medium
4 #
5 # You need to clone the original repo in ~/path/to/repo/whisper/
6 #
7 # git clone https://github.com/openai/whisper ~/path/to/repo/whisper/
8 #
9 # It is used to various assets needed by the algorithm:
10 #
11 # - tokenizer
12 # - mel filters
13 #
14 # Also, you need to have the original models in ~/.cache/whisper/
15 # See the original repo for more details.
16 #
17 # This script loads the specified model and whisper assets and saves them in ggml format.
18 # The output is a single binary file containing the following information:
19 #
20 # - hparams
21 # - mel filters
22 # - tokenizer vocab
23 # - model variables
24 #
25 # For each variable, write the following:
26 #
27 # - Number of dimensions (int)
28 # - Name length (int)
29 # - Dimensions (int[n_dims])
30 # - Name (char[name_length])
31 # - Data (float[n_dims])
32 #
33
34 import io
35 import os
36 import sys
37 import struct
38 import json
39 import code
40 import torch
41 import numpy as np
42 import base64
43 from pathlib import Path
44 #from transformers import GPTJForCausalLM
45 #from transformers import GPT2TokenizerFast
46
47 # ref: https://github.com/openai/whisper/blob/8cf36f3508c9acd341a45eb2364239a3d81458b9/whisper/tokenizer.py#L10-L110
48 #LANGUAGES = {
49 # "en": "english",
50 # "zh": "chinese",
51 # "de": "german",
52 # "es": "spanish",
53 # "ru": "russian",
54 # "ko": "korean",
55 # "fr": "french",
56 # "ja": "japanese",
57 # "pt": "portuguese",
58 # "tr": "turkish",
59 # "pl": "polish",
60 # "ca": "catalan",
61 # "nl": "dutch",
62 # "ar": "arabic",
63 # "sv": "swedish",
64 # "it": "italian",
65 # "id": "indonesian",
66 # "hi": "hindi",
67 # "fi": "finnish",
68 # "vi": "vietnamese",
69 # "iw": "hebrew",
70 # "uk": "ukrainian",
71 # "el": "greek",
72 # "ms": "malay",
73 # "cs": "czech",
74 # "ro": "romanian",
75 # "da": "danish",
76 # "hu": "hungarian",
77 # "ta": "tamil",
78 # "no": "norwegian",
79 # "th": "thai",
80 # "ur": "urdu",
81 # "hr": "croatian",
82 # "bg": "bulgarian",
83 # "lt": "lithuanian",
84 # "la": "latin",
85 # "mi": "maori",
86 # "ml": "malayalam",
87 # "cy": "welsh",
88 # "sk": "slovak",
89 # "te": "telugu",
90 # "fa": "persian",
91 # "lv": "latvian",
92 # "bn": "bengali",
93 # "sr": "serbian",
94 # "az": "azerbaijani",
95 # "sl": "slovenian",
96 # "kn": "kannada",
97 # "et": "estonian",
98 # "mk": "macedonian",
99 # "br": "breton",
100 # "eu": "basque",
101 # "is": "icelandic",
102 # "hy": "armenian",
103 # "ne": "nepali",
104 # "mn": "mongolian",
105 # "bs": "bosnian",
106 # "kk": "kazakh",
107 # "sq": "albanian",
108 # "sw": "swahili",
109 # "gl": "galician",
110 # "mr": "marathi",
111 # "pa": "punjabi",
112 # "si": "sinhala",
113 # "km": "khmer",
114 # "sn": "shona",
115 # "yo": "yoruba",
116 # "so": "somali",
117 # "af": "afrikaans",
118 # "oc": "occitan",
119 # "ka": "georgian",
120 # "be": "belarusian",
121 # "tg": "tajik",
122 # "sd": "sindhi",
123 # "gu": "gujarati",
124 # "am": "amharic",
125 # "yi": "yiddish",
126 # "lo": "lao",
127 # "uz": "uzbek",
128 # "fo": "faroese",
129 # "ht": "haitian creole",
130 # "ps": "pashto",
131 # "tk": "turkmen",
132 # "nn": "nynorsk",
133 # "mt": "maltese",
134 # "sa": "sanskrit",
135 # "lb": "luxembourgish",
136 # "my": "myanmar",
137 # "bo": "tibetan",
138 # "tl": "tagalog",
139 # "mg": "malagasy",
140 # "as": "assamese",
141 # "tt": "tatar",
142 # "haw": "hawaiian",
143 # "ln": "lingala",
144 # "ha": "hausa",
145 # "ba": "bashkir",
146 # "jw": "javanese",
147 # "su": "sundanese",
148 #}
149
150 ## ref: https://github.com/openai/whisper/blob/8cf36f3508c9acd341a45eb2364239a3d81458b9/whisper/tokenizer.py#L273-L292
151 #def build_tokenizer(path_to_whisper_repo: str, name: str = "gpt2"):
152 # os.environ["TOKENIZERS_PARALLELISM"] = "false"
153 # path = os.path.join(path_to_whisper_repo, "whisper/assets", name)
154 # tokenizer = GPT2TokenizerFast.from_pretrained(path)
155 #
156 # specials = [
157 # "<|startoftranscript|>",
158 # *[f"<|{lang}|>" for lang in LANGUAGES.keys()],
159 # "<|translate|>",
160 # "<|transcribe|>",
161 # "<|startoflm|>",
162 # "<|startofprev|>",
163 # "<|nocaptions|>",
164 # "<|notimestamps|>",
165 # ]
166 #
167 # tokenizer.add_special_tokens(dict(additional_special_tokens=specials))
168 # return tokenizer
169
170 # ref: https://github.com/openai/gpt-2/blob/master/src/encoder.py
171 def bytes_to_unicode():
172 """
173 Returns list of utf-8 byte and a corresponding list of unicode strings.
174 The reversible bpe codes work on unicode strings.
175 This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
176 When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
177 This is a signficant percentage of your normal, say, 32K bpe vocab.
178 To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
179 And avoids mapping to whitespace/control characters the bpe code barfs on.
180 """
181 bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
182 cs = bs[:]
183 n = 0
184 for b in range(2**8):
185 if b not in bs:
186 bs.append(b)
187 cs.append(2**8+n)
188 n += 1
189 cs = [chr(n) for n in cs]
190 return dict(zip(bs, cs))
191
192
193 if len(sys.argv) < 4:
194 print("Usage: convert-pt-to-ggml.py model.pt path-to-whisper-repo dir-output [use-f32]\n")
195 sys.exit(1)
196
197 fname_inp = Path(sys.argv[1])
198 dir_whisper = Path(sys.argv[2])
199 dir_out = Path(sys.argv[3])
200
201 # try to load PyTorch binary data
202 try:
203 model_bytes = open(fname_inp, "rb").read()
204 with io.BytesIO(model_bytes) as fp:
205 checkpoint = torch.load(fp, map_location="cpu")
206 except Exception:
207 print("Error: failed to load PyTorch model file:" , fname_inp)
208 sys.exit(1)
209
210 hparams = checkpoint["dims"]
211 print("hparams:", hparams)
212
213 list_vars = checkpoint["model_state_dict"]
214
215 #print(list_vars['encoder.positional_embedding'])
216 #print(list_vars['encoder.conv1.weight'])
217 #print(list_vars['encoder.conv1.weight'].shape)
218
219 # load mel filters
220 n_mels = hparams["n_mels"]
221 with np.load(dir_whisper / "whisper" / "assets" / "mel_filters.npz") as f:
222 filters = torch.from_numpy(f[f"mel_{n_mels}"])
223 #print (filters)
224
225 #code.interact(local=locals())
226
227 # load tokenizer
228 # for backwards compatibility, also check for older hf_transformers format tokenizer files
229 # old format: dir_whisper/whisper/assets/[multilingual/gpt2]/vocab.json
230 # new format: dir_whisper/whisper/assets/[multilingual/gpt2].tiktoken
231 multilingual = hparams["n_vocab"] >= 51865
232 tokenizer = dir_whisper / "whisper" / "assets" / (multilingual and "multilingual.tiktoken" or "gpt2.tiktoken")
233 tokenizer_type = "tiktoken"
234 if not tokenizer.is_file():
235 tokenizer = dir_whisper / "whisper" / "assets" / (multilingual and "multilingual" or "gpt2") / "vocab.json"
236 tokenizer_type = "hf_transformers"
237 if not tokenizer.is_file():
238 print("Error: failed to find either tiktoken or hf_transformers tokenizer file:", tokenizer)
239 sys.exit(1)
240
241 byte_encoder = bytes_to_unicode()
242 byte_decoder = {v:k for k, v in byte_encoder.items()}
243
244 if tokenizer_type == "tiktoken":
245 with open(tokenizer, "rb") as f:
246 contents = f.read()
247 tokens = {base64.b64decode(token): int(rank) for token, rank in (line.split() for line in contents.splitlines() if line)}
248 elif tokenizer_type == "hf_transformers":
249 with open(tokenizer, "r", encoding="utf8") as f:
250 _tokens_raw = json.load(f)
251 if '<|endoftext|>' in _tokens_raw:
252 # ensures exact same model as tokenizer_type == tiktoken
253 # details: https://github.com/ggerganov/whisper.cpp/pull/725
254 del _tokens_raw['<|endoftext|>']
255 tokens = {bytes([byte_decoder[c] for c in token]): int(idx) for token, idx in _tokens_raw.items()}
256
257 # output in the same directory as the model
258 fname_out = dir_out / "ggml-model.bin"
259
260 # use 16-bit or 32-bit floats
261 use_f16 = True
262 if len(sys.argv) > 4:
263 use_f16 = False
264 fname_out = dir_out / "ggml-model-f32.bin"
265
266 fout = fname_out.open("wb")
267
268 fout.write(struct.pack("i", 0x67676d6c)) # magic: ggml in hex
269 fout.write(struct.pack("i", hparams["n_vocab"]))
270 fout.write(struct.pack("i", hparams["n_audio_ctx"]))
271 fout.write(struct.pack("i", hparams["n_audio_state"]))
272 fout.write(struct.pack("i", hparams["n_audio_head"]))
273 fout.write(struct.pack("i", hparams["n_audio_layer"]))
274 fout.write(struct.pack("i", hparams["n_text_ctx"]))
275 fout.write(struct.pack("i", hparams["n_text_state"]))
276 fout.write(struct.pack("i", hparams["n_text_head"]))
277 fout.write(struct.pack("i", hparams["n_text_layer"]))
278 fout.write(struct.pack("i", hparams["n_mels"]))
279 fout.write(struct.pack("i", use_f16))
280
281 # write mel filters
282 fout.write(struct.pack("i", filters.shape[0]))
283 fout.write(struct.pack("i", filters.shape[1]))
284 for i in range(filters.shape[0]):
285 for j in range(filters.shape[1]):
286 fout.write(struct.pack("f", filters[i][j]))
287
288 # write tokenizer
289 fout.write(struct.pack("i", len(tokens)))
290
291 for key in tokens:
292 fout.write(struct.pack("i", len(key)))
293 fout.write(key)
294
295 for name in list_vars.keys():
296 data = list_vars[name].squeeze().numpy()
297 print("Processing variable: " , name , " with shape: ", data.shape)
298
299 # reshape conv bias from [n] to [n, 1]
300 if name in ["encoder.conv1.bias", "encoder.conv2.bias"]:
301 data = data.reshape(data.shape[0], 1)
302 print(f" Reshaped variable: {name} to shape: ", data.shape)
303
304 n_dims = len(data.shape)
305
306 # looks like the whisper models are in f16 by default
307 # so we need to convert the small tensors to f32 until we fully support f16 in ggml
308 # ftype == 0 -> float32, ftype == 1 -> float16
309 ftype = 1
310 if use_f16:
311 if n_dims < 2 or \
312 name == "encoder.conv1.bias" or \
313 name == "encoder.conv2.bias" or \
314 name == "encoder.positional_embedding" or \
315 name == "decoder.positional_embedding":
316 print(" Converting to float32")
317 data = data.astype(np.float32)
318 ftype = 0
319 else:
320 data = data.astype(np.float32)
321 ftype = 0
322
323 #if name.startswith("encoder"):
324 # if name.endswith("mlp.0.weight") or \
325 # name.endswith("mlp.2.weight"):
326 # print(" Transposing")
327 # data = data.transpose()
328
329 # header
330 str_ = name.encode('utf-8')
331 fout.write(struct.pack("iii", n_dims, len(str_), ftype))
332 for i in range(n_dims):
333 fout.write(struct.pack("i", data.shape[n_dims - 1 - i]))
334 fout.write(str_)
335
336 # data
337 data.tofile(fout)
338
339 fout.close()
340
341 print("Done. Output file: " , fname_out)
342 print("")