""" Batch inference with vLLM for reasoning models under various quantization methods. Supports: FP16, AWQ, GPTQ, BitsAndBytes NF4 Benchmarks: GSM8K, MATH-500, GPQA-Diamond """ import argparse import json import os import time from typing import Optional def load_benchmark(name: str, split: str = "test", max_samples: Optional[int] = None): """Load benchmark dataset.""" 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}. Supported: gsm8k, math500, gpqa") if max_samples: problems = problems[:max_samples] return problems def build_llm(model_name: str, quant: str, gpu_mem_util: float, max_model_len: int): """Instantiate a vLLM engine with the requested quantization backend.""" from vllm import LLM kwargs = dict( model=model_name, dtype="float16", trust_remote_code=True, gpu_memory_utilization=gpu_mem_util, max_model_len=max_model_len, enforce_eager=True, # skip CUDA-graph capture to save VRAM ) # AWQ / GPTQ produced by llmcompressor are in compressed-tensors format; # vLLM auto-detects this from the model's config.json, so we don't pass # `quantization=` for those (pointing it to local dirs is enough). if quant in ("fp16", "awq", "gptq"): pass elif quant == "bnb_nf4": kwargs["quantization"] = "bitsandbytes" kwargs["load_format"] = "bitsandbytes" else: raise ValueError(f"Unknown quantization method: {quant}") return LLM(**kwargs) def format_prompts(problems, tokenizer): """Apply the chat template to every problem's question.""" prompts = [] for prob in problems: messages = [{"role": "user", "content": prob["question"]}] text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) prompts.append(text) return prompts def main(): parser = argparse.ArgumentParser(description="Run inference with quantized reasoning models (vLLM)") parser.add_argument("--model", required=True, help="HuggingFace model name or path") parser.add_argument("--quant", default="fp16", choices=["fp16", "awq", "gptq", "bnb_nf4"]) parser.add_argument("--bits", type=int, default=4, help="Quantization bit-width (for tagging)") 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) parser.add_argument("--num-runs", type=int, default=1, help="Number of runs for variance estimation") parser.add_argument("--gpu-memory-utilization", type=float, default=0.90, help="Fraction of free VRAM vLLM may claim (lower if GPU is shared)") parser.add_argument("--max-model-len", type=int, default=8192, help="Max context length (prompt + output). Smaller = less KV-cache VRAM.") parser.add_argument("--temperature", type=float, default=0.0, help="Sampling temperature. 0.0 = greedy. Use 0.6-0.8 with --num-runs>1 for multi-seed.") parser.add_argument("--top-p", type=float, default=1.0, help="Nucleus sampling top-p.") parser.add_argument("--seed-start", type=int, default=0, help="Seed for run 0; subsequent runs use seed_start+run_idx.") parser.add_argument("--run-offset", type=int, default=0, help="Name runs as run{run_offset+i}.jsonl — useful for appending more seeds " "to an existing output dir without overwriting.") args = parser.parse_args() os.makedirs(args.output, exist_ok=True) from vllm import SamplingParams from transformers import AutoTokenizer print(f"Loading model: {args.model} ({args.quant})") llm = build_llm(args.model, args.quant, args.gpu_memory_utilization, args.max_model_len) tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True) print(f"Loading benchmark: {args.benchmark}") problems = load_benchmark(args.benchmark, max_samples=args.max_samples) print(f" {len(problems)} problems loaded") prompts = format_prompts(problems, tokenizer) quant_str = f"{args.quant}_w{args.bits}" if args.quant != "fp16" else "fp16" for run_idx in range(args.num_runs): run_name = args.run_offset + run_idx out_file = os.path.join(args.output, f"{args.benchmark}_run{run_name}.jsonl") # Different seed per run so runs aren't identical under sampling. sampling = SamplingParams( temperature=args.temperature, top_p=args.top_p, max_tokens=args.max_tokens, seed=args.seed_start + run_idx if args.temperature > 0 else None, ) start = time.time() outputs = llm.generate(prompts, sampling) elapsed = time.time() - start with open(out_file, "w") as f: for prob, out in zip(problems, outputs): gen = out.outputs[0] n_tokens = len(gen.token_ids) per_sample_time = elapsed / max(len(problems), 1) record = { "problem_id": prob["id"], "question": prob["question"], "gold_answer": prob["answer"], "model": args.model, "quantization": quant_str, "output": gen.text, "n_tokens": n_tokens, "time_seconds": per_sample_time, "tokens_per_second": n_tokens / per_sample_time if per_sample_time > 0 else 0, "batch_wall_seconds": elapsed, } f.write(json.dumps(record, ensure_ascii=False) + "\n") total_tokens = sum(len(o.outputs[0].token_ids) for o in outputs) throughput = total_tokens / elapsed if elapsed > 0 else 0 print(f" Run {run_idx}: {len(problems)} problems, {total_tokens} tokens in {elapsed:.1f}s " f"({throughput:.1f} tok/s)") print(f" Saved to {out_file}") print("Done!") if __name__ == "__main__": main()