#!/usr/bin/env python3 """Greedy-decode 64 tokens for the ref_compare prompts (token ids in results/ref_prompts.json) on a running server and save them; optionally compare with another variant's saved run (normally the eager one). At the first differing token, prints the reference run's top-2 logprob margin there, so near-ties (bf16 noise) can be told apart from real divergence. python3 tests/greedy_variant.py PORT OUT.json [REF.json] [--concurrent] """ import json, sys, urllib.request from concurrent.futures import ThreadPoolExecutor args = [a for a in sys.argv[1:] if not a.startswith("--")] port, out_path = int(args[0]), args[1] ref_path = args[2] if len(args) > 2 else None prompts = {k: v["prompt_ids"] for k, v in json.load(open("results/ref_prompts.json"))["results"].items()} N = 64 def gen(item): name, ids = item body = {"model": "lfm3-1.7b", "prompt": ids, "max_tokens": N, "temperature": 0.0, "repetition_penalty": 1.0, "ignore_eos": True, "logprobs": 2, "return_tokens_as_token_ids": True} req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) lp = json.loads(urllib.request.urlopen(req, timeout=600).read())["choices"][0]["logprobs"] toks = [int(t.split(":")[1]) for t in lp["tokens"]] margins = [v[0] - v[1] if len(v) > 1 else None for v in (sorted(top.values(), reverse=True) for top in lp["top_logprobs"])] return name, {"tokens": toks, "margins": margins} workers = len(prompts) if "--concurrent" in sys.argv else 1 with ThreadPoolExecutor(workers) as ex: res = dict(ex.map(gen, prompts.items())) json.dump(res, open(out_path, "w")) if ref_path: ref = json.load(open(ref_path)) total = 0 for name, r in res.items(): want = ref[name]["tokens"] same = next((i for i, (a, b) in enumerate(zip(r["tokens"], want)) if a != b), len(want)) total += same == len(want) note = "" if same == len(want) else f" (ref top-2 margin at pos {same}: {ref[name]['margins'][same]:.3f})" print(f"{name:<15} identical prefix {same}/{len(want)}{note}") print(f"{total}/{len(res)} prompts identical for all {N} tokens")