StepProbe / scripts /intervention_prompt_prefix.py
Akiyue's picture
Add files using upload-large-folder tool
3ccaf5a verified
Raw
History Blame Contribute Delete
7.09 kB
"""Intervention 1: Prompt-prefix injection.
For each test problem, prepend the first `k` steps of the full-precision
reference's chain of thought to the quantized model's prompt — effectively
short-circuiting the region where most failures occur (Figure~5 of the
paper shows >85% of failures concentrate in the first three steps).
No training required. The cost is exactly the FP16 inference we already
did to build the reference corpus.
Output shape matches run_inference.py so segment/diagnose/metrics/compute_ci
can consume the result with no changes.
"""
import argparse
import json
import os
import time
from typing import Dict, List
def load_benchmark(name: str, max_samples=None):
"""Same loader as run_inference.py — kept inline so this script is self-contained."""
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_prefixes(segmented_path: str, k: int) -> Dict[str, str]:
"""Map problem_id -> concatenation of the first `k` FP16 steps (as text)."""
prefixes: Dict[str, str] = {}
if not os.path.exists(segmented_path):
return prefixes
with open(segmented_path) as f:
for line in f:
t = json.loads(line)
pid = t.get("problem_id")
steps = (t.get("steps") or [])[:k]
if not steps:
continue
# Separate steps with a blank line so the downstream model treats
# them as discrete paragraphs.
prefix = "\n\n".join(s.get("text", "").strip() for s in steps if s.get("text"))
if prefix:
prefixes[pid] = prefix
return prefixes
def build_prompt(question: str, prefix: str, tokenizer) -> str:
"""Build a chat-formatted prompt with the assistant turn pre-filled by
the FP16 prefix. vLLM will then continue from the prefix."""
# Render up to (but not including) the assistant reply.
messages = [{"role": "user", "content": question}]
base = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
# Append the prefix text directly — this sits inside the assistant
# "turn" that the chat template just opened, so the model continues it.
return base + prefix + "\n\n"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model", required=True, help="Quantized model (path or HF name).")
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,
help="Path to fp16 segmented jsonl, e.g. results/segmented/fp16/<model>/<bench>_run0.jsonl")
parser.add_argument("--k", type=int, required=True,
help="Number of reference steps to prepend. k=0 is the un-intervened baseline.")
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} exists"); 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)
print(f"Loading benchmark: {args.benchmark}")
problems = load_benchmark(args.benchmark, args.max_samples)
print(f" {len(problems)} problems")
print(f"Loading FP16 prefixes (k={args.k}) from {args.fp16_segmented}")
prefixes = load_fp16_prefixes(args.fp16_segmented, args.k) if args.k > 0 else {}
print(f" prefix available for {len(prefixes)}/{len(problems)} problems")
prompts: List[str] = []
for p in problems:
pref = prefixes.get(p["id"], "")
prompts.append(build_prompt(p["question"], pref, tokenizer))
sampling = SamplingParams(temperature=0.0, max_tokens=args.max_tokens)
print("Generating...")
start = time.time()
outputs = llm.generate(prompts, sampling)
elapsed = time.time() - start
quant_str = f"{args.quant}_w{args.bits}" if args.quant != "fp16" else "fp16"
with open(out_file, "w") as f:
for p, out in zip(problems, outputs):
gen = out.outputs[0]
# Re-attach the injected prefix so downstream segmentation sees
# the same visible chain the model was conditioned on — without
# this, segment.py would see only the post-prefix continuation
# and falsely mark reasoning as starting mid-chain.
pref = prefixes.get(p["id"], "")
merged_output = (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 + f"_prefix_k{args.k}",
"output": merged_output,
"n_tokens": len(gen.token_ids),
"time_seconds": elapsed / max(len(problems), 1),
"tokens_per_second": len(gen.token_ids) / max(elapsed / max(len(problems), 1), 1e-6),
"batch_wall_seconds": elapsed,
"intervention": {"kind": "prompt_prefix", "k": args.k,
"had_prefix": bool(pref)},
}, ensure_ascii=False) + "\n")
print(f"Done: {len(problems)} problems in {elapsed:.1f}s")
if __name__ == "__main__":
main()