From c62bc26c3e123d2135ad8635e8f8019066e57ce9 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 6 Nov 2026 16:14:31 -0600 Subject: [PATCH] feat(omegallm): own byte-level BPE tokenizer in Omega (OLLMTOK1, ollm-tok) Trainer, encoder and decoder written in .om at omc pin e5b32567, no outside tokenizer or vocabulary. Ids 0-255 bytes, 256-263 chat markers, 264-271 reserved, 272..V-1 merges (V up to 32768). Checksummed merges file with refusal (exit 26) of any corrupted or ill-formed file. Spec in tests/omegallm/tok/FORMAT.md; check.sh compares against the Python test oracle oracle.py; ratio.sh measures compression. --- native/omegallm/tok/.crumb | 19 ++ native/omegallm/tok/tkcli.om | 386 +++++++++++++++++++++++++++++ native/omegallm/tok/tkcore.om | 387 +++++++++++++++++++++++++++++ native/omegallm/tok/tkfit.om | 432 +++++++++++++++++++++++++++++++++ native/omegallm/tok/tkio.om | 233 ++++++++++++++++++ tests/omegallm/tok/.crumb | 19 ++ tests/omegallm/tok/FORMAT.md | 129 ++++++++++ tests/omegallm/tok/build.sh | 27 +++ tests/omegallm/tok/chat.txt | 12 + tests/omegallm/tok/check.sh | 209 ++++++++++++++++ tests/omegallm/tok/oracle.py | 354 +++++++++++++++++++++++++++ tests/omegallm/tok/ratio.sh | 63 +++++ tests/omegallm/tok/unicode.txt | 11 + 13 files changed, 2281 insertions(+) create mode 100644 native/omegallm/tok/.crumb create mode 100644 native/omegallm/tok/tkcli.om create mode 100644 native/omegallm/tok/tkcore.om create mode 100644 native/omegallm/tok/tkfit.om create mode 100644 native/omegallm/tok/tkio.om create mode 100644 tests/omegallm/tok/.crumb create mode 100644 tests/omegallm/tok/FORMAT.md create mode 100755 tests/omegallm/tok/build.sh create mode 100644 tests/omegallm/tok/chat.txt create mode 100755 tests/omegallm/tok/check.sh create mode 100755 tests/omegallm/tok/oracle.py create mode 100755 tests/omegallm/tok/ratio.sh create mode 100644 tests/omegallm/tok/unicode.txt diff --git a/native/omegallm/tok/.crumb b/native/omegallm/tok/.crumb new file mode 100644 index 0000000..40bc2e1 --- /dev/null +++ b/native/omegallm/tok/.crumb @@ -0,0 +1,19 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-11-06T22:13:40Z", + "compiler": "crumb-compile/1", + "digest": "sha256:30b23dd535d503990c371ceaabe3d2b53c61cdc38eb6053ef9e49f9f52e07ceb", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 0, + "generated_at_commit": "ac4a7c1ed20e8aea37f604e91f438b06e4511c8b", + "source_tree": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + } + }, + "name": "tok", + "purpose": "Own byte-level BPE tokenizer of Omega LLM in Omega: OLLMTOK1 merges format, chunker, encoder, decoder (tkcore, embeddable in ollm) and the standalone trainer program ollm-tok (tkio, tkfit, tkcli). Spec: tests/omegallm/tok/FORMAT.md.", + "schema_version": "1.0.0" +} diff --git a/native/omegallm/tok/tkcli.om b/native/omegallm/tok/tkcli.om new file mode 100644 index 0000000..f01e661 --- /dev/null +++ b/native/omegallm/tok/tkcli.om @@ -0,0 +1,386 @@ +note SPDX-License-Identifier: AGPL-3.0-only +note omegallm tok/tkcli.om: the commands of the standalone tokenizer program ollm-tok (FORMAT.md +note section 6). No host words; tkio.om is the platform unit. Text and token files are read as a +note stream through the window tkw: tcws 0 = file offset of tkw[0], 1 = bytes in tkw, 2 = 1 once +note the file ended inside the window. +note ollm-tok toktrain MODE TEXT MERGES V MAXBYTES learn V - 272 merges (MAXBYTES 0: all) +note ollm-tok tokenc MODE MERGES TEXT TOKS encode to u16 LE tokens +note ollm-tok tokdec MERGES TOKS OUT decode +note ollm-tok tokinfo MERGES check a merges file +note MODE is raw (every byte is text) or chat (the chat markers are special tokens). +note Exits: 2 usage; 21 a capacity, a text of 2^33 bytes or more, or an odd token file; 25 a token +note that is not valid for the merges; 26 a bad merges file; 28 no pair left to merge; 70 I/O. +text tccmds "toktrain tokenc tokdec tokinfo " +text tcmodes "raw chat " +global tcws ulong 4 +global tcdg uchar 24 + +note slot k (9 bytes, space padded) of the 5-byte or 9-byte name table equals argv[i]? +fn tcis i ulong k ulong tab ulong to bool +r = tkargp i +w = ulong 9 +if eq tab 1 +w = ulong 5 +end +if ge r w +ret false +end +for j ulong add r 1 +c = ulong 32 +if lt j r +c = ulong get tkarg j +end +d = ulong 0 +if eq tab 0 +d = ulong get tccmds add mul k w j +else +d = ulong get tcmodes add mul k w j +end +if ne c d +ret false +end +end +ret true +end + +note argv[i] as raw (false) or chat (true); exit 2 otherwise +fn tcmode i ulong to bool +if tcis i 0 1 +ret false +end +if tcis i 1 1 +ret true +end +exit 2 +end + +note argv[i] as an unsigned decimal of 1 .. 19 digits +fn tcargu i ulong to ulong +n = tkargp i +if gt n 19 +exit 2 +end +v = ulong 0 +for k ulong n +c = ulong get tkarg k +if or lt c 48 gt c 57 +exit 2 +end +v = add mul v 10 sub c 48 +end +ret v +end + +note unsigned decimal v to stdout +fn tcpu v ulong to void +n = ulong 0 +x = v +dn = false +while not dn bound 24 +put tcdg n uchar add 48 rem x 10 +n = add n 1 +x = div x 10 +if eq x 0 +dn = true +end +end +for k ulong n +tkpc ulong get tcdg sub sub n 1 k +end +end + +note a space, then v +fn tcsu v ulong to void +tkpc 32 +tcpu v +end + +note window: tkw from byte 0 of argv[ai] +fn tcwstart ai ulong to void +wn = tkrdw ai 0 0 TKWCAP +put tcws 0 0 +put tcws 1 wn +put tcws 2 0 +if lt wn TKWCAP +put tcws 2 1 +end +end + +note window: move tkw[a .. wn) to the front and fill the rest from the file +fn tcwshift ai ulong a ulong to void +wn = get tcws 1 +cnt = sub wn a +i = ulong 0 +for o ulong 2 +lim = mul add o 1 999999 +if gt lim cnt +lim = cnt +end +while lt i lim bound 999999 +put tkw i get tkw add a i +i = add i 1 +end +end +wb = add get tcws 0 a +r = tkrdw ai add wb cnt cnt sub TKWCAP cnt +put tcws 0 wb +put tcws 1 add cnt r +put tcws 2 0 +if lt r sub TKWCAP cnt +put tcws 2 1 +end +end + +note window position of i after a refill: when fewer than need bytes are left from tkw[i] and the +note file goes on, tkw[i ..] moves to the front (0); else i +fn tcrefil ai ulong i ulong need ulong to ulong +if gt add i need get tcws 1 +if eq get tcws 2 0 +tcwshift ai i +ret 0 +end +end +ret i +end + +note token t to the output file as u16 LE +fn tcwtok t ulong to void +tkwb and t 255 +tkwb shr t 8 +end + +note encode: one chunk tkw[i .. i + l) to the output, through the type cache when it has room +fn tcenc1 i ulong l ulong to void +put tfst 2 add get tfst 2 1 +y = tffind i l +c = ulong 0 +if ne y TFTCAP +c = get tftc y +end +if eq c 0 +m = tkencc i l +if ne y TFTCAP +o = get tfst 1 +if le add o m TFSCAP +for k ulong m +put tfsy add o k get tkct k +end +put tfts y uint o +put tftn y uchar m +put tftc y 1 +put tfst 1 add o m +end +end +for k ulong m +tcwtok ulong get tkct k +end +put tfst 10 add get tfst 10 m +else +o = ulong get tfts y +m = ulong get tftn y +for k ulong m +tcwtok ulong get tfsy add o k +end +put tfst 10 add get tfst 10 m +end +end + +note one piece at tkw[i] of a text ending at n: a marker is counted in tfst 4 and, in mode 1, +note written as its special id; a chunk is counted (mode 0) or encoded (mode 1). Returns its length. +fn tcpiece i ulong n ulong chat bool mode ulong to ulong +l = tknext i n chat +sp = get tkv 1 +if ne sp 0 +put tfst 4 add get tfst 4 1 +if eq mode 1 +tcwtok sp +put tfst 10 add get tfst 10 1 +end +else +if eq mode 0 +tfcount i l +else +tcenc1 i l +end +end +ret l +end + +note the pieces of the first lim bytes of argv[ai] (all of it when shorter), through tcpiece. +note tfst 3 = bytes scanned. +fn tcscan ai ulong lim ulong chat bool mode ulong to void +tcwstart ai +i = ulong 0 +dn = false +while not dn bound 999999 +q = ulong 0 +while and not dn lt q 999999 bound 999999 +q = add q 1 +i = tcrefil ai i 80 +wb = get tcws 0 +n = get tcws 1 +if lt sub lim wb n +n = sub lim wb +end +if ge i n +dn = true +put tfst 3 add wb i +else +i = add i tcpiece i n chat mode +end +end +end +end + +note the u16 LE token at tkw[i]: exit 25 when it is not valid for the merges; mode 1 writes its bytes +fn tcdtok i ulong mode ulong to void +t = or ulong get tkw i shl ulong get tkw add i 1 8 +if not tkvalid t +exit 25 +end +if eq mode 1 +l = tkdec1 t +for k ulong l +tkwb ulong get tkdb k +end +put tfst 3 add get tfst 3 l +end +end + +note decode argv[ai] (u16 LE tokens; even length checked by the caller): mode 0 only checks every +note token (exit 25 on the first invalid one), mode 1 writes the bytes; returns the token count +fn tcdscan ai ulong mode ulong to ulong +tcwstart ai +i = ulong 0 +nt = ulong 0 +dn = false +while not dn bound 999999 +q = ulong 0 +while and not dn lt q 999999 bound 999999 +q = add q 1 +i = tcrefil ai i 2 +if ge add i 2 add get tcws 1 1 +dn = true +else +tcdtok i mode +nt = add nt 1 +i = add i 2 +end +end +end +ret nt +end + +note the merges file of argv[ai], checked and loaded; returns its V +fn tcload ai ulong to ulong +n = tkrdm ai +ret tkload n +end + +note toktrain MODE TEXT MERGES V MAXBYTES; prints T V types chunks bytes markers pairs nodes +fn tccmdtr to void +if ne tkargc 7 +exit 2 +end +chat = tcmode 2 +v = tcargu 5 +if or lt v TKFIRST gt v TKVMAX +exit 2 +end +lim = tcargu 6 +if eq lim 0 +lim = ulong 9223372036854775807 +end +tcscan 3 lim chat 0 +if ge get tfst 3 8589934592 +exit 21 +end +tfinit +tfmerge v +n = tkseal v +w = tkload n +tkmsave 4 n +tkpc 84 +tcsu w +tcsu get tfst 0 +tcsu get tfst 2 +tcsu get tfst 3 +tcsu get tfst 4 +tcsu get tfst 5 +tcsu get tfst 7 +tkpc 10 +end + +note tokenc MODE MERGES TEXT TOKS; prints E V bytes chunks tokens markers +fn tccmden to void +if ne tkargc 6 +exit 2 +end +chat = tcmode 2 +v = tcload 3 +tkwopen 5 +tcscan 4 9223372036854775807 chat 1 +tkwclose +tkpc 69 +tcsu v +tcsu get tfst 3 +tcsu get tfst 2 +tcsu get tfst 10 +tcsu get tfst 4 +tkpc 10 +end + +note tokdec MERGES TOKS OUT; prints D V tokens bytes. Every token is checked before OUT is opened. +fn tccmdde to void +if ne tkargc 5 +exit 2 +end +v = tcload 2 +if ne and tkfsz 3 1 0 +exit 21 +end +nt = tcdscan 3 0 +tkwopen 4 +nt = tcdscan 3 1 +tkwclose +tkpc 68 +tcsu v +tcsu nt +tcsu get tfst 3 +tkpc 10 +end + +note tokinfo MERGES; prints I V merges FNV +fn tccmdin to void +if ne tkargc 3 +exit 2 +end +v = tcload 2 +tkpc 73 +tcsu v +tcsu sub v TKFIRST +tcsu tkrd64 24 +tkpc 10 +end + +note run the command named by argv[1] +fn tkcmd to int +tkinit +if tcis 1 0 0 +tccmdtr +ret 0 +end +if tcis 1 1 0 +tccmden +ret 0 +end +if tcis 1 2 0 +tccmdde +ret 0 +end +if tcis 1 3 0 +tccmdin +ret 0 +end +exit 2 +end diff --git a/native/omegallm/tok/tkcore.om b/native/omegallm/tok/tkcore.om new file mode 100644 index 0000000..b9e7a1b --- /dev/null +++ b/native/omegallm/tok/tkcore.om @@ -0,0 +1,387 @@ +note SPDX-License-Identifier: AGPL-3.0-only +note omegallm tok/tkcore.om: core of the own byte-level BPE tokenizer, format OLLMTOK1 (spec: +note tests/omegallm/tok/FORMAT.md). No host words and about 1.7 MiB of globals, so a model unit +note can concatenate it beside bpe.om: the caller fills tkw (text) or tkmf (merges file) and calls +note tkinit, tkload, tknext, tkencc and tkdec1. Every name starts with tk. +note Token ids: 0 .. 255 bytes; 256 .. 271 special ids (256 .. 263 the chat markers below, 264 .. +note 271 reserved and never valid); 272 .. V - 1 the merges in rank order. 272 <= V <= 32768. +note Exits: 26 a bad merges file (any fault below). +const TKVMAX ulong 32768 +const TKFIRST ulong 272 +const TKNSP ulong 8 +const TKWCAP ulong 1048576 +const TKMFCAP ulong 130016 +text tkmagic "OLLMTOK1" +text tkmarks "<|end|><|system|><|user|><|assistant|><|tool_call|><|tool_result|><|pad|><|doc|>" +global tkw uchar 1048576 +global tkmf uchar 131072 +global tkma ushort 32768 +global tkmb ushort 32768 +global tkln uchar 32768 +global tkrk uint 65536 +global tkrt ushort 65536 +global tkv ulong 2 +global tkcl uchar 256 +global tkmo uchar 16 +global tkml uchar 16 +global tkct ushort 128 +global tkdb uchar 64 +global tksk ushort 128 + +note tkv: 0 V of the loaded merges (0 before tkload), 1 special id of the last tknext piece (0: +note a text chunk). + +note byte classes (FORMAT.md section 3): 1 A (digits, ASCII letters, bytes >= 128), 2 W (9 .. 13 +note and 32), 0 P (every other byte); and the offset and length of each chat marker in tkmarks. +fn tkinit to void +for c ulong 256 +v = uchar 0 +if or or and ge c 48 le c 57 and ge c 65 le c 90 or and ge c 97 le c 122 ge c 128 +v = uchar 1 +end +if or and ge c 9 le c 13 eq c 32 +v = uchar 2 +end +put tkcl c v +end +o = ulong 0 +k = ulong 0 +for j ulong len tkmarks +if eq get tkmarks j 62 +put tkmo k uchar o +put tkml k uchar sub add j 1 o +o = add j 1 +k = add k 1 +end +end +put tkv 0 0 +end + +note 256 + k when chat marker k starts at tkw[i] and ends by n; 0 when none does +fn tkmark i ulong n ulong to ulong +if ne get tkw i 60 +ret 0 +end +for k ulong TKNSP +l = ulong get tkml k +if le add i l n +o = ulong get tkmo k +hit = true +for j ulong l +if ne get tkw add i j get tkmarks add o j +hit = false +end +end +if hit +ret add 256 k +end +end +end +ret 0 +end + +note length (1 .. 64) of the chunk at tkw[i] in a text ending at n > i (FORMAT.md section 3). +note Reads at most tkw[i .. i + 65). +fn tkclen i ulong n ulong to ulong +c = ulong get tkw i +k = ulong get tkcl c +e = add i 64 +if lt n e +e = n +end +j = add i 1 +sp = false +if eq c 32 +if lt j n +if ne get tkcl get tkw j 2 +sp = true +end +end +end +if sp +k = ulong get tkcl get tkw j +j = add j 1 +end +while lt j e bound 64 +if ne ulong get tkcl get tkw j k +break +end +j = add j 1 +end +if and eq k 2 lt j n +if ne get tkcl get tkw j 2 +if and ge sub j i 2 eq get tkw sub j 1 32 +j = sub j 1 +end +end +end +ret sub j i +end + +note the next piece at tkw[i] of a text ending at n > i: in chat mode a marker (its length; tkv 1 +note = its special id), else a chunk (tkv 1 = 0) that ends before the next marker. Reads at most +note tkw[i .. i + 80): a caller streaming a file keeps 80 bytes ahead of i until the file ends. +fn tknext i ulong n ulong chat bool to ulong +put tkv 1 0 +e = add i 65 +if lt n e +e = n +end +if chat +m = tkmark i n +if ne m 0 +put tkv 1 m +ret ulong get tkml sub m 256 +end +j = add i 1 +while lt j e bound 65 +if eq get tkw j 60 +if ne tkmark j n 0 +e = j +break +end +end +j = add j 1 +end +end +ret tkclen i e +end + +note u16 and u64 little-endian at tkmf[p] +fn tkrd16 p ulong to ulong +ret or ulong get tkmf p shl ulong get tkmf add p 1 8 +end +fn tkrd64 p ulong to ulong +v = ulong 0 +for k ulong 8 +v = or v shl ulong get tkmf add p k mul k 8 +end +ret v +end +fn tkwr64 p ulong v ulong to void +for k ulong 8 +put tkmf add p k uchar and shr v mul k 8 255 +end +end + +note FNV-1a 64 of a merges file of n bytes: bytes 0 .. 23, then 32 .. n - 1 (all but the field) +fn tkfnv n ulong to ulong +h = ulong 14695981039346656037 +for k ulong 24 +h = mul xor h ulong get tkmf k 1099511628211 +end +for k ulong sub n 32 +h = mul xor h ulong get tkmf add 32 k 1099511628211 +end +ret h +end + +note header of a merges file of V = v whose pairs are already at tkmf[32 ..); returns its length +fn tkseal v ulong to ulong +for k ulong 8 +put tkmf k get tkmagic k +end +tkwr64 8 v +tkwr64 16 16 +n = add 32 mul 4 sub v TKFIRST +tkwr64 24 tkfnv n +ret n +end + +note may pair member a appear in merge token t? (a byte, or an earlier merge; never a special) +fn tkpok a ulong t ulong to bool +ret or lt a 256 and ge a TKFIRST lt a t +end + +note rank table: slot of key a 32768 + b +fn tkslot key ulong to ulong +ret shr mul add key 1 ulong 11400714819323198485 48 +end + +note put pair key -> merge token t in the rank table; false when the key is there already +fn tkrins key ulong t ulong to bool +s = tkslot key +for q ulong 65536 +k = ulong get tkrk s +if eq k 0 +put tkrk s uint add key 1 +put tkrt s ushort t +ret true +end +if eq k add key 1 +ret false +end +s = and add s 1 65535 +end +ret false +end + +note merge token of pair (a, b), or 65535 when (a, b) is not a merge +fn tkrank a ulong b ulong to ulong +key = or shl a 15 b +s = tkslot key +for q ulong 65536 +k = ulong get tkrk s +if eq k 0 +ret 65535 +end +if eq k add key 1 +ret ulong get tkrt s +end +s = and add s 1 65535 +end +ret 65535 +end + +note check merge k of a file being loaded (tkmf[32 + 4 k ..)) and use it; exit 26 on a fault +fn tkld1 k ulong to void +p = add 32 mul 4 k +a = tkrd16 p +b = tkrd16 add p 2 +t = add TKFIRST k +if not and tkpok a t tkpok b t +exit 26 +end +l = add ulong get tkln a ulong get tkln b +if gt l 64 +exit 26 +end +if not tkrins or shl a 15 b t +exit 26 +end +put tkma t ushort a +put tkmb t ushort b +put tkln t uchar l +end + +note check tkmf[0 .. n) as an OLLMTOK1 merges file (FORMAT.md section 2) and use it; returns its +note V. Exit 26 on any fault: length, magic, V, special count, length for V, checksum, a pair +note member that is a special or not below its own token, a token longer than 64 bytes, a pair +note that is already a merge. +fn tkload n ulong to ulong +put tkv 0 0 +if or lt n 32 gt n TKMFCAP +exit 26 +end +for k ulong 8 +if ne get tkmf k get tkmagic k +exit 26 +end +end +v = tkrd64 8 +if or lt v TKFIRST gt v TKVMAX +exit 26 +end +if ne tkrd64 16 16 +exit 26 +end +if ne n add 32 mul 4 sub v TKFIRST +exit 26 +end +if ne tkfnv n tkrd64 24 +exit 26 +end +for s ulong 65536 +put tkrk s 0 +end +for t ulong 256 +put tkln t 1 +end +for k ulong 16 +put tkln add 256 k 0 +end +for k ulong TKNSP +put tkln add 256 k get tkml k +end +for k ulong sub v TKFIRST +tkld1 k +end +put tkv 0 v +ret v +end + +note is t a token of the loaded merges? (below V and not a reserved special) +fn tkvalid t ulong to bool +if ge t get tkv 0 +ret false +end +ret or lt t add 256 TKNSP ge t TKFIRST +end + +note replace in tkct[0 .. m) every pair of merge token t, left to right without overlap +fn tkrepl m ulong t ulong to ulong +a = get tkma t +b = get tkmb t +w = ulong 0 +j = ulong 0 +while lt j m bound 128 +x = get tkct j +z = ushort 65535 +if lt add j 1 m +z = get tkct add j 1 +end +if and eq x a eq z b +put tkct w ushort t +j = add j 2 +else +put tkct w x +j = add j 1 +end +w = add w 1 +end +ret w +end + +note encode the chunk tkw[i .. i + l) (l <= 64) into tkct (FORMAT.md section 4: the present merge +note of lowest rank, until none is left); returns the token count +fn tkencc i ulong l ulong to ulong +for k ulong l +put tkct k ushort get tkw add i k +end +m = l +dn = false +while and not dn gt m 1 bound 64 +best = ulong 65535 +for j ulong sub m 1 +r = tkrank ulong get tkct j ulong get tkct add j 1 +if lt r best +best = r +end +end +if eq best 65535 +dn = true +else +m = tkrepl m best +end +end +ret m +end + +note the bytes of valid token t into tkdb; returns their count (1 .. 64) +fn tkdec1 t ulong to ulong +if and ge t 256 lt t TKFIRST +k = sub t 256 +o = ulong get tkmo k +l = ulong get tkml k +for j ulong l +put tkdb j get tkmarks add o j +end +ret l +end +put tksk 0 ushort t +sp = ulong 1 +w = ulong 0 +while gt sp 0 bound 200 +sp = sub sp 1 +x = ulong get tksk sp +if lt x 256 +put tkdb w uchar x +w = add w 1 +else +put tksk sp get tkmb x +put tksk add sp 1 get tkma x +sp = add sp 2 +end +end +ret w +end diff --git a/native/omegallm/tok/tkfit.om b/native/omegallm/tok/tkfit.om new file mode 100644 index 0000000..c1e4530 --- /dev/null +++ b/native/omegallm/tok/tkfit.om @@ -0,0 +1,432 @@ +note SPDX-License-Identifier: AGPL-3.0-only +note omegallm tok/tkfit.om: the merge learner of the own BPE (FORMAT.md section 5) and the chunk +note type table that tokenc also uses as its encode cache. No host words; about 441 MiB of +note globals, so it lives only in the standalone program ollm-tok, never in ollm. +note Fit counts chunk types (tkcli.om tcscan), then merges with a hashed pair table, per-pair lists +note of the types that hold the pair and a lazy max-heap keyed count << 30 | (32767 - a) << 15 | +note (32767 - b): the largest key is the largest count, then the smallest a, then the smallest b. +note A pair's count only falls once its newest token exists, so a popped key whose count is still +note current is the true maximum; a stale one is pushed again with its current count (if any). +note A merged pair never appears again, so the list nodes of its pair go back to a free list. +note Counts stay below 2^34 because tcscan refuses texts of 2^33 bytes or more. +note Exits: 21 a capacity below; 28 no pair left to merge. +note Capacities: 2097152 chunk types, 16777216 pool symbols, 6000000 pairs, 16777216 list nodes. +const TFTCAP ulong 2097152 +const TFHMSK ulong 4194303 +const TFSCAP ulong 16777216 +const TFPCAP ulong 6000000 +const TFPMSK ulong 8388607 +const TFNCAP ulong 16777216 +global tfhs uint 4194304 +global tfto uint 2097152 +global tftl uchar 2097152 +global tftn uchar 2097152 +global tftc ulong 2097152 +global tfts uint 2097152 +global tfsy ushort 16777216 +global tfpk uint 8388608 +global tfpc ulong 8388608 +global tfph uint 8388608 +global tfpl uint 8388608 +global tfnl uint 6000000 +global tfnt uint 16777216 +global tfnx uint 16777216 +global tfhp ulong 6000000 +global tfst ulong 16 + +note tfst: 0 types, 1 pool symbols used, 2 chunks, 3 bytes scanned, 4 special markers, 5 pairs, +note 6 new pairs of this merge (tfnl), 7 list nodes made, 8 heap entries, 9 free node list head +note (node + 1; 0 empty), 10 tokens written (tokenc). + +note FNV-1a 64 of tkw[i .. i + l) +fn tfhash i ulong l ulong to ulong +h = ulong 14695981039346656037 +for k ulong l +h = mul xor h ulong get tkw add i k 1099511628211 +end +ret h +end + +note does type y hold the bytes tkw[i .. i + l)? +fn tfsame y ulong i ulong l ulong to bool +if ne ulong get tftl y l +ret false +end +o = ulong get tfto y +for k ulong l +if ne ulong get tfsy add o k ulong get tkw add i k +ret false +end +end +ret true +end + +note new type in empty hash slot s for tkw[i .. i + l), its bytes as pool symbols; TFTCAP when +note the type table or the pool is full +fn tfins s ulong i ulong l ulong to ulong +nt = get tfst 0 +o = get tfst 1 +if ge nt TFTCAP +ret TFTCAP +end +if gt add o l TFSCAP +ret TFTCAP +end +put tfhs s uint add nt 1 +put tfto nt uint o +put tftl nt uchar l +put tftn nt uchar l +put tftc nt 0 +put tfts nt 0 +for k ulong l +put tfsy add o k ushort get tkw add i k +end +put tfst 0 add nt 1 +put tfst 1 add o l +ret nt +end + +note type id of the chunk tkw[i .. i + l), added when absent; TFTCAP when absent and full +fn tffind i ulong l ulong to ulong +s = and tfhash i l TFHMSK +for q ulong 4194305 +y = ulong get tfhs s +if eq y 0 +ret tfins s i l +end +y = sub y 1 +if tfsame y i l +ret y +end +s = and add s 1 TFHMSK +end +ret TFTCAP +end + +note fit: count one chunk +fn tfcount i ulong l ulong to void +y = tffind i l +if eq y TFTCAP +exit 21 +end +put tftc y add get tftc y 1 +put tfst 2 add get tfst 2 1 +end + +note pair table slot of key a 32768 + b, made (count 0, no list) when absent; new slots are listed +note in tfnl; exit 21 past TFPCAP pairs +fn tfpslot key ulong to ulong +s = shr mul add key 1 ulong 11400714819323198485 41 +for q ulong 8388609 +k = ulong get tfpk s +if eq k 0 +nf = get tfst 5 +if ge nf TFPCAP +exit 21 +end +put tfpk s uint add key 1 +put tfpc s 0 +put tfph s 0 +put tfpl s 0 +put tfst 5 add nf 1 +nn = get tfst 6 +put tfnl nn uint s +put tfst 6 add nn 1 +ret s +end +if eq k add key 1 +ret s +end +s = and add s 1 TFPMSK +end +ret s +end + +note list type y under pair slot s (once per type in a row), reusing a freed node when there is +note one; exit 21 past TFNCAP nodes +fn tfnode s ulong y ulong to void +if ne ulong get tfpl s add y 1 +put tfpl s uint add y 1 +f = get tfst 9 +q = ulong 0 +if gt f 0 +q = sub f 1 +put tfst 9 ulong get tfnx q +else +q = get tfst 7 +if ge q TFNCAP +exit 21 +end +put tfst 7 add q 1 +end +put tfnt q uint y +put tfnx q get tfph s +put tfph s uint add q 1 +end +end + +fn tfkey c ulong a ulong b ulong to ulong +ret or or shl c 30 shl sub 32767 a 15 sub 32767 b +end + +fn tfhpush x ulong to void +i = get tfst 8 +put tfst 8 add i 1 +dn = false +while and not dn gt i 0 bound 64 +p = div sub i 1 2 +v = get tfhp p +if ge v x +dn = true +else +put tfhp i v +i = p +end +end +put tfhp i x +end + +note pop the heap's largest key (the heap is not empty) +fn tfhpop to ulong +top = get tfhp 0 +n = sub get tfst 8 1 +put tfst 8 n +x = get tfhp n +i = ulong 0 +dn = false +while not dn bound 64 +l = add mul i 2 1 +if ge l n +dn = true +else +c = l +r = add l 1 +if lt r n +if gt get tfhp r get tfhp l +c = r +end +end +v = get tfhp c +if ge x v +dn = true +else +put tfhp i v +i = c +end +end +end +if gt n 0 +put tfhp i x +end +ret top +end + +note tfpc[s] += c and -= c, one big array per function +fn tfpcadd s ulong c ulong to void +put tfpc s add get tfpc s c +end +fn tfpcsub s ulong c ulong to void +put tfpc s sub get tfpc s c +end + +note count the pairs of type y and list y under them +fn tfinty y ulong to void +o = ulong get tfto y +c = get tftc y +for j ulong sub ulong get tftn y 1 +x = ulong get tfsy add o j +z = ulong get tfsy add add o j 1 +s = tfpslot or shl x 15 z +tfpcadd s c +tfnode s y +end +end + +note count the pairs of every type, list the types under them, heap every pair +fn tfinit to void +nt = get tfst 0 +y = ulong 0 +for o ulong 3 +lim = mul add o 1 999999 +if gt lim nt +lim = nt +end +while lt y lim bound 999999 +if gt ulong get tftn y 1 +tfinty y +end +y = add y 1 +end +end +for s ulong 8388608 +k = ulong get tfpk s +if ne k 0 +c = get tfpc s +if gt c 0 +k = sub k 1 +tfhpush tfkey c shr k 15 and k 32767 +end +end +end +end + +note the pair to merge: the slot of the heap's largest current key; exit 28 when none is left. +note Each pair has at most one heap entry, and one pop sequence meets a pair at most twice. +fn tfsel to ulong +for o ulong 13 +q = ulong 0 +while and gt get tfst 8 0 lt q 999999 bound 999999 +q = add q 1 +x = tfhpop +c = shr x 30 +a = sub 32767 and shr x 15 32767 +b = sub 32767 and x 32767 +s = tfpslot or shl a 15 b +cc = get tfpc s +if eq cc c +ret s +end +if gt cc 0 +tfhpush tfkey cc a b +end +end +end +exit 28 +end + +fn tfhas o ulong n ulong a ulong b ulong to bool +for j ulong sub n 1 +x = ulong get tfsy add o j +z = ulong get tfsy add add o j 1 +if and eq x a eq z b +ret true +end +end +ret false +end + +note take count c of every pair in tfsy[o .. o + n) +fn tfsub o ulong n ulong c ulong to void +for j ulong sub n 1 +x = ulong get tfsy add o j +z = ulong get tfsy add add o j 1 +s = tfpslot or shl x 15 z +tfpcsub s c +end +end + +note replace (a, b) by t in tfsy[o .. o + n), left to right without overlap; returns the length +fn tfrpool o ulong n ulong a ulong b ulong t ulong to ulong +w = ulong 0 +j = ulong 0 +while lt j n bound 128 +x = ulong get tfsy add o j +z = ulong 65535 +if lt add j 1 n +z = ulong get tfsy add add o j 1 +end +if and eq x a eq z b +put tfsy add o w ushort t +j = add j 2 +else +put tfsy add o w ushort x +j = add j 1 +end +w = add w 1 +end +ret w +end + +note add count c of every pair in tfsy[o .. o + m) of type y; list y under the pairs holding t +fn tfadd o ulong m ulong c ulong y ulong t ulong to void +for j ulong sub m 1 +x = ulong get tfsy add o j +z = ulong get tfsy add add o j 1 +s = tfpslot or shl x 15 z +tfpcadd s c +if or eq x t eq z t +tfnode s y +end +end +end + +note apply merge (a, b) -> t to type y, moving its pair counts +fn tfmtype y ulong a ulong b ulong t ulong to void +o = ulong get tfto y +n = ulong get tftn y +if tfhas o n a b +c = get tftc y +tfsub o n c +m = tfrpool o n a b t +put tftn y uchar m +tfadd o m c y t +end +end + +note free list node e; returns its successor (node + 1; 0 at the end) +fn tffree e ulong to ulong +nx = ulong get tfnx e +put tfnx e uint get tfst 9 +put tfst 9 add e 1 +ret nx +end + +note merge t into type y unless y already met this merge (stamp t - 271) +fn tfvisit y ulong a ulong b ulong t ulong to void +st = uint sub t 271 +if ne get tfts y st +put tfts y st +tfmtype y a b t +end +end + +note merge t over every type listed under pair slot s; the walked nodes go to the free list (the +note pair never comes back) +fn tfwalk s ulong a ulong b ulong t ulong to void +nd = ulong get tfph s +put tfph s 0 +for o ulong 17 +q = ulong 0 +while and gt nd 0 lt q 999999 bound 999999 +q = add q 1 +e = sub nd 1 +y = ulong get tfnt e +nd = tffree e +tfvisit y a b t +end +end +end + +note heap every pair slot made by this merge (tfnl[0 .. tfst 6)) that has a count +fn tfnewp to void +nw = get tfst 6 +for i ulong nw +q = ulong get tfnl i +c = get tfpc q +if gt c 0 +kq = sub ulong get tfpk q 1 +tfhpush tfkey c shr kq 15 and kq 32767 +end +end +end + +note merges 0 .. v - 273 into tkma/tkmb and the pair records of tkmf (tkseal adds the header) +fn tfmerge v ulong to void +for k ulong sub v TKFIRST +s = tfsel +key = sub ulong get tfpk s 1 +a = shr key 15 +b = and key 32767 +t = add TKFIRST k +put tkma t ushort a +put tkmb t ushort b +p = add 32 mul 4 k +put tkmf p uchar and a 255 +put tkmf add p 1 uchar shr a 8 +put tkmf add p 2 uchar and b 255 +put tkmf add p 3 uchar shr b 8 +put tfst 6 0 +tfwalk s a b t +tfnewp +end +end diff --git a/native/omegallm/tok/tkio.om b/native/omegallm/tok/tkio.om new file mode 100644 index 0000000..afcd52e --- /dev/null +++ b/native/omegallm/tok/tkio.om @@ -0,0 +1,233 @@ +note SPDX-License-Identifier: AGPL-3.0-only +note omegallm tok/tkio.om: the Linux platform unit of the standalone tokenizer program ollm-tok +note (units tkcore, tkio, tkfit, tkcli, concatenated in that order: globals before their uses). It is the only tok unit +note that uses host words: arguments, the positioned reads behind the text window, the buffered +note output file, the atomic merges save (PATH.tmp, fsync, rename) and stdout. Exits: 2 usage, 70 I/O. +global tkarg uchar 4100 +global tkpth uchar 4120 +global tkpk uchar 8300 +global tkob uchar 65536 +global tkobs long 2 +global tkso uchar 4096 +global tksn ulong 1 + +note tkobs: 0 bytes in tkob, 1 output fd + +fn tkargc to ulong +ret ulong argcnt +end + +note argv[i] into tkarg; returns its length (1 .. 4096) or exits 2 +fn tkargp i ulong to ulong +r = argread i tkarg 0 4096 +if or le r 0 gt r 4096 +exit 2 +end +ret ulong r +end + +fn main to int +if lt tkargc 2 +exit 2 +end +r = tkcmd +tkpfl +ret r +end + +note read up to n bytes of the file argv[ai] from byte pos into tkw[off ..); returns the bytes +note read (fewer only at the end of the file). Each pread pass adds a byte or ends. +fn tkrdw ai ulong pos ulong off ulong n ulong to ulong +pl = tkargp ai +fd = int fopen tkarg 0 pl 0 0 +if lt fd 0 +exit 70 +end +p = ulong 0 +dn = false +for o ulong 3 +while and not dn lt p n bound 999999 +r = pread fd tkw add off p sub n p long add pos p +if lt r 0 +exit 70 +end +if eq r 0 +dn = true +else +p = add p ulong r +end +end +end +if ne fclose fd 0 +exit 70 +end +ret p +end + +note read the first 131072 bytes (or fewer) of the file argv[ai] into tkmf; returns the count +fn tkrdm ai ulong to ulong +pl = tkargp ai +fd = int fopen tkarg 0 pl 0 0 +if lt fd 0 +exit 70 +end +p = ulong 0 +dn = false +while and not dn lt p 131072 bound 140000 +r = pread fd tkmf p sub 131072 p long p +if lt r 0 +exit 70 +end +if eq r 0 +dn = true +else +p = add p ulong r +end +end +if ne fclose fd 0 +exit 70 +end +ret p +end + +note the output file argv[i], created or emptied +fn tkwopen i ulong to void +pl = tkargp i +fd = fopen tkarg 0 pl 577 420 +if lt fd 0 +exit 70 +end +put tkobs 0 0 +put tkobs 1 fd +end + +fn tkwflush to void +n = ulong get tkobs 0 +fd = int get tkobs 1 +p = ulong 0 +while lt p n bound 65537 +w = write fd tkob p sub n p +if le w 0 +exit 70 +end +p = add p ulong w +end +put tkobs 0 0 +end + +fn tkwb c ulong to void +n = ulong get tkobs 0 +if ge n 65536 +tkwflush +n = ulong 0 +end +put tkob n uchar c +put tkobs 0 long add n 1 +end + +fn tkwclose to void +tkwflush +fd = int get tkobs 1 +if ne fsync fd 0 +exit 70 +end +if ne fclose fd 0 +exit 70 +end +end + +note write tkmf[0 .. n) to argv[ai] as PATH.tmp, fsync, then rename over PATH +fn tkmsave ai ulong n ulong to void +pl = tkargp ai +if gt pl 2000 +exit 2 +end +for i ulong pl +put tkpth i get tkarg i +end +put tkpth pl 46 +put tkpth add pl 1 116 +put tkpth add pl 2 109 +put tkpth add pl 3 112 +fd = int fopen tkpth 0 add pl 4 577 420 +if lt fd 0 +exit 70 +end +p = ulong 0 +while lt p n bound 140000 +w = write fd tkmf p sub n p +if le w 0 +exit 70 +end +p = add p ulong w +end +if ne fsync fd 0 +exit 70 +end +if ne fclose fd 0 +exit 70 +end +tkren pl +end + +note rename tkpth[0 .. pl + 4) to tkpth[0 .. pl) via a packed two-path list +fn tkren pl ulong to void +put tkpk 0 2 +put tkpk 1 0 +put tkpk 2 uchar and add pl 4 255 +put tkpk 3 uchar shr add pl 4 8 +for i ulong add pl 4 +put tkpk add 4 i get tkpth i +end +q = add 8 pl +put tkpk q uchar and pl 255 +put tkpk add q 1 uchar shr pl 8 +for j ulong pl +put tkpk add add q 2 j get tkpth j +end +r = renames tkpk 0 add add q 2 pl 0 +if ne r 0 +exit 70 +end +end + +fn tkpfl to void +n = get tksn 0 +p = ulong 0 +while lt p n bound 4097 +w = write 1 tkso p sub n p +if le w 0 +exit 70 +end +p = add p ulong w +end +put tksn 0 0 +end + +note one byte to stdout +fn tkpc c ulong to void +n = get tksn 0 +if ge n 4096 +tkpfl +n = ulong 0 +end +put tkso n uchar c +put tksn 0 add n 1 +end + +note size in bytes of the file argv[ai] +fn tkfsz ai ulong to ulong +pl = tkargp ai +fd = int fopen tkarg 0 pl 0 0 +if lt fd 0 +exit 70 +end +sz = fseek fd 0 2 +if lt sz 0 +exit 70 +end +if ne fclose fd 0 +exit 70 +end +ret ulong sz +end diff --git a/tests/omegallm/tok/.crumb b/tests/omegallm/tok/.crumb new file mode 100644 index 0000000..53ffd3e --- /dev/null +++ b/tests/omegallm/tok/.crumb @@ -0,0 +1,19 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-11-06T22:13:40Z", + "compiler": "crumb-compile/1", + "digest": "sha256:27258cc23b849f47d7e2fde68aa9917e3d8b3a396553b106f0e3662d1724736a", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 0, + "generated_at_commit": "ac4a7c1ed20e8aea37f604e91f438b06e4511c8b", + "source_tree": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + } + }, + "name": "tok-tests", + "purpose": "Build, oracle check, compression measurement and format spec of the own BPE tokenizer ollm-tok: build.sh, check.sh (Python test oracle oracle.py), ratio.sh, FORMAT.md, synthetic fixtures chat.txt and unicode.txt.", + "schema_version": "1.0.0" +} diff --git a/tests/omegallm/tok/FORMAT.md b/tests/omegallm/tok/FORMAT.md new file mode 100644 index 0000000..69d6cef --- /dev/null +++ b/tests/omegallm/tok/FORMAT.md @@ -0,0 +1,129 @@ +# Omega LLM own BPE tokenizer: format OLLMTOK1 + +This tokenizer belongs to Omega LLM. Its code lives in `native/omegallm/tok/*.om`, it is built with the pinned seeded omc (omega-mv e5b32567), and it learns its merges only from text we choose. It uses no outside tokenizer, vocabulary or model. The older v1 tokenizer, `bpe.om` (`OLLMBPE1`, V ≤ 4096), is a separate thing and is unchanged. + +## 1. Token ids + +| Ids | Meaning | +|---|---| +| 0 – 255 | the byte with that value | +| 256 | `<\|end\|>`: ends a turn | +| 257 | `<\|system\|>`: starts a system turn | +| 258 | `<\|user\|>`: starts a user turn | +| 259 | `<\|assistant\|>`: starts an assistant turn | +| 260 | `<\|tool_call\|>`: starts a tool call (inside an assistant turn) | +| 261 | `<\|tool_result\|>`: starts a tool result turn | +| 262 | `<\|pad\|>`: padding; carries no text | +| 263 | `<\|doc\|>`: starts a document; separates training documents | +| 264 – 271 | reserved; never valid (decode exits 25, a merge using one is refused) | +| 272 – V−1 | merge k = id − 272, in rank order (lower id merges first) | + +`272 ≤ V ≤ 32768`. Token files are u16 little-endian with no header. + +## 2. Merges file + +All integers are little-endian. + +| Offset | Size | Field | +|---|---|---| +| 0 | 8 | magic `OLLMTOK1` | +| 8 | 8 | V | +| 16 | 8 | special id count, always 16 (ids 256 – 271) | +| 24 | 8 | FNV-1a 64 of every byte of the file except bytes 24 – 31 | +| 32 | 4 (V − 272) | merge k: u16 a, u16 b; token 272 + k is a followed by b | + +A loader refuses the file with exit 26 when any of these hold: +- the length is below 32 or above 130016; +- the magic is wrong; +- V is outside 272 … 32768; +- the special count is not 16; +- the length is not 32 + 4 (V − 272); +- the checksum differs; +- a pair member is a special or reserved id, or is not a byte or an earlier merge; +- a token would decode to more than 64 bytes; +- a pair appears twice. + +FNV-1a catches any single changed byte. The file is integrity-checked, but it is not signed. + +## 3. Chunks + +Merges never cross a chunk boundary. Each byte belongs to one class: +- **A**: digits, ASCII letters, and every byte ≥ 128, so UTF-8 letters stay whole; +- **W**: 9 – 13 and space; +- **P**: every other byte. + +A text is cut left to right. At position i, with E = min(i + 64, n): + +1. A space followed by a byte that is not W makes one chunk: the space, then the longest run of the next byte's class. +2. Otherwise the chunk is the longest run of bytes of the class of byte i. +3. A W run of 2 or more bytes that ends with a space, and is followed by a byte that is not W, gives that last space to the next chunk, so `" hello"` becomes `" "` and `" hello"`. +4. A chunk never runs past E, so no chunk is longer than 64 bytes. + +## 4. Encoding and decoding + +In each chunk, repeatedly find the present adjacent pair with the lowest merge id and replace every occurrence of it, left to right and without overlap. Stop when no pair is a merge. This gives the same result as applying the merges in rank order. + +Decoding writes the bytes of each token. A special id writes its marker's bytes. The round trip `decode(encode(x)) = x` is exact for every byte string in both modes, including invalid UTF-8. + +## 5. Training + +Training counts chunk types, then repeats V − 272 times: +1. Take the adjacent pair with the largest count over all types, weighted by type count. Break ties by the smallest a, then the smallest b. +2. Record the pair as the next merge. +3. Replace it in every type, left to right and without overlap. + +If no pair is left before V is reached, training exits 28 and writes no file. The same text, mode, V and MAXBYTES always give the same file, byte for byte. Texts of 2^33 bytes or more are refused with exit 21. + +## 6. Chat format and the injection rule + +A conversation is a sequence of turns: + +``` +<|doc|><|system|>...<|end|><|user|>...<|end|><|assistant|>...<|tool_call|>{json}<|end|><|tool_result|>...<|end|><|assistant|>...<|end|> +``` + +- In **chat** mode, every exact marker string becomes its special id. Any other text, including near misses such as `<|user` or `<|USER|>`, is ordinary text, and chunks never span a marker. +- In **raw** mode, no special id is ever produced, so marker strings are just bytes. + +**Injection rule:** content that did not come from the conversation's own structure must be encoded in raw mode, segment by segment, with the specials inserted by the program that builds the turn. This covers user text, tool output, files and web pages. Then a user cannot forge `<|assistant|>` or `<|tool_result|>`. Chat mode is only for trusted, already-structured text, such as our own training transcripts. + +## 7. Program `ollm-tok` + +Build it with `sh tests/omegallm/tok/build.sh`. It combines the units `tkcore tkio tkfit tkcli`. + +``` +ollm-tok toktrain MODE TEXT MERGES V MAXBYTES -> T V types chunks bytes markers pairs nodes +ollm-tok tokenc MODE MERGES TEXT TOKS -> E V bytes chunks tokens markers +ollm-tok tokdec MERGES TOKS OUT -> D V tokens bytes +ollm-tok tokinfo MERGES -> I V merges checksum +``` + +`MODE` is `raw` or `chat`. A `MAXBYTES` of 0 means the whole text. The merges file is written as `MERGES.tmp`, fsynced, and then renamed over `MERGES`. `tokdec` checks every token before it creates `OUT`. + +Exit codes: + +| Code | Meaning | +|---|---| +| 2 | usage | +| 21 | a capacity limit was reached, the text is too big, or the token file has an odd length | +| 25 | invalid token | +| 26 | bad merges file | +| 28 | no pair left | +| 70 | I/O error | + +Trainer capacities: + +| Item | Limit | +|---|---| +| Chunk types | 2,097,152 | +| Pool symbols | 16,777,216 | +| Pairs | 6,000,000 | +| List nodes | 16,777,216 | + +`tkcore.om` uses about 1.7 MiB of globals and no host words. A model program can concatenate it and call `tkinit`, `tkload`, `tknext`, `tkencc` and `tkdec1`. The trainer, at about 441 MiB, stays in `ollm-tok` because `ollm` already uses about 954 MiB of the 1 GiB global limit. + +## 8. Tests + +- `check.sh` compares the program against the Python test oracle `oracle.py`, which is used for verification only. It covers training, encoding, decoding, round trips, specials, determinism, refusals of corrupted files and every exit code. +- `ratio.sh` measures compression on a public-domain sample. +- The fixtures `chat.txt` and `unicode.txt` are synthetic and were written for these tests. diff --git a/tests/omegallm/tok/build.sh b/tests/omegallm/tok/build.sh new file mode 100755 index 0000000..a97d002 --- /dev/null +++ b/tests/omegallm/tok/build.sh @@ -0,0 +1,27 @@ +#!/bin/sh +# Build ollm-tok, the standalone own-BPE tokenizer program (tests/omegallm/tok/FORMAT.md), from +# native/omegallm/tok/*.om with the pinned seeded omc (omega-mv e5b32567, aarch64 Linux). +# Usage: sh tests/omegallm/tok/build.sh +# Env: OMC (default ../omega-mv/seed/out/omc beside this clone), OUT (default ../build beside it), +# CORES (taskset core list, default 18-19; omc runs at nice 10). +# Units, in this order (a global must come before its first use): tkcore (format, chunker, encoder, +# decoder; host-free, small enough for a model unit to concatenate), tkio (the Linux platform unit +# and fn main), tkfit (merge learner, about 441 MiB of globals) and tkcli (the commands). +set -eu +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../../.." && pwd) +src="$root/native/omegallm/tok" +OMC=${OMC:-$root/../omega-mv/seed/out/omc} +OUT=${OUT:-$root/../build} +CORES=${CORES:-18-19} +PIN=2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f +[ -x "$OMC" ] || { echo "tok/build: omc not found at $OMC (set OMC)" >&2; exit 2; } +got=$(sha256sum "$OMC" | cut -d' ' -f1) +[ "$got" = "$PIN" ] || { echo "tok/build: omc sha256 $got is not the pin $PIN" >&2; exit 2; } +mkdir -p "$OUT" +cat "$src/tkcore.om" "$src/tkio.om" "$src/tkfit.om" "$src/tkcli.om" > "$OUT/ollm-tok.om" +taskset -c "$CORES" nice -n 10 "$OMC" < "$OUT/ollm-tok.om" > "$OUT/ollm-tok.part" || { + rc=$?; rm -f "$OUT/ollm-tok.part"; echo "tok/build: omc exit $rc" >&2; exit "$rc"; } +chmod 755 "$OUT/ollm-tok.part" +mv "$OUT/ollm-tok.part" "$OUT/ollm-tok" +echo "tok/build: $OUT/ollm-tok sha256 $(sha256sum "$OUT/ollm-tok" | cut -d' ' -f1) omc $PIN" diff --git a/tests/omegallm/tok/chat.txt b/tests/omegallm/tok/chat.txt new file mode 100644 index 0000000..17005e1 --- /dev/null +++ b/tests/omegallm/tok/chat.txt @@ -0,0 +1,12 @@ +<|doc|><|system|>You are a careful assistant. Answer briefly; cite the file and line.<|end|> +<|user|>What does `tkclen` return for " hello" and for "\t\tx"?<|end|> +<|assistant|>It returns the white-space run without its last space, so the space joins the word.<|end|> +<|assistant|><|tool_call|>{"name": "read", "args": {"path": "tok/tkcore.om:85-119"}}<|end|> +<|tool_result|>fn tkclen i ulong n ulong to ulong +c = ulong get tkw i +...<|end|> +<|user|>Is "<|user" a marker? And "<|end>" or "<||>" or "<|USER|>"? What about x<|user|>y?<|end|> +<|assistant|>Only exact markers count: <|<|end|> has one, <|end|<|end|> has one too.<|end|> +<|pad|><|pad|><|pad|> +Numbers 12345678901234567890 and 3.14159, punctuation !!!??? and ---- and tabs end. +<|end|> \ No newline at end of file diff --git a/tests/omegallm/tok/check.sh b/tests/omegallm/tok/check.sh new file mode 100755 index 0000000..380e947 --- /dev/null +++ b/tests/omegallm/tok/check.sh @@ -0,0 +1,209 @@ +#!/bin/sh +# Own BPE tokenizer check (tests/omegallm/tok/FORMAT.md): ollm-tok toktrain, tokenc, tokdec and +# tokinfo against the test oracle tests/omegallm/tok/oracle.py (Python, verification only) on +# synthetic texts and fixtures, exact round trips on random bytes and Unicode, determinism, every +# exit code, and refusal of corrupted merges files. Needs no data directory; runs in about a minute. +# +# BIN=path/to/ollm-tok sh tests/omegallm/tok/check.sh +# +# Environment: BIN (required, from tests/omegallm/tok/build.sh), WORK (scratch, default +# scratch-tok-check beside the clone), CORES (taskset core list, default 18-19). The whole script +# runs at nice 10 inside bwrap with no network; only WORK is writable. +# One PASS/FAIL line per case, then `SUMMARY pass=N fail=M`; exit 0 iff fail=0. +# Negative controls: the comparison must see a deliberately changed token file, and every +# corrupted merges file (flipped byte, wrong length, rehashed bad pair) must be refused with 26. +set -u +here=$(cd "$(dirname "$0")" && pwd) +BIN=${BIN:?set BIN to the ollm-tok binary} +BIN=$(cd "$(dirname "$BIN")" && pwd)/$(basename "$BIN") +WORK=${WORK:-$here/../../../../scratch-tok-check} +CORES=${CORES:-18-19} +if [ -z "${TOK_CHECK_PINNED:-}" ]; then + mkdir -p "$WORK" + WORK=$(cd "$WORK" && pwd) + export TOK_CHECK_PINNED=1 WORK BIN + exec taskset -c "$CORES" nice -n 10 bwrap --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp \ + --bind "$WORK" "$WORK" --unshare-net --die-with-parent -- sh "$0" "$@" +fi +export PYTHONDONTWRITEBYTECODE=1 +ORACLE="$here/oracle.py" +[ -x "$BIN" ] || { echo "tok-check: BIN $BIN is not executable" >&2; exit 2; } +IN="$WORK/in" REF="$WORK/ref" GOT="$WORK/bin" +rm -rf "$IN" "$REF" "$GOT" +mkdir -p "$IN" "$REF" "$GOT" +echo "tok-check: bin sha256=$(sha256sum "$BIN" | cut -c1-16) cores=$CORES" + +pass=0 fail=0 +ok() { echo "PASS $1${2:+ ($2)}"; pass=$((pass + 1)); } +ko() { echo "FAIL $1${2:+ ($2)}" | sed "s|$WORK/||g"; fail=$((fail + 1)); } +# r DIR TAG CMD...: run CMD in DIR; TAG.out, TAG.err, TAG.rc +r() { _d=$1 _t=$2; shift 2; (cd "$_d" && "$@" >"$_t.out" 2>"$_t.err"; echo $? >"$_t.rc"); } +both() { _t=$1; shift; r "$REF" "$_t" python3 "$ORACLE" "$@"; r "$GOT" "$_t" "$BIN" "$@"; } +rc() { cat "$1/$2.rc"; } +# chk NAME TAG RC [FILE|!FILE]...: both exits must be RC, both stdouts equal (the binary's T line +# cut to six fields), each FILE equal in both dirs, each !FILE absent from both dirs +chk() { + _n=$1 _t=$2 _rc=$3; shift 3 + _a=$(rc "$REF" "$_t") _b=$(rc "$GOT" "$_t") + if [ "$_a" != "$_rc" ] || [ "$_b" != "$_rc" ]; then ko "$_n" "exit oracle=$_a bin=$_b want $_rc"; return; fi + if [ "$(cat "$REF/$_t.out")" != "$(cut -d' ' -f1-6 "$GOT/$_t.out")" ]; then + ko "$_n" "stdout oracle='$(cat "$REF/$_t.out")' bin='$(cat "$GOT/$_t.out")'"; return; fi + for _f in "$@"; do + case $_f in + !*) _f=${_f#!} + if [ -e "$REF/$_f" ] || [ -e "$GOT/$_f" ]; then ko "$_n" "$_f left behind"; return; fi ;; + *) if ! cmp -s "$REF/$_f" "$GOT/$_f"; then ko "$_n" "$_f differs"; return; fi ;; + esac + done + ok "$_n" "$(cut -d' ' -f1-6 "$GOT/$_t.out" | tr -d '\n')" +} +# rt NAME MERGES MODE TEXT: binary encode then decode must give TEXT back byte for byte +rt() { + _n=$1 _m=$2 _mode=$3 _x=$4 + r "$GOT" rt "$BIN" tokenc "$_mode" "$_m" "$_x" rt.tok + r "$GOT" rtd "$BIN" tokdec "$_m" rt.tok rt.back + if [ "$(rc "$GOT" rt)" != 0 ] || [ "$(rc "$GOT" rtd)" != 0 ]; then + ko "$_n" "exit enc=$(rc "$GOT" rt) dec=$(rc "$GOT" rtd)"; return; fi + if cmp -s "$_x" "$GOT/rt.back"; then ok "$_n" "$(cat "$GOT/rt.out")"; else ko "$_n" "decoded bytes differ"; fi +} +# flip FILE OFFSET: xor the byte at OFFSET with 1 +flip() { + _v=$(od -An -tu1 -j"$2" -N1 "$1" | tr -d ' ') + printf "\\$(printf %03o $((_v ^ 1)))" | dd of="$1" bs=1 seek="$2" conv=notrunc 2>/dev/null +} +# spec FILE: how many u16 tokens of FILE are special ids (256 .. 271) +spec() { od -An -tu2 -v "$1" | tr -s ' ' '\n' | awk '$1 >= 256 && $1 < 272 { n++ } END { print n + 0 }'; } + +python3 "$ORACLE" gen 400000 1 "$IN/g1.txt" +python3 "$ORACLE" gen 3200000 2 "$IN/g2.txt" +head -c 200000 /dev/urandom > "$IN/rand200k.bin" +head -c 1048576 /dev/urandom > "$IN/rand1m.bin" +cat "$here/chat.txt" "$IN/g1.txt" "$here/chat.txt" > "$IN/chatmix.txt" +cat "$here/unicode.txt" > "$IN/uni.txt" +printf '\377\376\303(\355\240\200\300\257 \360\237\230 end\200\n' >> "$IN/uni.txt" +echo "tok-check: inputs rand1m sha256=$(sha256sum "$IN/rand1m.bin" | cut -c1-16) g2=$(wc -c < "$IN/g2.txt") bytes" + +# 1. usage and argument errors +r "$GOT" u0 "$BIN" +both u1 bogus +both u2 toktrain raw "$IN/g1.txt" m.bin 1000 +both u3 toktrain RAW "$IN/g1.txt" m.bin 1000 0 +both u4 toktrain raw "$IN/g1.txt" m.bin 271 0 +both u5 toktrain raw "$IN/g1.txt" m.bin 32769 0 +both u6 toktrain raw "$IN/g1.txt" m.bin 10a0 0 +[ "$(rc "$GOT" u0)" = 2 ] && ok "usage: no command exits 2" || ko "usage: no command" "exit $(rc "$GOT" u0)" +chk "usage: unknown command" u1 2 +chk "usage: wrong argument count" u2 2 '!m.bin' +chk "usage: unknown mode" u3 2 '!m.bin' +chk "usage: V 271 below 272" u4 2 '!m.bin' +chk "usage: V 32769 above 32768" u5 2 '!m.bin' +chk "usage: V not a number" u6 2 '!m.bin' +r "$GOT" u7 "$BIN" tokinfo "$IN/absent.bin" +[ "$(rc "$GOT" u7)" = 70 ] && ok "missing merges file exits 70" || ko "missing merges file" "exit $(rc "$GOT" u7)" + +# 2. against the oracle: training, encoding, decoding, raw and chat +both tr1 toktrain raw "$IN/g1.txt" m1.bin 1500 0 +chk "train raw V=1500 on 400 kB synthetic: same merges file" tr1 0 m1.bin +both tr2 toktrain chat "$IN/chatmix.txt" m2.bin 1200 0 +chk "train chat V=1200 on chat fixture + synthetic: same merges file" tr2 0 m2.bin +both tr3 toktrain raw "$IN/g2.txt" m3.bin 800 250000 +chk "train raw MAXBYTES=250000 of a 3.2 MB text: same merges file" tr3 0 m3.bin +both tr4 toktrain raw "$IN/rand200k.bin" m4.bin 600 0 +chk "train raw V=600 on 200 kB random bytes: same merges file" tr4 0 m4.bin +both in1 tokinfo "$IN/g1.txt" +chk "tokinfo refuses a text file" in1 26 +cp "$GOT/m1.bin" "$IN/m1.bin"; cp "$GOT/m2.bin" "$IN/m2.bin"; cp "$GOT/m4.bin" "$IN/m4.bin" +both in2 tokinfo "$IN/m1.bin" +chk "tokinfo V, merges, checksum" in2 0 +both en1 tokenc raw "$IN/m1.bin" "$IN/g2.txt" t1.tok +chk "encode raw 3.2 MB (window refills): same tokens" en1 0 t1.tok +both en2 tokenc chat "$IN/m2.bin" "$IN/chatmix.txt" t2.tok +chk "encode chat: same tokens and markers" en2 0 t2.tok +both en3 tokenc raw "$IN/m2.bin" "$IN/chatmix.txt" t3.tok +chk "encode raw text holding markers: same tokens" en3 0 t3.tok +both en4 tokenc raw "$IN/m4.bin" "$IN/rand1m.bin" t4.tok +chk "encode raw 1 MiB random bytes: same tokens" en4 0 t4.tok +both en5 tokenc chat "$IN/m1.bin" "$IN/uni.txt" t5.tok +chk "encode chat Unicode + invalid UTF-8: same tokens" en5 0 t5.tok +cp "$GOT/t1.tok" "$IN/t1.tok"; cp "$GOT/t2.tok" "$IN/t2.tok" +both de1 tokdec "$IN/m1.bin" "$IN/t1.tok" d1.txt +chk "decode raw 3.2 MB: same bytes" de1 0 d1.txt +both de2 tokdec "$IN/m2.bin" "$IN/t2.tok" d2.txt +chk "decode chat: same bytes" de2 0 d2.txt + +# 3. exact round trips +rt "round trip raw 1 MiB random bytes (merges from random)" "$IN/m4.bin" raw "$IN/rand1m.bin" +rt "round trip chat 1 MiB random bytes (merges from text)" "$IN/m2.bin" chat "$IN/rand1m.bin" +rt "round trip raw Unicode + invalid UTF-8" "$IN/m1.bin" raw "$IN/uni.txt" +rt "round trip chat Unicode + invalid UTF-8" "$IN/m2.bin" chat "$IN/uni.txt" +rt "round trip chat fixture (chat mode)" "$IN/m2.bin" chat "$here/chat.txt" +rt "round trip chat fixture (raw mode)" "$IN/m2.bin" raw "$here/chat.txt" +rt "round trip 3.2 MB synthetic (chat mode)" "$IN/m1.bin" chat "$IN/g2.txt" +: > "$IN/empty.txt" +rt "round trip empty text" "$IN/m1.bin" raw "$IN/empty.txt" + +# 4. chat special tokens +r "$GOT" sp1 "$BIN" tokenc chat "$IN/m2.bin" "$here/chat.txt" sp1.tok +r "$GOT" sp2 "$BIN" tokenc raw "$IN/m2.bin" "$here/chat.txt" sp2.tok +n1=$(spec "$GOT/sp1.tok") n2=$(spec "$GOT/sp2.tok") f1=$(cut -d' ' -f6 "$GOT/sp1.out") f2=$(cut -d' ' -f6 "$GOT/sp2.out") +nm=$(python3 -c 'import sys; sys.path.insert(0, sys.argv[1]); import oracle; t = open(sys.argv[2], "rb").read(); print(sum(1 for s, c in oracle.pieces(t, True) if s))' "$here" "$here/chat.txt") +if [ "$n1" = "$nm" ] && [ "$f1" = "$nm" ] && [ "$nm" -gt 20 ]; then ok "chat mode: every exact marker is one special token" "$n1 of $nm"; else ko "chat mode specials" "tokens=$n1 field=$f1 oracle=$nm"; fi +if [ "$n2" = 0 ] && [ "$f2" = 0 ]; then ok "raw mode: no special token, markers stay text"; else ko "raw mode specials" "tokens=$n2 field=$f2"; fi +od -An -tu2 -v "$GOT/sp1.tok" | tr -s ' ' '\n' | awk '$1 >= 256 && $1 < 264 { s[$1] = 1 } END { for (k = 256; k < 264; k++) if (!(k in s)) exit 1 }' \ + && ok "chat fixture uses all eight markers 256..263" || ko "chat fixture lacks a marker id" + +# 5. determinism +r "$GOT" dt1 "$BIN" toktrain chat "$IN/chatmix.txt" dt1.bin 1200 0 +r "$GOT" dt2 "$BIN" toktrain chat "$IN/chatmix.txt" dt2.bin 1200 0 +h1=$(sha256sum "$GOT/dt1.bin" | cut -d' ' -f1) h2=$(sha256sum "$GOT/dt2.bin" | cut -d' ' -f1) h0=$(sha256sum "$IN/m2.bin" | cut -d' ' -f1) +[ "$h1" = "$h2" ] && [ "$h1" = "$h0" ] && ok "determinism: three trainings, one merges sha256" "${h1%"${h1#????????????????}"}" || ko "determinism" "$h0 $h1 $h2" +r "$GOT" dt3 "$BIN" tokenc chat "$GOT/dt1.bin" "$IN/chatmix.txt" dt3.tok +cmp -s "$GOT/dt3.tok" "$GOT/t2.tok" && ok "determinism: same tokens from a retrained file" || ko "determinism tokens" +ls "$GOT"/*.tmp >/dev/null 2>&1 && ko "atomic save: a .tmp file was left" || ok "atomic save: no .tmp file left" + +# 6. refusals of corrupted merges files (each exit 26 from tokinfo, tokenc and tokdec, no output) +bad() { + _n=$1 _f=$2 + both b1 tokinfo "$_f" + both b2 tokenc raw "$_f" "$IN/g1.txt" b2.tok + both b3 tokdec "$_f" "$IN/t1.tok" b3.txt + for _t in b1 b2 b3; do + if [ "$(rc "$REF" $_t)" != 26 ] || [ "$(rc "$GOT" $_t)" != 26 ]; then + ko "refuse $_n" "$_t exit oracle=$(rc "$REF" $_t) bin=$(rc "$GOT" $_t)"; return; fi + done + if [ -e "$GOT/b2.tok" ] || [ -e "$GOT/b3.txt" ]; then ko "refuse $_n" "output left behind"; return; fi + ok "refuse $_n" "26 x3" +} +sz=$(wc -c < "$IN/m1.bin") +for o in 0 8 16 24 32 $((sz / 2)) $((sz - 1)); do + cp "$IN/m1.bin" "$IN/f$o.bin"; flip "$IN/f$o.bin" "$o"; bad "flipped byte at $o" "$IN/f$o.bin" +done +head -c $((sz - 1)) "$IN/m1.bin" > "$IN/short1.bin"; bad "one byte short" "$IN/short1.bin" +head -c $((sz - 4)) "$IN/m1.bin" > "$IN/short4.bin"; bad "one pair short" "$IN/short4.bin" +head -c 31 "$IN/m1.bin" > "$IN/short31.bin"; bad "31-byte header" "$IN/short31.bin" +cat "$IN/m1.bin" "$IN/empty.txt" > "$IN/extra.bin"; printf x >> "$IN/extra.bin"; bad "one extra byte" "$IN/extra.bin" +bad "empty file" "$IN/empty.txt" +for k in special reserved forward self dup long; do + python3 "$ORACLE" mkbad $k "$IN/m1.bin" "$IN/k$k.bin"; bad "rehashed bad pair: $k" "$IN/k$k.bin" +done + +# 7. token file errors and an exhausted text +printf '\010\001' > "$IN/tres.tok" +printf '\334\005' > "$IN/tbig.tok" +printf 'abc' > "$IN/todd.tok" +both te1 tokdec "$IN/m1.bin" "$IN/tres.tok" te1.txt +chk "decode refuses reserved id 264 (25, no output)" te1 25 '!te1.txt' +both te2 tokdec "$IN/m1.bin" "$IN/tbig.tok" te2.txt +chk "decode refuses id 1500 = V (25, no output)" te2 25 '!te2.txt' +both te3 tokdec "$IN/m1.bin" "$IN/todd.tok" te3.txt +chk "decode refuses an odd-length token file (21, no output)" te3 21 '!te3.txt' +printf 'ab ab ab' > "$IN/tiny.txt" +both te4 toktrain raw "$IN/tiny.txt" te4.bin 300 0 +chk "train exits 28 when no pair is left (no file)" te4 28 '!te4.bin' '!te4.bin.tmp' + +# 8. negative control: the comparison sees one changed token +cp "$GOT/t1.tok" "$WORK/neg.tok"; flip "$WORK/neg.tok" 1000 +cmp -s "$WORK/neg.tok" "$REF/t1.tok" && ko "negative control: changed token not seen" || ok "negative control: changed token file differs from the oracle's" + +echo "SUMMARY pass=$pass fail=$fail" +[ "$fail" = 0 ] diff --git a/tests/omegallm/tok/oracle.py b/tests/omegallm/tok/oracle.py new file mode 100755 index 0000000..0ea3d7f --- /dev/null +++ b/tests/omegallm/tok/oracle.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +"""Test oracle for the own BPE tokenizer ollm-tok (tests/omegallm/tok/FORMAT.md). + +Verification only, never part of the build: a naive, independent reading of FORMAT.md in +Python 3 standard library, with the same command line, stdout lines, output files and exit +codes as the .om program, so check.sh can compare the two byte for byte. It recounts every pair +after every merge, so it is meant for texts of a few hundred KB. + + oracle.py toktrain MODE TEXT MERGES V MAXBYTES -> T V types chunks bytes markers + oracle.py tokenc MODE MERGES TEXT TOKS -> E V bytes chunks tokens markers + oracle.py tokdec MERGES TOKS OUT -> D V tokens bytes + oracle.py tokinfo MERGES -> I V merges fnv + oracle.py mkbad KIND IN OUT -> rehashed merges file with one bad pair + oracle.py gen BYTES SEED OUT -> synthetic test text (word salad) + +The training line of ollm-tok carries two more fields (pairs, list nodes) that depend on its data +structures; check.sh compares the first six fields only. +""" + +import random +import struct +import sys + +FIRST = 272 +VMAX = 32768 +MARKS = [b"<|end|>", b"<|system|>", b"<|user|>", b"<|assistant|>", b"<|tool_call|>", + b"<|tool_result|>", b"<|pad|>", b"<|doc|>"] +MAXCAP = 130016 +FNV0 = 14695981039346656037 +FNVP = 1099511628211 +M64 = (1 << 64) - 1 + + +def cls(c): + if 48 <= c <= 57 or 65 <= c <= 90 or 97 <= c <= 122 or c >= 128: + return 1 + if 9 <= c <= 13 or c == 32: + return 2 + return 0 + + +CL = [cls(c) for c in range(256)] + + +def clen(t, i, n): + """FORMAT.md section 3: length of the chunk at t[i] in a text ending at n.""" + e = min(i + 64, n) + k = CL[t[i]] + j = i + 1 + if t[i] == 32 and j < n and CL[t[j]] != 2: + k = CL[t[j]] + j += 1 + while j < e and CL[t[j]] == k: + j += 1 + if k == 2 and j < n and CL[t[j]] != 2 and j - i >= 2 and t[j - 1] == 32: + j -= 1 + return j - i + + +def mark_at(t, i): + for k, m in enumerate(MARKS): + if t.startswith(m, i): + return 256 + k + return 0 + + +def pieces(t, chat): + """yields (special id, b'') for a marker and (0, chunk) for a text chunk""" + n = len(t) + i = 0 + nxt = -1 + while i < n: + if chat: + m = mark_at(t, i) + if m: + yield m, b"" + i += len(MARKS[m - 256]) + continue + if nxt <= i: + nxt = n + j = t.find(b"<|", i + 1) + while j >= 0: + if mark_at(t, j): + nxt = j + break + j = t.find(b"<|", j + 1) + e = nxt + else: + e = n + l = clen(t, i, e) + yield 0, t[i:i + l] + i += l + + +def fnv(buf): + h = FNV0 + for c in buf[:24] + buf[32:]: + h = ((h ^ c) * FNVP) & M64 + return h + + +def seal(v, pairs): + body = b"".join(struct.pack(" MAXCAP or buf[:8] != b"OLLMTOK1": + sys.exit(26) + v, ns, h = struct.unpack(" VMAX or ns != 16 or n != 32 + 4 * (v - FIRST) or fnv(buf) != h: + sys.exit(26) + ln = [1] * 256 + [0] * 16 + for k, m in enumerate(MARKS): + ln[256 + k] = len(m) + pairs = [] + seen = set() + for k in range(v - FIRST): + a, b = struct.unpack(" 64 or (a, b) in seen: + sys.exit(26) + seen.add((a, b)) + pairs.append((a, b)) + ln.append(ln[a] + ln[b]) + return v, pairs + + +def replace(seq, a, b, t): + out = [] + j = 0 + while j < len(seq): + if j + 1 < len(seq) and seq[j] == a and seq[j + 1] == b: + out.append(t) + j += 2 + else: + out.append(seq[j]) + j += 1 + return out + + +def mode(s): + if s == "raw": + return False + if s == "chat": + return True + sys.exit(2) + + +def num(s): + if not (1 <= len(s) <= 19) or not s.isdigit(): + sys.exit(2) + return int(s) + + +def train(argv): + if len(argv) != 5: + sys.exit(2) + chat = mode(argv[0]) + v = num(argv[3]) + if v < FIRST or v > VMAX: + sys.exit(2) + lim = num(argv[4]) + t = open(argv[1], "rb").read() + if lim: + t = t[:lim] + if len(t) >= 1 << 33: + sys.exit(21) + types = {} + chunks = marks = 0 + for sp, c in pieces(t, chat): + if sp: + marks += 1 + else: + chunks += 1 + types[c] = types.get(c, 0) + 1 + words = [[list(c), n] for c, n in types.items()] + pairs = [] + for k in range(v - FIRST): + cnt = {} + for seq, n in words: + for j in range(len(seq) - 1): + p = (seq[j], seq[j + 1]) + cnt[p] = cnt.get(p, 0) + n + best = None + for p, n in cnt.items(): + if best is None or (n, -p[0], -p[1]) > (cnt[best], -best[0], -best[1]): + best = p + if best is None: + sys.exit(28) + tok = FIRST + k + pairs.append(best) + for w in words: + if len(w[0]) > 1: + w[0] = replace(w[0], best[0], best[1], tok) + with open(argv[2], "wb") as f: + f.write(seal(v, pairs)) + print("T %d %d %d %d %d" % (v, len(types), chunks, len(t), marks)) + + +def encode_chunk(c, rank, pairs): + seq = list(c) + while len(seq) > 1: + best = min(rank.get((seq[j], seq[j + 1]), 65535) for j in range(len(seq) - 1)) + if best == 65535: + break + a, b = pairs[best - FIRST] + seq = replace(seq, a, b, best) + return seq + + +def enc(argv): + if len(argv) != 4: + sys.exit(2) + chat = mode(argv[0]) + v, pairs = load(argv[1]) + rank = {p: FIRST + k for k, p in enumerate(pairs)} + t = open(argv[2], "rb").read() + out = [] + memo = {} + chunks = marks = 0 + for sp, c in pieces(t, chat): + if sp: + marks += 1 + out.append(sp) + else: + chunks += 1 + if c not in memo: + memo[c] = encode_chunk(c, rank, pairs) + out.extend(memo[c]) + with open(argv[3], "wb") as f: + f.write(struct.pack("<%dH" % len(out), *out)) + print("E %d %d %d %d %d" % (v, len(t), chunks, len(out), marks)) + + +def dec(argv): + if len(argv) != 3: + sys.exit(2) + v, pairs = load(argv[0]) + raw = open(argv[1], "rb").read() + if len(raw) % 2: + sys.exit(21) + toks = struct.unpack("<%dH" % (len(raw) // 2), raw) + for t in toks: + if t >= v or 256 + len(MARKS) <= t < FIRST: + sys.exit(25) + memo = {} + + def bytes_of(t): + if t < 256: + return bytes([t]) + if t < FIRST: + return MARKS[t - 256] + if t not in memo: + a, b = pairs[t - FIRST] + memo[t] = bytes_of(a) + bytes_of(b) + return memo[t] + + out = b"".join(bytes_of(t) for t in toks) + with open(argv[2], "wb") as f: + f.write(out) + print("D %d %d %d" % (v, len(toks), len(out))) + + +def info(argv): + if len(argv) != 1: + sys.exit(2) + v, _ = load(argv[0]) + h = struct.unpack(" 64) + chain = [(97, 97)] + [(FIRST + k, FIRST + k) for k in range(6)] + if len(pairs) < len(chain): + sys.exit(2) + pairs = chain + pairs[len(chain):] + else: + sys.exit(2) + with open(dst, "wb") as f: + f.write(seal(v, pairs)) + + +def gen(argv): + """deterministic synthetic text: words, digits, punctuation, runs of white space, UTF-8 and + near misses of the chat markers; no private and no outside text""" + n, seed = int(argv[0]), int(argv[1]) + rnd = random.Random(seed) + syl = ["ka", "lo", "mi", "ra", "sen", "to", "vu", "el", "an", "the", "ing", "er", "qu", + "st", "ch", "o", "a", "i"] + uni = ["\u00e9t\u00e9", "na\u00efve", "\u00fcber", "\u0436\u0438\u0437\u043d\u044c", + "\u03bb\u03cc\u03b3\u03bf\u03c2", "\u65e5\u672c\u8a9e", "\u0645\u0631\u062d\u0628\u0627", + "\U0001f600", "\u2603"] + words = ["".join(rnd.choice(syl) for _ in range(rnd.randint(1, 4))) for _ in range(400)] + out = [] + size = 0 + while size < n: + r = rnd.random() + if r < 0.80: + w = rnd.choice(words) + if rnd.random() < 0.1: + w = w.capitalize() + elif r < 0.85: + w = rnd.choice(uni) + elif r < 0.90: + w = str(rnd.randint(0, 99999)) + elif r < 0.97: + w = rnd.choice([".", ",", "!", "?", "...", "--", "\"", "'s", "(", ")", ":", ";"]) + else: + w = rnd.choice(["<|", "|>", "<|user", "<|end>", "<||>", ""]) + sp = rnd.choice([" ", " ", " ", " ", " ", "\n", " ", "\n\n", "\t", " \n ", " "]) + piece = (w + sp).encode() + out.append(piece) + size += len(piece) + with open(argv[2], "wb") as f: + f.write(b"".join(out)[:n]) + + +def main(): + cmds = {"toktrain": train, "tokenc": enc, "tokdec": dec, "tokinfo": info, + "mkbad": mkbad, "gen": gen} + if len(sys.argv) < 2 or sys.argv[1] not in cmds: + sys.exit(2) + cmds[sys.argv[1]](sys.argv[2:]) + + +if __name__ == "__main__": + main() diff --git a/tests/omegallm/tok/ratio.sh b/tests/omegallm/tok/ratio.sh new file mode 100755 index 0000000..26f90cd --- /dev/null +++ b/tests/omegallm/tok/ratio.sh @@ -0,0 +1,63 @@ +#!/bin/sh +# Own BPE compression measurement: train ollm-tok merges on a prefix of a training text, then +# encode a public-domain sample and a held-out text, prove both round trips exact, and print the +# byte and token counts (the ratio bytes/tokens is computed outside this script). +# +# BIN=path/to/ollm-tok TRAIN=text V=8192 MAXBYTES=100000000 PD=pg1342.txt HELD=valid.txt \ +# sh tests/omegallm/tok/ratio.sh +# +# PD is Project Gutenberg eBook #1342 (Pride and Prejudice, public domain in the USA), fetched by the +# operator from https://www.gutenberg.org/cache/epub/1342/pg1342.txt and checked by sha256 below; +# only the text between the START and END lines is encoded. It is never committed. A missing or +# different PD file gives NOT_RUN for that sample. HELD (optional) is any held-out text. +# Environment: WORK (scratch, default scratch-tok-ratio beside the clone; keep it under a private +# directory when TRAIN is private), CORES (default 18-19), MODE (raw or chat, default raw). +# Runs at nice 10 inside bwrap with no network; only WORK is writable. +set -u +here=$(cd "$(dirname "$0")" && pwd) +BIN=${BIN:?set BIN} +TRAIN=${TRAIN:?set TRAIN} +V=${V:-8192} +MAXBYTES=${MAXBYTES:-0} +PD=${PD:-} +HELD=${HELD:-} +MODE=${MODE:-raw} +WORK=${WORK:-$here/../../../../scratch-tok-ratio} +CORES=${CORES:-18-19} +PDSHA=3f6bb9d6f78e0293b56acd4714dd68cb7d6d1d293402031ce9d5a216bcaf9d75 +if [ -z "${TOK_RATIO_PINNED:-}" ]; then + mkdir -p "$WORK" + WORK=$(cd "$WORK" && pwd) + export TOK_RATIO_PINNED=1 WORK BIN TRAIN V MAXBYTES PD HELD MODE + exec taskset -c "$CORES" nice -n 10 bwrap --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp \ + --bind "$WORK" "$WORK" --unshare-net --die-with-parent -- sh "$0" "$@" +fi +cd "$WORK" || exit 2 +echo "tok-ratio: bin sha256=$(sha256sum "$BIN" | cut -c1-16) mode=$MODE V=$V maxbytes=$MAXBYTES train_bytes=$(wc -c < "$TRAIN")" +/usr/bin/time -f "TIME toktrain %e s %M KiB" "$BIN" toktrain "$MODE" "$TRAIN" merges.bin "$V" "$MAXBYTES" || { echo "FAIL toktrain exit $?"; exit 1; } +echo "MERGES sha256=$(sha256sum merges.bin | cut -d' ' -f1) bytes=$(wc -c < merges.bin)" +fail=0 +sample() { + _n=$1 _f=$2 + /usr/bin/time -f "TIME tokenc $_n %e s" "$BIN" tokenc "$MODE" merges.bin "$_f" "$_n.tok" || { echo "FAIL $_n tokenc"; fail=1; return; } + "$BIN" tokdec merges.bin "$_n.tok" "$_n.back" >/dev/null || { echo "FAIL $_n tokdec"; fail=1; return; } + if cmp -s "$_f" "$_n.back"; then + echo "MEASURED $_n bytes=$(wc -c < "$_f") tokens=$(( $(wc -c < "$_n.tok") / 2 )) round_trip=PASS" + else + echo "FAIL $_n round trip"; fail=1 + fi + rm -f "$_n.back" +} +if [ -n "$PD" ] && [ -r "$PD" ] && [ "$(sha256sum "$PD" | cut -d' ' -f1)" = "$PDSHA" ]; then + sed -n '/^\*\*\* START OF THE PROJECT GUTENBERG EBOOK/,/^\*\*\* END OF THE PROJECT GUTENBERG EBOOK/p' "$PD" \ + | sed '1d;$d' > pd-body.txt + sample pg1342-body pd-body.txt +else + echo "NOT_RUN pg1342-body: PD sample absent or not sha256 $PDSHA" +fi +if [ -n "$HELD" ] && [ -r "$HELD" ]; then + sample held "$HELD" +else + echo "NOT_RUN held: no HELD text" +fi +[ "$fail" = 0 ] diff --git a/tests/omegallm/tok/unicode.txt b/tests/omegallm/tok/unicode.txt new file mode 100644 index 0000000..d27e546 --- /dev/null +++ b/tests/omegallm/tok/unicode.txt @@ -0,0 +1,11 @@ +Synthetic Unicode fixture for the own BPE (written for this test; no outside text). +Latin: café, naïve, über, façade, Ångström, smørrebrød, Łódź, İstanbul. +Greek: λόγος και αριθμός. Cyrillic: жизнь и время. Armenian: բարեւ. +Hebrew: שלום עולם. Arabic: مرحبا بالعالم. Devanagari: नमस्ते दुनिया. +Thai: สวัสดีชาวโลก. CJK: 日本語の文章、中文句子、한국어 문장. +Symbols: ∀x∈ℝ: x² ≥ 0; ½ + ¼ = ¾; €100 → £86; ©®™ ✓ ✗ ★ ☃. +Emoji: 😀 🚀 👩‍💻 🇳🇿 👍🏽 (ZWJ and modifiers). +Combining: e\u0301 vs é; fi ligature; zero width: a​b; BOM: x; NBSP: a b. +Wide run: ABC123 and long word: Donaudampfschifffahrtsgesellschaftskapitänsmützenabzeichenträgerinnenbund. +Mixed white space: two spaces, tab, + indented line, four spaces before.