| """Evaluate Dream-7B-Instruct with baseline / CCD / CCD-DS on Trip Plan or HumanEval. |
| |
| Hyperparameters follow the Dream authors' official eval scripts, which is what the |
| paper says it does ("we follow the base models' default settings without tuning"): |
| |
| Trip Plan : steps=256, max_new_tokens=256, temperature=0, top_p=1, alg=entropy |
| (DreamLM/Dream eval/eval_dream_gen_planning.sh) -- 2-shot prompt |
| HumanEval : steps=768, max_new_tokens=768, temperature=0.1, top_p=0.9, alg=entropy |
| (DreamLM/Dream eval_instruct/eval.sh) -- 0-shot, chat template |
| |
| Usage: |
| python run_eval.py --task trip --method ccd_ds --limit 100 --out outputs/x.json |
| """ |
| import argparse, json, os, random, sys, time |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
|
|
| import numpy as np |
| import torch |
| from transformers import AutoModel, AutoTokenizer |
|
|
| import ccd_decode |
| from trip_metric import parse_response, compute_example_score |
| from sanitize_utils import sanitize |
|
|
| MODEL = "Dream-org/Dream-v0-Instruct-7B" |
| HERE = os.path.dirname(os.path.abspath(__file__)) |
| DATA = os.path.join(HERE, "..", "data") |
|
|
| TASK_DEFAULTS = { |
| "trip": dict(steps=256, max_new_tokens=256, temperature=0.0, top_p=1.0), |
| "humaneval": dict(steps=768, max_new_tokens=768, temperature=0.1, top_p=0.9), |
| } |
|
|
|
|
| |
|
|
| def load_trip(limit=None, num_cities=None, seed=0): |
| """Load Trip Plan examples. |
| |
| IMPORTANT: the benchmark file is ordered by difficulty -- the first 200 of the |
| 1600 examples all have num_cities=3 (the easiest tier), then 200 with 4, etc. |
| Taking a prefix therefore samples ONLY the easiest tier and inflates the score |
| (measured: 55% on a prefix-60 vs the paper's 15.10% over the full set). |
| When no explicit tier is requested we take a *stratified* sample: equal numbers |
| from each num_cities tier, so the subset matches the full benchmark's mix. |
| """ |
| with open(os.path.join(DATA, "trip_planning.json")) as f: |
| data = json.load(f) |
| items = list(data.values()) |
| if num_cities is not None: |
| |
| |
| items = [i for i in items if i["num_cities"] == str(num_cities)] |
| if limit: |
| items = items[:limit] |
| elif limit: |
| tiers = sorted({i["num_cities"] for i in items}, key=int) |
| per = limit // len(tiers) |
| rng = random.Random(seed) |
| picked = [] |
| for t in tiers: |
| pool = [i for i in items if i["num_cities"] == t] |
| picked.extend(rng.sample(pool, min(per, len(pool)))) |
| |
| if len(picked) < limit: |
| rest = [i for i in items if i not in picked] |
| picked.extend(rng.sample(rest, limit - len(picked))) |
| items = picked |
| |
| prompts = [] |
| for i in items: |
| splits = i["prompt_5shot"].split("TASK:") |
| prompts.append("TASK:".join(splits[:3] + [splits[-1]])) |
| return items, prompts |
|
|
|
|
| def load_humaneval(limit=None, offset=0): |
| """HumanEval problems [offset, offset+limit). |
| |
| The offset lets us EXTEND an existing run instead of repeating it: having |
| already scored problems 0..31, we buy problems 32..63 and merge to n=64 for |
| the price of the increment rather than re-running the whole prefix. |
| """ |
| from datasets import load_dataset |
| ds = load_dataset("openai/openai_humaneval", split="test") |
| items = list(ds)[offset:] |
| if limit: |
| items = items[:limit] |
| return items |
|
|
|
|
| def humaneval_prompt(tok, doc): |
| """lm_eval humaneval_instruct: user doc_to_text + assistant gen_prefix, continued.""" |
| user = ("Write a solution to the following problem and make sure that it " |
| "passes the tests:\n```" + doc["prompt"]) |
| prefix = "Here is the completed function:\n```python\n" + doc["prompt"] + "\n" |
| chat = [{"role": "user", "content": user}, |
| {"role": "assistant", "content": prefix}] |
| return tok.apply_chat_template(chat, tokenize=False, |
| add_generation_prompt=False, |
| continue_final_message=True) |
|
|
|
|
| |
|
|
| def score_trip(items, responses): |
| scores = [] |
| for item, r in zip(items, responses): |
| r = r.split("<|endoftext|>")[0].split("\n\nTASK")[0] |
| scores.append(compute_example_score(item["cities"], item["durations"], |
| parse_response(r))) |
| return 100.0 * sum(scores) / len(scores), scores |
|
|
|
|
| def score_humaneval(items, responses): |
| """pass@1 via subprocess exec, mirroring lm_eval's code_eval + build_predictions_instruct.""" |
| import subprocess, tempfile |
| scores = [] |
| for doc, r in zip(items, responses): |
| for stop in ["\nclass", "\ndef", "\n#", "\nif", "\nprint"]: |
| r = r.split(stop)[0] |
| body = r.split("```python\n", 1)[-1].split("```")[0] |
| code = sanitize(doc["prompt"] + "\n" + body, doc["entry_point"]) |
| program = code + "\n" + doc["test"] + "\n" + f"check({doc['entry_point']})\n" |
| with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f: |
| f.write(program); path = f.name |
| try: |
| p = subprocess.run([sys.executable, path], capture_output=True, timeout=15) |
| scores.append(1.0 if p.returncode == 0 else 0.0) |
| except subprocess.TimeoutExpired: |
| scores.append(0.0) |
| finally: |
| os.unlink(path) |
| return 100.0 * sum(scores) / len(scores), scores |
|
|
|
|
| |
|
|
| class _NoMaskLogits(torch.nn.Module): |
| """Dry-run only: forbid emitting <|mask|> as a clean-data prediction. |
| |
| A trained Dream never does; a randomly initialised tiny model does, which |
| re-masks positions and hides real bugs behind noise. |
| """ |
| def __init__(self, inner, mask_id): |
| super().__init__() |
| self.inner, self.mask_id = inner, mask_id |
| self.config = inner.config |
|
|
| def forward(self, *a, **kw): |
| out = self.inner(*a, **kw) |
| out.logits[..., self.mask_id] = -1e4 |
| return out |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--task", choices=["trip", "humaneval"], required=True) |
| ap.add_argument("--method", choices=["baseline", "ccd", "ccd_ds"], required=True) |
| ap.add_argument("--limit", type=int, default=None) |
| ap.add_argument("--offset", type=int, default=0, |
| help="skip the first N problems (HumanEval; lets a run extend an earlier one)") |
| ap.add_argument("--num-cities", type=int, default=None) |
| ap.add_argument("--buffer-V", type=int, default=4) |
| ap.add_argument("--history-d", type=int, default=3) |
| ap.add_argument("--temperature", type=float, default=None) |
| ap.add_argument("--top-p", type=float, default=None, |
| help="override top_p; 1.0 disables nucleus filtering") |
| ap.add_argument("--steps", type=int, default=None) |
| ap.add_argument("--out", required=True) |
| ap.add_argument("--seed", type=int, default=0, |
| help="RNG seed for temperature sampling. Only bites when temperature>0: " |
| "at T=0 ccd_decode._pick_token takes the argmax, so those runs are " |
| "deterministic with or without it. Does NOT affect which examples are " |
| "evaluated -- load_trip's stratified sample is fixed at seed 0 so every " |
| "arm scores the same examples.") |
| ap.add_argument("--tiny", action="store_true", |
| help="local CPU dry-run with tiny random weights") |
| args = ap.parse_args() |
|
|
| |
| |
| |
| |
| random.seed(args.seed) |
| np.random.seed(args.seed) |
| torch.manual_seed(args.seed) |
| torch.cuda.manual_seed_all(args.seed) |
|
|
| cfg = dict(TASK_DEFAULTS[args.task]) |
| if args.temperature is not None: |
| cfg["temperature"] = args.temperature |
| if args.top_p is not None: |
| cfg["top_p"] = args.top_p |
| if args.steps is not None: |
| cfg["steps"] = args.steps; cfg["max_new_tokens"] = args.steps |
|
|
| print(f"[cfg] task={args.task} method={args.method} V={args.buffer_V} d={args.history_d} " |
| f"seed={args.seed} {cfg}", flush=True) |
|
|
| tok = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=True) |
| if args.tiny: |
| |
| |
| from transformers import AutoConfig |
| cfg_m = AutoConfig.from_pretrained(MODEL, trust_remote_code=True) |
| cfg_m.num_hidden_layers, cfg_m.hidden_size = 2, 128 |
| cfg_m.intermediate_size, cfg_m.num_attention_heads = 256, 4 |
| cfg_m.num_key_value_heads, cfg_m.tie_word_embeddings = 2, True |
| model = AutoModel.from_config(cfg_m, trust_remote_code=True).eval() |
| model = _NoMaskLogits(model, cfg_m.mask_token_id) |
| device = "cpu" |
| else: |
| model = AutoModel.from_pretrained(MODEL, torch_dtype=torch.bfloat16, |
| trust_remote_code=True).to("cuda").eval() |
| device = "cuda" |
| mask_id = model.config.mask_token_id |
|
|
| if args.task == "trip": |
| items, prompts = load_trip(args.limit, args.num_cities) |
| else: |
| items = load_humaneval(args.limit, args.offset) |
| prompts = [humaneval_prompt(tok, d) for d in items] |
|
|
| responses, all_steps, all_budgets, n_fallback = [], [], [], 0 |
| all_ic, all_stable = [], [] |
| t0 = time.time() |
| for n, prompt in enumerate(prompts): |
| enc = tok(prompt, return_tensors="pt") |
| input_ids = enc.input_ids.to(device) |
| attn = enc.attention_mask.to(device) |
| x, st = ccd_decode.generate( |
| model, input_ids, attention_mask=attn, |
| max_new_tokens=cfg["max_new_tokens"], steps=cfg["steps"], |
| temperature=cfg["temperature"], top_p=cfg["top_p"], |
| mask_token_id=mask_id, method=args.method, |
| buffer_V=args.buffer_V, history_d=args.history_d, |
| ) |
| gen = x[0, input_ids.shape[1]:] |
| text = tok.decode(gen.tolist()).split(tok.eos_token)[0] |
| responses.append(text) |
| all_steps.append(st["steps"]) |
| all_budgets.append(st["budgets"]) |
| all_ic.append(st["ic_sizes"]) |
| all_stable.append(st["n_stable"]) |
| n_fallback += st["fallbacks"] |
| if n == 0: |
| print(f"--- example 0 response ---\n{text[:600]}\n---", flush=True) |
| if (n + 1) % 10 == 0: |
| el = time.time() - t0 |
| print(f"[{n+1}/{len(prompts)}] mean_steps={sum(all_steps)/len(all_steps):.2f} " |
| f"elapsed={el/60:.1f}min eta={el/(n+1)*(len(prompts)-n-1)/60:.1f}min", flush=True) |
|
|
| if args.task == "trip": |
| score, per_ex = score_trip(items, responses) |
| else: |
| score, per_ex = score_humaneval(items, responses) |
|
|
| mean_steps = sum(all_steps) / len(all_steps) |
| result = { |
| "task": args.task, "method": args.method, "config": cfg, |
| "buffer_V": args.buffer_V, "history_d": args.history_d, |
| "n_examples": len(items), "score": score, "offset": args.offset, "seed": args.seed, |
| "mean_steps": mean_steps, |
| "speedup_vs_uniform": cfg["steps"] / mean_steps, |
| "fallback_steps": n_fallback, |
| "wall_clock_s": time.time() - t0, |
| "per_example_score": per_ex, "per_example_steps": all_steps, |
| "responses": responses, |
| "budgets": all_budgets, |
| "ic_sizes": all_ic, "n_stable": all_stable, |
| } |
| os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True) |
| with open(args.out, "w") as f: |
| json.dump(result, f, indent=1) |
|
|
| print(f"\n=== RESULT {args.task}/{args.method} V={args.buffer_V} d={args.history_d} ===") |
| print(f"score={score:.2f} mean_steps={mean_steps:.2f} " |
| f"speedup={cfg['steps']/mean_steps:.2f}x n={len(items)} " |
| f"fallback_steps={n_fallback} wall={result['wall_clock_s']/60:.1f}min") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|