File size: 7,088 Bytes
3ccaf5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()