Skip to content

Commit 16dba2b

Browse files
committed
resolve comments
1 parent 41cd2c7 commit 16dba2b

File tree

2 files changed

+57
-27
lines changed

2 files changed

+57
-27
lines changed

convert-refact-hf-to-gguf.py

Lines changed: 56 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env python3
2-
# HF falcon--> gguf conversion
2+
# HF refact--> gguf conversion
33

44
from __future__ import annotations
55

@@ -15,8 +15,8 @@
1515
import torch
1616
from transformers import AutoTokenizer # type: ignore[import]
1717

18-
if 'NO_LOCAL_GGUF' not in os.environ:
19-
sys.path.insert(1, str(Path(__file__).parent / 'gguf-py' / 'gguf'))
18+
if "NO_LOCAL_GGUF" not in os.environ:
19+
sys.path.insert(1, str(Path(__file__).parent / "gguf-py" / "gguf"))
2020
import gguf
2121

2222

@@ -31,13 +31,17 @@ def bytes_to_unicode():
3131
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
3232
And avoids mapping to whitespace/control characters the bpe code barfs on.
3333
"""
34-
bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
34+
bs = (
35+
list(range(ord("!"), ord("~") + 1))
36+
+ list(range(ord("¡"), ord("¬") + 1))
37+
+ list(range(ord("®"), ord("ÿ") + 1))
38+
)
3539
cs = bs[:]
3640
n = 0
3741
for b in range(2**8):
3842
if b not in bs:
3943
bs.append(b)
40-
cs.append(2**8+n)
44+
cs.append(2**8 + n)
4145
n += 1
4246
return dict(zip(bs, (chr(n) for n in cs)))
4347

@@ -54,32 +58,41 @@ def count_model_parts(dir_model: Path) -> int:
5458

5559

5660
def parse_args() -> argparse.Namespace:
57-
parser = argparse.ArgumentParser(description="Convert a Refact model to a GGML compatible file")
61+
parser = argparse.ArgumentParser(
62+
description="Convert a Refact model to a GGML compatible file"
63+
)
5864
parser.add_argument(
59-
"--vocab-only", action="store_true",
65+
"--vocab-only",
66+
action="store_true",
6067
help="extract only the vocab",
6168
)
6269
parser.add_argument(
63-
"--outfile", type=Path,
70+
"--outfile",
71+
type=Path,
6472
help="path to write to; default: based on input",
6573
)
6674
parser.add_argument(
67-
"model", type=Path,
75+
"model",
76+
type=Path,
6877
help="directory containing model file, or model file itself (*.bin)",
6978
)
7079
parser.add_argument(
71-
"ftype", type=int, choices=[0, 1], default=1, nargs='?',
80+
"ftype",
81+
type=int,
82+
choices=[0, 1],
83+
default=1,
84+
nargs="?",
7285
help="output format - use 0 for float32, 1 for float16",
7386
)
7487
return parser.parse_args()
7588

89+
7690
args = parse_args()
7791

7892
dir_model = args.model
7993
ftype = args.ftype
8094
if not dir_model.is_dir():
81-
82-
print(f'Error: {args.model} is not a directory', file = sys.stderr)
95+
print(f"Error: {args.model} is not a directory", file=sys.stderr)
8396
sys.exit(1)
8497

8598
# possible tensor data types
@@ -93,9 +106,9 @@ def parse_args() -> argparse.Namespace:
93106
fname_out = args.outfile
94107
else:
95108
# output in the same directory as the model by default
96-
fname_out = dir_model / f'ggml-model-{ftype_str[ftype]}.gguf'
109+
fname_out = dir_model / f"ggml-model-{ftype_str[ftype]}.gguf"
97110

98-
print("gguf: loading model "+dir_model.name)
111+
print("gguf: loading model " + dir_model.name)
99112

100113
with open(dir_model / "config.json", "r", encoding="utf-8") as f:
101114
hparams = json.load(f)
@@ -108,7 +121,7 @@ def parse_args() -> argparse.Namespace:
108121
# get number of model parts
109122
num_parts = count_model_parts(dir_model)
110123

111-
ARCH=gguf.MODEL_ARCH.REFACT
124+
ARCH = gguf.MODEL_ARCH.REFACT
112125
gguf_writer = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH])
113126

114127
print("gguf: get model metadata")
@@ -142,9 +155,9 @@ def parse_args() -> argparse.Namespace:
142155
scores: list[float] = []
143156
toktypes: list[int] = []
144157

145-
tokenizer_json_file = dir_model / 'tokenizer.json'
158+
tokenizer_json_file = dir_model / "tokenizer.json"
146159
if not tokenizer_json_file.is_file():
147-
print(f'Error: Missing {tokenizer_json_file}', file = sys.stderr)
160+
print(f"Error: Missing {tokenizer_json_file}", file=sys.stderr)
148161
sys.exit(1)
149162

150163
# gpt2 tokenizer
@@ -157,7 +170,11 @@ def parse_args() -> argparse.Namespace:
157170

158171
# The number of tokens in tokenizer.json can differ from the expected vocab size.
159172
# This causes downstream issues with mismatched tensor sizes when running the inference
160-
vocab_size = hparams["vocab_size"] if "vocab_size" in hparams else len(tokenizer_json["model"]["vocab"])
173+
vocab_size = (
174+
hparams["vocab_size"]
175+
if "vocab_size" in hparams
176+
else len(tokenizer_json["model"]["vocab"])
177+
)
161178

162179
tokenizer = AutoTokenizer.from_pretrained(dir_model, trust_remote_code=True)
163180

@@ -176,29 +193,29 @@ def parse_args() -> argparse.Namespace:
176193
if ord(c) < 256: # single byte character
177194
text.append(byte_decoder[ord(c)])
178195
else: # multibyte special token character
179-
text.extend(c.encode('utf-8'))
196+
text.extend(c.encode("utf-8"))
180197
else:
181198
print(f"Key {i} not in tokenizer vocabulary. Padding with an arbitrary token.")
182199
pad_token = f"[PAD{i}]".encode("utf8")
183200
text = bytearray(pad_token)
184201

185202
tokens.append(text)
186-
scores.append(0.0) # dymmy
203+
scores.append(0.0) # dymmy
187204
toktypes.append(gguf.TokenType.NORMAL) # dummy
188205

189206
gguf_writer.add_token_list(tokens)
190207
gguf_writer.add_token_scores(scores)
191208
gguf_writer.add_token_types(toktypes)
192209

193-
special_vocab = gguf.SpecialVocab(dir_model, load_merges = True)
210+
special_vocab = gguf.SpecialVocab(dir_model, load_merges=True)
194211
special_vocab.add_to_gguf(gguf_writer)
195212

196213
# TENSORS
197214

198-
tensor_map = gguf.get_tensor_name_map(ARCH,block_count)
215+
tensor_map = gguf.get_tensor_name_map(ARCH, block_count)
199216

200217
# params for qkv transform
201-
n_head = hparams["n_head"]
218+
n_head = hparams["n_head"]
202219
n_head_kv = 1
203220

204221
head_dim = hparams["n_embd"] // n_head
@@ -230,7 +247,7 @@ def parse_args() -> argparse.Namespace:
230247
data = data.squeeze().numpy()
231248

232249
# map tensor names
233-
new_name = tensor_map.get_name(name, try_suffixes = (".weight", ))
250+
new_name = tensor_map.get_name(name, try_suffixes=(".weight",))
234251
if new_name is None:
235252
print("Can not map tensor '" + name + "'")
236253
sys.exit()
@@ -247,10 +264,23 @@ def parse_args() -> argparse.Namespace:
247264
data = data.astype(np.float32)
248265

249266
# if f16 desired, convert any float32 2-dim weight tensors to float16
250-
if ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
267+
if (
268+
ftype == 1
269+
and data_dtype == np.float32
270+
and name.endswith(".weight")
271+
and n_dims == 2
272+
):
251273
data = data.astype(np.float16)
252274

253-
print(new_name + ", n_dims = " + str(n_dims) + ", " + str(old_dtype) + " --> " + str(data.dtype))
275+
print(
276+
new_name
277+
+ ", n_dims = "
278+
+ str(n_dims)
279+
+ ", "
280+
+ str(old_dtype)
281+
+ " --> "
282+
+ str(data.dtype)
283+
)
254284

255285
gguf_writer.add_tensor(new_name, data)
256286

llama.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4129,7 +4129,7 @@ static bool llama_eval_internal(
41294129
// If all tensors can be run on the GPU then using more than 1 thread is detrimental.
41304130
const bool full_offload_supported = model.arch == LLM_ARCH_LLAMA ||
41314131
model.arch == LLM_ARCH_BAICHUAN ||
4132-
model.arch == LLM_ARCH_FALCON ||
4132+
model.arch == LLM_ARCH_FALCON ||
41334133
model.arch == LLM_ARCH_REFACT;
41344134
const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 3;
41354135
if (ggml_cpu_has_cublas() && full_offload_supported && fully_offloaded) {

0 commit comments

Comments
 (0)