File size: 5,605 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
"""
Inference script for restored (QLoRA/DPO adapter) models.
Loads a quantized base model + LoRA adapter and runs inference.

Uses HuggingFace transformers (not vLLM) because vLLM doesn't support
dynamic PEFT adapter loading with BnB quantization.
"""

import argparse
import json
import os
import time
import sys

import torch
from tqdm import tqdm

# Allow importing from project root
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def load_benchmark(name: str, split: str = "test", max_samples=None):
    """Load benchmark dataset (same logic as run_inference.py)."""
    from datasets import load_dataset

    if name == "gsm8k":
        ds = load_dataset("openai/gsm8k", "main", split=split)
        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}")

    if max_samples:
        problems = problems[:max_samples]
    return problems


def generate_cot(model, tokenizer, question: str, max_tokens: int = 4096):
    """Generate chain-of-thought output for a single question."""
    messages = [{"role": "user", "content": question}]
    text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    inputs = tokenizer(text, return_tensors="pt").to(model.device)

    start = time.time()
    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_new_tokens=max_tokens,
            do_sample=False,
            temperature=None,
            top_p=None,
        )
    elapsed = time.time() - start

    # Decode only the generated tokens (strip the prompt)
    new_ids = output_ids[0, inputs["input_ids"].shape[1]:]
    output_text = tokenizer.decode(new_ids, skip_special_tokens=True)

    return {
        "output": output_text,
        "n_tokens": len(new_ids),
        "time_seconds": elapsed,
        "tokens_per_second": len(new_ids) / elapsed if elapsed > 0 else 0,
    }


def load_restored_model(model_name: str, adapter_path: str, quant: str = "bnb_nf4"):
    """Load quantized base model + LoRA adapter."""
    from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
    from peft import PeftModel

    tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)

    if quant == "bnb_nf4":
        bnb_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_compute_dtype=torch.bfloat16,
            bnb_4bit_use_double_quant=True,
        )
        model = AutoModelForCausalLM.from_pretrained(
            model_name, quantization_config=bnb_config,
            device_map="auto", trust_remote_code=True,
        )
    else:
        model = AutoModelForCausalLM.from_pretrained(
            model_name, torch_dtype=torch.bfloat16,
            device_map="auto", trust_remote_code=True,
        )

    # Load LoRA adapter
    print(f"Loading adapter from: {adapter_path}")
    model = PeftModel.from_pretrained(model, adapter_path)
    model = model.merge_and_unload()

    return model, tokenizer


def main():
    parser = argparse.ArgumentParser(description="Run inference with restored (QLoRA/DPO) model")
    parser.add_argument("--model", required=True, help="Base model name")
    parser.add_argument("--adapter", required=True, help="Path to LoRA adapter directory")
    parser.add_argument("--quant", default="bnb_nf4", choices=["bnb_nf4", "fp16"])
    parser.add_argument("--benchmark", required=True, choices=["gsm8k", "math500", "gpqa"])
    parser.add_argument("--output", required=True, help="Output directory")
    parser.add_argument("--max-samples", type=int, default=None)
    parser.add_argument("--max-tokens", type=int, default=4096)
    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} already exists")
        return

    print(f"Loading restored model: {args.model} + {args.adapter}")
    model, tokenizer = load_restored_model(args.model, args.adapter, args.quant)

    print(f"Loading benchmark: {args.benchmark}")
    problems = load_benchmark(args.benchmark, max_samples=args.max_samples)

    records = []
    for prob in tqdm(problems, desc="Restored inference"):
        result = generate_cot(model, tokenizer, prob["question"], args.max_tokens)
        record = {
            "problem_id": prob["id"],
            "question": prob["question"],
            "gold_answer": prob["answer"],
            "model": args.model,
            "quantization": f"{args.quant}_restored",
            **result,
        }
        records.append(record)

    with open(out_file, "w") as f:
        for r in records:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")

    print(f"Saved {len(records)} results -> {out_file}")

    if torch.cuda.is_available():
        mem = torch.cuda.max_memory_allocated() / 1e9
        print(f"Peak GPU memory: {mem:.1f} GB")


if __name__ == "__main__":
    main()