mirror of
https://github.com/nomic-ai/gpt4all.git
synced 2025-08-14 22:23:37 +00:00
feat: converter scripts from hf
This commit is contained in:
parent
cfd70b69fc
commit
c7f0cf0cd2
101
gpt4all-quantizer/converter/convert_bert_hf_to_ggml.py
Normal file
101
gpt4all-quantizer/converter/convert_bert_hf_to_ggml.py
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
import sys
|
||||||
|
import struct
|
||||||
|
import json
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from transformers import AutoModel, AutoTokenizer
|
||||||
|
|
||||||
|
if len(sys.argv) < 3:
|
||||||
|
print("Usage: convert-h5-to-ggml.py dir-model [use-f32]\n")
|
||||||
|
print(" ftype == 0 -> float32")
|
||||||
|
print(" ftype == 1 -> float16")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# output in the same directory as the model
|
||||||
|
dir_model = sys.argv[1]
|
||||||
|
fname_out = sys.argv[1] + "/ggml-model.bin"
|
||||||
|
|
||||||
|
with open(dir_model + "/tokenizer.json", "r", encoding="utf-8") as f:
|
||||||
|
encoder = json.load(f)
|
||||||
|
|
||||||
|
with open(dir_model + "/config.json", "r", encoding="utf-8") as f:
|
||||||
|
hparams = json.load(f)
|
||||||
|
|
||||||
|
with open(dir_model + "/vocab.txt", "r", encoding="utf-8") as f:
|
||||||
|
vocab = f.readlines()
|
||||||
|
# possible data types
|
||||||
|
# ftype == 0 -> float32
|
||||||
|
# ftype == 1 -> float16
|
||||||
|
#
|
||||||
|
# map from ftype to string
|
||||||
|
ftype_str = ["f32", "f16"]
|
||||||
|
|
||||||
|
ftype = 1
|
||||||
|
if len(sys.argv) > 2:
|
||||||
|
ftype = int(sys.argv[2])
|
||||||
|
if ftype < 0 or ftype > 1:
|
||||||
|
print("Invalid ftype: " + str(ftype))
|
||||||
|
sys.exit(1)
|
||||||
|
fname_out = sys.argv[1] + "/ggml-model-" + ftype_str[ftype] + ".bin"
|
||||||
|
|
||||||
|
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained(dir_model)
|
||||||
|
model = AutoModel.from_pretrained(dir_model, low_cpu_mem_usage=True)
|
||||||
|
print (model)
|
||||||
|
|
||||||
|
print(tokenizer.encode('I believe the meaning of life is'))
|
||||||
|
|
||||||
|
list_vars = model.state_dict()
|
||||||
|
for name in list_vars.keys():
|
||||||
|
print(name, list_vars[name].shape, list_vars[name].dtype)
|
||||||
|
|
||||||
|
fout = open(fname_out, "wb")
|
||||||
|
|
||||||
|
print(hparams)
|
||||||
|
|
||||||
|
fout.write(struct.pack("i", 0x62657274)) # magic: ggml in hex
|
||||||
|
fout.write(struct.pack("i", hparams["vocab_size"]))
|
||||||
|
fout.write(struct.pack("i", hparams["max_position_embeddings"]))
|
||||||
|
fout.write(struct.pack("i", hparams["hidden_size"]))
|
||||||
|
fout.write(struct.pack("i", hparams["intermediate_size"]))
|
||||||
|
fout.write(struct.pack("i", hparams["num_attention_heads"]))
|
||||||
|
fout.write(struct.pack("i", hparams["num_hidden_layers"]))
|
||||||
|
fout.write(struct.pack("i", ftype))
|
||||||
|
|
||||||
|
for i in range(hparams["vocab_size"]):
|
||||||
|
text = vocab[i][:-1] # strips newline at the end
|
||||||
|
#print(f"{i}:{text}")
|
||||||
|
data = bytes(text, 'utf-8')
|
||||||
|
fout.write(struct.pack("i", len(data)))
|
||||||
|
fout.write(data)
|
||||||
|
|
||||||
|
for name in list_vars.keys():
|
||||||
|
data = list_vars[name].squeeze().numpy()
|
||||||
|
if name in ['embeddings.position_ids', 'pooler.dense.weight', 'pooler.dense.bias']:
|
||||||
|
continue
|
||||||
|
print("Processing variable: " + name + " with shape: ", data.shape)
|
||||||
|
|
||||||
|
n_dims = len(data.shape);
|
||||||
|
|
||||||
|
# ftype == 0 -> float32, ftype == 1 -> float16
|
||||||
|
if ftype == 1 and name[-7:] == ".weight" and n_dims == 2:
|
||||||
|
print(" Converting to float16")
|
||||||
|
data = data.astype(np.float16)
|
||||||
|
l_type = 1
|
||||||
|
else:
|
||||||
|
l_type = 0
|
||||||
|
|
||||||
|
# header
|
||||||
|
str = name.encode('utf-8')
|
||||||
|
fout.write(struct.pack("iii", n_dims, len(str), l_type))
|
||||||
|
for i in range(n_dims):
|
||||||
|
fout.write(struct.pack("i", data.shape[n_dims - 1 - i]))
|
||||||
|
fout.write(str);
|
||||||
|
|
||||||
|
# data
|
||||||
|
data.tofile(fout)
|
||||||
|
|
||||||
|
fout.close()
|
||||||
|
|
||||||
|
print("Done. Output file: " + fname_out)
|
||||||
|
print("")
|
143
gpt4all-quantizer/converter/convert_falcon_hf_to_ggml.py
Normal file
143
gpt4all-quantizer/converter/convert_falcon_hf_to_ggml.py
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
# Based on: https://github.com/KerfuffleV2/ggml-falcon/blob/feat-improve-falcon-convert-hf/examples/falcon/convert-hf-to-ggml.py
|
||||||
|
# Convert Hugging Face fine-tuned bloom-like models to ggml format
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
#
|
||||||
|
# python3 convert_falcon_hf_to_ggml.py model_directory output_directory [use-f32]
|
||||||
|
#
|
||||||
|
# This script is similar to "convert-pt-to-ggml.py"
|
||||||
|
#
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import struct
|
||||||
|
import json
|
||||||
|
import code
|
||||||
|
import torch
|
||||||
|
import numpy as np
|
||||||
|
import gc
|
||||||
|
|
||||||
|
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
|
||||||
|
|
||||||
|
# ref: https://github.com/openai/gpt-2/blob/master/src/encoder.py
|
||||||
|
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 significant 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))
|
||||||
|
|
||||||
|
if len(sys.argv) < 3:
|
||||||
|
print("INFO: GGML V1 files produced are meant to be finalized through examples/falcon_quantize which will bring them to latest version and precision of choice");
|
||||||
|
print("Usage: python convert_falcon_hf_to_ggml.py model_directory output_directory [use-f32]")
|
||||||
|
print(" model_directory: name of the directory and model you convert (it should be a subdirectory)")
|
||||||
|
print(" output-directory: directory where the output file will be written")
|
||||||
|
print(" use-f32: if present, use float32 instead of float16 (f32 is recommended)")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# num_parts = int(sys.argv[1])
|
||||||
|
dir_model = sys.argv[1] # name and dir of model
|
||||||
|
dir_out = sys.argv[2] # output directory
|
||||||
|
|
||||||
|
# make sure the output directory exists
|
||||||
|
os.makedirs(dir_out, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
# possible data types
|
||||||
|
# ftype == 0 -> float32
|
||||||
|
# ftype == 1 -> float16
|
||||||
|
#
|
||||||
|
# map from ftype to string
|
||||||
|
ftype_str = ["f32", "f16"]
|
||||||
|
ftype = 1
|
||||||
|
if len(sys.argv) > 3:
|
||||||
|
ftype = 0
|
||||||
|
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained(dir_model)
|
||||||
|
# print(tokenizer)
|
||||||
|
config = AutoConfig.from_pretrained(dir_model, trust_remote_code=True)
|
||||||
|
model = AutoModelForCausalLM.from_pretrained(dir_model, trust_remote_code=True, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
|
||||||
|
hparams = config.to_dict()
|
||||||
|
|
||||||
|
n_head = hparams["n_head"]
|
||||||
|
n_head_kv = hparams["n_head_kv"] if "n_head_kv" in hparams else 1
|
||||||
|
head_dim = hparams["hidden_size"] // n_head
|
||||||
|
print("* Loading model from: ", dir_model)
|
||||||
|
|
||||||
|
fname_out = dir_out + f"/ggml-model-{dir_model.split('/')[-1]}-{ftype_str[ftype]}.bin"
|
||||||
|
fout = open(fname_out, "wb")
|
||||||
|
fout.write(struct.pack("i", 0x67676a74)) # magic: ggmf in hex (version 1) - possibly change to ggfc ?
|
||||||
|
fout.write(struct.pack("i", 1)) # version
|
||||||
|
fout.write(struct.pack("i", hparams["vocab_size"]))
|
||||||
|
fout.write(struct.pack("i", hparams["hidden_size"]))
|
||||||
|
fout.write(struct.pack("i", n_head))
|
||||||
|
fout.write(struct.pack("i", n_head_kv))
|
||||||
|
fout.write(struct.pack("i", hparams["n_layer"]))
|
||||||
|
fout.write(struct.pack("i", 40 if "n_head_kv" in hparams else 7)) # obsolete field that breaks ggml compatibility - todo again remove one day
|
||||||
|
fout.write(struct.pack("i", ftype))
|
||||||
|
|
||||||
|
reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.vocab.items()}
|
||||||
|
byte_encoder = bytes_to_unicode()
|
||||||
|
byte_decoder = {v:k for k, v in byte_encoder.items()}
|
||||||
|
|
||||||
|
for i in range(hparams["vocab_size"]):
|
||||||
|
text = bytearray([byte_decoder[c] for c in reverse_vocab[i]])
|
||||||
|
fout.write(struct.pack("i", len(text)))
|
||||||
|
fout.write(text)
|
||||||
|
fout.write(struct.pack("f", 0.0)) # falcon uses bpe on RefinedWeb - no probability scores used
|
||||||
|
|
||||||
|
model = model.state_dict()
|
||||||
|
for name in model.keys():
|
||||||
|
src = name
|
||||||
|
# The original query_key_value tensor contains n_head_kv "kv groups",
|
||||||
|
# each consisting of n_head/n_head_kv query weights followed by one key
|
||||||
|
# and one value weight (shared by all query heads in the kv group).
|
||||||
|
# This layout makes it a big pain to work with in GGML.
|
||||||
|
# So we rearrange them here,, so that we have n_head query weights
|
||||||
|
# followed by n_head_kv key weights followed by n_head_kv value weights,
|
||||||
|
# in contiguous fashion.
|
||||||
|
|
||||||
|
if "query_key_value" in src:
|
||||||
|
qkv = model[src].view(
|
||||||
|
n_head_kv, n_head // n_head_kv + 2, head_dim, head_dim * n_head)
|
||||||
|
|
||||||
|
q = qkv[:, :-2 ].reshape(n_head * head_dim, head_dim * n_head)
|
||||||
|
k = qkv[:, [-2]].reshape(n_head_kv * head_dim, head_dim * n_head)
|
||||||
|
v = qkv[:, [-1]].reshape(n_head_kv * head_dim, head_dim * n_head)
|
||||||
|
|
||||||
|
model[src] = torch.cat((q,k,v)).reshape_as(model[src])
|
||||||
|
data = model[src].squeeze()
|
||||||
|
n_dims = len(data.shape)
|
||||||
|
# default type is fp32
|
||||||
|
ftype_cur = 1 if ftype == 1 and n_dims > 1 else 0
|
||||||
|
data = data.to(dtype = torch.float16 if ftype_cur == 1 else torch.float32).numpy()
|
||||||
|
print(f' |', name, data.shape, '->', data.dtype)
|
||||||
|
# header
|
||||||
|
str = name.encode('utf-8')
|
||||||
|
fout.write(struct.pack("iii", n_dims, len(str), ftype_cur))
|
||||||
|
for i in range(n_dims):
|
||||||
|
fout.write(struct.pack("i", data.shape[n_dims - 1 - i]))
|
||||||
|
fout.write(str)
|
||||||
|
|
||||||
|
# data
|
||||||
|
data.tofile(fout)
|
||||||
|
|
||||||
|
fout.close()
|
||||||
|
|
||||||
|
print("Done. Output file: " + fname_out)
|
||||||
|
print("")
|
1239
gpt4all-quantizer/converter/convert_llama_hf_to_ggml.py
Normal file
1239
gpt4all-quantizer/converter/convert_llama_hf_to_ggml.py
Normal file
File diff suppressed because it is too large
Load Diff
142
gpt4all-quantizer/converter/convert_mpt_hf_to_ggml.py
Normal file
142
gpt4all-quantizer/converter/convert_mpt_hf_to_ggml.py
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
# Convert Hugging Face fine-tuned bloom-like models to ggml format
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
#
|
||||||
|
# python3 models/convert-h5-to-ggml.py
|
||||||
|
#
|
||||||
|
# This script is similar to "convert-pt-to-ggml.py"
|
||||||
|
#
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import struct
|
||||||
|
import torch
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
|
||||||
|
|
||||||
|
# ref: https://github.com/openai/gpt-2/blob/master/src/encoder.py
|
||||||
|
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 significant 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))
|
||||||
|
|
||||||
|
if len(sys.argv) < 3:
|
||||||
|
print("Usage: python convert-hf-to-ggml.py model_name dir-output [use-f32]")
|
||||||
|
print(" model_name: name of the model to convert. Example: 'bigscience/bloomz-560m'")
|
||||||
|
print(" dir-output: directory where the output file will be written")
|
||||||
|
print(" use-f32: if present, use float32 instead of float16")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
model_name = sys.argv[1]
|
||||||
|
dir_out = sys.argv[2]
|
||||||
|
|
||||||
|
# make sure the output directory exists
|
||||||
|
os.makedirs(dir_out, exist_ok=True)
|
||||||
|
|
||||||
|
# possible data types
|
||||||
|
# ftype == 0 -> float32
|
||||||
|
# ftype == 1 -> float16
|
||||||
|
#
|
||||||
|
# map from ftype to string
|
||||||
|
ftype_str = ["f32", "f16"]
|
||||||
|
ftype = 1
|
||||||
|
if len(sys.argv) > 3:
|
||||||
|
ftype = 0
|
||||||
|
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
||||||
|
config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
|
||||||
|
hparams = config.to_dict()
|
||||||
|
print("Loading model: ", model_name)
|
||||||
|
model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True, config=config, torch_dtype=torch.float16 if ftype == 1 else torch.float32, low_cpu_mem_usage=True)
|
||||||
|
print("Model loaded: ", model_name)
|
||||||
|
|
||||||
|
|
||||||
|
fname_out = dir_out + f"/ggml-model-{model_name.split('/')[-1]}-{ftype_str[ftype]}.bin"
|
||||||
|
fout = open(fname_out, "wb")
|
||||||
|
vocab = tokenizer.vocab
|
||||||
|
|
||||||
|
hparams["multiple_of"] = 1
|
||||||
|
fout.write(struct.pack("I", 0x67676d6d)) # magic: ggml in hex
|
||||||
|
fout.write(struct.pack("I", model.config.vocab_size))
|
||||||
|
fout.write(struct.pack("I", model.config.max_seq_len))
|
||||||
|
fout.write(struct.pack("I", model.config.n_layers))
|
||||||
|
fout.write(struct.pack("I", model.config.n_heads))
|
||||||
|
fout.write(struct.pack("I", model.config.d_model))
|
||||||
|
fout.write(struct.pack("f", model.config.attn_config['alibi_bias_max']))
|
||||||
|
clip_qkv = model.config.attn_config['clip_qkv']
|
||||||
|
fout.write(struct.pack("f", clip_qkv if clip_qkv is not None else 0))
|
||||||
|
fout.write(struct.pack("I", ftype))
|
||||||
|
|
||||||
|
# # Is this correct??
|
||||||
|
# dot_token = tokenizer.encode(".")[0]
|
||||||
|
# write tokens to ggml file
|
||||||
|
dot_token = tokenizer.encode('.')[0]
|
||||||
|
fout.write(struct.pack("I", model.config.vocab_size))
|
||||||
|
|
||||||
|
for i in range(model.config.vocab_size):
|
||||||
|
text = tokenizer.decode([dot_token, i]).encode('utf-8')
|
||||||
|
# remove the first byte (it's always '.')
|
||||||
|
text = text[1:]
|
||||||
|
enclen = len(text)
|
||||||
|
if i in tokenizer.all_special_ids:
|
||||||
|
print(f"special token: {text}")
|
||||||
|
enclen = enclen | 1<<31
|
||||||
|
fout.write(struct.pack("I", enclen))
|
||||||
|
fout.write(text)
|
||||||
|
|
||||||
|
list_vars = model.state_dict()
|
||||||
|
for name in list_vars.keys():
|
||||||
|
data = list_vars[name].squeeze().numpy()
|
||||||
|
print("Processing variable: " + name + " with shape: ", data.shape)
|
||||||
|
|
||||||
|
n_dims = len(data.shape);
|
||||||
|
|
||||||
|
# ftype == 0 -> float32, ftype == 1 -> float16
|
||||||
|
ftype_cur = 0;
|
||||||
|
if ftype != 0:
|
||||||
|
# Keep token embeddings in fp32
|
||||||
|
if name[-7:] == ".weight" and n_dims == 2 and ".wte" not in name:
|
||||||
|
print(" Converting to float16")
|
||||||
|
data = data.astype(np.float16)
|
||||||
|
ftype_cur = 1
|
||||||
|
else:
|
||||||
|
print(" Converting to float32")
|
||||||
|
data = data.astype(np.float32)
|
||||||
|
ftype_cur = 0
|
||||||
|
else:
|
||||||
|
if data.dtype != np.float32:
|
||||||
|
print(" Converting to float32")
|
||||||
|
data = data.astype(np.float32)
|
||||||
|
ftype_cur = 0
|
||||||
|
|
||||||
|
# header
|
||||||
|
str = name.encode('utf-8')
|
||||||
|
fout.write(struct.pack("iii", n_dims, len(str), ftype_cur))
|
||||||
|
for i in range(n_dims):
|
||||||
|
fout.write(struct.pack("i", data.shape[n_dims - 1 - i]))
|
||||||
|
fout.write(str);
|
||||||
|
|
||||||
|
# data
|
||||||
|
data.tofile(fout)
|
||||||
|
|
||||||
|
fout.close()
|
||||||
|
|
||||||
|
print("Done. Output file: " + fname_out)
|
||||||
|
print("")
|
137
gpt4all-quantizer/converter/convert_replit_hf_to_ggml.py
Normal file
137
gpt4all-quantizer/converter/convert_replit_hf_to_ggml.py
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import struct
|
||||||
|
import json
|
||||||
|
import numpy as np
|
||||||
|
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||||
|
from huggingface_hub import hf_hub_download
|
||||||
|
import sentencepiece.sentencepiece_model_pb2 as model
|
||||||
|
|
||||||
|
if len(sys.argv) < 3:
|
||||||
|
print("Usage: convert-h5-to-ggml.py model_name out_dir [use-f32]\n")
|
||||||
|
print(" ftype == 0 -> float32")
|
||||||
|
print(" ftype == 1 -> float16")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
# output in the same directory as the model
|
||||||
|
model_name = sys.argv[1]
|
||||||
|
out_dir = sys.argv[2]
|
||||||
|
if not os.path.exists(out_dir):
|
||||||
|
os.mkdir(out_dir)
|
||||||
|
|
||||||
|
fname_out = sys.argv[2] + "/ggml-replit-code-v1-3b.bin"
|
||||||
|
|
||||||
|
if not os.path.exists(model_name):
|
||||||
|
hf_hub_download(repo_id=model_name, filename="config.json", local_dir=out_dir)
|
||||||
|
hf_hub_download(repo_id=model_name, filename="spiece.model", local_dir=out_dir)
|
||||||
|
else:
|
||||||
|
# copy file from model_name to out_dir
|
||||||
|
os.system("cp " + model_name + "/config.json " + out_dir)
|
||||||
|
os.system("cp " + model_name + "/spiece.model " + out_dir)
|
||||||
|
|
||||||
|
|
||||||
|
with open(out_dir + "/config.json", "r", encoding="utf-8") as f:
|
||||||
|
hparams = json.load(f)
|
||||||
|
|
||||||
|
sp_proto = model.ModelProto()
|
||||||
|
sp_proto.ParseFromString(open(Path(out_dir) / "spiece.model", "rb").read())
|
||||||
|
|
||||||
|
|
||||||
|
# possible data types
|
||||||
|
# ftype == 0 -> float32
|
||||||
|
# ftype == 1 -> float16
|
||||||
|
#
|
||||||
|
# map from ftype to string
|
||||||
|
ftype_str = ["f32", "f16"]
|
||||||
|
|
||||||
|
ftype = 1
|
||||||
|
if len(sys.argv) > 3:
|
||||||
|
ftype = int(sys.argv[3])
|
||||||
|
if ftype < 0 or ftype > 1:
|
||||||
|
print("Invalid ftype: " + str(ftype))
|
||||||
|
sys.exit(1)
|
||||||
|
fname_out = sys.argv[1] + "/ggml-replit-code-v1-3b-" + ftype_str[ftype] + ".bin"
|
||||||
|
|
||||||
|
|
||||||
|
model = AutoModelForCausalLM.from_pretrained(
|
||||||
|
model_name, low_cpu_mem_usage=True, trust_remote_code=True
|
||||||
|
)
|
||||||
|
# print (model)
|
||||||
|
|
||||||
|
# print(tokenizer.encode('I believe the meaning of life is'))
|
||||||
|
|
||||||
|
list_vars = model.state_dict()
|
||||||
|
for name in list_vars.keys():
|
||||||
|
print(name, list_vars[name].shape, list_vars[name].dtype)
|
||||||
|
|
||||||
|
fout = open(fname_out, "wb")
|
||||||
|
|
||||||
|
print(hparams)
|
||||||
|
|
||||||
|
fout.write(struct.pack("i", 0x7265706c)) # magic: repl in hex
|
||||||
|
fout.write(struct.pack("i", hparams["vocab_size"]))
|
||||||
|
fout.write(struct.pack("i", hparams["max_seq_len"]))
|
||||||
|
fout.write(struct.pack("i", hparams["d_model"]))
|
||||||
|
fout.write(struct.pack("i", hparams["n_heads"]))
|
||||||
|
fout.write(struct.pack("i", hparams["n_layers"]))
|
||||||
|
fout.write(struct.pack("i", ftype))
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: temporary hack to not deal with implementing the tokenizer
|
||||||
|
for piece in sp_proto.pieces:
|
||||||
|
encoded_piece = piece.piece.encode("utf-8")
|
||||||
|
fout.write(struct.pack("i", len(encoded_piece)))
|
||||||
|
fout.write(encoded_piece)
|
||||||
|
fout.write(struct.pack("f", piece.score))
|
||||||
|
|
||||||
|
name_mapping = {
|
||||||
|
"norm_1": "ln_1",
|
||||||
|
"norm_2": "ln_2",
|
||||||
|
"ffn": "mlp",
|
||||||
|
"up_proj": "mlp_up",
|
||||||
|
"down_proj": "mlp_down",
|
||||||
|
"norm_f": "ln_f"
|
||||||
|
}
|
||||||
|
for name in list_vars.keys():
|
||||||
|
data = list_vars[name].squeeze().numpy()
|
||||||
|
print("Processing variable: " + name + " with shape: ", data.shape)
|
||||||
|
|
||||||
|
n_dims = len(data.shape)
|
||||||
|
|
||||||
|
# ftype == 0 -> float32, ftype == 1 -> float16
|
||||||
|
ftype_cur = 0
|
||||||
|
if ftype != 0:
|
||||||
|
if name[-7:] == ".weight" and n_dims == 2:
|
||||||
|
print(" Converting to float16")
|
||||||
|
data = data.astype(np.float16)
|
||||||
|
ftype_cur = 1
|
||||||
|
else:
|
||||||
|
print(" Converting to float32")
|
||||||
|
data = data.astype(np.float32)
|
||||||
|
ftype_cur = 0
|
||||||
|
else:
|
||||||
|
if data.dtype != np.float32:
|
||||||
|
print(" Converting to float32")
|
||||||
|
data = data.astype(np.float32)
|
||||||
|
ftype_cur = 0
|
||||||
|
|
||||||
|
for x in ["norm_1", "norm_2", "ffn", "up_proj", "down_proj", "norm_f"]:
|
||||||
|
if x in name:
|
||||||
|
name = name.replace(x, name_mapping[x])
|
||||||
|
print(" Renaming to: " + name)
|
||||||
|
# header
|
||||||
|
str = name.encode("utf-8")
|
||||||
|
fout.write(struct.pack("iii", n_dims, len(str), ftype_cur))
|
||||||
|
for i in range(n_dims):
|
||||||
|
fout.write(struct.pack("i", data.shape[n_dims - 1 - i]))
|
||||||
|
fout.write(str)
|
||||||
|
|
||||||
|
# data
|
||||||
|
data.tofile(fout)
|
||||||
|
|
||||||
|
fout.close()
|
||||||
|
|
||||||
|
print("Done. Output file: " + fname_out)
|
||||||
|
print("")
|
Loading…
Reference in New Issue
Block a user