|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import io |
|
import os |
|
import sys |
|
import struct |
|
import json |
|
import code |
|
import torch |
|
import numpy as np |
|
import base64 |
|
from pathlib import Path |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def bytes_to_unicode(): |
|
""" |
|
Returns list of utf-8 byte and a corresponding list of unicode strings. |
|
The reversible bpe codes work on unicode strings. |
|
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. |
|
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. |
|
This is a signficant percentage of your normal, say, 32K bpe vocab. |
|
To avoid that, we want lookup tables between utf-8 bytes and unicode strings. |
|
And avoids mapping to whitespace/control characters the bpe code barfs on. |
|
""" |
|
bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) |
|
cs = bs[:] |
|
n = 0 |
|
for b in range(2**8): |
|
if b not in bs: |
|
bs.append(b) |
|
cs.append(2**8+n) |
|
n += 1 |
|
cs = [chr(n) for n in cs] |
|
return dict(zip(bs, cs)) |
|
|
|
|
|
|
|
def hf_to_whisper_states(text): |
|
return (text |
|
.replace("model.", "") |
|
.replace("layers", "blocks") |
|
.replace("fc1", "mlp.0") |
|
.replace("fc2", "mlp.2") |
|
.replace("final_layer_norm", "mlp_ln") |
|
.replace(".self_attn.q_proj", ".attn.query") |
|
.replace(".self_attn.k_proj", ".attn.key") |
|
.replace(".self_attn.v_proj", ".attn.value") |
|
.replace(".self_attn_layer_norm", ".attn_ln") |
|
.replace(".self_attn.out_proj", ".attn.out") |
|
.replace(".encoder_attn.q_proj", ".cross_attn.query") |
|
.replace(".encoder_attn.k_proj", ".cross_attn.key") |
|
.replace(".encoder_attn.v_proj", ".cross_attn.value") |
|
.replace(".encoder_attn_layer_norm", ".cross_attn_ln") |
|
.replace(".encoder_attn.out_proj", ".cross_attn.out") |
|
.replace("decoder.layer_norm.", "decoder.ln.") |
|
.replace("encoder.layer_norm.", "encoder.ln_post.") |
|
.replace("embed_tokens", "token_embedding") |
|
.replace("encoder.embed_positions.weight", "encoder.positional_embedding") |
|
.replace("decoder.embed_positions.weight", "decoder.positional_embedding") |
|
.replace("layer_norm", "ln_post") |
|
) |
|
|
|
if len(sys.argv) < 4: |
|
print("Usage: convert-pt-to-ggml.py model.pt path-to-whisper-repo dir-output [use-f32]\n") |
|
sys.exit(1) |
|
|
|
fname_inp = Path(sys.argv[1]) |
|
dir_whisper = Path(sys.argv[2]) |
|
dir_out = Path(sys.argv[3]) |
|
|
|
|
|
try: |
|
model_bytes = open(fname_inp, "rb").read() |
|
with io.BytesIO(model_bytes) as fp: |
|
checkpoint = torch.load(fp, map_location="cpu") |
|
except Exception: |
|
print("Error: failed to load PyTorch model file:" , fname_inp) |
|
sys.exit(1) |
|
|
|
|
|
|
|
hparams = { |
|
'n_mels': 128, |
|
'n_vocab': 51866, |
|
'n_audio_ctx': 1500, |
|
'n_audio_state': 1280, |
|
'n_audio_head': 20, |
|
'n_audio_layer': 32, |
|
'n_text_ctx': 448, |
|
'n_text_state': 1280, |
|
'n_text_head': 20, |
|
'n_text_layer': 32 |
|
} |
|
print("hparams:", hparams) |
|
|
|
list_vars = checkpoint |
|
|
|
|
|
|
|
|
|
|
|
|
|
n_mels = hparams["n_mels"] |
|
with np.load(dir_whisper / "whisper" / "assets" / "mel_filters.npz") as f: |
|
filters = torch.from_numpy(f[f"mel_{n_mels}"]) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
multilingual = hparams["n_vocab"] >= 51865 |
|
tokenizer = dir_whisper / "whisper" / "assets" / (multilingual and "multilingual.tiktoken" or "gpt2.tiktoken") |
|
tokenizer_type = "tiktoken" |
|
if not tokenizer.is_file(): |
|
tokenizer = dir_whisper / "whisper" / "assets" / (multilingual and "multilingual" or "gpt2") / "vocab.json" |
|
tokenizer_type = "hf_transformers" |
|
if not tokenizer.is_file(): |
|
print("Error: failed to find either tiktoken or hf_transformers tokenizer file:", tokenizer) |
|
sys.exit(1) |
|
|
|
byte_encoder = bytes_to_unicode() |
|
byte_decoder = {v:k for k, v in byte_encoder.items()} |
|
|
|
if tokenizer_type == "tiktoken": |
|
with open(tokenizer, "rb") as f: |
|
contents = f.read() |
|
tokens = {base64.b64decode(token): int(rank) for token, rank in (line.split() for line in contents.splitlines() if line)} |
|
elif tokenizer_type == "hf_transformers": |
|
with open(tokenizer, "r", encoding="utf8") as f: |
|
_tokens_raw = json.load(f) |
|
if '<|endoftext|>' in _tokens_raw: |
|
|
|
|
|
del _tokens_raw['<|endoftext|>'] |
|
tokens = {bytes([byte_decoder[c] for c in token]): int(idx) for token, idx in _tokens_raw.items()} |
|
|
|
|
|
fname_out = dir_out / "ggml-model.bin" |
|
|
|
|
|
use_f16 = True |
|
if len(sys.argv) > 4: |
|
use_f16 = False |
|
fname_out = dir_out / "ggml-model-f32.bin" |
|
|
|
fout = fname_out.open("wb") |
|
|
|
fout.write(struct.pack("i", 0x67676d6c)) |
|
fout.write(struct.pack("i", hparams["n_vocab"])) |
|
fout.write(struct.pack("i", hparams["n_audio_ctx"])) |
|
fout.write(struct.pack("i", hparams["n_audio_state"])) |
|
fout.write(struct.pack("i", hparams["n_audio_head"])) |
|
fout.write(struct.pack("i", hparams["n_audio_layer"])) |
|
fout.write(struct.pack("i", hparams["n_text_ctx"])) |
|
fout.write(struct.pack("i", hparams["n_text_state"])) |
|
fout.write(struct.pack("i", hparams["n_text_head"])) |
|
fout.write(struct.pack("i", hparams["n_text_layer"])) |
|
fout.write(struct.pack("i", hparams["n_mels"])) |
|
fout.write(struct.pack("i", use_f16)) |
|
|
|
|
|
fout.write(struct.pack("i", filters.shape[0])) |
|
fout.write(struct.pack("i", filters.shape[1])) |
|
for i in range(filters.shape[0]): |
|
for j in range(filters.shape[1]): |
|
fout.write(struct.pack("f", filters[i][j])) |
|
|
|
|
|
fout.write(struct.pack("i", len(tokens))) |
|
|
|
for key in tokens: |
|
fout.write(struct.pack("i", len(key))) |
|
fout.write(key) |
|
|
|
for name in sorted(list_vars.keys(), key=hf_to_whisper_states): |
|
if name == 'proj_out.weight': |
|
continue |
|
data = list_vars[name].squeeze().numpy() |
|
name = hf_to_whisper_states(name) |
|
print("Processing variable: " , name , " with shape: ", data.shape) |
|
|
|
|
|
if name in ["encoder.conv1.bias", "encoder.conv2.bias"]: |
|
data = data.reshape(data.shape[0], 1) |
|
print(f" Reshaped variable: {name} to shape: ", data.shape) |
|
|
|
n_dims = len(data.shape) |
|
|
|
|
|
|
|
|
|
ftype = 1 |
|
if use_f16: |
|
if n_dims < 2 or \ |
|
name == "encoder.conv1.bias" or \ |
|
name == "encoder.conv2.bias" or \ |
|
name == "encoder.positional_embedding" or \ |
|
name == "decoder.positional_embedding": |
|
print(" Converting to float32") |
|
data = data.astype(np.float32) |
|
ftype = 0 |
|
else: |
|
data = data.astype(np.float16) |
|
else: |
|
data = data.astype(np.float32) |
|
ftype = 0 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
str_ = name.encode('utf-8') |
|
fout.write(struct.pack("iii", n_dims, len(str_), ftype)) |
|
for i in range(n_dims): |
|
fout.write(struct.pack("i", data.shape[n_dims - 1 - i])) |
|
fout.write(str_) |
|
|
|
|
|
data.tofile(fout) |
|
|
|
fout.close() |
|
|
|
print("Done. Output file: " , fname_out) |
|
print("") |
|
|