File size: 12,661 Bytes
b222eb5 2a88bc9 b222eb5 2a88bc9 b222eb5 ed62109 b222eb5 ed62109 b222eb5 ed62109 b222eb5 7d05566 b222eb5 7d05566 b222eb5 7d05566 b222eb5 63502da b222eb5 2a88bc9 b222eb5 2a88bc9 b222eb5 63502da b222eb5 2a88bc9 b222eb5 7d05566 b222eb5 02bdb20 b222eb5 02bdb20 b222eb5 2a88bc9 b222eb5 02bdb20 b222eb5 | 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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | """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),
}
# ---------------------------------------------------------------- data / prompts
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:
# single-tier request (e.g. the Claim 5 City=3 ablation): prefix is fine,
# every example in the tier is equivalent for sampling purposes
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))))
# top up any remainder deterministically from the unpicked 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
# 2-shot prompt, exactly as DreamLM/Dream eval_planning.py::eval_trip
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)
# ---------------------------------------------------------------- scoring
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
# ---------------------------------------------------------------- main
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()
# Seed every RNG that can touch decoding. NOTE: the temperature-sweep results
# shipped in outputs/ (c6_*_t0.1/0.4/0.7/1.0) were produced BEFORE this was
# added and therefore do not reproduce bit-exactly from this seed; the T=0
# runs (Trip Plan, HumanEval, the ablations) are argmax and always did.
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:
# Local CPU dry-run: real tokenizer/prompts/metrics, tiny random weights.
# Exercises the whole pipeline end-to-end so no GPU minute is spent on a crash.
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()
|