Huong commited on
Commit
060e759
·
1 Parent(s): 933e631

converting OLMoASR-esque model to HF model script

Browse files
Files changed (1) hide show
  1. convert_openai_to_hf.py +370 -0
convert_openai_to_hf.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Converts a Whisper model in OpenAI format to Hugging Face format."""
3
+ # Copyright 2022 The HuggingFace Inc. team and the OpenAI team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import argparse
18
+ import io
19
+ import json
20
+ import os
21
+ import tempfile
22
+ import urllib
23
+ import warnings
24
+ from typing import Any, List, Optional, Tuple
25
+
26
+ import torch
27
+ from huggingface_hub.utils import insecure_hashlib
28
+ from torch import nn
29
+ from tqdm import tqdm
30
+
31
+ from transformers import (
32
+ GenerationConfig,
33
+ WhisperConfig,
34
+ WhisperFeatureExtractor,
35
+ WhisperForConditionalGeneration,
36
+ WhisperProcessor,
37
+ WhisperTokenizer,
38
+ WhisperTokenizerFast,
39
+ )
40
+ from transformers.models.whisper.tokenization_whisper import LANGUAGES, bytes_to_unicode
41
+ from transformers.utils.import_utils import _is_package_available
42
+
43
+
44
+ _MODELS = {
45
+ "tiny.en": "https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt",
46
+ "tiny": "https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt",
47
+ "base.en": "https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt",
48
+ "base": "https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt",
49
+ "small.en": "https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt",
50
+ "small": "https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt",
51
+ "medium.en": "https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt",
52
+ "medium": "https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt",
53
+ "large": "https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt",
54
+ "large-v2": "https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt",
55
+ "large-v3": "https://openaipublic.azureedge.net/main/whisper/models/e5b1a55b89c1367dacf97e3e19bfd829a01529dbfdeefa8caeb59b3f1b81dadb/large-v3.pt",
56
+ }
57
+
58
+
59
+ _TOKENIZERS = {
60
+ "multilingual": "https://raw.githubusercontent.com/openai/whisper/main/whisper/assets/multilingual.tiktoken",
61
+ "english": "https://raw.githubusercontent.com/openai/whisper/main/whisper/assets/gpt2.tiktoken",
62
+ }
63
+
64
+
65
+ def _get_generation_config(
66
+ is_multilingual: bool,
67
+ num_languages: int = 100,
68
+ openai_version: Optional[str] = None,
69
+ ) -> GenerationConfig:
70
+ """
71
+ Loads the appropriate generation config from HF repo
72
+ """
73
+ if openai_version is not None:
74
+ repo = f"openai/whisper-{openai_version}"
75
+ elif not is_multilingual:
76
+ repo = "openai/whisper-medium.en"
77
+ elif num_languages < 100:
78
+ repo = "openai/whisper-large-v2"
79
+ else:
80
+ repo = "openai/whisper-large-v3"
81
+
82
+ gen_cfg = GenerationConfig.from_pretrained(repo)
83
+ if openai_version is None:
84
+ gen_cfg.alignment_heads = None
85
+ warnings.warn(
86
+ "Alignment heads have not been included in the generation config, since they are available "
87
+ "only for the original OpenAI checkpoints."
88
+ "If you want to use word-level timestamps with a custom version of Whisper,"
89
+ "see https://github.com/openai/whisper/blob/main/notebooks/Multilingual_ASR.ipynb"
90
+ "for the example of how to produce word-level timestamps manually."
91
+ )
92
+
93
+ return gen_cfg
94
+
95
+
96
+ def remove_ignore_keys_(state_dict):
97
+ ignore_keys = ["layers", "blocks"]
98
+ for k in ignore_keys:
99
+ state_dict.pop(k, None)
100
+
101
+
102
+ WHISPER_MAPPING = {
103
+ "blocks": "layers",
104
+ "mlp.0": "fc1",
105
+ "mlp.2": "fc2",
106
+ "mlp_ln": "final_layer_norm",
107
+ ".attn.query": ".self_attn.q_proj",
108
+ ".attn.key": ".self_attn.k_proj",
109
+ ".attn.value": ".self_attn.v_proj",
110
+ ".attn_ln": ".self_attn_layer_norm",
111
+ ".attn.out": ".self_attn.out_proj",
112
+ ".cross_attn.query": ".encoder_attn.q_proj",
113
+ ".cross_attn.key": ".encoder_attn.k_proj",
114
+ ".cross_attn.value": ".encoder_attn.v_proj",
115
+ ".cross_attn_ln": ".encoder_attn_layer_norm",
116
+ ".cross_attn.out": ".encoder_attn.out_proj",
117
+ "decoder.ln.": "decoder.layer_norm.",
118
+ "encoder.ln.": "encoder.layer_norm.",
119
+ "token_embedding": "embed_tokens",
120
+ "encoder.positional_embedding": "encoder.embed_positions.weight",
121
+ "decoder.positional_embedding": "decoder.embed_positions.weight",
122
+ "ln_post": "layer_norm",
123
+ }
124
+
125
+
126
+ def rename_keys(s_dict):
127
+ keys = list(s_dict.keys())
128
+ for key in keys:
129
+ new_key = key
130
+ for k, v in WHISPER_MAPPING.items():
131
+ if k in key:
132
+ new_key = new_key.replace(k, v)
133
+
134
+ print(f"{key} -> {new_key}")
135
+
136
+ s_dict[new_key] = s_dict.pop(key)
137
+ return s_dict
138
+
139
+
140
+ def make_linear_from_emb(emb):
141
+ vocab_size, emb_size = emb.weight.shape
142
+ lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
143
+ lin_layer.weight.data = emb.weight.data
144
+ return lin_layer
145
+
146
+
147
+ def _download(url: str, root: str) -> Any:
148
+ os.makedirs(root, exist_ok=True)
149
+ filename = os.path.basename(url)
150
+
151
+ expected_sha256 = url.split("/")[-2]
152
+ download_target = os.path.join(root, filename)
153
+
154
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
155
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
156
+
157
+ if os.path.isfile(download_target):
158
+ model_bytes = open(download_target, "rb").read()
159
+ if insecure_hashlib.sha256(model_bytes).hexdigest() == expected_sha256:
160
+ return torch.load(io.BytesIO(model_bytes))
161
+ else:
162
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
163
+
164
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
165
+ with tqdm(
166
+ total=int(source.info().get("Content-Length")), ncols=80, unit="iB", unit_scale=True, unit_divisor=1024
167
+ ) as loop:
168
+ while True:
169
+ buffer = source.read(8192)
170
+ if not buffer:
171
+ break
172
+
173
+ output.write(buffer)
174
+ loop.update(len(buffer))
175
+
176
+ model_bytes = open(download_target, "rb").read()
177
+ if insecure_hashlib.sha256(model_bytes).hexdigest() != expected_sha256:
178
+ raise RuntimeError(
179
+ "Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model."
180
+ )
181
+
182
+ return torch.load(io.BytesIO(model_bytes))
183
+
184
+
185
+ def convert_openai_whisper_to_tfms(
186
+ checkpoint_path, pytorch_dump_folder_path
187
+ ) -> Tuple[WhisperForConditionalGeneration, bool, int]:
188
+ if ".pt" not in checkpoint_path:
189
+ root = os.path.dirname(pytorch_dump_folder_path) or "."
190
+ original_checkpoint = _download(_MODELS[checkpoint_path], root)
191
+ openai_version = checkpoint_path
192
+ else:
193
+ original_checkpoint = torch.load(checkpoint_path, map_location="cpu")
194
+ openai_version = None
195
+
196
+ dimensions = original_checkpoint["dims"]
197
+ state_dict = original_checkpoint["model_state_dict"]
198
+ proj_out_weights = state_dict["decoder.token_embedding.weight"]
199
+ remove_ignore_keys_(state_dict)
200
+ rename_keys(state_dict)
201
+ tie_embeds = True
202
+ ffn_dim = state_dict["decoder.layers.0.fc1.weight"].shape[0]
203
+
204
+ # a hacky way to properly set up the bos/eos/pad token ids in the model
205
+ endoftext_id = 50257 if dimensions["n_vocab"] > 51865 else 50256
206
+
207
+ config = WhisperConfig(
208
+ vocab_size=dimensions["n_vocab"],
209
+ encoder_ffn_dim=ffn_dim,
210
+ decoder_ffn_dim=ffn_dim,
211
+ num_mel_bins=dimensions["n_mels"],
212
+ d_model=dimensions["n_audio_state"],
213
+ max_target_positions=dimensions["n_text_ctx"],
214
+ encoder_layers=dimensions["n_audio_layer"],
215
+ encoder_attention_heads=dimensions["n_audio_head"],
216
+ decoder_layers=dimensions["n_text_layer"],
217
+ decoder_attention_heads=dimensions["n_text_head"],
218
+ max_source_positions=dimensions["n_audio_ctx"],
219
+ eos_token_id=endoftext_id,
220
+ bos_token_id=endoftext_id,
221
+ pad_token_id=endoftext_id,
222
+ decoder_start_token_id=endoftext_id + 1,
223
+ )
224
+
225
+ model = WhisperForConditionalGeneration(config)
226
+ missing, unexpected = model.model.load_state_dict(state_dict, strict=False)
227
+ if len(missing) > 0 and not set(missing) <= {
228
+ "encoder.embed_positions.weights",
229
+ "decoder.embed_positions.weights",
230
+ }:
231
+ raise ValueError(
232
+ "Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,"
233
+ f" but all the following weights are missing {missing}"
234
+ )
235
+
236
+ if tie_embeds:
237
+ model.proj_out = make_linear_from_emb(model.model.decoder.embed_tokens)
238
+ else:
239
+ model.proj_out.weight.data = proj_out_weights
240
+
241
+ # determine those parameters from a model checkpoint as Whisper repo does
242
+ is_multilingual = model.config.vocab_size >= 51865
243
+ num_languages = model.config.vocab_size - 51765 - int(is_multilingual)
244
+
245
+ model.generation_config = _get_generation_config(
246
+ is_multilingual,
247
+ num_languages,
248
+ openai_version,
249
+ )
250
+
251
+ return model, is_multilingual, num_languages
252
+
253
+
254
+ # Adapted from https://github.com/openai/tiktoken/issues/60#issuecomment-1499977960
255
+ def _bpe(mergeable_ranks, token: bytes, max_rank=None) -> List[bytes]:
256
+ parts = [bytes([b]) for b in token]
257
+ while True:
258
+ min_idx = None
259
+ min_rank = None
260
+ for i, pair in enumerate(zip(parts[:-1], parts[1:])):
261
+ rank = mergeable_ranks.get(pair[0] + pair[1])
262
+ if rank is not None and (min_rank is None or rank < min_rank):
263
+ min_idx = i
264
+ min_rank = rank
265
+ if min_rank is None or (max_rank is not None and min_rank >= max_rank):
266
+ break
267
+ assert min_idx is not None
268
+ parts = parts[:min_idx] + [parts[min_idx] + parts[min_idx + 1]] + parts[min_idx + 2 :]
269
+ return parts
270
+
271
+
272
+ def convert_tiktoken_bpe_to_hf(tiktoken_url: str):
273
+ bpe_ranks = load_tiktoken_bpe(tiktoken_url)
274
+ byte_encoder = bytes_to_unicode()
275
+
276
+ def token_bytes_to_string(b):
277
+ return "".join([byte_encoder[ord(char)] for char in b.decode("latin-1")])
278
+
279
+ merges = []
280
+ vocab = {}
281
+ for token, rank in bpe_ranks.items():
282
+ vocab[token_bytes_to_string(token)] = rank
283
+ if len(token) == 1:
284
+ continue
285
+ merged = tuple(_bpe(bpe_ranks, token, max_rank=rank))
286
+ if len(merged) == 2: # account for empty token
287
+ merges.append(" ".join(map(token_bytes_to_string, merged)))
288
+ return vocab, merges
289
+
290
+
291
+ def convert_tiktoken_to_hf(
292
+ multilingual: bool = True, num_languages: int = 100, time_precision=0.02
293
+ ) -> WhisperTokenizer:
294
+ # requires whisper, unless we use the path to the tiktoken file
295
+ tiktoken_tokenizer_path = _TOKENIZERS["multilingual" if multilingual else "english"]
296
+ start_of_transcript = ["<|endoftext|>", "<|startoftranscript|>"]
297
+ control_tokens = [
298
+ "<|translate|>",
299
+ "<|transcribe|>",
300
+ "<|startoflm|>",
301
+ "<|startofprev|>",
302
+ "<|nospeech|>",
303
+ "<|notimestamps|>",
304
+ ]
305
+ # these are special tokens, not normalized
306
+ language_tokens = [f"<|{k}|>" for k in list(LANGUAGES)[:num_languages]]
307
+ # These are not special but normalized
308
+ timestamp_tokens = [("<|%.2f|>" % (i * time_precision)) for i in range(1500 + 1)]
309
+
310
+ vocab, merges = convert_tiktoken_bpe_to_hf(tiktoken_tokenizer_path)
311
+
312
+ with tempfile.TemporaryDirectory() as tmpdirname:
313
+ vocab_file = f"{tmpdirname}/vocab.json"
314
+ merge_file = f"{tmpdirname}/merges.txt"
315
+ with open(vocab_file, "w", encoding="utf-8") as f:
316
+ f.write(json.dumps(vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
317
+
318
+ with open(merge_file, "w", encoding="utf-8") as writer:
319
+ writer.write("#version: 0.2\n")
320
+ for bpe_tokens in merges:
321
+ writer.write(bpe_tokens + "\n")
322
+
323
+ hf_tokenizer = WhisperTokenizer(vocab_file, merge_file)
324
+
325
+ hf_tokenizer.add_tokens(start_of_transcript + language_tokens + control_tokens, special_tokens=True)
326
+ hf_tokenizer.add_tokens(timestamp_tokens, special_tokens=False)
327
+ return hf_tokenizer
328
+
329
+
330
+ if __name__ == "__main__":
331
+ parser = argparse.ArgumentParser()
332
+ # # Required parameters
333
+ parser.add_argument("--checkpoint_path", type=str, help="Path to the downloaded checkpoints")
334
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
335
+ parser.add_argument(
336
+ "--convert_preprocessor",
337
+ type=bool,
338
+ default=False,
339
+ help="Whether or not the preprocessor (tokenizer + feature extractor) should be converted along with the model.",
340
+ )
341
+ args = parser.parse_args()
342
+
343
+ model, is_multilingual, num_languages = convert_openai_whisper_to_tfms(
344
+ args.checkpoint_path, args.pytorch_dump_folder_path
345
+ )
346
+
347
+ if args.convert_preprocessor:
348
+ try:
349
+ if not _is_package_available("tiktoken"):
350
+ raise ModuleNotFoundError(
351
+ """`tiktoken` is not installed, use `pip install tiktoken` to convert the tokenizer"""
352
+ )
353
+ except Exception as e:
354
+ print(e)
355
+ else:
356
+ from tiktoken.load import load_tiktoken_bpe
357
+
358
+ tokenizer = convert_tiktoken_to_hf(is_multilingual, num_languages)
359
+ feature_extractor = WhisperFeatureExtractor(
360
+ feature_size=model.config.num_mel_bins,
361
+ # the rest of default parameters are the same as hardcoded in openai/whisper
362
+ )
363
+ processor = WhisperProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor)
364
+ processor.save_pretrained(args.pytorch_dump_folder_path)
365
+
366
+ # save fast tokenizer as well
367
+ fast_tokenizer = WhisperTokenizerFast.from_pretrained(args.pytorch_dump_folder_path)
368
+ fast_tokenizer.save_pretrained(args.pytorch_dump_folder_path, legacy_format=False)
369
+
370
+ model.save_pretrained(args.pytorch_dump_folder_path)