| """ |
| StepProbe: Targeted Restoration |
| |
| Given the diagnosis results, construct minimal "Silver Bullet" datasets |
| and apply QLoRA or DPO fine-tuning to restore reasoning capability |
| at the identified failure points. |
| |
| Key insight: We don't need to fine-tune on everything — just on the |
| specific error patterns that quantization introduces. |
| """ |
|
|
| import json |
| import os |
| import random |
| from typing import List, Dict, Optional, Tuple |
| from dataclasses import dataclass, field |
|
|
| from stepprobe.utils import load_jsonl, save_jsonl, set_seed |
|
|
|
|
| @dataclass |
| class RestorationSample: |
| """A single training sample for restoration.""" |
| problem_id: str |
| problem_text: str |
| |
| correct_cot: str |
| |
| incorrect_cot: Optional[str] = None |
| |
| error_type: str = "" |
| failure_step: int = -1 |
|
|
|
|
| |
| |
| |
|
|
| def build_silver_bullet_dataset( |
| diagnosed_traces: List[dict], |
| ref_traces: List[dict], |
| problems: List[dict], |
| max_samples: int = 500, |
| target_error_types: Optional[List[str]] = None, |
| seed: int = 42, |
| sampling_strategy: str = "silver_bullet", |
| ) -> Tuple[List[RestorationSample], Dict[str, int]]: |
| """ |
| Build a training dataset from diagnosed traces. |
| |
| `sampling_strategy` controls which problems get selected. The three |
| strategies are used for ablation / baseline comparison so the value of |
| the step-level diagnosis is falsifiable: |
| |
| - "silver_bullet" (default): failed problems only, proportional |
| allocation across the four error types. |
| - "failed_only": failed problems only, uniform random (no |
| error-type balancing). Isolates the contribution of error-type |
| proportional allocation. |
| - "random": ALL diagnosed problems sampled uniformly (both |
| failed and correct). Isolates whether diagnosis matters at all |
| — a negative control. |
| |
| Args: |
| diagnosed_traces: Output from diagnose_batch |
| ref_traces: FP16 segmented traces |
| problems: Original problems |
| max_samples: Maximum dataset size |
| target_error_types: If specified, only include these error types |
| seed: Random seed |
| sampling_strategy: One of {"silver_bullet", "failed_only", "random"} |
| |
| Returns: |
| (samples, stats) where stats maps error_type -> count |
| """ |
| assert sampling_strategy in {"silver_bullet", "failed_only", "random"}, \ |
| f"unknown sampling_strategy: {sampling_strategy}" |
| set_seed(seed) |
|
|
| ref_by_id = {t["problem_id"]: t for t in ref_traces} |
| prob_by_id = {p.get("problem_id", p.get("id", "")): p for p in problems} |
|
|
| |
| |
| |
| failures_by_type: Dict[str, List[RestorationSample]] = { |
| "conceptual": [], "methodological": [], "executional": [], "logical": [], |
| } |
| correct_pool: List[RestorationSample] = [] |
|
|
| for trace in diagnosed_traces: |
| pid = trace["problem_id"] |
| ref = ref_by_id.get(pid) |
| prob = prob_by_id.get(pid, {}) |
| if ref is None: |
| continue |
|
|
| is_failure = trace.get("is_correct_final", True) is False |
|
|
| |
| first_error_type = "executional" |
| first_error_step = -1 |
| for step in trace.get("steps", []): |
| if step.get("is_correct") is False: |
| first_error_type = step.get("error_type", "executional") |
| first_error_step = step.get("index", -1) |
| break |
|
|
| if target_error_types and is_failure and first_error_type not in target_error_types: |
| continue |
|
|
| sample = RestorationSample( |
| problem_id=pid, |
| problem_text=prob.get("question", prob.get("problem", "")), |
| correct_cot=ref.get("raw_output", ""), |
| incorrect_cot=trace.get("raw_output", "") if is_failure else None, |
| error_type=first_error_type if is_failure else "correct", |
| failure_step=first_error_step, |
| ) |
|
|
| if is_failure and first_error_type in failures_by_type: |
| failures_by_type[first_error_type].append(sample) |
| elif not is_failure: |
| correct_pool.append(sample) |
|
|
| failed_all = [s for pool in failures_by_type.values() for s in pool] |
|
|
| if sampling_strategy == "random": |
| pool_all = failed_all + correct_pool |
| if not pool_all: |
| print("[WARN] No diagnosed traces available.") |
| return [], {} |
| n_alloc = min(max_samples, len(pool_all)) |
| samples = random.sample(pool_all, n_alloc) |
| stats: Dict[str, int] = {} |
| for s in samples: |
| stats[s.error_type] = stats.get(s.error_type, 0) + 1 |
| random.shuffle(samples) |
| print(f"[random baseline] {len(samples)} samples from {len(pool_all)} diagnosed problems") |
| for k, v in sorted(stats.items()): |
| print(f" {k}: {v}") |
| return samples, stats |
|
|
| if sampling_strategy == "failed_only": |
| if not failed_all: |
| print("[WARN] No failures found.") |
| return [], {} |
| n_alloc = min(max_samples, len(failed_all)) |
| samples = random.sample(failed_all, n_alloc) |
| stats = {} |
| for s in samples: |
| stats[s.error_type] = stats.get(s.error_type, 0) + 1 |
| random.shuffle(samples) |
| print(f"[failed-only baseline] {len(samples)} samples from {len(failed_all)} failures") |
| for k, v in sorted(stats.items()): |
| print(f" {k}: {v}") |
| return samples, stats |
|
|
| |
| total_failures = sum(len(v) for v in failures_by_type.values()) |
| if total_failures == 0: |
| print("[WARN] No failures found. Nothing to restore.") |
| return [], {} |
|
|
| samples = [] |
| stats = {} |
| for etype, pool in failures_by_type.items(): |
| if not pool: |
| continue |
| n_alloc = max(1, int(max_samples * len(pool) / total_failures)) |
| n_alloc = min(n_alloc, len(pool)) |
| selected = random.sample(pool, n_alloc) |
| samples.extend(selected) |
| stats[etype] = n_alloc |
|
|
| random.shuffle(samples) |
| samples = samples[:max_samples] |
|
|
| print(f"Silver Bullet dataset: {len(samples)} samples from {total_failures} failures") |
| for etype, count in sorted(stats.items()): |
| print(f" {etype}: {count}") |
|
|
| return samples, stats |
|
|
|
|
| def format_for_sft(samples: List[RestorationSample]) -> List[dict]: |
| """Format samples for supervised fine-tuning (SFT / QLoRA).""" |
| formatted = [] |
| for s in samples: |
| formatted.append({ |
| "messages": [ |
| {"role": "user", "content": s.problem_text}, |
| {"role": "assistant", "content": s.correct_cot}, |
| ], |
| "metadata": { |
| "problem_id": s.problem_id, |
| "error_type": s.error_type, |
| "failure_step": s.failure_step, |
| }, |
| }) |
| return formatted |
|
|
|
|
| def format_for_dpo(samples: List[RestorationSample]) -> List[dict]: |
| """Format samples for Direct Preference Optimization (DPO).""" |
| formatted = [] |
| for s in samples: |
| if not s.incorrect_cot: |
| continue |
| formatted.append({ |
| "prompt": s.problem_text, |
| "chosen": s.correct_cot, |
| "rejected": s.incorrect_cot, |
| "metadata": { |
| "problem_id": s.problem_id, |
| "error_type": s.error_type, |
| "failure_step": s.failure_step, |
| }, |
| }) |
| return formatted |
|
|
|
|
| |
| |
| |
|
|
| def run_qlora_restoration( |
| model_name: str, |
| train_data: List[dict], |
| output_dir: str, |
| r: int = 16, |
| lora_alpha: int = 32, |
| target_modules: List[str] = None, |
| learning_rate: float = 2e-4, |
| num_epochs: int = 3, |
| batch_size: int = 4, |
| gradient_accumulation_steps: int = 4, |
| max_seq_length: int = 2048, |
| ): |
| """ |
| Run QLoRA fine-tuning for targeted restoration. |
| |
| This loads the model in 4-bit, applies LoRA adapters, |
| and fine-tunes on the Silver Bullet dataset. |
| """ |
| import torch |
| from transformers import ( |
| AutoModelForCausalLM, AutoTokenizer, |
| BitsAndBytesConfig, TrainingArguments, |
| ) |
| from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training |
| from trl import SFTTrainer, SFTConfig |
| from datasets import Dataset |
|
|
| if target_modules is None: |
| target_modules = ["q_proj", "v_proj", "k_proj", "o_proj"] |
|
|
| os.makedirs(output_dir, exist_ok=True) |
|
|
| print(f"Loading model: {model_name} (4-bit)") |
| bnb_config = BitsAndBytesConfig( |
| load_in_4bit=True, |
| bnb_4bit_quant_type="nf4", |
| bnb_4bit_compute_dtype=torch.float16, |
| bnb_4bit_use_double_quant=True, |
| ) |
|
|
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
|
|
| model = AutoModelForCausalLM.from_pretrained( |
| model_name, |
| quantization_config=bnb_config, |
| device_map="auto", |
| trust_remote_code=True, |
| ) |
| model = prepare_model_for_kbit_training(model) |
|
|
| |
| lora_config = LoraConfig( |
| r=r, |
| lora_alpha=lora_alpha, |
| target_modules=target_modules, |
| lora_dropout=0.05, |
| bias="none", |
| task_type="CAUSAL_LM", |
| ) |
| model = get_peft_model(model, lora_config) |
| model.print_trainable_parameters() |
|
|
| |
| def format_messages(example): |
| text = tokenizer.apply_chat_template( |
| example["messages"], tokenize=False, add_generation_prompt=False |
| ) |
| return {"text": text} |
|
|
| dataset = Dataset.from_list(train_data) |
| dataset = dataset.map(format_messages) |
|
|
| |
| |
| |
| training_args = SFTConfig( |
| output_dir=output_dir, |
| num_train_epochs=num_epochs, |
| per_device_train_batch_size=1, |
| gradient_accumulation_steps=batch_size * gradient_accumulation_steps, |
| learning_rate=learning_rate, |
| weight_decay=0.01, |
| warmup_ratio=0.1, |
| lr_scheduler_type="cosine", |
| logging_steps=10, |
| save_strategy="steps", |
| save_steps=25, |
| save_total_limit=2, |
| bf16=True, |
| max_length=max_seq_length, |
| dataset_text_field="text", |
| gradient_checkpointing=True, |
| report_to="none", |
| ) |
|
|
| trainer = SFTTrainer( |
| model=model, |
| processing_class=tokenizer, |
| train_dataset=dataset, |
| args=training_args, |
| ) |
|
|
| |
| |
| |
| import glob as _glob |
| existing_ckpts = sorted( |
| _glob.glob(os.path.join(output_dir, "checkpoint-*")), |
| key=lambda p: int(p.rsplit("-", 1)[-1]) if p.rsplit("-", 1)[-1].isdigit() else -1, |
| ) |
| if existing_ckpts: |
| latest = existing_ckpts[-1] |
| print(f"Resuming from checkpoint: {latest}") |
| print(f"Starting QLoRA training: {len(train_data)} samples, {num_epochs} epochs (resume)") |
| trainer.train(resume_from_checkpoint=latest) |
| else: |
| print(f"Starting QLoRA training: {len(train_data)} samples, {num_epochs} epochs") |
| trainer.train() |
|
|
| |
| adapter_path = os.path.join(output_dir, "adapter") |
| model.save_pretrained(adapter_path) |
| tokenizer.save_pretrained(adapter_path) |
| print(f"Adapter saved to {adapter_path}") |
|
|
| |
| |
| for ck in _glob.glob(os.path.join(output_dir, "checkpoint-*")): |
| import shutil |
| shutil.rmtree(ck, ignore_errors=True) |
|
|
| return adapter_path |
|
|
|
|
| |
| |
| |
|
|
| def run_dpo_restoration( |
| model_name: str, |
| train_data: List[dict], |
| output_dir: str, |
| beta: float = 0.1, |
| learning_rate: float = 5e-5, |
| num_epochs: int = 1, |
| batch_size: int = 2, |
| gradient_accumulation_steps: int = 8, |
| max_seq_length: int = 1024, |
| ): |
| """ |
| Run DPO fine-tuning using (correct, incorrect) CoT pairs. |
| """ |
| import torch |
| from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig |
| from peft import LoraConfig, prepare_model_for_kbit_training |
| from trl import DPOTrainer, DPOConfig |
| from datasets import Dataset |
|
|
| os.makedirs(output_dir, exist_ok=True) |
|
|
| print(f"Loading model: {model_name} (4-bit)") |
| bnb_config = BitsAndBytesConfig( |
| load_in_4bit=True, |
| bnb_4bit_quant_type="nf4", |
| bnb_4bit_compute_dtype=torch.float16, |
| bnb_4bit_use_double_quant=True, |
| ) |
|
|
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
|
|
| model = AutoModelForCausalLM.from_pretrained( |
| model_name, |
| quantization_config=bnb_config, |
| device_map="auto", |
| trust_remote_code=True, |
| ) |
|
|
| lora_config = LoraConfig( |
| r=16, |
| lora_alpha=32, |
| target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], |
| lora_dropout=0.05, |
| bias="none", |
| task_type="CAUSAL_LM", |
| ) |
|
|
| |
| dataset = Dataset.from_list(train_data) |
|
|
| training_args = DPOConfig( |
| output_dir=output_dir, |
| num_train_epochs=num_epochs, |
| per_device_train_batch_size=1, |
| gradient_accumulation_steps=batch_size * gradient_accumulation_steps, |
| learning_rate=learning_rate, |
| beta=beta, |
| warmup_ratio=0.1, |
| lr_scheduler_type="cosine", |
| logging_steps=10, |
| save_strategy="steps", |
| save_steps=25, |
| save_total_limit=2, |
| bf16=True, |
| max_length=max_seq_length, |
| gradient_checkpointing=True, |
| report_to="none", |
| ) |
|
|
| trainer = DPOTrainer( |
| model=model, |
| ref_model=None, |
| processing_class=tokenizer, |
| train_dataset=dataset, |
| args=training_args, |
| peft_config=lora_config, |
| ) |
|
|
| |
| import glob as _glob |
| existing_ckpts = sorted( |
| _glob.glob(os.path.join(output_dir, "checkpoint-*")), |
| key=lambda p: int(p.rsplit("-", 1)[-1]) if p.rsplit("-", 1)[-1].isdigit() else -1, |
| ) |
| if existing_ckpts: |
| latest = existing_ckpts[-1] |
| print(f"Resuming DPO training from checkpoint: {latest}") |
| trainer.train(resume_from_checkpoint=latest) |
| else: |
| print(f"Starting DPO training: {len(train_data)} pairs, beta={beta}") |
| trainer.train() |
|
|
| adapter_path = os.path.join(output_dir, "adapter") |
| trainer.save_model(adapter_path) |
| tokenizer.save_pretrained(adapter_path) |
| print(f"Adapter saved to {adapter_path}") |
|
|
| |
| for ck in _glob.glob(os.path.join(output_dir, "checkpoint-*")): |
| import shutil |
| shutil.rmtree(ck, ignore_errors=True) |
|
|
| return adapter_path |
|
|
|
|
| |
| |
| |
|
|
| if __name__ == "__main__": |
| import argparse |
|
|
| parser = argparse.ArgumentParser(description="Targeted restoration of quantized reasoning models") |
| parser.add_argument("--model", required=True, help="Base model name") |
| parser.add_argument("--diagnosis", required=True, help="Directory with diagnosed traces") |
| parser.add_argument("--ref", required=True, help="Directory with FP16 segmented traces") |
| parser.add_argument("--problems", default=None, help="JSONL with original problems") |
| parser.add_argument("--output", required=True, help="Output directory") |
| parser.add_argument("--method", default="qlora", choices=["qlora", "dpo"]) |
| parser.add_argument("--max-samples", type=int, default=500) |
| parser.add_argument("--target-errors", nargs="*", default=None, |
| help="Target specific error types (e.g., executional conceptual)") |
| parser.add_argument("--sampling-strategy", default="silver_bullet", |
| choices=["silver_bullet", "failed_only", "random"], |
| help="Dataset construction: silver_bullet (failures " |
| "balanced across error types), failed_only (failures " |
| "uniformly sampled), or random (sample from ALL " |
| "diagnosed problems including correct ones). The " |
| "latter two are baselines against which silver_bullet " |
| "is measured.") |
| parser.add_argument("--epochs", type=int, default=3) |
| parser.add_argument("--lr", type=float, default=2e-4) |
| parser.add_argument("--batch-size", type=int, default=4) |
| parser.add_argument("--max-seq-length", type=int, default=2048, |
| help="Max sequence length during training. Drop to 1024 " |
| "if training OOMs under memory pressure.") |
| parser.add_argument("--lora-rank", type=int, default=16, |
| help="LoRA rank. Halve (8) if training OOMs.") |
| args = parser.parse_args() |
|
|
| import glob |
|
|
| |
| diagnosed = [] |
| for f in sorted(glob.glob(os.path.join(args.diagnosis, "*.jsonl"))): |
| diagnosed.extend(load_jsonl(f)) |
|
|
| ref_traces = [] |
| for f in sorted(glob.glob(os.path.join(args.ref, "*.jsonl"))): |
| ref_traces.extend(load_jsonl(f)) |
|
|
| problems = [] |
| if args.problems: |
| problems = load_jsonl(args.problems) |
| else: |
| |
| |
| from datasets import load_dataset |
| _bench_cache = {} |
| def _load_bench(bench_name): |
| if bench_name in _bench_cache: |
| return _bench_cache[bench_name] |
| qs = [] |
| if bench_name == "gsm8k": |
| ds = load_dataset("openai/gsm8k", "main", split="test") |
| qs = [ex["question"] for ex in ds] |
| elif bench_name == "math500": |
| ds = load_dataset("HuggingFaceH4/MATH-500", split="test") |
| qs = [ex["problem"] for ex in ds] |
| elif bench_name == "gpqa": |
| ds = load_dataset("Idavidrein/gpqa", "gpqa_diamond", split="train") |
| qs = [ex["Question"] for ex in ds] |
| _bench_cache[bench_name] = qs |
| return qs |
|
|
| def _get_question(problem_id: str) -> str: |
| parts = problem_id.rsplit("_", 1) |
| if len(parts) != 2 or not parts[1].isdigit(): |
| return "" |
| bench_name, idx = parts[0], int(parts[1]) |
| qs = _load_bench(bench_name) |
| return qs[idx] if idx < len(qs) else "" |
|
|
| for t in ref_traces: |
| pid = t["problem_id"] |
| problems.append({ |
| "problem_id": pid, |
| "question": _get_question(pid), |
| "answer": t.get("final_answer", ""), |
| }) |
|
|
| |
| samples, stats = build_silver_bullet_dataset( |
| diagnosed_traces=diagnosed, |
| ref_traces=ref_traces, |
| sampling_strategy=args.sampling_strategy, |
| problems=problems, |
| max_samples=args.max_samples, |
| target_error_types=args.target_errors, |
| ) |
|
|
| if not samples: |
| print("No samples to train on. Exiting.") |
| exit(0) |
|
|
| |
| dataset_dir = os.path.join(args.output, "dataset") |
| os.makedirs(dataset_dir, exist_ok=True) |
|
|
| if args.method == "qlora": |
| train_data = format_for_sft(samples) |
| save_jsonl(train_data, os.path.join(dataset_dir, "sft_train.jsonl")) |
| print(f"\nSFT dataset saved: {len(train_data)} samples") |
|
|
| adapter_path = run_qlora_restoration( |
| model_name=args.model, |
| train_data=train_data, |
| output_dir=os.path.join(args.output, "qlora"), |
| learning_rate=args.lr, |
| num_epochs=args.epochs, |
| batch_size=args.batch_size, |
| r=args.lora_rank, |
| lora_alpha=args.lora_rank * 2, |
| max_seq_length=args.max_seq_length, |
| ) |
| elif args.method == "dpo": |
| train_data = format_for_dpo(samples) |
| save_jsonl(train_data, os.path.join(dataset_dir, "dpo_train.jsonl")) |
| print(f"\nDPO dataset saved: {len(train_data)} pairs") |
|
|
| adapter_path = run_dpo_restoration( |
| model_name=args.model, |
| train_data=train_data, |
| output_dir=os.path.join(args.output, "dpo"), |
| learning_rate=args.lr, |
| num_epochs=args.epochs, |
| batch_size=args.batch_size, |
| ) |
|
|
| |
| save_jsonl([{"stats": stats, "n_samples": len(samples), "method": args.method}], |
| os.path.join(args.output, "restoration_stats.jsonl")) |
|
|
| print(f"\nRestoration complete! Adapter at: {adapter_path}") |
|
|