aien-train
AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished.
Brought by drakestapleton
aien-train / tests / omegallm / tok / oracle.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Test oracle for the own BPE tokenizer ollm-tok (tests/omegallm/tok/FORMAT.md). |
| 3 | |
| 4 | Verification only, never part of the build: a naive, independent reading of FORMAT.md in |
| 5 | Python 3 standard library, with the same command line, stdout lines, output files and exit |
| 6 | codes as the .om program, so check.sh can compare the two byte for byte. It recounts every pair |
| 7 | after every merge, so it is meant for texts of a few hundred KB. |
| 8 | |
| 9 | oracle.py toktrain MODE TEXT MERGES V MAXBYTES -> T V types chunks bytes markers |
| 10 | oracle.py tokenc MODE MERGES TEXT TOKS -> E V bytes chunks tokens markers |
| 11 | oracle.py tokdec MERGES TOKS OUT -> D V tokens bytes |
| 12 | oracle.py tokinfo MERGES -> I V merges fnv |
| 13 | oracle.py mkbad KIND IN OUT -> rehashed merges file with one bad pair |
| 14 | oracle.py gen BYTES SEED OUT -> synthetic test text (word salad) |
| 15 | |
| 16 | The training line of ollm-tok carries two more fields (pairs, list nodes) that depend on its data |
| 17 | structures; check.sh compares the first six fields only. |
| 18 | """ |
| 19 | |
| 20 | import random |
| 21 | import struct |
| 22 | import sys |
| 23 | |
| 24 | FIRST = 272 |
| 25 | VMAX = 32768 |
| 26 | MARKS = [b"<|end|>", b"<|system|>", b"<|user|>", b"<|assistant|>", b"<|tool_call|>", |
| 27 | b"<|tool_result|>", b"<|pad|>", b"<|doc|>"] |
| 28 | MAXCAP = 130016 |
| 29 | FNV0 = 14695981039346656037 |
| 30 | FNVP = 1099511628211 |
| 31 | M64 = (1 << 64) - 1 |
| 32 | |
| 33 | |
| 34 | def cls(c): |
| 35 | if 48 <= c <= 57 or 65 <= c <= 90 or 97 <= c <= 122 or c >= 128: |
| 36 | return 1 |
| 37 | if 9 <= c <= 13 or c == 32: |
| 38 | return 2 |
| 39 | return 0 |
| 40 | |
| 41 | |
| 42 | CL = [cls(c) for c in range(256)] |
| 43 | |
| 44 | |
| 45 | def clen(t, i, n): |
| 46 | """FORMAT.md section 3: length of the chunk at t[i] in a text ending at n.""" |
| 47 | e = min(i + 64, n) |
| 48 | k = CL[t[i]] |
| 49 | j = i + 1 |
| 50 | if t[i] == 32 and j < n and CL[t[j]] != 2: |
| 51 | k = CL[t[j]] |
| 52 | j += 1 |
| 53 | while j < e and CL[t[j]] == k: |
| 54 | j += 1 |
| 55 | if k == 2 and j < n and CL[t[j]] != 2 and j - i >= 2 and t[j - 1] == 32: |
| 56 | j -= 1 |
| 57 | return j - i |
| 58 | |
| 59 | |
| 60 | def mark_at(t, i): |
| 61 | for k, m in enumerate(MARKS): |
| 62 | if t.startswith(m, i): |
| 63 | return 256 + k |
| 64 | return 0 |
| 65 | |
| 66 | |
| 67 | def pieces(t, chat): |
| 68 | """yields (special id, b'') for a marker and (0, chunk) for a text chunk""" |
| 69 | n = len(t) |
| 70 | i = 0 |
| 71 | nxt = -1 |
| 72 | while i < n: |
| 73 | if chat: |
| 74 | m = mark_at(t, i) |
| 75 | if m: |
| 76 | yield m, b"" |
| 77 | i += len(MARKS[m - 256]) |
| 78 | continue |
| 79 | if nxt <= i: |
| 80 | nxt = n |
| 81 | j = t.find(b"<|", i + 1) |
| 82 | while j >= 0: |
| 83 | if mark_at(t, j): |
| 84 | nxt = j |
| 85 | break |
| 86 | j = t.find(b"<|", j + 1) |
| 87 | e = nxt |
| 88 | else: |
| 89 | e = n |
| 90 | l = clen(t, i, e) |
| 91 | yield 0, t[i:i + l] |
| 92 | i += l |
| 93 | |
| 94 | |
| 95 | def fnv(buf): |
| 96 | h = FNV0 |
| 97 | for c in buf[:24] + buf[32:]: |
| 98 | h = ((h ^ c) * FNVP) & M64 |
| 99 | return h |
| 100 | |
| 101 | |
| 102 | def seal(v, pairs): |
| 103 | body = b"".join(struct.pack("<HH", a, b) for a, b in pairs) |
| 104 | buf = bytearray(b"OLLMTOK1" + struct.pack("<QQQ", v, 16, 0) + body) |
| 105 | buf[24:32] = struct.pack("<Q", fnv(bytes(buf))) |
| 106 | return bytes(buf) |
| 107 | |
| 108 | |
| 109 | def load(path): |
| 110 | """the merges of a checked OLLMTOK1 file: (V, pairs); exit 26 on any fault""" |
| 111 | buf = open(path, "rb").read(131072) |
| 112 | n = len(buf) |
| 113 | if n < 32 or n > MAXCAP or buf[:8] != b"OLLMTOK1": |
| 114 | sys.exit(26) |
| 115 | v, ns, h = struct.unpack("<QQQ", buf[8:32]) |
| 116 | if v < FIRST or v > VMAX or ns != 16 or n != 32 + 4 * (v - FIRST) or fnv(buf) != h: |
| 117 | sys.exit(26) |
| 118 | ln = [1] * 256 + [0] * 16 |
| 119 | for k, m in enumerate(MARKS): |
| 120 | ln[256 + k] = len(m) |
| 121 | pairs = [] |
| 122 | seen = set() |
| 123 | for k in range(v - FIRST): |
| 124 | a, b = struct.unpack("<HH", buf[32 + 4 * k:36 + 4 * k]) |
| 125 | t = FIRST + k |
| 126 | for x in (a, b): |
| 127 | if not (x < 256 or FIRST <= x < t): |
| 128 | sys.exit(26) |
| 129 | if ln[a] + ln[b] > 64 or (a, b) in seen: |
| 130 | sys.exit(26) |
| 131 | seen.add((a, b)) |
| 132 | pairs.append((a, b)) |
| 133 | ln.append(ln[a] + ln[b]) |
| 134 | return v, pairs |
| 135 | |
| 136 | |
| 137 | def replace(seq, a, b, t): |
| 138 | out = [] |
| 139 | j = 0 |
| 140 | while j < len(seq): |
| 141 | if j + 1 < len(seq) and seq[j] == a and seq[j + 1] == b: |
| 142 | out.append(t) |
| 143 | j += 2 |
| 144 | else: |
| 145 | out.append(seq[j]) |
| 146 | j += 1 |
| 147 | return out |
| 148 | |
| 149 | |
| 150 | def mode(s): |
| 151 | if s == "raw": |
| 152 | return False |
| 153 | if s == "chat": |
| 154 | return True |
| 155 | sys.exit(2) |
| 156 | |
| 157 | |
| 158 | def num(s): |
| 159 | if not (1 <= len(s) <= 19) or not s.isdigit(): |
| 160 | sys.exit(2) |
| 161 | return int(s) |
| 162 | |
| 163 | |
| 164 | def train(argv): |
| 165 | if len(argv) != 5: |
| 166 | sys.exit(2) |
| 167 | chat = mode(argv[0]) |
| 168 | v = num(argv[3]) |
| 169 | if v < FIRST or v > VMAX: |
| 170 | sys.exit(2) |
| 171 | lim = num(argv[4]) |
| 172 | t = open(argv[1], "rb").read() |
| 173 | if lim: |
| 174 | t = t[:lim] |
| 175 | if len(t) >= 1 << 33: |
| 176 | sys.exit(21) |
| 177 | types = {} |
| 178 | chunks = marks = 0 |
| 179 | for sp, c in pieces(t, chat): |
| 180 | if sp: |
| 181 | marks += 1 |
| 182 | else: |
| 183 | chunks += 1 |
| 184 | types[c] = types.get(c, 0) + 1 |
| 185 | words = [[list(c), n] for c, n in types.items()] |
| 186 | pairs = [] |
| 187 | for k in range(v - FIRST): |
| 188 | cnt = {} |
| 189 | for seq, n in words: |
| 190 | for j in range(len(seq) - 1): |
| 191 | p = (seq[j], seq[j + 1]) |
| 192 | cnt[p] = cnt.get(p, 0) + n |
| 193 | best = None |
| 194 | for p, n in cnt.items(): |
| 195 | if best is None or (n, -p[0], -p[1]) > (cnt[best], -best[0], -best[1]): |
| 196 | best = p |
| 197 | if best is None: |
| 198 | sys.exit(28) |
| 199 | tok = FIRST + k |
| 200 | pairs.append(best) |
| 201 | for w in words: |
| 202 | if len(w[0]) > 1: |
| 203 | w[0] = replace(w[0], best[0], best[1], tok) |
| 204 | with open(argv[2], "wb") as f: |
| 205 | f.write(seal(v, pairs)) |
| 206 | print("T %d %d %d %d %d" % (v, len(types), chunks, len(t), marks)) |
| 207 | |
| 208 | |
| 209 | def encode_chunk(c, rank, pairs): |
| 210 | seq = list(c) |
| 211 | while len(seq) > 1: |
| 212 | best = min(rank.get((seq[j], seq[j + 1]), 65535) for j in range(len(seq) - 1)) |
| 213 | if best == 65535: |
| 214 | break |
| 215 | a, b = pairs[best - FIRST] |
| 216 | seq = replace(seq, a, b, best) |
| 217 | return seq |
| 218 | |
| 219 | |
| 220 | def enc(argv): |
| 221 | if len(argv) != 4: |
| 222 | sys.exit(2) |
| 223 | chat = mode(argv[0]) |
| 224 | v, pairs = load(argv[1]) |
| 225 | rank = {p: FIRST + k for k, p in enumerate(pairs)} |
| 226 | t = open(argv[2], "rb").read() |
| 227 | out = [] |
| 228 | memo = {} |
| 229 | chunks = marks = 0 |
| 230 | for sp, c in pieces(t, chat): |
| 231 | if sp: |
| 232 | marks += 1 |
| 233 | out.append(sp) |
| 234 | else: |
| 235 | chunks += 1 |
| 236 | if c not in memo: |
| 237 | memo[c] = encode_chunk(c, rank, pairs) |
| 238 | out.extend(memo[c]) |
| 239 | with open(argv[3], "wb") as f: |
| 240 | f.write(struct.pack("<%dH" % len(out), *out)) |
| 241 | print("E %d %d %d %d %d" % (v, len(t), chunks, len(out), marks)) |
| 242 | |
| 243 | |
| 244 | def dec(argv): |
| 245 | if len(argv) != 3: |
| 246 | sys.exit(2) |
| 247 | v, pairs = load(argv[0]) |
| 248 | raw = open(argv[1], "rb").read() |
| 249 | if len(raw) % 2: |
| 250 | sys.exit(21) |
| 251 | toks = struct.unpack("<%dH" % (len(raw) // 2), raw) |
| 252 | for t in toks: |
| 253 | if t >= v or 256 + len(MARKS) <= t < FIRST: |
| 254 | sys.exit(25) |
| 255 | memo = {} |
| 256 | |
| 257 | def bytes_of(t): |
| 258 | if t < 256: |
| 259 | return bytes([t]) |
| 260 | if t < FIRST: |
| 261 | return MARKS[t - 256] |
| 262 | if t not in memo: |
| 263 | a, b = pairs[t - FIRST] |
| 264 | memo[t] = bytes_of(a) + bytes_of(b) |
| 265 | return memo[t] |
| 266 | |
| 267 | out = b"".join(bytes_of(t) for t in toks) |
| 268 | with open(argv[2], "wb") as f: |
| 269 | f.write(out) |
| 270 | print("D %d %d %d" % (v, len(toks), len(out))) |
| 271 | |
| 272 | |
| 273 | def info(argv): |
| 274 | if len(argv) != 1: |
| 275 | sys.exit(2) |
| 276 | v, _ = load(argv[0]) |
| 277 | h = struct.unpack("<Q", open(argv[0], "rb").read(32)[24:32])[0] |
| 278 | print("I %d %d %d" % (v, v - FIRST, h)) |
| 279 | |
| 280 | |
| 281 | def mkbad(argv): |
| 282 | """KIND special|reserved|forward|self|dup|long: one bad pair, rehashed so only it is wrong""" |
| 283 | kind, src, dst = argv |
| 284 | buf = open(src, "rb").read() |
| 285 | v = struct.unpack("<Q", buf[8:16])[0] |
| 286 | pairs = [struct.unpack("<HH", buf[32 + 4 * k:36 + 4 * k]) for k in range(v - FIRST)] |
| 287 | last = FIRST + len(pairs) - 1 |
| 288 | if kind == "special": |
| 289 | pairs[-1] = (259, 97) |
| 290 | elif kind == "reserved": |
| 291 | pairs[-1] = (97, 270) |
| 292 | elif kind == "forward": |
| 293 | pairs[-1] = (97, last + 1) |
| 294 | elif kind == "self": |
| 295 | pairs[-1] = (last, 97) |
| 296 | elif kind == "dup": |
| 297 | pairs[-1] = pairs[0] |
| 298 | elif kind == "long": |
| 299 | # merges whose decoded lengths double: 2, 4, 8, 16, 32, 64, then 128 (> 64) |
| 300 | chain = [(97, 97)] + [(FIRST + k, FIRST + k) for k in range(6)] |
| 301 | if len(pairs) < len(chain): |
| 302 | sys.exit(2) |
| 303 | pairs = chain + pairs[len(chain):] |
| 304 | else: |
| 305 | sys.exit(2) |
| 306 | with open(dst, "wb") as f: |
| 307 | f.write(seal(v, pairs)) |
| 308 | |
| 309 | |
| 310 | def gen(argv): |
| 311 | """deterministic synthetic text: words, digits, punctuation, runs of white space, UTF-8 and |
| 312 | near misses of the chat markers; no private and no outside text""" |
| 313 | n, seed = int(argv[0]), int(argv[1]) |
| 314 | rnd = random.Random(seed) |
| 315 | syl = ["ka", "lo", "mi", "ra", "sen", "to", "vu", "el", "an", "the", "ing", "er", "qu", |
| 316 | "st", "ch", "o", "a", "i"] |
| 317 | uni = ["\u00e9t\u00e9", "na\u00efve", "\u00fcber", "\u0436\u0438\u0437\u043d\u044c", |
| 318 | "\u03bb\u03cc\u03b3\u03bf\u03c2", "\u65e5\u672c\u8a9e", "\u0645\u0631\u062d\u0628\u0627", |
| 319 | "\U0001f600", "\u2603"] |
| 320 | words = ["".join(rnd.choice(syl) for _ in range(rnd.randint(1, 4))) for _ in range(400)] |
| 321 | out = [] |
| 322 | size = 0 |
| 323 | while size < n: |
| 324 | r = rnd.random() |
| 325 | if r < 0.80: |
| 326 | w = rnd.choice(words) |
| 327 | if rnd.random() < 0.1: |
| 328 | w = w.capitalize() |
| 329 | elif r < 0.85: |
| 330 | w = rnd.choice(uni) |
| 331 | elif r < 0.90: |
| 332 | w = str(rnd.randint(0, 99999)) |
| 333 | elif r < 0.97: |
| 334 | w = rnd.choice([".", ",", "!", "?", "...", "--", "\"", "'s", "(", ")", ":", ";"]) |
| 335 | else: |
| 336 | w = rnd.choice(["<|", "|>", "<|user", "<|end>", "<||>", "<x|end|>"]) |
| 337 | sp = rnd.choice([" ", " ", " ", " ", " ", "\n", " ", "\n\n", "\t", " \n ", " "]) |
| 338 | piece = (w + sp).encode() |
| 339 | out.append(piece) |
| 340 | size += len(piece) |
| 341 | with open(argv[2], "wb") as f: |
| 342 | f.write(b"".join(out)[:n]) |
| 343 | |
| 344 | |
| 345 | def main(): |
| 346 | cmds = {"toktrain": train, "tokenc": enc, "tokdec": dec, "tokinfo": info, |
| 347 | "mkbad": mkbad, "gen": gen} |
| 348 | if len(sys.argv) < 2 or sys.argv[1] not in cmds: |
| 349 | sys.exit(2) |
| 350 | cmds[sys.argv[1]](sys.argv[2:]) |
| 351 | |
| 352 | |
| 353 | if __name__ == "__main__": |
| 354 | main() |