Skip to content

Commit 8cce8a4

Browse files
committed
build(python): Package scripts with pip-0517 compliance
1 parent 023b880 commit 8cce8a4

9 files changed

+1661
-35
lines changed

.gitignore

Lines changed: 6 additions & 5 deletions
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 renamed to convert_hf_to_gguf_update.py

Lines changed: 128 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ class TOKENIZER_TYPE(IntEnum):
4949

5050
# TODO: this string has to exercise as much pre-tokenizer functionality as possible
5151
# will be updated with time - contributions welcome
52-
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'
52+
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"
5353

5454
if len(sys.argv) == 2:
5555
token = sys.argv[1]
@@ -63,29 +63,121 @@ class TOKENIZER_TYPE(IntEnum):
6363

6464
# TODO: add models here, base models preferred
6565
models = [
66-
{"name": "llama-spm", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/meta-llama/Llama-2-7b-hf", },
67-
{"name": "llama-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/meta-llama/Meta-Llama-3-8B", },
68-
{"name": "phi-3", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct", },
69-
{"name": "deepseek-llm", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/deepseek-llm-7b-base", },
70-
{"name": "deepseek-coder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/deepseek-coder-6.7b-base", },
71-
{"name": "falcon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tiiuae/falcon-7b", },
72-
{"name": "bert-bge", "tokt": TOKENIZER_TYPE.WPM, "repo": "https://huggingface.co/BAAI/bge-small-en-v1.5", },
73-
{"name": "mpt", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/mosaicml/mpt-7b", },
74-
{"name": "starcoder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/bigcode/starcoder2-3b", },
75-
{"name": "gpt-2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/openai-community/gpt2", },
76-
{"name": "stablelm2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/stabilityai/stablelm-2-zephyr-1_6b", },
77-
{"name": "refact", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/smallcloudai/Refact-1_6-base", },
78-
{"name": "command-r", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/CohereForAI/c4ai-command-r-v01", },
79-
{"name": "qwen2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/Qwen/Qwen1.5-7B", },
80-
{"name": "olmo", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/allenai/OLMo-1.7-7B-hf", },
81-
{"name": "dbrx", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/databricks/dbrx-base", },
82-
{"name": "jina-v2-en", "tokt": TOKENIZER_TYPE.WPM, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-en", }, # WPM!
83-
{"name": "jina-v2-es", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-es", },
84-
{"name": "jina-v2-de", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-de", },
85-
{"name": "smaug-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/abacusai/Smaug-Llama-3-70B-Instruct", },
86-
{"name": "poro-chat", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LumiOpen/Poro-34B-chat", },
87-
{"name": "jina-v2-code", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-code", },
88-
{"name": "viking", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LumiOpen/Viking-7B", }, # Also used for Viking 13B and 33B
66+
{
67+
"name": "llama-spm",
68+
"tokt": TOKENIZER_TYPE.SPM,
69+
"repo": "https://huggingface.co/meta-llama/Llama-2-7b-hf",
70+
},
71+
{
72+
"name": "llama-bpe",
73+
"tokt": TOKENIZER_TYPE.BPE,
74+
"repo": "https://huggingface.co/meta-llama/Meta-Llama-3-8B",
75+
},
76+
{
77+
"name": "phi-3",
78+
"tokt": TOKENIZER_TYPE.SPM,
79+
"repo": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct",
80+
},
81+
{
82+
"name": "deepseek-llm",
83+
"tokt": TOKENIZER_TYPE.BPE,
84+
"repo": "https://huggingface.co/deepseek-ai/deepseek-llm-7b-base",
85+
},
86+
{
87+
"name": "deepseek-coder",
88+
"tokt": TOKENIZER_TYPE.BPE,
89+
"repo": "https://huggingface.co/deepseek-ai/deepseek-coder-6.7b-base",
90+
},
91+
{
92+
"name": "falcon",
93+
"tokt": TOKENIZER_TYPE.BPE,
94+
"repo": "https://huggingface.co/tiiuae/falcon-7b",
95+
},
96+
{
97+
"name": "bert-bge",
98+
"tokt": TOKENIZER_TYPE.WPM,
99+
"repo": "https://huggingface.co/BAAI/bge-small-en-v1.5",
100+
},
101+
{
102+
"name": "mpt",
103+
"tokt": TOKENIZER_TYPE.BPE,
104+
"repo": "https://huggingface.co/mosaicml/mpt-7b",
105+
},
106+
{
107+
"name": "starcoder",
108+
"tokt": TOKENIZER_TYPE.BPE,
109+
"repo": "https://huggingface.co/bigcode/starcoder2-3b",
110+
},
111+
{
112+
"name": "gpt-2",
113+
"tokt": TOKENIZER_TYPE.BPE,
114+
"repo": "https://huggingface.co/openai-community/gpt2",
115+
},
116+
{
117+
"name": "stablelm2",
118+
"tokt": TOKENIZER_TYPE.BPE,
119+
"repo": "https://huggingface.co/stabilityai/stablelm-2-zephyr-1_6b",
120+
},
121+
{
122+
"name": "refact",
123+
"tokt": TOKENIZER_TYPE.BPE,
124+
"repo": "https://huggingface.co/smallcloudai/Refact-1_6-base",
125+
},
126+
{
127+
"name": "command-r",
128+
"tokt": TOKENIZER_TYPE.BPE,
129+
"repo": "https://huggingface.co/CohereForAI/c4ai-command-r-v01",
130+
},
131+
{
132+
"name": "qwen2",
133+
"tokt": TOKENIZER_TYPE.BPE,
134+
"repo": "https://huggingface.co/Qwen/Qwen1.5-7B",
135+
},
136+
{
137+
"name": "olmo",
138+
"tokt": TOKENIZER_TYPE.BPE,
139+
"repo": "https://huggingface.co/allenai/OLMo-1.7-7B-hf",
140+
},
141+
{
142+
"name": "dbrx",
143+
"tokt": TOKENIZER_TYPE.BPE,
144+
"repo": "https://huggingface.co/databricks/dbrx-base",
145+
},
146+
{
147+
"name": "jina-v2-en",
148+
"tokt": TOKENIZER_TYPE.WPM,
149+
"repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-en",
150+
}, # WPM!
151+
{
152+
"name": "jina-v2-es",
153+
"tokt": TOKENIZER_TYPE.BPE,
154+
"repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-es",
155+
},
156+
{
157+
"name": "jina-v2-de",
158+
"tokt": TOKENIZER_TYPE.BPE,
159+
"repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-de",
160+
},
161+
{
162+
"name": "smaug-bpe",
163+
"tokt": TOKENIZER_TYPE.BPE,
164+
"repo": "https://huggingface.co/abacusai/Smaug-Llama-3-70B-Instruct",
165+
},
166+
{
167+
"name": "poro-chat",
168+
"tokt": TOKENIZER_TYPE.BPE,
169+
"repo": "https://huggingface.co/LumiOpen/Poro-34B-chat",
170+
},
171+
{
172+
"name": "jina-v2-code",
173+
"tokt": TOKENIZER_TYPE.BPE,
174+
"repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-code",
175+
},
176+
{
177+
"name": "viking",
178+
"tokt": TOKENIZER_TYPE.BPE,
179+
"repo": "https://huggingface.co/LumiOpen/Viking-7B",
180+
}, # Also used for Viking 13B and 33B
89181
]
90182

91183

@@ -94,7 +186,7 @@ def download_file_with_auth(url, token, save_path):
94186
response = sess.get(url, headers=headers)
95187
response.raise_for_status()
96188
os.makedirs(os.path.dirname(save_path), exist_ok=True)
97-
with open(save_path, 'wb') as f:
189+
with open(save_path, "wb") as f:
98190
f.write(response.content)
99191
logger.info(f"File {save_path} downloaded successfully")
100192

@@ -144,7 +236,9 @@ def download_model(model):
144236
try:
145237
tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
146238
except OSError as e:
147-
logger.error(f"Error loading tokenizer for model {name}. The model may not exist or is not accessible with the provided token. Error: {e}")
239+
logger.error(
240+
f"Error loading tokenizer for model {name}. The model may not exist or is not accessible with the provided token. Error: {e}"
241+
)
148242
continue # Skip to the next model if the tokenizer can't be loaded
149243

150244
chktok = tokenizer.encode(chktxt)
@@ -164,13 +258,15 @@ def download_model(model):
164258
pre_tokenizer = cfg["pre_tokenizer"]
165259
logger.info("pre_tokenizer: " + json.dumps(pre_tokenizer, indent=4))
166260
if "ignore_merges" in cfg["model"]:
167-
logger.info("ignore_merges: " + json.dumps(cfg["model"]["ignore_merges"], indent=4))
261+
logger.info(
262+
"ignore_merges: " + json.dumps(cfg["model"]["ignore_merges"], indent=4)
263+
)
168264

169265
logger.info("")
170266

171-
src_ifs += f" if chkhsh == \"{chkhsh}\":\n"
267+
src_ifs += f' if chkhsh == "{chkhsh}":\n'
172268
src_ifs += f" # ref: {model['repo']}\n"
173-
src_ifs += f" res = \"{name}\"\n"
269+
src_ifs += f' res = "{name}"\n'
174270

175271
src_func = f"""
176272
def get_vocab_base_pre(self, tokenizer) -> str:
@@ -326,6 +422,8 @@ def get_vocab_base_pre(self, tokenizer) -> str:
326422
for model in models:
327423
name = model["name"]
328424

329-
print(f"python3 convert-hf-to-gguf.py models/tokenizers/{name}/ --outfile models/ggml-vocab-{name}.gguf --vocab-only") # noqa: NP100
425+
print(
426+
f"python3 convert-hf-to-gguf.py models/tokenizers/{name}/ --outfile models/ggml-vocab-{name}.gguf --vocab-only"
427+
) # noqa: NP100
330428

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

convert_lora_to_ggml.py

Lines changed: 149 additions & 0 deletions
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+

0 commit comments

Comments
 (0)