interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / allen / catalog / qwentok.py

56 lines · 1770 bytes Raw Blame History
1"""Exact Qwen3.6 token count for ASCII text, stdlib only (no model call).
2
3Byte-level BPE from the model's tokenizer.json; the pre-tokenizer regex is the
4model's with \\p{L}/\\p{M}/\\p{N} narrowed to ASCII, which is exact for ASCII input.
5Usage: qwentok.py TOKENIZER_JSON FILE...
6"""
7
8import json
9import re
10import sys
11
12PRE = re.compile(r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\nA-Za-z0-9]?[A-Za-z]+|[0-9]| ?[^\sA-Za-z0-9]+[\r\n]*"
13 r"|\s*[\r\n]+|\s+(?!\S)|\s+")
14
15
16def byte_map():
17 bs = list(range(33, 127)) + list(range(161, 173)) + list(range(174, 256))
18 cs, n = bs[:], 0
19 for b in range(256):
20 if b not in bs:
21 bs.append(b)
22 cs.append(256 + n)
23 n += 1
24 return {b: chr(c) for b, c in zip(bs, cs)}
25
26
27class Tok:
28 def __init__(self, path):
29 m = json.load(open(path, encoding="utf-8"))["model"]
30 self.vocab = m["vocab"]
31 self.ranks = {tuple(x.split(" ", 1)) if isinstance(x, str) else tuple(x): i
32 for i, x in enumerate(m["merges"])}
33 self.bmap = byte_map()
34
35 def bpe(self, word):
36 parts = list(word)
37 while len(parts) > 1:
38 best = min(((self.ranks.get((a, b), 1 << 30), i) for i, (a, b) in enumerate(zip(parts, parts[1:]))))
39 if best[0] == 1 << 30:
40 break
41 i = best[1]
42 parts[i:i + 2] = [parts[i] + parts[i + 1]]
43 return parts
44
45 def count(self, text):
46 text.encode("ascii")
47 n = 0
48 for piece in PRE.findall(text):
49 n += len(self.bpe("".join(self.bmap[b] for b in piece.encode())))
50 return n
51
52
53if __name__ == "__main__":
54 t = Tok(sys.argv[1])
55 for f in sys.argv[2:]:
56 print(t.count(open(f, encoding="ascii").read()), f)