Download tokenizer.py from SOYORiN/Susu: direct link, hf CLI and curl.
- Browser
- Download file 5.66 kB
-
https://huggingface.co/SOYORiN/Susu/resolve/main/tokenizer.py
- Command line
-
hf download hf://SOYORiN/Susu/tokenizer.py
-
curl -L -o tokenizer.py https://huggingface.co/SOYORiN/Susu/resolve/main/tokenizer.py
5.66 kB
| """Production: byte-level BPE (optional tokenizers dependency). | |
| Debug: byte fallback plus frequent characters, for offline pipeline tests only. | |
| The debug tokenizer is deliberately NOT a substitute for the research BPE. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| from collections import Counter | |
| SPECIAL=['<|pad|>','<|bos|>','<|end|>','<|system|>','<|user|>','<|assistant|>'] | |
| PAD,BOS,EOS,SYSTEM,USER,ASSISTANT=range(6) | |
| ROLE={'system':SYSTEM,'user':USER,'assistant':ASSISTANT} | |
| DEFAULT_SYSTEM='你是一个友善的聊天伙伴。自然、简短地回应,以中文为主,也能说简单英语。' | |
| class ChatTokenizer: | |
| def __init__(self,path): | |
| self.path=Path(path); self.meta=json.loads(self.path.read_text(encoding='utf-8')) | |
| self.debug=self.meta['type']=='debug-char-byte' | |
| if self.debug: | |
| self.chars=self.meta['characters']; self.lookup={c:i+262 for i,c in enumerate(self.chars)} | |
| self.size=262+len(self.chars); self.capacity=self.meta['capacity'] | |
| else: | |
| from tokenizers import Tokenizer | |
| self.engine=Tokenizer.from_file(str(self.path.parent/self.meta['file'])) | |
| self.size=self.engine.get_vocab_size(); self.capacity=self.size | |
| for i,t in enumerate(SPECIAL): | |
| if self.engine.token_to_id(t)!=i: raise ValueError('Special token IDs changed') | |
| def encode(self,text): | |
| # Raw content may not inject role delimiters. We preserve ordinary text. | |
| if any(s in text for s in SPECIAL): raise ValueError('Literal role delimiter in content') | |
| if self.debug: | |
| ids=[] | |
| for c in text: | |
| if c in self.lookup: ids.append(self.lookup[c]) | |
| else: ids.extend(b+6 for b in c.encode('utf-8')) | |
| return ids | |
| return self.engine.encode(text,add_special_tokens=False).ids | |
| def decode(self,ids): | |
| if not self.debug: return self.engine.decode(ids,skip_special_tokens=True) | |
| raw=bytearray() | |
| for i in ids: | |
| if 6<=i<262: raw.append(i-6) | |
| elif 262<=i<self.size: raw.extend(self.chars[i-262].encode('utf-8')) | |
| return raw.decode('utf-8',errors='replace') | |
| def iter_texts(path): | |
| with open(path,encoding='utf-8') as f: | |
| for line in f: | |
| obj=json.loads(line) | |
| if 'text' in obj: yield obj['text'] | |
| else: | |
| for m in obj['messages']: yield m['content'] | |
| def train_tokenizer(train_file,out_dir,vocab_size=6144,debug=False): | |
| out=Path(out_dir); out.mkdir(parents=True,exist_ok=True) | |
| meta=out/'tokenizer_meta.json' | |
| if meta.exists(): raise FileExistsError(f'Refusing to overwrite tokenizer: {out}') | |
| if vocab_size<300: raise ValueError('Vocabulary too small') | |
| if debug: | |
| counts=Counter() | |
| for text in iter_texts(train_file): counts.update(text) | |
| chars=[c for c,n in sorted(counts.items(),key=lambda x:(-x[1],x[0]))[:vocab_size-262]] | |
| spec={'type':'debug-char-byte','capacity':vocab_size,'characters':chars, | |
| 'warning':'Debug only; unused embedding rows do not add language knowledge.'} | |
| else: | |
| from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers | |
| tok=Tokenizer(models.BPE()) | |
| tok.pre_tokenizer=pre_tokenizers.ByteLevel(add_prefix_space=False) | |
| tok.decoder=decoders.ByteLevel() | |
| trainer=trainers.BpeTrainer(vocab_size=vocab_size,min_frequency=2,special_tokens=SPECIAL, | |
| initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),max_token_length=32) | |
| tok.train_from_iterator(iter_texts(train_file),trainer=trainer) | |
| if tok.get_vocab_size()!=vocab_size: | |
| raise ValueError(f'Only {tok.get_vocab_size()} tokens learned; add real training text, do not pad a research tokenizer.') | |
| tok.save(str(out/'bpe.json')); spec={'type':'byte-bpe','file':'bpe.json','capacity':vocab_size} | |
| meta.write_text(json.dumps(spec,ensure_ascii=False,indent=2),encoding='utf-8') | |
| t=ChatTokenizer(meta) | |
| for s in ['今天有点累,想聊聊。','Hello! I like tea.','名字:𠮷野🙂,价格3.14元。']: | |
| if t.decode(t.encode(s))!=s: raise RuntimeError('Tokenizer roundtrip failed') | |
| return meta | |
| def serialize(messages,tok,assistant_only=True): | |
| if not messages: raise ValueError('Empty conversation') | |
| ids=[BOS]; mask=[0 if assistant_only else 1] | |
| expected='user' | |
| for i,m in enumerate(messages): | |
| role=m.get('role'); text=m.get('content') | |
| if role not in ROLE or not isinstance(text,str) or not text.strip(): raise ValueError('Bad message') | |
| if role=='system': | |
| if i!=0: raise ValueError('System must be first') | |
| else: | |
| if role!=expected: raise ValueError('Expected alternating user/assistant messages') | |
| expected='assistant' if role=='user' else 'user' | |
| body=tok.encode(text); ids+=[ROLE[role]]+body+[EOS] | |
| mask+=([1]*(len(body)+2) if not assistant_only else [0]+[int(role=='assistant')]*(len(body)+1)) | |
| return ids,mask | |
| def prompt_ids(history,tok,max_prompt): | |
| """Drop oldest complete user/assistant turns, never truncate a role boundary.""" | |
| if not history or history[-1]['role']!='user': raise ValueError('Prompt must end with user') | |
| work=[dict(m) for m in history] | |
| while True: | |
| ids,_=serialize(work,tok) | |
| ids.append(ASSISTANT) | |
| if len(ids)<=max_prompt: return ids | |
| start=1 if work[0]['role']=='system' else 0 | |
| if len(work)-start<=1: raise ValueError('Latest message exceeds remaining context') | |
| del work[start:start+2] | |