Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

fix(tokenizer): validate JSON structure and ids before indexing

Rudy Celekli88c894795649
diff --git a/c/tests/test_tok_load_validation.py b/c/tests/test_tok_load_validation.py
new file mode 100644
index 00000000..1cf67fbd
--- /dev/null
+++ b/c/tests/test_tok_load_validation.py
@@ -0,0 +1,84 @@
+"""Exercise corrupt tokenizer files through the native public loader."""
+import json
+import os
+from pathlib import Path
+import shlex
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+C_DIR = Path(__file__).resolve().parents[1]
+
+
+class TokenizerLoadValidation(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ compiler = shlex.split(os.environ.get("CC", "cc"))
+ if not compiler or shutil.which(compiler[0]) is None:
+ raise unittest.SkipTest("a C compiler is required for the native loader")
+ cls.tmp = tempfile.TemporaryDirectory()
+ cls.addClassCleanup(cls.tmp.cleanup)
+ cls.root = Path(cls.tmp.name)
+ source = cls.root / "load.c"
+ source.write_text('#include "tok.h"\nint main(int argc, char **argv) {\n'
+ ' if (argc != 2) return 2;\n'
+ ' Tok t; tok_load(&t, argv[1]); tok_free(&t); return 0;\n}\n')
+ cls.binary = cls.root / ("load.exe" if os.name == "nt" else "load")
+ subprocess.run(compiler + ["-O1", "-Wall", "-Wextra", "-Wno-unused-function",
+ "-I", str(C_DIR), str(source), "-o", str(cls.binary)],
+ check=True, capture_output=True, text=True)
+
+ def load(self, payload):
+ path = self.root / "tokenizer.json"
+ path.write_bytes(payload.encode() if isinstance(payload, str) else payload)
+ return subprocess.run([str(self.binary), str(path)], capture_output=True,
+ text=True, timeout=10)
+
+ def reject(self, payload):
+ result = self.load(payload)
+ self.assertEqual(result.returncode, 1, result.stderr)
+ self.assertIn("tokenizer.json:", result.stderr)
+
+ def test_invalid_container_types(self):
+ for field, value in (("vocab", [0]), ("vocab", "abc"),
+ ("merges", {"a b": 0}), ("added_tokens", {"a": 0})):
+ with self.subTest(field=field, value=value):
+ document = {"model": {"vocab": {"a": 0}, "merges": []}}
+ if field == "added_tokens":
+ document[field] = value
+ else:
+ document["model"][field] = value
+ self.reject(json.dumps(document))
+
+ def test_vocab_and_added_ids_must_be_bounded_integers(self):
+ for value in ("-0.5", "0.5", "1e100", "1e309", "2097153", "-1", '"0"'):
+ with self.subTest(value=value):
+ self.reject('{"model":{"vocab":{"a":' + value + '}}}')
+ self.reject('{"model":{"vocab":{"a":0}},'
+ '"added_tokens":[{"content":"<s>","id":' + value + '}]}')
+
+ def test_partial_or_malformed_json_is_rejected(self):
+ prefix = '{"model":{"vocab":{"a":0}}'
+ for payload in (prefix, prefix + ',}', prefix + '} trailing',
+ (prefix + '}').encode() + b'\0garbage'):
+ with self.subTest(payload=payload):
+ self.reject(payload)
+
+ def test_valid_sparse_ids_and_integral_exponents(self):
+ for value in ("0", "2e0", "3.0"):
+ with self.subTest(value=value):
+ result = self.load('{"model":{"vocab":{"a":' + value + '},"merges":[]},'
+ '"added_tokens":[{"content":"<s>","id":8,"special":true}]}')
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_merge_forms_remain_supported(self):
+ for merge in (["a", "b"], "a b"):
+ with self.subTest(merge=merge):
+ result = self.load(json.dumps({"model": {"vocab": {"a": 0, "b": 1, "ab": 2},
+ "merges": [merge]}}))
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tok.h b/c/tok.h
index 49f6c56c..d16697c4 100644
--- a/c/tok.h
+++ b/c/tok.h
@@ -20,6 +20,7 @@
#include <string.h>
#include <stdint.h>
#include <limits.h>
+#include <math.h>
#include "json.h"
#include "tok_unicode.h"
#include "tok_unicode_o200k.h"
@@ -140,18 +141,32 @@ static void tok_free(Tok *T){
memset(T,0,sizeof(*T));
}
+/* Validate the JSON number before converting it: casting an infinite or
+ * out-of-range double to int is undefined, and fractional ids silently alias
+ * a different token. The same bound applies to vocabulary and added tokens. */
+static int tk_checked_id(const jval *value){
+ if(!value || value->t!=J_NUM || !isfinite(value->num) ||
+ value->num<0 || value->num>(1<<21) || value->num!=(double)(int)value->num){
+ fprintf(stderr,"tokenizer.json: token id must be an integer between 0 and %d\n",1<<21);
+ exit(1);
+ }
+ return (int)value->num;
+}
+
static void tok_load(Tok *T, const char *path){
memset(T,0,sizeof(*T));
tk_build_bytemap(T);
long fn; char *buf=tk_read_file(path,&fn);
- char *arena=NULL; jval *root=json_parse(buf,&arena);
+ jval *root=memchr(buf,0,(size_t)fn) ? NULL : json_parse_checked(buf);
free(buf);
- (void)arena;
+ if(!root){ fprintf(stderr,"tokenizer.json: malformed JSON\n"); exit(1); }
jval *model=json_get(root,"model");
jval *vocab=json_get(model,"vocab");
jval *merges=json_get(model,"merges");
jval *added=json_get(root,"added_tokens");
- if(!vocab){ fprintf(stderr,"tokenizer.json: missing model.vocab\n"); exit(1); }
+ if(!vocab || vocab->t!=J_OBJ){ fprintf(stderr,"tokenizer.json: model.vocab must be an object\n"); exit(1); }
+ if(merges && merges->t!=J_ARR){ fprintf(stderr,"tokenizer.json: model.merges must be an array\n"); exit(1); }
+ if(added && added->t!=J_ARR){ fprintf(stderr,"tokenizer.json: added_tokens must be an array\n"); exit(1); }
if(!merges||merges->len==0){ T->rankbpe=1; merges=NULL; }
/* id massimo per dimensionare id2str. Gli id vengono da un tokenizer.json di
@@ -159,15 +174,11 @@ static void tok_load(Tok *T, const char *path){
* (OOB write) e un added_token privo di "id"/"content" darebbe NULL-deref. */
int maxid=0;
for(int i=0;i<vocab->len;i++){
- if(vocab->kids[i]->t!=J_NUM){ fprintf(stderr,"tokenizer.json: non-numeric vocab id at %d\n",i); exit(1); }
- int id=(int)vocab->kids[i]->num;
- if(id<0){ fprintf(stderr,"tokenizer.json: negative vocab id %d\n",id); exit(1); }
+ int id=tk_checked_id(vocab->kids[i]);
if(id>maxid)maxid=id; }
if(added) for(int i=0;i<added->len;i++){
jval *ji=json_get(added->kids[i],"id");
- if(!ji||ji->t!=J_NUM){ fprintf(stderr,"tokenizer.json: added_token missing numeric id\n"); exit(1); }
- int id=(int)ji->num;
- if(id<0){ fprintf(stderr,"tokenizer.json: negative added id %d\n",id); exit(1); }
+ int id=tk_checked_id(ji);
if(id>maxid)maxid=id; }
/* an id near INT_MAX would overflow n_ids=maxid+1 (UB) and calloc multi-GB */
if(maxid > (1<<21)){ fprintf(stderr,"tokenizer.json: implausible max vocab id %d\n",maxid); exit(1); }