Skip to content

Commit b0a4699

Browse files
ditsukeSomeoneSerge
authored andcommitted
build(python): Package scripts with pip-0517 compliance
1 parent 807b0c4 commit b0a4699

9 files changed

+1546
-12
lines changed

.gitignore

+6-5
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,14 @@ examples/server/*.mjs.hpp
9898

9999
# Python
100100

101-
__pycache__
102-
.venv
103-
/Pipfile
104-
dist
105-
poetry.lock
101+
/.venv
102+
/__pycache__/
103+
*/poetry.lock
106104
poetry.toml
107105

106+
# Nix
107+
/result
108+
108109
# Test binaries
109110
/tests/test-backend-ops
110111
/tests/test-double-float

__init__.py

Whitespace-only changes.
File renamed without changes.

convert-hf-to-gguf-update.py convert_hf_to_gguf_update.py

+13-7
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ class TOKENIZER_TYPE(IntEnum):
5050

5151
# TODO: this string has to exercise as much pre-tokenizer functionality as possible
5252
# will be updated with time - contributions welcome
53-
chktxt = '\n \n\n \n\n\n \t \t\t \t\n \n \n \n \n🚀 (normal) 😶‍🌫️ (multiple emojis concatenated) ✅ 🦙🦙 3 33 333 3333 33333 333333 3333333 33333333 3.3 3..3 3...3 កាន់តែពិសេសអាច😁 ?我想在apple工作1314151天~ ------======= нещо на Български \'\'\'\'\'\'```````\"\"\"\"......!!!!!!?????? I\'ve been \'told he\'s there, \'RE you sure? \'M not sure I\'ll make it, \'D you like some tea? We\'Ve a\'lL'
53+
chktxt = "\n \n\n \n\n\n \t \t\t \t\n \n \n \n \n🚀 (normal) 😶‍🌫️ (multiple emojis concatenated) ✅ 🦙🦙 3 33 333 3333 33333 333333 3333333 33333333 3.3 3..3 3...3 កាន់តែពិសេសអាច😁 ?我想在apple工作1314151天~ ------======= нещо на Български ''''''```````\"\"\"\"......!!!!!!?????? I've been 'told he's there, 'RE you sure? 'M not sure I'll make it, 'D you like some tea? We'Ve a'lL"
5454

5555
if len(sys.argv) == 2:
5656
token = sys.argv[1]
@@ -99,7 +99,7 @@ def download_file_with_auth(url, token, save_path):
9999
response = sess.get(url, headers=headers)
100100
response.raise_for_status()
101101
os.makedirs(os.path.dirname(save_path), exist_ok=True)
102-
with open(save_path, 'wb') as f:
102+
with open(save_path, "wb") as f:
103103
f.write(response.content)
104104
logger.info(f"File {save_path} downloaded successfully")
105105

@@ -156,7 +156,9 @@ def download_model(model):
156156
else:
157157
tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
158158
except OSError as e:
159-
logger.error(f"Error loading tokenizer for model {name}. The model may not exist or is not accessible with the provided token. Error: {e}")
159+
logger.error(
160+
f"Error loading tokenizer for model {name}. The model may not exist or is not accessible with the provided token. Error: {e}"
161+
)
160162
continue # Skip to the next model if the tokenizer can't be loaded
161163

162164
chktok = tokenizer.encode(chktxt)
@@ -176,13 +178,15 @@ def download_model(model):
176178
pre_tokenizer = cfg["pre_tokenizer"]
177179
logger.info("pre_tokenizer: " + json.dumps(pre_tokenizer, indent=4))
178180
if "ignore_merges" in cfg["model"]:
179-
logger.info("ignore_merges: " + json.dumps(cfg["model"]["ignore_merges"], indent=4))
181+
logger.info(
182+
"ignore_merges: " + json.dumps(cfg["model"]["ignore_merges"], indent=4)
183+
)
180184

181185
logger.info("")
182186

183-
src_ifs += f" if chkhsh == \"{chkhsh}\":\n"
187+
src_ifs += f' if chkhsh == "{chkhsh}":\n'
184188
src_ifs += f" # ref: {model['repo']}\n"
185-
src_ifs += f" res = \"{name}\"\n"
189+
src_ifs += f' res = "{name}"\n'
186190

187191
src_func = f"""
188192
def get_vocab_base_pre(self, tokenizer) -> str:
@@ -343,6 +347,8 @@ def get_vocab_base_pre(self, tokenizer) -> str:
343347
for model in models:
344348
name = model["name"]
345349

346-
print(f"python3 convert-hf-to-gguf.py models/tokenizers/{name}/ --outfile models/ggml-vocab-{name}.gguf --vocab-only") # noqa: NP100
350+
print(
351+
f"python3 convert-hf-to-gguf.py models/tokenizers/{name}/ --outfile models/ggml-vocab-{name}.gguf --vocab-only"
352+
) # noqa: NP100
347353

348354
logger.info("\n")
File renamed without changes.

convert_lora_to_ggml.py

+149
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
#!/usr/bin/env python3
2+
from __future__ import annotations
3+
4+
import json
5+
import os
6+
import struct
7+
import sys
8+
from pathlib import Path
9+
from typing import Any, BinaryIO, Sequence
10+
11+
import numpy as np
12+
import torch
13+
14+
if 'NO_LOCAL_GGUF' not in os.environ:
15+
sys.path.insert(1, str(Path(__file__).parent / 'gguf-py' / 'gguf'))
16+
import gguf
17+
18+
NUMPY_TYPE_TO_FTYPE: dict[str, int] = {"float32": 0, "float16": 1}
19+
20+
21+
def write_file_header(fout: BinaryIO, params: dict[str, Any]) -> None:
22+
fout.write(b"ggla"[::-1]) # magic (ggml lora)
23+
fout.write(struct.pack("i", 1)) # file version
24+
fout.write(struct.pack("i", params["r"]))
25+
# https://opendelta.readthedocs.io/en/latest/modules/deltas.html says that `lora_alpha` is an int
26+
# but some models ship a float value instead
27+
# let's convert to int, but fail if lossless conversion is not possible
28+
assert (
29+
int(params["lora_alpha"]) == params["lora_alpha"]
30+
), "cannot convert float to int losslessly"
31+
fout.write(struct.pack("i", int(params["lora_alpha"])))
32+
33+
34+
def write_tensor_header(fout: BinaryIO, name: str, shape: Sequence[int], data_type: np.dtype[Any]) -> None:
35+
sname = name.encode("utf-8")
36+
fout.write(
37+
struct.pack(
38+
"iii",
39+
len(shape),
40+
len(sname),
41+
NUMPY_TYPE_TO_FTYPE[data_type.name],
42+
)
43+
)
44+
fout.write(struct.pack("i" * len(shape), *shape[::-1]))
45+
fout.write(sname)
46+
fout.seek((fout.tell() + 31) & -32)
47+
48+
49+
if __name__ == '__main__':
50+
if len(sys.argv) < 2:
51+
print(f"Usage: python {sys.argv[0]} <path> [arch]")
52+
print(
53+
"Path must contain HuggingFace PEFT LoRA files 'adapter_config.json' and 'adapter_model.bin'"
54+
)
55+
print(f"Arch must be one of {list(gguf.MODEL_ARCH_NAMES.values())} (default: llama)")
56+
sys.exit(1)
57+
58+
input_json = os.path.join(sys.argv[1], "adapter_config.json")
59+
input_model = os.path.join(sys.argv[1], "adapter_model.bin")
60+
output_path = os.path.join(sys.argv[1], "ggml-adapter-model.bin")
61+
62+
if os.path.exists(input_model):
63+
model = torch.load(input_model, map_location="cpu")
64+
else:
65+
input_model = os.path.join(sys.argv[1], "adapter_model.safetensors")
66+
# lazy import load_file only if lora is in safetensors format.
67+
from safetensors.torch import load_file
68+
model = load_file(input_model, device="cpu")
69+
70+
arch_name = sys.argv[2] if len(sys.argv) == 3 else "llama"
71+
72+
if arch_name not in gguf.MODEL_ARCH_NAMES.values():
73+
print(f"Error: unsupported architecture {arch_name}")
74+
sys.exit(1)
75+
76+
arch = list(gguf.MODEL_ARCH_NAMES.keys())[list(gguf.MODEL_ARCH_NAMES.values()).index(arch_name)]
77+
name_map = gguf.TensorNameMap(arch, 200) # 200 layers ought to be enough for anyone
78+
79+
with open(input_json, "r") as f:
80+
params = json.load(f)
81+
82+
if params["peft_type"] != "LORA":
83+
print(f"Error: unsupported adapter type {params['peft_type']}, expected LORA")
84+
sys.exit(1)
85+
86+
if params["fan_in_fan_out"] is True:
87+
print("Error: param fan_in_fan_out is not supported")
88+
sys.exit(1)
89+
90+
if params["bias"] is not None and params["bias"] != "none":
91+
print("Error: param bias is not supported")
92+
sys.exit(1)
93+
94+
# TODO: these seem to be layers that have been trained but without lora.
95+
# doesn't seem widely used but eventually should be supported
96+
if params["modules_to_save"] is not None and len(params["modules_to_save"]) > 0:
97+
print("Error: param modules_to_save is not supported")
98+
sys.exit(1)
99+
100+
with open(output_path, "wb") as fout:
101+
fout.truncate()
102+
103+
write_file_header(fout, params)
104+
for k, v in model.items():
105+
orig_k = k
106+
if k.endswith(".default.weight"):
107+
k = k.replace(".default.weight", ".weight")
108+
if k in ["llama_proj.weight", "llama_proj.bias"]:
109+
continue
110+
if k.endswith("lora_A.weight"):
111+
if v.dtype != torch.float16 and v.dtype != torch.float32:
112+
v = v.float()
113+
v = v.T
114+
else:
115+
v = v.float()
116+
117+
t = v.detach().numpy()
118+
119+
prefix = "base_model.model."
120+
if k.startswith(prefix):
121+
k = k[len(prefix) :]
122+
123+
lora_suffixes = (".lora_A.weight", ".lora_B.weight")
124+
if k.endswith(lora_suffixes):
125+
suffix = k[-len(lora_suffixes[0]):]
126+
k = k[: -len(lora_suffixes[0])]
127+
else:
128+
print(f"Error: unrecognized tensor name {orig_k}")
129+
sys.exit(1)
130+
131+
tname = name_map.get_name(k)
132+
if tname is None:
133+
print(f"Error: could not map tensor name {orig_k}")
134+
print(" Note: the arch parameter must be specified if the model is not llama")
135+
sys.exit(1)
136+
137+
if suffix == ".lora_A.weight":
138+
tname += ".weight.loraA"
139+
elif suffix == ".lora_B.weight":
140+
tname += ".weight.loraB"
141+
else:
142+
assert False
143+
144+
print(f"{k} => {tname} {t.shape} {t.dtype} {t.nbytes/1024/1024:.2f}MB")
145+
write_tensor_header(fout, tname, t.shape, t.dtype)
146+
t.tofile(fout)
147+
148+
print(f"Converted {input_json} and {input_model} to {output_path}")
149+

convert_persimmon_to_gguf.py

+137
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
#!/usr/bin/env python3
2+
import argparse
3+
import os
4+
import sys
5+
from pathlib import Path
6+
from pprint import pprint
7+
8+
import torch
9+
from sentencepiece import SentencePieceProcessor
10+
11+
if 'NO_LOCAL_GGUF' not in os.environ:
12+
sys.path.insert(1, str(Path(__file__).parent / 'gguf-py'))
13+
import gguf
14+
15+
16+
def _flatten_dict(dct, tensors, prefix=None):
17+
assert isinstance(dct, dict)
18+
for key in dct.keys():
19+
new_prefix = prefix + '.' + key if prefix is not None else key
20+
if isinstance(dct[key], torch.Tensor):
21+
tensors[new_prefix] = dct[key]
22+
elif isinstance(dct[key], dict):
23+
_flatten_dict(dct[key], tensors, new_prefix)
24+
else:
25+
raise ValueError(type(dct[key]))
26+
return None
27+
28+
29+
def _get_sentencepiece_tokenizer_info(dir_model: Path):
30+
tokenizer_path = dir_model / 'adept_vocab.model'
31+
print('gguf: getting sentencepiece tokenizer from', tokenizer_path)
32+
tokenizer = SentencePieceProcessor(str(tokenizer_path))
33+
print('gguf: adding tokens')
34+
tokens: list[bytes] = []
35+
scores: list[float] = []
36+
toktypes: list[int] = []
37+
38+
for i in range(tokenizer.vocab_size()):
39+
text: bytes
40+
score: float
41+
42+
piece = tokenizer.id_to_piece(i)
43+
text = piece.encode("utf-8")
44+
score = tokenizer.get_score(i)
45+
46+
toktype = 1
47+
if tokenizer.is_unknown(i):
48+
toktype = 2
49+
if tokenizer.is_control(i):
50+
toktype = 3
51+
if tokenizer.is_unused(i):
52+
toktype = 5
53+
if tokenizer.is_byte(i):
54+
toktype = 6
55+
56+
tokens.append(text)
57+
scores.append(score)
58+
toktypes.append(toktype)
59+
pass
60+
return tokens, scores, toktypes
61+
62+
63+
def main():
64+
parser = argparse.ArgumentParser(description="Convert a Persimmon model from Adept (e.g. Persimmon 8b chat) to a GGML compatible file")
65+
parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
66+
parser.add_argument("--ckpt-path", type=Path, help="path to persimmon checkpoint .pt file")
67+
parser.add_argument("--model-dir", type=Path, help="directory containing model e.g. 8b_chat_model_release")
68+
parser.add_argument("--adept-inference-dir", type=str, help="path to adept-inference code directory")
69+
args = parser.parse_args()
70+
sys.path.append(str(args.adept_inference_dir))
71+
persimmon_model = torch.load(args.ckpt_path)
72+
hparams = persimmon_model['args']
73+
pprint(hparams)
74+
tensors: dict[str, torch.Tensor] = {}
75+
_flatten_dict(persimmon_model['model'], tensors, None)
76+
77+
arch = gguf.MODEL_ARCH.PERSIMMON
78+
gguf_writer = gguf.GGUFWriter(args.outfile, gguf.MODEL_ARCH_NAMES[arch])
79+
80+
block_count = hparams.num_layers
81+
head_count = hparams.num_attention_heads
82+
head_count_kv = head_count
83+
ctx_length = hparams.seq_length
84+
hidden_size = hparams.hidden_size
85+
86+
gguf_writer.add_name('persimmon-8b-chat')
87+
gguf_writer.add_context_length(ctx_length)
88+
gguf_writer.add_embedding_length(hidden_size)
89+
gguf_writer.add_block_count(block_count)
90+
gguf_writer.add_feed_forward_length(hparams.ffn_hidden_size)
91+
# ref: https://github.com/ggerganov/llama.cpp/pull/4889/commits/eea19039fc52ea2dbd1aab45b59ab4e3e29a3443
92+
gguf_writer.add_rope_dimension_count(hidden_size // head_count // 2)
93+
gguf_writer.add_head_count(head_count)
94+
gguf_writer.add_head_count_kv(head_count_kv)
95+
gguf_writer.add_rope_freq_base(hparams.rotary_emb_base)
96+
gguf_writer.add_layer_norm_eps(hparams.layernorm_epsilon)
97+
98+
tokens, scores, toktypes = _get_sentencepiece_tokenizer_info(args.model_dir)
99+
gguf_writer.add_tokenizer_model('llama')
100+
gguf_writer.add_token_list(tokens)
101+
gguf_writer.add_token_scores(scores)
102+
gguf_writer.add_token_types(toktypes)
103+
gguf_writer.add_bos_token_id(71013)
104+
gguf_writer.add_eos_token_id(71013)
105+
106+
tensor_map = gguf.get_tensor_name_map(arch, block_count)
107+
print(tensor_map)
108+
for name in tensors.keys():
109+
data = tensors[name]
110+
if name.endswith(".self_attention.rotary_emb.inv_freq"):
111+
continue
112+
old_dtype = data.dtype
113+
# TODO: FP16 conversion produces garbage outputs. (Q8_0 does not, so..?)
114+
data = data.to(torch.float32).squeeze().numpy()
115+
new_name = tensor_map.get_name(name, try_suffixes = (".weight", ".bias"))
116+
if new_name is None:
117+
print("Can not map tensor '" + name + "'")
118+
sys.exit()
119+
n_dims = len(data.shape)
120+
print(new_name + ", n_dims = " + str(n_dims) + ", " + str(old_dtype) + " --> " + str(data.dtype))
121+
gguf_writer.add_tensor(new_name, data)
122+
print("gguf: write header")
123+
gguf_writer.write_header_to_file()
124+
print("gguf: write metadata")
125+
gguf_writer.write_kv_data_to_file()
126+
print("gguf: write tensors")
127+
gguf_writer.write_tensors_to_file()
128+
129+
gguf_writer.close()
130+
131+
print(f"gguf: model successfully exported to '{args.outfile}'")
132+
print("")
133+
134+
135+
if __name__ == '__main__':
136+
main()
137+

0 commit comments

Comments
 (0)