"""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