Download eval_sample_forced.py from tts-sft/round4-forcing-cut: direct link, hf CLI and curl.
- Browser
- Download file 8.45 kB
-
https://huggingface.co/datasets/tts-sft/round4-forcing-cut/resolve/main/eval_sample_forced.py
- Command line
-
hf download hf://datasets/tts-sft/round4-forcing-cut/eval_sample_forced.py
-
curl -L -o eval_sample_forced.py https://huggingface.co/datasets/tts-sft/round4-forcing-cut/resolve/main/eval_sample_forced.py
8.45 kB
| #!/usr/bin/env python3 | |
| """Budget-forcing sampler: extend gpt-oss reasoning at inference (s1-style). | |
| Harman 08-24 directive: keep reasoning effort MEDIUM, but when the model ends | |
| its analysis (thinking) channel before a token floor, insert continuation | |
| tokens ("Wait, let me continue.") and resume thinking. Up to ~3x tokens is a | |
| legitimate adaptive-inference gain. | |
| Mechanism (raw /v1/completions + hand-rendered Harmony template; the chat API | |
| cannot continue inside the analysis channel): | |
| 1. prompt = system(Reasoning: medium) + user(question) + analysis header | |
| 2. generate with stop_token_ids=[<|end|>] (end of analysis channel) | |
| 3. if finish==stop and generated think tokens < --min-think-tokens: | |
| append --inject text inside the analysis channel, goto 2 | |
| 4. close analysis, open final channel, generate answer | |
| with stop_token_ids=[<|return|>, <|end|>] | |
| FLOOR=0 (min-think-tokens 0) never injects: use it as the same-harness | |
| unforced control arm. | |
| Output schema is a superset of eval_sample.py's, so eval_grade.py / | |
| eval_report.py work unchanged: {id,k,seed,text,rt,finish,pt,ct, | |
| max_completion_tokens} + forcing fields {n_forces,think_tokens,think_capped, | |
| min_think_tokens,inject,pt_last}. ct = TOTAL completion tokens across all | |
| calls (cost-accounting compatible). rt = full analysis text including the | |
| injected markers (that is the CoT the final answer actually conditioned on). | |
| Protocol match: temp 1.0, top_p 0.95, per-sample seed = base_seed + k, | |
| resumable via existing (id,k) rows in --out, --shard i/N, --ids file. | |
| python3 eval_sample_forced.py --testset testset.jsonl --model <name> \ | |
| --base-url http://localhost:8000/v1 --k 16 --ids b0_ids.txt \ | |
| --min-think-tokens 7300 --out out/samples_s0.jsonl | |
| Run probe_parity.py against the live server FIRST (verifies Harmony special | |
| token ids and render parity with the server chat template). | |
| """ | |
| import argparse, asyncio, json, os | |
| # o200k_harmony special tokens (verified by probe_parity.py against server) | |
| TOK_RETURN = 200002 # <|return|> ends the final channel | |
| TOK_END = 200007 # <|end|> ends every other message incl. analysis | |
| SYSTEM_TMPL = ( | |
| "You are ChatGPT, a large language model trained by OpenAI.\n" | |
| "Knowledge cutoff: 2024-06\n" | |
| "Current date: {date}\n\n" | |
| "Reasoning: {effort}\n\n" | |
| "# Valid channels: analysis, commentary, final. " | |
| "Channel must be included for every message." | |
| ) | |
| def render_prompt(question, date, effort="medium", system_tmpl=SYSTEM_TMPL): | |
| """Harmony prompt up to (and including) the open analysis header.""" | |
| sys_msg = system_tmpl.format(date=date, effort=effort) | |
| return ( | |
| f"<|start|>system<|message|>{sys_msg}<|end|>" | |
| f"<|start|>user<|message|>{question}<|end|>" | |
| f"<|start|>assistant<|channel|>analysis<|message|>" | |
| ) | |
| FINAL_HEADER = "<|end|><|start|>assistant<|channel|>final<|message|>" | |
| async def sample_one(client, a, r, k): | |
| seed = a.base_seed + k | |
| base_prompt = render_prompt(r["question"], a.current_date, a.effort) | |
| async def call(prompt, max_tokens, stop_ids): | |
| resp = await client.completions.create( | |
| model=a.model, prompt=prompt, max_tokens=max_tokens, | |
| temperature=1.0, top_p=0.95, seed=seed, timeout=a.timeout, | |
| extra_body={"stop_token_ids": stop_ids, | |
| "include_stop_str_in_output": False}) | |
| ch = resp.choices[0] | |
| u = resp.usage | |
| return (ch.text or "", ch.finish_reason, | |
| u.completion_tokens if u else 0, | |
| u.prompt_tokens if u else None) | |
| think, think_tokens, n_forces, pt_first, pt_last = "", 0, 0, None, None | |
| think_capped = False | |
| while True: | |
| remaining = a.max_think_tokens - think_tokens | |
| if remaining <= 0: | |
| think_capped = True | |
| break | |
| text, finish, ct_chunk, pt = await call( | |
| base_prompt + think, remaining, [TOK_END]) | |
| if pt_first is None: | |
| pt_first = pt | |
| pt_last = pt | |
| think += text | |
| think_tokens += ct_chunk | |
| if finish == "length": | |
| think_capped = think_tokens >= a.max_think_tokens | |
| break | |
| # finish == "stop": model closed the analysis channel | |
| if think_tokens >= a.min_think_tokens or n_forces >= a.max_forces: | |
| break | |
| think += a.inject | |
| n_forces += 1 | |
| final_text, final_finish, ct_final, pt_final = await call( | |
| base_prompt + think + FINAL_HEADER, a.final_max_tokens, | |
| [TOK_RETURN, TOK_END]) | |
| return {"id": r["id"], "k": k, "seed": seed, | |
| "text": final_text, "rt": think, "finish": final_finish, | |
| "pt": pt_first, "ct": think_tokens + ct_final, | |
| "max_completion_tokens": a.max_think_tokens + a.final_max_tokens, | |
| "n_forces": n_forces, "think_tokens": think_tokens, | |
| "think_capped": think_capped, | |
| "min_think_tokens": a.min_think_tokens, | |
| "inject": a.inject, "pt_last": pt_final} | |
| async def main(a): | |
| from openai import AsyncOpenAI | |
| rows = [json.loads(l) for l in open(a.testset)] | |
| rows.sort(key=lambda r: r["id"]) | |
| if a.ids: | |
| want = {l.strip() for l in open(a.ids) if l.strip()} | |
| rows = [r for r in rows if r["id"] in want] | |
| if a.shard: | |
| i, n = map(int, a.shard.split("/")) | |
| rows = rows[i::n] | |
| done = set() | |
| if os.path.exists(a.out): | |
| for l in open(a.out): | |
| try: | |
| r = json.loads(l) | |
| done.add((r["id"], r["k"])) | |
| except Exception: | |
| pass | |
| todo = [(r, k) for r in rows for k in range(a.k) if (r["id"], k) not in done] | |
| print(f"{len(rows)} problems x k={a.k}; floor={a.min_think_tokens}; " | |
| f"{len(done)} done, {len(todo)} to sample", flush=True) | |
| import httpx | |
| # local vLLM endpoint: never route through proxy env (SOCKS boxes) | |
| client = AsyncOpenAI(base_url=a.base_url, api_key=a.api_key, | |
| timeout=a.timeout, | |
| http_client=httpx.AsyncClient(trust_env=False, | |
| timeout=a.timeout)) | |
| sem = asyncio.Semaphore(a.concurrency) | |
| outf = open(a.out, "a") | |
| lock = asyncio.Lock() | |
| async def one(r, k): | |
| async with sem: | |
| for attempt in range(5): | |
| try: | |
| rec = await sample_one(client, a, r, k) | |
| async with lock: | |
| outf.write(json.dumps(rec) + "\n"); outf.flush() | |
| return | |
| except Exception as e: # noqa: BLE001 | |
| if attempt == 4: | |
| print(f"GIVEUP {r['id']} k={k}: {type(e).__name__}", | |
| flush=True) | |
| return | |
| await asyncio.sleep(min(60, 2 ** attempt * 5)) | |
| CH = 2000 | |
| for i in range(0, len(todo), CH): | |
| await asyncio.gather(*(one(r, k) for r, k in todo[i:i + CH])) | |
| print(f"{min(i + CH, len(todo))}/{len(todo)}", flush=True) | |
| outf.close() | |
| print("SAMPLING DONE", flush=True) | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--testset", required=True) | |
| ap.add_argument("--model", required=True) | |
| ap.add_argument("--base-url", default="http://localhost:8000/v1") | |
| ap.add_argument("--api-key", default="EMPTY") | |
| ap.add_argument("--k", type=int, default=16) | |
| ap.add_argument("--min-think-tokens", type=int, required=True, | |
| help="forcing floor; 0 = unforced same-harness control") | |
| ap.add_argument("--max-think-tokens", type=int, default=24576) | |
| ap.add_argument("--final-max-tokens", type=int, default=8192) | |
| ap.add_argument("--inject", default="\nWait, let me continue.") | |
| ap.add_argument("--max-forces", type=int, default=24) | |
| ap.add_argument("--effort", default="medium") | |
| ap.add_argument("--current-date", default="2026-08-24", | |
| help="pinned so every arm shares one system prompt") | |
| ap.add_argument("--shard", default=None, help="i/N over sorted problem ids") | |
| ap.add_argument("--ids", default=None, help="file of ids (one per line)") | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--base-seed", type=int, default=1234) | |
| ap.add_argument("--concurrency", type=int, default=128) | |
| ap.add_argument("--timeout", type=float, default=1800) | |
| args = ap.parse_args() | |
| asyncio.run(main(args)) | |