StepProbe / scripts /intervention_prompt_prefix_correct_only.py
Akiyue's picture
Add files using upload-large-folder tool
3ccaf5a verified
Raw
History Blame Contribute Delete
6.72 kB
"""Prompt-prefix injection ablation: only use prefixes from FP16-CORRECT problems.
This is the foundational ablation flagged by a reviewer concern: the original
prompt-prefix experiment (scripts/intervention_prompt_prefix.py) injects
reference-model steps into the quantized model's prompt regardless of
whether the reference model's final answer is correct. If the reference
is wrong on ~27% of MATH-500 problems, the prefix leaks a wrong opening
~27% of the time; conversely, the accuracy boost may be partially
explained by the fact that FP16-correct prefixes bias the set of
problems where the prefix is ``useful.''
This script restricts the prefix source to problems where FP16's final
answer matches the gold, and injects an empty prefix otherwise.
Comparing this result to the original sweep isolates ``partial-solution
leak from a known-good reference'' from ``conditional subset selection
bias.''
"""
import argparse
import json
import os
import sys
import time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def load_benchmark(name, max_samples=None):
from datasets import load_dataset
if name == "gsm8k":
ds = load_dataset("openai/gsm8k", "main", split="test")
problems = [{"id": f"gsm8k_{i}", "question": ex["question"], "answer": ex["answer"]} for i, ex in enumerate(ds)]
elif name == "math500":
ds = load_dataset("HuggingFaceH4/MATH-500", split="test")
problems = [{"id": f"math500_{i}", "question": ex["problem"], "answer": ex["answer"]} for i, ex in enumerate(ds)]
elif name == "gpqa":
ds = load_dataset("Idavidrein/gpqa", "gpqa_diamond", split="train")
problems = [{"id": f"gpqa_{i}", "question": ex["Question"], "answer": ex.get("Correct Answer", "")} for i, ex in enumerate(ds)]
else:
raise ValueError(f"Unknown benchmark: {name}")
return problems[:max_samples] if max_samples else problems
def load_fp16_correct_prefixes(segmented_path: str, benchmark: str, k: int):
"""Return {problem_id: prefix_text} restricted to FP16-correct problems.
Correctness is checked via scripts/eval_accuracy.py which uses math_verify
for LaTeX-aware comparison.
"""
from eval_accuracy import extract_pred, _equiv, _load_gold
golds = _load_gold(benchmark)
prefixes = {}
n_total, n_correct, n_with_prefix = 0, 0, 0
with open(segmented_path) as f:
for line in f:
t = json.loads(line)
pid = t.get("problem_id")
n_total += 1
gold = t.get("gold_answer") or golds.get(pid, "")
pred = extract_pred(t)
if _equiv(pred, gold):
n_correct += 1
steps = (t.get("steps") or [])[:k]
if steps:
prefix = "\n\n".join(s.get("text", "").strip()
for s in steps if s.get("text"))
if prefix:
prefixes[pid] = prefix
n_with_prefix += 1
print(f" FP16 correct: {n_correct}/{n_total} ({n_correct/n_total:.1%})")
print(f" Prefixes available: {n_with_prefix}")
return prefixes
def build_prompt(question, prefix, tokenizer):
messages = [{"role": "user", "content": question}]
base = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
return base + prefix + "\n\n" if prefix else base
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model", required=True)
parser.add_argument("--quant", default="bnb_nf4", choices=["fp16", "awq", "gptq", "bnb_nf4"])
parser.add_argument("--bits", type=int, default=4)
parser.add_argument("--benchmark", required=True, choices=["gsm8k", "math500", "gpqa"])
parser.add_argument("--fp16-segmented", required=True)
parser.add_argument("--k", type=int, required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--max-samples", type=int, default=None)
parser.add_argument("--max-tokens", type=int, default=4096)
parser.add_argument("--gpu-memory-utilization", type=float, default=0.55)
parser.add_argument("--max-model-len", type=int, default=8192)
args = parser.parse_args()
os.makedirs(args.output, exist_ok=True)
out_file = os.path.join(args.output, f"{args.benchmark}_run0.jsonl")
if os.path.exists(out_file):
print(f"[SKIP] {out_file}"); return
from vllm import LLM, SamplingParams
from transformers import AutoTokenizer
kwargs = dict(model=args.model, dtype="float16", trust_remote_code=True,
gpu_memory_utilization=args.gpu_memory_utilization,
max_model_len=args.max_model_len, enforce_eager=True)
if args.quant == "bnb_nf4":
kwargs["quantization"] = "bitsandbytes"; kwargs["load_format"] = "bitsandbytes"
print(f"Loading model: {args.model} ({args.quant})")
llm = LLM(**kwargs)
tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
problems = load_benchmark(args.benchmark, args.max_samples)
print(f" {len(problems)} problems")
print(f"Loading FP16-CORRECT prefixes (k={args.k}) from {args.fp16_segmented}")
prefixes = load_fp16_correct_prefixes(args.fp16_segmented, args.benchmark, args.k) if args.k > 0 else {}
prompts = [build_prompt(p["question"], prefixes.get(p["id"], ""), tokenizer) for p in problems]
sampling = SamplingParams(temperature=0.0, max_tokens=args.max_tokens)
start = time.time()
outputs = llm.generate(prompts, sampling)
elapsed = time.time() - start
quant_str = f"{args.quant}_w{args.bits}_prefix_fp16correct_k{args.k}"
n_with_prefix = sum(1 for p in problems if prefixes.get(p["id"]))
with open(out_file, "w") as f:
for p, out in zip(problems, outputs):
gen = out.outputs[0]
pref = prefixes.get(p["id"], "")
merged = (pref + "\n\n" + gen.text) if pref else gen.text
f.write(json.dumps({
"problem_id": p["id"],
"question": p["question"],
"gold_answer": p["answer"],
"model": args.model,
"quantization": quant_str,
"output": merged,
"n_tokens": len(gen.token_ids),
"time_seconds": elapsed / max(len(problems), 1),
"intervention": {"kind": "prompt_prefix_fp16_correct_only",
"k": args.k,
"had_prefix": bool(pref)},
}, ensure_ascii=False) + "\n")
print(f"Done: {len(problems)} problems ({n_with_prefix} with prefix) in {elapsed:.1f}s")
if __name__ == "__main__":
main()