#!/usr/bin/env python3 """Content-addressed, model-specific token compilation for SmolCUA. This module is intentionally independent of torch/vLLM. Fast HF tokenizers process *all* selected benchmark prompts in CPU batches before inference; inference engines only consume token IDs. A content-addressed persistent cache skips that CPU work on later runs of the same model and dataset revision. """ from __future__ import annotations import hashlib import json import os from pathlib import Path import statistics import time VERSION = 2 def stable_json(value): return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str) def sha(value): return hashlib.sha256(value if isinstance(value, bytes) else str(value).encode('utf-8')).hexdigest() def tokenizer_fingerprint(tokenizer): """Fingerprint the *actual* tokenizer, not only its HF repository name. The backend tokenization graph changes if merges/vocabulary/pre-tokenizer change without a revision bump. Slow custom tokenizers use their vocab. """ fp = hashlib.sha256() for obj in (type(tokenizer).__module__ + '.' + type(tokenizer).__qualname__, getattr(tokenizer, 'init_kwargs', {}), getattr(tokenizer, 'special_tokens_map', {}), getattr(tokenizer, 'added_tokens_decoder', {}), getattr(tokenizer, 'chat_template', None), getattr(tokenizer, 'bos_token_id', None), getattr(tokenizer, 'eos_token_id', None)): fp.update(sha(stable_json(obj)).encode()) backend = getattr(tokenizer, 'backend_tokenizer', None) if backend is not None and hasattr(backend, 'to_str'): fp.update(sha(backend.to_str()).encode()) elif hasattr(tokenizer, 'get_vocab'): fp.update(sha(stable_json(tokenizer.get_vocab())).encode()) return fp.hexdigest() def compile_key(rows, tokenizer, args, dataset_sha): settings = { 'cache_version': VERSION, 'dataset_sha256': dataset_sha, 'selected_ids_sha256': sha(stable_json([r['id'] for r in rows])), 'tokenizer_repo': getattr(args, 'tokenizer', None) or args.model, 'tokenizer_revision': getattr(args, 'tokenizer_revision', None) or args.revision, 'tokenizer_fingerprint': tokenizer_fingerprint(tokenizer), 'prompt_mode': args.prompt_mode, 'chat_template_kwargs': args.chat_template_kwargs, 'prompt_formatter_version': getattr(args, 'prompt_formatter_version', 'smolcua:1'), 'prompt_content_sha256': sha(stable_json(rows)), } return sha(stable_json(settings)), settings def effective_style(tokenizer, mode): has_template = bool(getattr(tokenizer, 'chat_template', None)) if mode == 'chat' and not has_template: raise ValueError('This tokenizer has no chat template: use --prompt-mode plain') return ('chat' if has_template else 'plain') if mode == 'auto' else mode def build_text(row, tokenizer, mode, template_kwargs, format_prompt): prompt = format_prompt(row) if effective_style(tokenizer, mode) == 'plain': return prompt + '\n\nAnswer:\n' return tokenizer.apply_chat_template( [{'role': 'user', 'content': prompt}], tokenize=False, add_generation_prompt=True, **template_kwargs) def token_stats(items): lengths = sorted(len(v['input_ids']) for v in items.values()) if not lengths: return {'count': 0, 'input_tokens': 0, 'max_input_tokens': 0, 'p50_input_tokens': 0, 'p95_input_tokens': 0} return {'count': len(lengths), 'input_tokens': sum(lengths), 'max_input_tokens': lengths[-1], 'p50_input_tokens': int(statistics.median(lengths)), 'p95_input_tokens': lengths[min(len(lengths)-1, int((len(lengths)-1)*.95))]} def compile_tokens(rows, tokenizer, args, dataset_sha, format_prompt, prompt_builder=None): """Return (id -> tokenized prompt, performance info). The entire list is compiled *before* the first model.generate call. Reused caches preserve exact token sequences and do not repeat tokenizer calls. Cache files are local to the evaluating user; never upload token caches or real model responses with the public benchmark questions. """ progress = getattr(args, '_progress', None) if progress: progress.update(stage=f'checking token cache ({len(rows)} prompts)', force=True) started = time.perf_counter() key, settings = compile_key(rows, tokenizer, args, dataset_sha) cache_root = Path(getattr(args, 'token_cache_dir', None) or '~/.cache/smolcua/tokens').expanduser() use_disk = not getattr(args, 'no_token_cache', False) rebuild = getattr(args, 'rebuild_token_cache', False) path = cache_root / (key + '.json') if use_disk else None wanted_ids = [r['id'] for r in rows] if path is not None and path.exists() and not rebuild: try: obj = json.loads(path.read_text(encoding='utf-8')) valid = (obj.get('settings') == settings and list(obj.get('items', {})) == wanted_ids and obj.get('tokens_sha256') == sha(stable_json(obj.get('items', {})))) if valid: items = obj['items'] valid = all(isinstance(p.get('input_ids'), list) and p['input_ids'] and all(isinstance(t, int) and t >= 0 for t in p['input_ids']) for p in items.values()) if valid: if progress: progress.update(stage=f'token cache hit: {len(items)}/{len(rows)} prompts', force=True) return items, { 'status': 'hit', 'path': str(path), 'elapsed_seconds': round(time.perf_counter()-started, 4), **token_stats(items)} except (OSError, ValueError, KeyError, TypeError, AttributeError): pass # A stale/partial cache is rebuilt, not silently used. batch_size = int(getattr(args, 'tokenize_batch_size', 512)) if batch_size <= 0: raise ValueError('--tokenize-batch-size must be positive') items = {} for off in range(0, len(rows), batch_size): group = rows[off:off+batch_size] prompts = [prompt_builder(q) if prompt_builder else build_text(q, tokenizer, args.prompt_mode, args.chat_template_kwargs, format_prompt) for q in group] # Batched Rust tokenizer threads when available; no padding and NEVER truncate. # Chat templates already inject their own special tokens, so disable # add_special_tokens to avoid BOS/EOS duplication. enc = tokenizer(prompts, add_special_tokens=False, padding=False, truncation=False, return_attention_mask=False) ids = enc['input_ids'] if len(ids) != len(group): raise ValueError('Tokenizer returned incorrect number of sequences') types = enc.get('token_type_ids') if hasattr(enc, 'get') else None for i, (row, sequence) in enumerate(zip(group, ids)): seq = [int(t) for t in sequence] if not seq or min(seq) < 0: raise ValueError(f'Empty/invalid tokenized benchmark prompt: {row["id"]}') if row['id'] in items: raise ValueError(f'Duplicate row ID: {row["id"]}') item = {'input_ids': seq} if types is not None: t = [int(x) for x in types[i]] if len(t) != len(seq): raise ValueError('token_type_ids shape mismatch') item['token_type_ids'] = t items[row['id']] = item if progress: progress.update(stage=f'pretokenized {len(items)}/{len(rows)} prompts', force=True) elif not getattr(args, 'quiet', False): print(f'Pretokenized {len(items)}/{len(rows)} prompts', flush=True) if path is not None: cache_root.mkdir(parents=True, exist_ok=True, mode=0o700) tmp = path.with_name(path.name + f'.{os.getpid()}.tmp') try: with open(tmp, 'w', encoding='utf-8') as f: os.chmod(tmp, 0o600) json.dump({'settings': settings, 'items': items, 'tokens_sha256': sha(stable_json(items))}, f, ensure_ascii=False, separators=(',', ':')) os.replace(tmp, path) finally: if tmp.exists(): tmp.unlink() return items, {'status': 'built' if use_disk else 'memory', 'path': str(path) if path else None, 'elapsed_seconds': round(time.perf_counter()-started, 4), **token_stats(items)} def padded_batch(group, pad_token_id, padding_side='left', include_token_types=True): """Pad cached token IDs directly into torch tensors without tokenizer calls.""" import torch if not group: raise ValueError('Cannot pad an empty group') if pad_token_id is None: raise ValueError('Tokenizer must have a valid pad token ID for Transformers batching') maxlen = max(len(t['input_ids']) for t in group) input_ids = torch.full((len(group), maxlen), int(pad_token_id), dtype=torch.long) attention_mask = torch.zeros((len(group), maxlen), dtype=torch.long) has_types = include_token_types and all('token_type_ids' in t for t in group) types = torch.zeros((len(group), maxlen), dtype=torch.long) if has_types else None for i, item in enumerate(group): toks = item['input_ids'] start = (maxlen - len(toks)) if padding_side == 'left' else 0 end = start + len(toks) input_ids[i, start:end] = torch.as_tensor(toks, dtype=torch.long) attention_mask[i, start:end] = 1 if has_types: types[i, start:end] = torch.as_tensor(item['token_type_ids'], dtype=torch.long) out = {'input_ids': input_ids, 'attention_mask': attention_mask} if has_types: out['token_type_ids'] = types return out