okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3ed9dafa1
main
1"""The draft head's token subset (rt/draft_vocab.bin): the vocabulary rows the MTP draft layer may propose. 2 3The engine reads rt/draft_vocab.bin (int32 token ids) when the draft layer binds and computes the draft logits over 4those rows only: a smaller head is faster and takes less VRAM, but a token outside the subset can never be drafted. 5The shipped subset was built from English and code and had 27 of the vocabulary's 55,328 Han tokens, so an answer in 6Chinese drafted almost nothing (#137). This adds whole scripts to a subset: 7 8python tools/draft_vocab.py --gguf <model>-00001-of-0000N.gguf --base data/draft_vocab.bin --add cjk \ 9--out data/draft_vocab.bin 10 11--add takes han, kana, hangul, cjk_punct, cjk (those four) or cyrillic. The base ids keep their order; the added ones follow in 12id order. --stats prints what a subset holds. 13 14A language written in a script the base already holds (French, Spanish, German... in Latin letters) needs specific 15words and word pieces, not a whole script. --corpus adds the tokens of a text corpus in that language: the most 16frequent ones that together cover --coverage (default 0.99) of the corpus's token occurrences (#597): 17 18python tools/draft_vocab.py --gguf <model>-00001-of-0000N.gguf --base data/draft_vocab_en.bin \ 19--corpus fr1.txt fr2.txt ... --coverage 0.99 --out data/draft_vocab_fr.bin 20 21It prints the share of the corpus's occurrences outside the base and outside the new subset. --add and --corpus 22can be combined. 23""" 24from __future__import annotations 25 26import argparse 27import sys 28from array import array 29from collections import Counter 30from pathlib import Path 31 32sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 33import strata_tokenizer as ST # noqa: E402 34 35SCRIPTS = { 36"han" : [(0x3400 ,0x4DBF ), (0x4E00 ,0x9FFF ), (0xF900 ,0xFAFF ), (0x20000 ,0x2FA1F )], 37"kana" : [(0x3040 ,0x30FF ), (0x31F0 ,0x31FF ), (0xFF66 ,0xFF9F )], 38"hangul" : [(0x1100 ,0x11FF ), (0x3130 ,0x318F ), (0xAC00 ,0xD7AF )], 39"cjk_punct" : [(0x3000 ,0x303F ), (0xFF00 ,0xFF65 ), (0xFFA0 ,0xFFEF )], 40# Ukrainian, Russian, Bulgarian, Serbian...: the shipped subset held 142 of the vocabulary's 18,580 Cyrillic tokens 41"cyrillic" : [(0x0400 ,0x04FF ), (0x0500 ,0x052F ), (0x1C80 ,0x1C8F ), (0x2DE0 ,0x2DFF ), (0xA640 ,0xA69F )], 42} 43GROUPS = {"cjk" : ["han" ,"kana" ,"hangul" ,"cjk_punct" ]} 44 45 46def scripts_of (text :str )-> set [str ]: 47found = set () 48for ch in text : 49c = ord (ch ) 50for name ,ranges in SCRIPTS .items (): 51if any (a <= c <= b for a ,b in ranges ): 52found .add (name ) 53return found 54 55 56def token_text (tok ,i :int )-> str | None : 57"""A token's text, or None when its bytes are not whole UTF-8 characters (a piece of one) or it is special.""" 58try : 59return tok .token_bytes (i ).decode ("utf-8" ) 60except (KeyError ,UnicodeDecodeError ,IndexError ): 61return None 62 63 64def corpus_counts (tok ,paths )-> Counter : 65"""Token occurrences over the corpus files (UTF-8 text, tokenized as plain text: no special tokens).""" 66counts :Counter = Counter () 67for path in paths : 68counts .update (tok .encode (Path (path ).read_text (encoding = "utf-8" ))) 69return counts 70 71 72def covering (counts :Counter ,coverage :float )-> list [int ]: 73"""The most frequent ids (ties: the lower id first) that together cover `coverage` of the occurrences.""" 74total = sum (counts .values ()) 75picked ,covered = [],0 76for i ,c in sorted (counts .items (),key = lambda kv : (- kv [1 ],kv [0 ])): 77if covered >= coverage * total : 78break 79picked .append (i ) 80covered += c 81return picked 82 83 84def outside (counts :Counter ,ids )-> float : 85"""The share of the occurrences whose token is not in `ids`.""" 86total = sum (counts .values ()) 87have = set (ids ) 88return sum (c for i ,c in counts .items ()if i not in have )/ total if total else 0.0 89 90 91def main ()-> int : 92ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 93ap .add_argument ("--gguf" ,required = True ,help = "the model's (first) GGUF file: its vocabulary" ) 94ap .add_argument ("--base" ,help = "the subset to extend (int32 ids)" ) 95ap .add_argument ("--add" ,default = "" ,help = "comma list: han, kana, hangul, cjk_punct, cjk, cyrillic" ) 96ap .add_argument ("--corpus" ,nargs = "+" ,default = [],help = "UTF-8 text files in the language to add (#597)" ) 97ap .add_argument ("--coverage" ,type = float ,default = 0.99 , 98help = "with --corpus: the share of its token occurrences the added tokens cover (default 0.99)" ) 99ap .add_argument ("--out" ,help = "where to write the new subset" ) 100ap .add_argument ("--stats" ,action = "store_true" ,help = "print what the base (and the new) subset holds" ) 101a = ap .parse_args () 102 103tok = ST .Tokenizer .from_gguf (a .gguf ) 104n = len (tok .tokens ) 105kinds = [scripts_of (t )if (t := token_text (tok ,i ))is not None else set ()for i in range (n )] 106base = list (array ("i" ,Path (a .base ).read_bytes ()))if a .base else [] 107if any (i < 0 or i >= n for i in base ): 108sys .exit (f" { a . base } has ids outside the vocabulary ( { n } )" ) 109 110want = set () 111for x in filter (None , (s .strip ()for s in a .add .split ("," ))): 112names = GROUPS .get (x , [x ]) 113if any (nm not in SCRIPTS for nm in names ): 114sys .exit (f"--add { x } : expected one of { ', ' . join ([ * SCRIPTS , * GROUPS ]) } " ) 115want .update (names ) 116if not 0 < a .coverage <= 1 : 117sys .exit ("--coverage: expected a share in (0, 1]" ) 118counts = corpus_counts (tok ,a .corpus )if a .corpus else Counter () 119from_corpus = set (covering (counts ,a .coverage ))if counts else set () 120have = set (base ) 121added = [i for i in range (n )if i not in have and (kinds [i ]& want or i in from_corpus )] 122ids = base + added 123 124def stats (label ,sel ): 125counts = {nm :sum (1 for i in sel if nm in kinds [i ])for nm in SCRIPTS } 126full = {nm :sum (1 for k in kinds if nm in k )for nm in SCRIPTS } 127f" { label } : { len ( sel ) } ids; " + ", " .join (f" { nm } { counts [ nm ] } / { full [ nm ] } " for nm in SCRIPTS )) 128 129if a .stats or not a .out : 130if base : 131stats ("base" ,base ) 132if added : 133stats ("new" ,ids ) 134if counts : 135f"corpus: { sum ( counts . values ()) } token occurrences, { len ( counts ) } distinct; " 136f" { len ( from_corpus ) } tokens cover { a . coverage :g } , { len ( from_corpus - have ) } of them not in the base" ) 137f"corpus occurrences outside the base: { outside ( counts , base ):.2% } , outside the new subset: " 138f" { outside ( counts , ids ):.2% } " ) 139if a .out : 140Path (a .out ).write_bytes (array ("i" ,ids ).tobytes ()) 141f"wrote { a . out } : { len ( ids ) } ids ( { len ( added ) } added)" ) 142return 0 143 144 145if __name__ == "__main__" : 146sys .exit (main ())