"""Build fixed-length chat prompts (512 / 4096 / 16384 tokens) for each model's tokenizer. Body text = the click 8.1.8 source (BSD-3, downloaded from PyPI into corpus/), cut so that the full chat-templated prompt (thinking disabled) is exactly N tokens. Each prompt starts with a 4-digit request nonce ("Request 0001.") so no backend can reuse a cached prefix between runs; digits tokenize one per token, so every nonce variant has the same length (asserted below). Usage: HF_HUB_OFFLINE=1 python make_prompts.py --out prompts """ import argparse import glob import json import os from transformers import AutoTokenizer HF = os.path.expanduser("~/.cache/huggingface/hub") MODELS = { # config -> HF repo whose tokenizer/chat template is used "A": "mlx-community/Qwen3.8-27B-4bit", "B": "mlx-community/Qwen3.8-27B-4bit", # same model as A; ollama gets the identical text "C": "mlx-community/Qwen3.6-35B-A3B-4bit", "D": "LiquidAI/LFM2.5-24B-A2B-MLX-4bit", } LENGTHS = [512, 4096, 16384] N_VARIANTS = 4 # nonce 0 = warm-up, 1..3 = timed reps HEADER = "Below is the source code of a Python library.\n\n" INSTRUCTION = "\n\nSummarize the above in 5 bullet points." def snapshot(repo): d = os.path.join(HF, "models--" + repo.replace("/", "--"), "snapshots") return sorted(glob.glob(os.path.join(d, "*")))[0] def corpus_text(): files = sorted(glob.glob("corpus/click_src/click/*.py")) assert files, "corpus missing: run setup (see README)" return "".join(f"# file: click/{os.path.basename(f)}\n{open(f).read()}\n" for f in files) FILLERS = ["", ".", "#", " #", "\n#"] # tried in order if a cut point can't hit n exactly def build(tok, body_ids, k, nonce, filler=""): text = HEADER + tok.decode(body_ids[:k]).rstrip() + filler + INSTRUCTION msgs = [{"role": "user", "content": f"Request {nonce:04d}.\n" + text}] s = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False) if s.endswith(""): # LFM2.5 always opens a think block; close it empty (= no reasoning) s += "\n\n\n" return s, tok.encode(s, add_special_tokens=False) def fit(tok, body_ids, n): """Find k body tokens so the templated prompt is exactly n tokens.""" _, ids0 = build(tok, body_ids, 0, 0) k = n - len(ids0) for _ in range(10): _, ids = build(tok, body_ids, k, 0) if len(ids) == n: return k, "" k += n - len(ids) # decode/re-encode merges can make the count jump by 2 at the cut; try nearby cut points # and a one-character filler before the instruction for filler in FILLERS: for d in range(0, 16): for kk in (k - d, k + d): if len(build(tok, body_ids, kk, 0, filler)[1]) == n: return kk, filler raise RuntimeError(f"could not hit {n} tokens exactly near k={k}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default="prompts") ap.add_argument("--configs", default="A,B,C,D") args = ap.parse_args() os.makedirs(args.out, exist_ok=True) corpus = corpus_text() cache = {} for cfg in args.configs.split(","): repo = MODELS[cfg] if repo not in cache: tok = AutoTokenizer.from_pretrained(snapshot(repo)) body_ids = tok.encode(corpus, add_special_tokens=False) cache[repo] = {} for n in LENGTHS: k, filler = fit(tok, body_ids, n) variants = [] for v in range(N_VARIANTS): s, ids = build(tok, body_ids, k, v, filler) assert len(ids) == n, (repo, n, v, len(ids)) variants.append({"nonce": v, "text": s, "ids": ids}) cache[repo][n] = {"body_tokens": k, "filler": filler, "variants": variants} print(f"{cfg} {repo}: {n} tokens (body {k} tokens, corpus {len(body_ids)})") out = {"config": cfg, "tokenizer_repo": repo, "instruction": INSTRUCTION.strip(), "lengths": {str(n): cache[repo][n] for n in LENGTHS}} with open(os.path.join(args.out, f"{cfg}.json"), "w") as f: json.dump(out, f) if __name__ == "__main__": main()