Skip to content

Commit a5e7dbd

Browse files
llama : validate special token ids are in range when loading GGUF model (#3635)
* Add validation for special token ids to llama.cpp Small optimization for llama_byte_to_token SPM mode * Fix BPE newline check, only I could break something so simple * Killll meeeeee * Account for GGUF_KEY_KEY only setting when the key exists * Minor code cleanups. * Fix convert.py error msg when added tokens are out of range * Make gguf SpecialVocab vocab size-aware Update conversion scripts accordingly * Avoid a string copy Co-authored-by: Georgi Gerganov <[email protected]> --------- Co-authored-by: Georgi Gerganov <[email protected]>
1 parent d3956ae commit a5e7dbd

11 files changed

+72
-32
lines changed

convert-baichuan-hf-to-gguf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ def parse_args() -> argparse.Namespace:
230230
gguf_writer.add_token_scores(scores)
231231
gguf_writer.add_token_types(toktypes)
232232

233-
special_vocab = gguf.SpecialVocab(dir_model)
233+
special_vocab = gguf.SpecialVocab(dir_model, n_vocab = len(tokens))
234234
special_vocab.add_to_gguf(gguf_writer)
235235

236236
# TENSORS

convert-bloom-hf-to-gguf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def parse_args() -> argparse.Namespace:
129129
gguf_writer.add_token_scores(scores)
130130
gguf_writer.add_token_types(toktypes)
131131

132-
special_vocab = gguf.SpecialVocab(dir_model, load_merges=True)
132+
special_vocab = gguf.SpecialVocab(dir_model, load_merges=True, n_vocab = len(tokens))
133133
special_vocab.add_to_gguf(gguf_writer)
134134

135135
# TENSORS

convert-falcon-hf-to-gguf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def parse_args() -> argparse.Namespace:
152152
gguf_writer.add_token_scores(scores)
153153
gguf_writer.add_token_types(toktypes)
154154

155-
special_vocab = gguf.SpecialVocab(dir_model, load_merges = True)
155+
special_vocab = gguf.SpecialVocab(dir_model, load_merges = True, n_vocab = len(tokens))
156156
special_vocab.add_to_gguf(gguf_writer)
157157

158158
# TENSORS

convert-gptneox-hf-to-gguf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def parse_args() -> argparse.Namespace:
134134
gguf_writer.add_token_scores(scores)
135135
gguf_writer.add_token_types(toktypes)
136136

137-
special_vocab = gguf.SpecialVocab(dir_model, load_merges = True)
137+
special_vocab = gguf.SpecialVocab(dir_model, load_merges = True, n_vocab = len(tokens))
138138
special_vocab.add_to_gguf(gguf_writer)
139139

140140
# TENSORS

convert-llama-ggml-to-gguf.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,9 @@ def handle_metadata(cfg, hp):
388388
cfg.vocab_dir if cfg.vocab_dir is not None else cfg.model_metadata_dir,
389389
cfg.vocabtype )
390390
# FIXME: Respect cfg.vocab_dir?
391-
svocab = gguf.SpecialVocab(cfg.model_metadata_dir)
391+
svocab = gguf.SpecialVocab(cfg.model_metadata_dir,
392+
load_merges = cfg.vocabtype == 'bpe',
393+
n_vocab = vocab.vocab_size)
392394
convert.check_vocab_size(params, vocab)
393395
return (params, vocab, svocab)
394396

convert-mpt-hf-to-gguf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ def parse_args() -> argparse.Namespace:
139139
gguf_writer.add_token_scores(scores)
140140
gguf_writer.add_token_types(toktypes)
141141

142-
special_vocab = gguf.SpecialVocab(dir_model, load_merges = True)
142+
special_vocab = gguf.SpecialVocab(dir_model, load_merges = True, n_vocab = len(tokens))
143143
special_vocab.add_to_gguf(gguf_writer)
144144

145145
# TENSORS

convert-refact-hf-to-gguf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def parse_args() -> argparse.Namespace:
150150
gguf_writer.add_token_scores(scores)
151151
gguf_writer.add_token_types(toktypes)
152152

153-
special_vocab = gguf.SpecialVocab(dir_model, load_merges=True)
153+
special_vocab = gguf.SpecialVocab(dir_model, load_merges=True, n_vocab = len(tokens))
154154
special_vocab.add_to_gguf(gguf_writer)
155155

156156
# TENSORS

convert-starcoder-hf-to-gguf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def parse_args() -> argparse.Namespace:
122122
gguf_writer.add_token_scores(scores)
123123
gguf_writer.add_token_types(toktypes)
124124

125-
special_vocab = gguf.SpecialVocab(dir_model, load_merges = True)
125+
special_vocab = gguf.SpecialVocab(dir_model, load_merges = True, n_vocab = len(tokens))
126126
special_vocab.add_to_gguf(gguf_writer)
127127

128128
# TENSORS

convert.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> No
369369
expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
370370
actual_ids = sorted(added_tokens.values())
371371
if expected_ids != actual_ids:
372-
raise Exception(f"Expected added token IDs to be sequential and start at {len(added_tokens)}; got {actual_ids}")
372+
raise Exception(f"Expected added token IDs to be sequential and start at {vocab_size}; got {actual_ids}")
373373

374374
items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
375375
self.added_tokens_list = [text for (text, idx) in items]
@@ -1163,10 +1163,13 @@ def main(args_in: list[str] | None = None) -> None:
11631163

11641164
vocab: Vocab
11651165
if args.vocab_only:
1166-
assert args.outfile, "need --outfile if using --vocab-only"
1166+
if not args.outfile:
1167+
raise ValueError("need --outfile if using --vocab-only")
11671168
# FIXME: Try to respect vocab_dir somehow?
11681169
vocab = load_vocab(args.vocab_dir or args.model, args.vocabtype)
1169-
special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent, load_merges = args.vocabtype == 'bpe')
1170+
special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent,
1171+
load_merges = args.vocabtype == 'bpe',
1172+
n_vocab = vocab.vocab_size)
11701173
outfile = args.outfile
11711174
OutputFile.write_vocab_only(outfile, params, vocab, special_vocab)
11721175
print(f"Wrote {outfile}")
@@ -1178,7 +1181,9 @@ def main(args_in: list[str] | None = None) -> None:
11781181
vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent
11791182
vocab = load_vocab(vocab_dir, args.vocabtype)
11801183
# FIXME: Try to respect vocab_dir somehow?
1181-
special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent, load_merges = args.vocabtype == 'bpe')
1184+
special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent,
1185+
load_merges = args.vocabtype == 'bpe',
1186+
n_vocab = vocab.vocab_size)
11821187

11831188
model = model_plus.model
11841189
model = convert_model_names(model, params)

gguf-py/gguf/gguf.py

+25-11
Original file line numberDiff line numberDiff line change
@@ -987,12 +987,15 @@ class SpecialVocab:
987987
merges: list[str] = []
988988
special_token_types: tuple[str, ...] = ('bos', 'eos', 'unk', 'sep', 'pad')
989989
special_token_ids: dict[str, int] = {}
990+
n_vocab: int | None = None
990991

991992
def __init__(
992993
self, path: str | os.PathLike[str], load_merges: bool = False,
993994
special_token_types: tuple[str, ...] | None = None,
995+
n_vocab: int | None = None,
994996
):
995997
self.special_token_ids = {}
998+
self.n_vocab = n_vocab
996999
self.load_merges = load_merges
9971000
if special_token_types is not None:
9981001
self.special_token_types = special_token_types
@@ -1002,6 +1005,16 @@ def _load(self, path: Path) -> None:
10021005
if not self._try_load_from_tokenizer_json(path):
10031006
self._try_load_from_config_json(path)
10041007

1008+
def _set_special_token(self, typ: str, tid: Any):
1009+
if not isinstance(tid, int) or tid < 0:
1010+
return
1011+
if self.n_vocab is None or tid < self.n_vocab:
1012+
self.special_token_ids[typ] = tid
1013+
return
1014+
print(f'gguf: WARNING: Special token type {typ}, id {tid} out of range, must be under {self.n_vocab} - skipping',
1015+
file = sys.stderr)
1016+
1017+
10051018
def _try_load_from_tokenizer_json(self, path: Path) -> bool:
10061019
tokenizer_file = path / 'tokenizer.json'
10071020
if not tokenizer_file.is_file():
@@ -1029,10 +1042,11 @@ def _try_load_from_tokenizer_json(self, path: Path) -> bool:
10291042
tc_content = entry_content
10301043
else:
10311044
continue
1032-
for maybe_token_id in (atok.get('id') for atok in added_tokens if atok.get('content') == tc_content):
1033-
if isinstance(maybe_token_id, int) and maybe_token_id >= 0:
1034-
self.special_token_ids[typ] = maybe_token_id
1035-
break
1045+
# We only need the first match here.
1046+
maybe_token_id = next((
1047+
atok.get('id') for atok in added_tokens
1048+
if atok.get('content') == tc_content), None)
1049+
self._set_special_token(typ, maybe_token_id)
10361050
return True
10371051

10381052
def _try_load_from_config_json(self, path: Path) -> bool:
@@ -1042,21 +1056,21 @@ def _try_load_from_config_json(self, path: Path) -> bool:
10421056
with open(config_file, encoding = 'utf-8') as f:
10431057
config = json.load(f)
10441058
for typ in self.special_token_types:
1045-
maybe_token_id = config.get(f'{typ}_token_id')
1046-
if isinstance(maybe_token_id, int) and maybe_token_id >= 0:
1047-
self.special_token_ids[typ] = maybe_token_id
1059+
self._set_special_token(typ, config.get(f'{typ}_token_id'))
10481060
return True
10491061

1050-
def add_to_gguf(self, gw: GGUFWriter) -> None:
1062+
def add_to_gguf(self, gw: GGUFWriter, quiet: bool = False) -> None:
10511063
if len(self.merges) > 0:
1052-
print(f'gguf: Adding {len(self.merges)} merge(s).')
1064+
if not quiet:
1065+
print(f'gguf: Adding {len(self.merges)} merge(s).')
10531066
gw.add_token_merges(self.merges)
10541067
for typ, tokid in self.special_token_ids.items():
10551068
handler: Callable[[int], None] | None = getattr(gw, f'add_{typ}_token_id', None)
10561069
if handler is None:
1057-
print(f'gguf: WARNING: No handler for special token type {typ} with id {tokid} - skipping')
1070+
print(f'gguf: WARNING: No handler for special token type {typ} with id {tokid} - skipping', file = sys.stderr)
10581071
continue
1059-
print(f'gguf: Setting special token type {typ} to {tokid}')
1072+
if not quiet:
1073+
print(f'gguf: Setting special token type {typ} to {tokid}')
10601074
handler(tokid)
10611075

10621076
def __repr__(self) -> str:

llama.cpp

+28-9
Original file line numberDiff line numberDiff line change
@@ -2238,15 +2238,35 @@ static void llm_load_vocab(
22382238
if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
22392239
vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
22402240
} else {
2241-
vocab.linefeed_id = llama_tokenize_internal(vocab, "\u010A", false)[0];
2241+
const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
2242+
GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
2243+
vocab.linefeed_id = ids[0];
22422244
}
22432245

22442246
// special tokens
2245-
GGUF_GET_KEY(ctx, vocab.special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_BOS_ID));
2246-
GGUF_GET_KEY(ctx, vocab.special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_EOS_ID));
2247-
GGUF_GET_KEY(ctx, vocab.special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_UNK_ID));
2248-
GGUF_GET_KEY(ctx, vocab.special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_SEP_ID));
2249-
GGUF_GET_KEY(ctx, vocab.special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_PAD_ID));
2247+
{
2248+
const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
2249+
{ LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
2250+
{ LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
2251+
{ LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
2252+
{ LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
2253+
{ LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
2254+
};
2255+
for (const auto & it : special_token_types) {
2256+
const std::string & key = kv(std::get<0>(it));
2257+
int32_t & id = std::get<1>(it), old_id = id;
2258+
2259+
GGUF_GET_KEY(ctx, id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, key);
2260+
// Must be >= -1 and < vocab size. Since the key is unsigned, -1
2261+
// can only come from the default value, so there's no point in
2262+
// validating that.
2263+
if (size_t(id + 1) > vocab.id_to_token.size()) {
2264+
LLAMA_LOG_WARN("%s: bad special token: '%s' = %d, using default id %d\n",
2265+
__func__, key.c_str(), id, old_id);
2266+
id = old_id;
2267+
}
2268+
}
2269+
}
22502270

22512271
// build special tokens cache
22522272
{
@@ -6103,11 +6123,10 @@ static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
61036123
}
61046124

61056125
static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
6126+
static const char * hex = "0123456789ABCDEF";
61066127
switch (llama_vocab_get_type(vocab)) {
61076128
case LLAMA_VOCAB_TYPE_SPM: {
6108-
char buf[7];
6109-
int result = snprintf(buf, sizeof(buf), "<0x%02X>", ch);
6110-
GGML_ASSERT(0 <= result && result < 7);
6129+
const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
61116130
return vocab.token_to_id.at(buf);
61126131
}
61136132
case LLAMA_VOCAB_TYPE_BPE: {

0 commit comments

Comments
 (0)