Skip to content

Commit bdbe117

Browse files
committed
refact : fix convert script + zero out KV cache to avoid nans
1 parent 0e797c2 commit bdbe117

File tree

4 files changed

+28
-78
lines changed

4 files changed

+28
-78
lines changed

convert-refact-hf-to-gguf.py

Lines changed: 8 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -17,33 +17,6 @@
1717
sys.path.insert(1, str(Path(__file__).parent / "gguf-py" / "gguf"))
1818
import gguf
1919

20-
21-
def bytes_to_unicode():
22-
# ref: https://github.com/openai/gpt-2/blob/master/src/encoder.py
23-
"""
24-
Returns list of utf-8 byte and a corresponding list of unicode strings.
25-
The reversible bpe codes work on unicode strings.
26-
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
27-
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
28-
This is a significant percentage of your normal, say, 32K bpe vocab.
29-
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
30-
And avoids mapping to whitespace/control characters the bpe code barfs on.
31-
"""
32-
bs = (
33-
list(range(ord("!"), ord("~") + 1))
34-
+ list(range(ord("¡"), ord("¬") + 1))
35-
+ list(range(ord("®"), ord("ÿ") + 1))
36-
)
37-
cs = bs[:]
38-
n = 0
39-
for b in range(2**8):
40-
if b not in bs:
41-
bs.append(b)
42-
cs.append(2**8 + n)
43-
n += 1
44-
return dict(zip(bs, (chr(n) for n in cs)))
45-
46-
4720
def count_model_parts(dir_model: Path) -> int:
4821
num_parts = 0
4922
for filename in os.listdir(dir_model):
@@ -153,53 +126,25 @@ def parse_args() -> argparse.Namespace:
153126
scores: list[float] = []
154127
toktypes: list[int] = []
155128

156-
tokenizer_json_file = dir_model / "tokenizer.json"
157-
if not tokenizer_json_file.is_file():
158-
print(f"Error: Missing {tokenizer_json_file}", file=sys.stderr)
159-
sys.exit(1)
160-
161129
# gpt2 tokenizer
162130
gguf_writer.add_tokenizer_model("gpt2")
163131

164-
with open(tokenizer_json_file, "r", encoding="utf-8") as f:
165-
tokenizer_json = json.load(f)
166-
167132
print("gguf: get gpt2 tokenizer vocab")
168133

134+
# ref: https://github.com/cmp-nct/ggllm.cpp/blob/master/falcon_convert.py
135+
tokenizer = AutoTokenizer.from_pretrained(dir_model)
136+
169137
# The number of tokens in tokenizer.json can differ from the expected vocab size.
170138
# This causes downstream issues with mismatched tensor sizes when running the inference
171-
vocab_size = (
172-
hparams["vocab_size"]
173-
if "vocab_size" in hparams
174-
else len(tokenizer_json["model"]["vocab"])
175-
)
176-
177-
tokenizer = AutoTokenizer.from_pretrained(dir_model, trust_remote_code=True)
139+
vocab_size = hparams.get("vocab_size", len(tokenizer.vocab))
140+
assert max(tokenizer.vocab.values()) < vocab_size
178141

179142
reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.vocab.items()}
180-
byte_encoder = bytes_to_unicode()
181-
byte_decoder = {v: k for k, v in byte_encoder.items()}
182143

183144
for i in range(vocab_size):
184-
if i in reverse_vocab:
185-
text = reverse_vocab[i]
186-
try:
187-
text = bytearray([byte_decoder[c] for c in reverse_vocab[i]])
188-
except KeyError:
189-
text = bytearray()
190-
for c in reverse_vocab[i]:
191-
if ord(c) < 256: # single byte character
192-
text.append(byte_decoder[ord(c)])
193-
else: # multibyte special token character
194-
text.extend(c.encode("utf-8"))
195-
else:
196-
print(f"Key {i} not in tokenizer vocabulary. Padding with an arbitrary token.")
197-
pad_token = f"[PAD{i}]".encode("utf8")
198-
text = bytearray(pad_token)
199-
200-
tokens.append(text)
201-
scores.append(0.0) # dymmy
202-
toktypes.append(gguf.TokenType.NORMAL) # dummy
145+
tokens.append(reverse_vocab[i] if i in reverse_vocab else f"[PAD{i}]")
146+
scores.append(0.0) # dummy
147+
toktypes.append(gguf.TokenType.NORMAL)
203148

204149
gguf_writer.add_token_list(tokens)
205150
gguf_writer.add_token_scores(scores)

examples/parallel/parallel.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ int main(int argc, char ** argv) {
167167

168168
// the max batch size is as large as the context to handle cases where we get very long input prompt from multiple
169169
// users. regardless of the size, the main loop will chunk the batch into a maximum of params.n_batch tokens at a time
170-
llama_batch batch = llama_batch_init(params.n_ctx, 0);
170+
llama_batch batch = llama_batch_init(n_ctx, 0);
171171

172172
int32_t n_total_prompt = 0;
173173
int32_t n_total_gen = 0;

ggml.c

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3923,6 +3923,8 @@ inline static void ggml_vec_gelu_quick_f32(const int n, float * y, const float *
39233923

39243924
// Sigmoid Linear Unit (SiLU) function
39253925
inline static float ggml_silu_f32(float x) {
3926+
if (x == -INFINITY) return 0.0f;
3927+
39263928
return x/(1.0f + expf(-x));
39273929
}
39283930

@@ -11256,7 +11258,7 @@ static void ggml_compute_forward_silu_f32(
1125611258

1125711259
#ifndef NDEBUG
1125811260
for (int k = 0; k < nc; k++) {
11259-
const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
11261+
const float x = ((float *) ((char *) dst->data + i1*(dst->nb[1])))[k];
1126011262
UNUSED(x);
1126111263
assert(!isnan(x));
1126211264
assert(!isinf(x));
@@ -13089,17 +13091,17 @@ static void ggml_compute_forward_alibi_f32(
1308913091

1309013092
assert(n_past >= 0);
1309113093

13092-
const int ne0 = src0->ne[0]; // all_seq_len = n_past + ne1
13093-
const int ne1 = src0->ne[1]; // seq_len_without_past
13094-
const int ne2 = src0->ne[2]; // n_head -> this is k
13095-
//const int ne3 = src0->ne[3]; // 1 -> bsz
13094+
const int64_t ne0 = src0->ne[0]; // all_seq_len = n_past + ne1
13095+
const int64_t ne1 = src0->ne[1]; // seq_len_without_past
13096+
const int64_t ne2 = src0->ne[2]; // n_head -> this is k
13097+
//const int64_t ne3 = src0->ne[3]; // 1 -> bsz
1309613098

13097-
const int n = ggml_nrows(src0);
13098-
const int ne2_ne3 = n/ne1; // ne2*ne3
13099+
const int64_t n = ggml_nrows(src0);
13100+
const int64_t ne2_ne3 = n/ne1; // ne2*ne3
1309913101

13100-
const int nb0 = src0->nb[0];
13101-
const int nb1 = src0->nb[1];
13102-
const int nb2 = src0->nb[2];
13102+
const size_t nb0 = src0->nb[0];
13103+
const size_t nb1 = src0->nb[1];
13104+
const size_t nb2 = src0->nb[2];
1310313105
//const int nb3 = src0->nb[3];
1310413106

1310513107
GGML_ASSERT(nb0 == sizeof(float));
@@ -13111,9 +13113,9 @@ static void ggml_compute_forward_alibi_f32(
1311113113
const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
1311213114
const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_heads_log2_floor);
1311313115

13114-
for (int i = 0; i < ne0; i++) {
13115-
for (int j = 0; j < ne1; j++) {
13116-
for (int k = 0; k < ne2_ne3; k++) {
13116+
for (int64_t i = 0; i < ne0; i++) {
13117+
for (int64_t j = 0; j < ne1; j++) {
13118+
for (int64_t k = 0; k < ne2_ne3; k++) {
1311713119
float * const src = (float *)((char *) src0->data + i*nb0 + j*nb1 + k*nb2);
1311813120
float * pdst = (float *)((char *) dst->data + i*nb0 + j*nb1 + k*nb2);
1311913121

@@ -13128,7 +13130,6 @@ static void ggml_compute_forward_alibi_f32(
1312813130
}
1312913131

1313013132
pdst[0] = i * m_k + src[0];
13131-
1313213133
}
1313313134
}
1313413135
}

llama.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1325,7 +1325,11 @@ static bool llama_kv_cache_init(
13251325
cache.cells.clear();
13261326
cache.cells.resize(n_ctx);
13271327

1328+
// TODO: this should be:
1329+
// cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*ggml_tensor_overhead());
1330+
// change it and test that it works
13281331
cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
1332+
memset(cache.buf.data, 0, cache.buf.size);
13291333

13301334
struct ggml_init_params params;
13311335
params.mem_size = cache.buf.size;

0 commit comments

Comments
 (0)