"""Second-chance pass for reasoning models whose answer was cut off by the per-family token cap (finish_reason == 'length'). The capped records are archived to responses_truncated/.jsonl and removed from the main response file; the same queries are then re-generated with a 14,336-token budget (shrunk automatically when prompt + budget would exceed the 16,384 context). This is equivalent to having used the larger budget from the start (same seeds), so the final dataset carries ONE response per (query, model); archived records document the capped attempt. Run only when no other generation is running. Usage: python extend_truncated.py [--models a,b] """ import argparse, hashlib, json, sys, time from pathlib import Path import pandas as pd sys.path.insert(0, "src") from llmroute.seqroute import serve as S from llmroute.seqroute.client import run_jobs, read_ids ROOT = Path("/mnt/localssd/seqroute1m") EXT_BUDGET = 14336 # 14k-token sequences exhaust the KV cache of data-parallel replicas of the larger models (preemption thrash): use TP2 and cap concurrency there EXT_TP = {"magistral_small_24b": 2, "r1_distill_qwen_14b": 2} EXT_SEQS = {1: 40, 2: 64} ap = argparse.ArgumentParser(); ap.add_argument("--models", default=""); a = ap.parse_args() specs = [m for m in json.load(open(ROOT / "manifests/models.json")) if m["reasoning"]] if a.models: specs = [m for m in specs if m["id"] in a.models.split(",")] q = pd.read_parquet(ROOT / "queries/queries_20k.parquet", columns=["query_id", "prompt"]).set_index("query_id").prompt (ROOT / "responses_truncated").mkdir(exist_ok=True) for spec in specs: mid = spec["id"]; f = ROOT / "responses" / f"{mid}.jsonl" arch = ROOT / "responses_truncated" / f"{mid}.jsonl" keep, cut = [], [] for l in open(f): r = json.loads(l) (cut if r["finish_reason"] == "length" and r["id"] in q.index and r.get("budget", 0) < EXT_BUDGET else keep).append(l) done_arch = read_ids(arch) with open(arch, "a") as g: for l in cut: if json.loads(l)["id"] not in done_arch: g.write(l) if cut: tmp = f.with_suffix(".tmp"); tmp.write_text("".join(keep)); tmp.replace(f) ids = [json.loads(l)["id"] for l in open(arch)] have_ids = read_ids(f) todo_ids = [i for i in dict.fromkeys(ids) if i not in have_ids] print(f"{mid}: {len(cut)} newly archived, {len(todo_ids)} to regenerate at budget {EXT_BUDGET}", flush=True) if not todo_ids: continue jobs = [dict(id=i, prompt=q[i], max_tokens=EXT_BUDGET, seed=int(hashlib.sha1(f"{i}|{mid}".encode()).hexdigest()[:8], 16) % (2 ** 31)) for i in todo_ids] sspec = dict(spec, tp=EXT_TP.get(mid, spec["tp"])) t0 = time.time(); S.stop_servers(); ports = S.start_servers(sspec, max_num_seqs=EXT_SEQS[sspec["tp"]]); S.wait_ready(ports); t1 = time.time() params = dict(temperature=spec["temperature"], top_p=spec["top_p"], chat_template_kwargs=spec["chat_template_kwargs"], system=spec.get("system")) st = {} for att in range(3): run_jobs(jobs, f, mid, ports, params, per_server=EXT_SEQS[sspec["tp"]] * 2, every=1000, stats=st) have = read_ids(f); jobs = [j for j in jobs if j["id"] not in have] if not jobs: break Path(str(f) + ".errors").rename(str(f) + f".ext_round{att}") wall = time.time() - t1; S.stop_servers() json.dump(dict(model=mid, wave="ext", n_generated=len(todo_ids), n_failed_final=len(jobs), gen_wall_s=wall, startup_s=t1 - t0, n_gpus=8, gpu_seconds=wall * 8, completion_tokens=st.get("completion_tokens", 0), prompt_tokens=st.get("prompt_tokens", 0), ctx_shrunk=st.get("ctx_shrunk", 0), ts=time.strftime("%F %T")), open(ROOT / "responses" / f"{mid}.ext.stats.json", "w"), indent=1) print("ext done")