File size: 22,047 Bytes
1e59964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
"""
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
    # For SFT/QLoRA
    correct_cot: str          # full correct CoT from FP16
    # For DPO
    incorrect_cot: Optional[str] = None  # incorrect CoT from quantized
    # Metadata
    error_type: str = ""
    failure_step: int = -1


# ============================================================
# Silver Bullet Dataset Construction
# ============================================================

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}

    # Collect candidate samples. For "random", we include correct traces too
    # (whose "error type" is tagged as "correct") so the baseline gets to
    # sample from the full set.
    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

        # Identify first error + type (applicable only for failures).
        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

    # Default: silver_bullet (proportional across error types)
    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


# ============================================================
# QLoRA Fine-Tuning
# ============================================================

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)

    # Apply LoRA
    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()

    # Format data
    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 — save every 25 steps so an OOM crash mid-epoch loses at most
    # ~25 steps of work rather than the whole run. save_total_limit=2 keeps
    # disk usage bounded (each LoRA checkpoint is only ~30 MB).
    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,
    )

    # Auto-resume from the latest checkpoint if one exists. HuggingFace's
    # `resume_from_checkpoint=True` fails loudly when no checkpoint is on
    # disk, so we detect by hand.
    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()

    # Save final adapter at a stable path the rest of the pipeline looks for.
    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}")

    # Clean up intermediate checkpoints so subsequent runs don't accidentally
    # resume stale training on top of a newer dataset (and to save disk).
    for ck in _glob.glob(os.path.join(output_dir, "checkpoint-*")):
        import shutil
        shutil.rmtree(ck, ignore_errors=True)

    return adapter_path


# ============================================================
# DPO Fine-Tuning
# ============================================================

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",
    )

    # Build DPO dataset
    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,  # use implicit reference with peft
        processing_class=tokenizer,
        train_dataset=dataset,
        args=training_args,
        peft_config=lora_config,
    )

    # Auto-resume from the latest checkpoint if one exists.
    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}")

    # Drop intermediate checkpoints once the final adapter is on disk.
    for ck in _glob.glob(os.path.join(output_dir, "checkpoint-*")):
        import shutil
        shutil.rmtree(ck, ignore_errors=True)

    return adapter_path


# ============================================================
# CLI
# ============================================================

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

    # Load data
    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:
        # Reconstruct questions from the original benchmark datasets.
        # problem_ids are like "gsm8k_0", "math500_123", "gpqa_42".
        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", ""),
            })

    # Build training dataset under the chosen sampling strategy.
    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)

    # Save dataset
    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 stats
    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}")