Skip to content

Commit abb29f1

Browse files
committed
add convert script for plamo-13b
1 parent eee42c6 commit abb29f1

File tree

1 file changed

+226
-0
lines changed

1 file changed

+226
-0
lines changed

Diff for: convert-plamo-hf-to-gguf.py

+226
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
import argparse
2+
import json
3+
import sys
4+
import os
5+
import torch
6+
import numpy as np
7+
from pathlib import Path
8+
import gguf
9+
from sentencepiece import SentencePieceProcessor # type: ignore[import]
10+
11+
12+
def count_model_parts(dir_model: Path) -> int:
13+
num_parts = 0
14+
for filename in os.listdir(dir_model):
15+
if filename.startswith("pytorch_model-"):
16+
num_parts += 1
17+
18+
if num_parts > 0:
19+
print("gguf: found " + str(num_parts) + " model parts")
20+
return num_parts
21+
22+
23+
def parse_args() -> argparse.Namespace:
24+
parser = argparse.ArgumentParser(description="Convert a PLaMo model to a GGML compatible file")
25+
parser.add_argument(
26+
"--vocab-only", action="store_true",
27+
help="extract only the vocab",
28+
)
29+
parser.add_argument(
30+
"--outfile", type=Path,
31+
help="path to write to; default: based on input",
32+
)
33+
parser.add_argument(
34+
"model", type=Path,
35+
help="directory containing model file, or model file itself (*.bin)",
36+
)
37+
parser.add_argument(
38+
"ftype", type=int, choices=[0, 1], default=1, nargs='?',
39+
help="output format - use 0 for float32, 1 for float16",
40+
)
41+
return parser.parse_args()
42+
43+
44+
args = parse_args()
45+
46+
dir_model = args.model
47+
ftype = args.ftype
48+
if not dir_model.is_dir():
49+
print(f'Error: {args.model} is not a directory', file = sys.stderr)
50+
sys.exit(1)
51+
52+
53+
# possible tensor data types
54+
# ftype == 0 -> float32
55+
# ftype == 1 -> float16
56+
57+
# map from ftype to string
58+
ftype_str = ["f32", "f16"]
59+
60+
if args.outfile is not None:
61+
fname_out = args.outfile
62+
else:
63+
# output in the same directory as the model by default
64+
fname_out = dir_model / f'ggml-model-{ftype_str[ftype]}.gguf'
65+
66+
print("gguf: loading model "+dir_model.name)
67+
68+
with open(dir_model / "config.json", "r", encoding="utf-8") as f:
69+
hparams = json.load(f)
70+
71+
if hparams["architectures"][0] != "PlamoForCausalLM":
72+
print("Model architecture not supported: " + hparams["architectures"][0])
73+
74+
sys.exit(1)
75+
76+
# get number of model parts
77+
num_parts = count_model_parts(dir_model)
78+
79+
ARCH=gguf.MODEL_ARCH.PLAMO
80+
gguf_writer = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH])
81+
82+
print("gguf: get model metadata")
83+
84+
block_count = hparams["num_hidden_layers"]
85+
86+
gguf_writer.add_name("PLaMo")
87+
gguf_writer.add_context_length(4096) # not in config.json
88+
gguf_writer.add_embedding_length(hparams["hidden_size"])
89+
gguf_writer.add_feed_forward_length(hparams["intermediate_size"])
90+
gguf_writer.add_block_count(block_count)
91+
gguf_writer.add_head_count(hparams["num_attention_heads"])
92+
gguf_writer.add_head_count_kv(5) # hparams["num_key_value_heads"]) is wrong
93+
gguf_writer.add_layer_norm_rms_eps(hparams["rms_norm_eps"])
94+
gguf_writer.add_file_type(ftype)
95+
96+
97+
# TOKENIZATION
98+
99+
print("gguf: get tokenizer metadata")
100+
101+
tokens: list[bytes] = []
102+
scores: list[float] = []
103+
toktypes: list[int] = []
104+
105+
tokenizer_model_file = dir_model / 'tokenizer.model'
106+
if not tokenizer_model_file.is_file():
107+
print(f'Error: Missing {tokenizer_model_file}', file = sys.stderr)
108+
sys.exit(1)
109+
110+
# vocab type sentencepiece
111+
print("gguf: get sentencepiece tokenizer vocab, scores and token types")
112+
113+
tokenizer = SentencePieceProcessor(str(tokenizer_model_file))
114+
115+
for i in range(tokenizer.vocab_size()):
116+
text: bytes
117+
score: float
118+
119+
piece = tokenizer.id_to_piece(i)
120+
text = piece.encode("utf-8")
121+
score = tokenizer.get_score(i)
122+
123+
toktype = 1 # defualt to normal token type
124+
if tokenizer.is_unknown(i):
125+
toktype = 2
126+
if tokenizer.is_control(i):
127+
toktype = 3
128+
129+
# toktype = 4 is user-defined = tokens from added_tokens.json
130+
131+
if tokenizer.is_unused(i):
132+
toktype = 5
133+
if tokenizer.is_byte(i):
134+
toktype = 6
135+
136+
tokens.append(text)
137+
scores.append(score)
138+
toktypes.append(toktype)
139+
140+
gguf_writer.add_tokenizer_model("llama")
141+
gguf_writer.add_token_list(tokens)
142+
gguf_writer.add_token_scores(scores)
143+
gguf_writer.add_token_types(toktypes)
144+
gguf_writer.add_sep_token_id(5)
145+
gguf_writer.add_pad_token_id(3)
146+
147+
special_vocab = gguf.SpecialVocab(dir_model)
148+
special_vocab.add_to_gguf(gguf_writer)
149+
150+
# TENSORS
151+
152+
tensor_map = gguf.get_tensor_name_map(ARCH,block_count)
153+
154+
# params for qkv transform
155+
n_head = hparams["num_attention_heads"]
156+
n_head_kv = hparams["num_key_value_heads"]
157+
158+
head_dim = hparams["hidden_size"] // n_head
159+
160+
# tensor info
161+
print("gguf: get tensor metadata")
162+
163+
if num_parts == 0:
164+
part_names = iter(("pytorch_model.bin",))
165+
else:
166+
part_names = (
167+
f"pytorch_model-{n:05}-of-{num_parts:05}.bin" for n in range(1, num_parts + 1)
168+
)
169+
170+
for part_name in part_names:
171+
if args.vocab_only:
172+
break
173+
print("gguf: loading model part '" + part_name + "'")
174+
model_part = torch.load(dir_model / part_name, map_location="cpu")
175+
176+
for name in model_part.keys():
177+
if "self_attn.rotary_emb.inv_freq" in name:
178+
continue
179+
data = model_part[name]
180+
181+
old_dtype = data.dtype
182+
183+
# convert any unsupported data types to float32
184+
if data.dtype != torch.float16 and data.dtype != torch.float32:
185+
data = data.to(torch.float32)
186+
187+
data = data.squeeze().numpy()
188+
189+
# map tensor names
190+
new_name = tensor_map.get_name(name, try_suffixes = (".weight", ".bias"))
191+
if new_name is None:
192+
print("Can not map tensor '" + name + "'")
193+
sys.exit()
194+
195+
n_dims = len(data.shape)
196+
data_dtype = data.dtype
197+
198+
# if f32 desired, convert any float16 to float32
199+
if ftype == 0 and data_dtype == np.float16:
200+
data = data.astype(np.float32)
201+
202+
# TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
203+
if ftype == 1 and data_dtype == np.float16 and n_dims == 1:
204+
data = data.astype(np.float32)
205+
206+
# if f16 desired, convert any float32 2-dim weight tensors to float16
207+
if ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
208+
data = data.astype(np.float16)
209+
210+
print(new_name + ", n_dims = " + str(n_dims) + ", " + str(old_dtype) + " --> " + str(data.dtype))
211+
212+
gguf_writer.add_tensor(new_name, data)
213+
214+
215+
print("gguf: write header")
216+
gguf_writer.write_header_to_file()
217+
print("gguf: write metadata")
218+
gguf_writer.write_kv_data_to_file()
219+
if not args.vocab_only:
220+
print("gguf: write tensors")
221+
gguf_writer.write_tensors_to_file()
222+
223+
gguf_writer.close()
224+
225+
print(f"gguf: model successfully exported to '{fname_out}'")
226+
print("")

0 commit comments

Comments
 (0)