File size: 5,349 Bytes
688186a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | #!/usr/bin/env python3
"""Teacher-forced top-k prompt logprobs from a running vLLM OpenAI server.
Usage: dump_logprobs.py --tokenizer MODEL_DIR --set chat|wikitext --out out.json [--prompts prompts.json]
Each sequence is tokenized client-side and sent as token ids to /v1/completions with
max_tokens=1 and prompt_logprobs=K, so both checkpoints see identical ids. Chat sequences are
full conversations (user + assistant turn) rendered through the model's chat template with a pinned
reasoning_effort. Output: {"meta": {...}, "seqs": [{"ids": [...], "lp": [{tok: logprob}, ...]}]};
"seqs" entries match the sensenova list schema (compare_logprobs.py reads both).
"""
import argparse
import json
import re
import sys
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
def chatml_to_messages(s: str) -> list[dict]:
"""Legacy sensenova prompts are ChatML strings; recover the message list."""
msgs = [
{"role": r, "content": c}
for r, c in re.findall(r"<\|im_start\|>(\w+)\n(.*?)<\|im_end\|>", s, flags=re.S)
]
if not msgs:
raise SystemExit("could not parse ChatML prompt: " + s[:80])
return msgs
def load_items(kind: str, path: str | None) -> list:
if path and Path(path).is_file():
items = json.loads(Path(path).read_text())
if not isinstance(items, list) or not items:
raise SystemExit(f"empty prompts file: {path}")
return items
if kind == "chat":
raise SystemExit("chat set needs --prompts (results/chat_prompts.json)")
from datasets import load_dataset
ds = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1", split="test")
return [t.strip()[:6000] for t in ds["text"] if len(t) > 800][:200]
def post(url: str, payload: dict, timeout: int) -> dict:
req = urllib.request.Request(
url, json.dumps(payload).encode(), {"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.load(r)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--tokenizer", required=True, help="local model dir (tokenizer + chat template)")
ap.add_argument("--set", dest="kind", choices=["chat", "wikitext"], required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--prompts", default=None)
ap.add_argument("--base-url", default="http://localhost:8000/v1")
ap.add_argument("--model", default="inkling", help="served model name")
ap.add_argument("--reasoning-effort", default="low", help="chat template kwarg (chat set only)")
ap.add_argument("--topk", type=int, default=20)
ap.add_argument("--max-tokens", type=int, default=4096, help="truncate sequences to this many tokens")
ap.add_argument("--concurrency", type=int, default=1) # >1 makes logprobs batch-dependent (self-KL 0.017 at 4)
ap.add_argument("--timeout", type=int, default=600)
args = ap.parse_args()
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(args.tokenizer)
items = load_items(args.kind, args.prompts)
seqs_ids: list[list[int]] = []
for it in items:
if args.kind == "chat":
msgs = chatml_to_messages(it) if isinstance(it, str) else it
text = tok.apply_chat_template(
msgs, tokenize=False, reasoning_effort=args.reasoning_effort
)
# The rendered template already carries every special token; do not add more.
ids = tok(text, add_special_tokens=False)["input_ids"]
else:
ids = tok(str(it))["input_ids"]
seqs_ids.append(ids[: args.max_tokens])
def one(ids: list[int]) -> dict:
resp = post(
f"{args.base_url}/completions",
{
"model": args.model,
"prompt": ids,
"max_tokens": 1,
"temperature": 0,
"prompt_logprobs": args.topk,
},
args.timeout,
)
plp = resp["choices"][0].get("prompt_logprobs") or []
seq = []
for pos in plp[1:]: # position 0 has no logprob
if pos is None:
continue
seq.append({k: v["logprob"] for k, v in pos.items()})
if len(seq) != len(ids) - 1:
raise RuntimeError(f"got {len(seq)} logprob positions for {len(ids)} tokens")
return {"ids": ids, "lp": seq}
with ThreadPoolExecutor(args.concurrency) as ex:
data = []
for i, d in enumerate(ex.map(one, seqs_ids), 1):
data.append(d)
if i % 20 == 0:
print(f"{i}/{len(seqs_ids)}", file=sys.stderr, flush=True)
meta = {
"set": args.kind,
"model": args.model,
"tokenizer": str(Path(args.tokenizer).resolve()),
"reasoning_effort": args.reasoning_effort if args.kind == "chat" else None,
"topk": args.topk,
"max_tokens": args.max_tokens,
"n_seqs": len(data),
"prompts": args.prompts,
"eos_token": tok.eos_token,
}
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
with open(args.out, "w", encoding="utf-8") as f:
json.dump({"meta": meta, "seqs": data}, f)
print(f"saved {len(data)} sequences -> {args.out}")
if __name__ == "__main__":
main()
|