File size: 31,634 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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
#!/usr/bin/env bash
###############################################################################
# StepProbe — Master Orchestrator
# 
# Runs the ENTIRE experiment pipeline from scratch:
#   0. Setup environment
#   1. Download / quantize models
#   2. FP16 baseline inference on all benchmarks
#   3. Quantized inference (all methods x bit-widths x models)
#   4. Segment all CoT traces
#   5. Diagnose step-level errors
#   6. Compute metrics
#   7. Build Silver Bullet datasets + QLoRA restoration
#   8. Re-evaluate restored models
#   9. Generate paper figures + summary tables
#
# Usage:
#   bash run_all.sh                   # full run
#   bash run_all.sh --quick           # 50 samples per benchmark (testing)
#   bash run_all.sh --phase 5         # resume from phase 5
#   bash run_all.sh --models small    # only 1.5B + 7B models
#   bash run_all.sh --dry-run         # print commands without executing
###############################################################################
set -euo pipefail

# Avoid spurious HF download retries on slow/shared bandwidth (default is 10s).
export HF_HUB_DOWNLOAD_TIMEOUT=300

# Pin to a specific GPU (GPU 0 is often shared on this box).
export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-1}"

# ========================== CONFIG ==========================
PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
RESULTS_DIR="${PROJECT_DIR}/results"
FIGURES_DIR="${PROJECT_DIR}/figures"
LOGS_DIR="${PROJECT_DIR}/logs"
QUANT_MODELS_DIR="${RESULTS_DIR}/quantized_models"
# llmcompressor and vLLM have mutually exclusive dep pins, so quantization runs
# in its own conda env. Quantized models on disk are env-agnostic.
QUANT_ENV_PYTHON="/home/aiteam1/anaconda3/envs/sonthh-stepprobe-quant/bin/python"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOG_FILE="${LOGS_DIR}/run_all_${TIMESTAMP}.log"

# Defaults
MAX_SAMPLES=""          # empty = full dataset
START_PHASE=0
MODEL_SET="full"        # full | small | primary
DRY_RUN=false
USE_LLM_JUDGE=false
JUDGE_PROVIDER="openai"
SEED=42
NUM_RUNS=1
MAX_TOKENS=4096

# ========================== PARSE ARGS ==========================
while [[ $# -gt 0 ]]; do
    case $1 in
        --quick)        MAX_SAMPLES=50; NUM_RUNS=1; shift ;;
        --medium)       MAX_SAMPLES=200; NUM_RUNS=1; shift ;;
        --phase)        START_PHASE=$2; shift 2 ;;
        --models)       MODEL_SET=$2; shift 2 ;;
        --dry-run)      DRY_RUN=true; shift ;;
        --llm-judge)    USE_LLM_JUDGE=true; shift ;;
        --judge)        JUDGE_PROVIDER=$2; shift 2 ;;
        --samples)      MAX_SAMPLES=$2; shift 2 ;;
        --runs)         NUM_RUNS=$2; shift 2 ;;
        --seed)         SEED=$2; shift 2 ;;
        --help|-h)
            echo "Usage: bash run_all.sh [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --quick           50 samples per benchmark (fast test)"
            echo "  --medium          200 samples per benchmark"
            echo "  --samples N       Custom sample limit"
            echo "  --phase N         Resume from phase N (0-9)"
            echo "  --models SET      Model set: full|small|primary (default: full)"
            echo "  --runs N          Number of inference runs (default: 1)"
            echo "  --llm-judge       Use LLM judge (costs API money)"
            echo "  --judge PROVIDER  openai|anthropic (default: openai)"
            echo "  --dry-run         Print commands without running"
            echo "  --seed N          Random seed (default: 42)"
            exit 0 ;;
        *) echo "Unknown option: $1"; exit 1 ;;
    esac
done

# ========================== MODEL DEFINITIONS ==========================
# Format: "HF_NAME|TAG|FP16_VRAM_GB|NOTES"
declare -a PRIMARY_MODELS=(
    "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B|r1-qwen-7b|14|primary"
)

declare -a SMALL_MODELS=(
    "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B|r1-qwen-1.5b|3|small"
    "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B|r1-qwen-7b|14|primary"
)

declare -a FULL_MODELS=(
    "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B|r1-qwen-1.5b|3|small"
    "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B|r1-qwen-7b|14|primary"
    "deepseek-ai/DeepSeek-R1-Distill-Qwen-14B|r1-qwen-14b|28|4bit-only"
    "deepseek-ai/DeepSeek-R1-Distill-Llama-8B|r1-llama-8b|16|cross-arch"
    "Qwen/Qwen2.5-7B-Instruct|qwen25-7b|14|non-reasoning-control"
)

# Quantization configs: "METHOD|BITS"
# Note: only 4-bit and 8-bit int schemes are supported by vLLM's
# compressed-tensors backend, so w2/w3 GPTQ are omitted. autoawq is 4-bit only.
declare -a QUANT_CONFIGS=(
    "bnb_nf4|4"
    "gptq|4"
    "awq|4"
)

# Benchmarks
declare -a BENCHMARKS=(
    "gsm8k"
    "math500"
    "gpqa"
)

# Select model set
case $MODEL_SET in
    full)    MODELS=("${FULL_MODELS[@]}") ;;
    small)   MODELS=("${SMALL_MODELS[@]}") ;;
    primary) MODELS=("${PRIMARY_MODELS[@]}") ;;
    *)       echo "Unknown model set: $MODEL_SET"; exit 1 ;;
esac

# ========================== HELPERS ==========================
mkdir -p "$LOGS_DIR"

log() {
    local msg="[$(date '+%H:%M:%S')] $1"
    echo "$msg" | tee -a "$LOG_FILE"
}

run_cmd() {
    local cmd="$1"
    if $DRY_RUN; then
        echo "  [DRY-RUN] $cmd"
    else
        log "  CMD: $cmd"
        eval "$cmd" 2>&1 | tee -a "$LOG_FILE"
    fi
}

check_gpu() {
    if command -v nvidia-smi &>/dev/null; then
        nvidia-smi --query-gpu=name,memory.total,memory.used --format=csv,noheader 2>/dev/null || true
    else
        echo "No GPU detected (nvidia-smi not found)"
    fi
}

get_sample_flag() {
    if [[ -n "$MAX_SAMPLES" ]]; then
        echo "--max-samples $MAX_SAMPLES"
    fi
}

can_run_fp16() {
    # Check if model fits in FP16 on 24GB
    local vram=$1
    [[ $vram -le 22 ]]
}

get_quant_for_model() {
    local vram=$1
    if [[ $vram -le 22 ]]; then
        # Can run FP16 + all quantizations
        echo "all"
    else
        # Too big for FP16, only run quantized
        echo "quant-only"
    fi
}

# Return 0 (truthy) only if a PEFT adapter directory contains the files that
# save_pretrained() writes. If training was interrupted the adapter/ subdir
# may not exist at all, or it may exist with only a subset of files written.
# Plain `[[ -d ... ]]` is not enough — use this instead.
is_complete_adapter() {
    local d=$1
    [[ -f "${d}/adapter_config.json" ]] || return 1
    [[ -f "${d}/adapter_model.safetensors" || -f "${d}/adapter_model.bin" ]] || return 1
    return 0
}

# Resolve the model path to pass to run_inference.py:
#   - awq / gptq: local pre-quantized dir (must exist from phase1b)
#   - bnb_nf4:    original HF name (runtime quantization)
#   - fp16:       original HF name
resolve_model_path() {
    local hf_name=$1
    local tag=$2
    local method=$3
    local bits=$4

    if [[ "$method" == "awq" || "$method" == "gptq" ]]; then
        echo "${QUANT_MODELS_DIR}/${tag}_${method}_w${bits}"
    else
        echo "$hf_name"
    fi
}

# ========================== PHASE 0: SETUP ==========================
phase0_setup() {
    log "=============================================="
    log "PHASE 0: Environment Setup"
    log "=============================================="

    log "Project dir: $PROJECT_DIR"
    log "Results dir: $RESULTS_DIR"
    log "Model set:   $MODEL_SET (${#MODELS[@]} models)"
    log "Benchmarks:  ${BENCHMARKS[*]}"
    log "Samples:     ${MAX_SAMPLES:-all}"
    log "Runs:        $NUM_RUNS"
    log "LLM Judge:   $USE_LLM_JUDGE"
    log "GPU:"
    check_gpu | while read -r line; do log "  $line"; done

    # Install dependencies
    log "Installing Python dependencies..."
    run_cmd "pip install -r ${PROJECT_DIR}/requirements.txt --break-system-packages -q"

    # Verify imports
    run_cmd "python -c 'from stepprobe import segment, align, diagnose, metrics, restore, utils; print(\"All modules OK\")'"

    mkdir -p "$RESULTS_DIR"/{inference,segmented,diagnosis,metrics,restored,silver_bullet}
    mkdir -p "$FIGURES_DIR"

    log "Setup complete."
}

# ========================== PHASE 1: DOWNLOAD MODELS ==========================
phase1_download() {
    log "=============================================="
    log "PHASE 1: Download / Verify Models"
    log "=============================================="

    for model_spec in "${MODELS[@]}"; do
        IFS='|' read -r hf_name tag vram notes <<< "$model_spec"
        log "Checking model: $hf_name ($tag)"

        run_cmd "python -c \"
from huggingface_hub import snapshot_download, HfApi
try:
    api = HfApi()
    info = api.model_info('${hf_name}')
    print(f'  Model found: {info.id}, size: {info.siblings and len(info.siblings)} files')
except Exception as e:
    print(f'  Downloading: ${hf_name}...')
    snapshot_download('${hf_name}', local_dir_use_symlinks=True)
\""
    done

    log "Model verification complete."
}

# ========================== PHASE 1b: OFFLINE QUANTIZATION ==========================
# Quantize each (model, method, bits) ONCE with a fixed WikiText-2 calibration
# set. Skipped for bnb_nf4 (runtime quantization) and fp16 (not quantized).
phase1b_quantize() {
    log "=============================================="
    log "PHASE 1b: Offline AWQ / GPTQ Quantization"
    log "=============================================="

    mkdir -p "$QUANT_MODELS_DIR"

    for model_spec in "${MODELS[@]}"; do
        IFS='|' read -r hf_name tag vram notes <<< "$model_spec"

        # Offline quantization loads the full FP16 model with CPU offload.
        # On a 24 GB card this is practical up to ~14B (verified); 32B+ either
        # OOMs or runs for many hours via disk-offloaded forward passes.
        if [[ $vram -gt 30 ]]; then
            log "SKIP quantize for $tag (FP16 size ${vram}GB too large for offline quantization on 24GB GPU)"
            continue
        fi

        for quant_spec in "${QUANT_CONFIGS[@]}"; do
            IFS='|' read -r method bits <<< "$quant_spec"

            # Skip methods that don't need offline quantization
            [[ "$method" == "awq" || "$method" == "gptq" ]] || continue

            local out_dir="${QUANT_MODELS_DIR}/${tag}_${method}_w${bits}"

            if [[ -f "${out_dir}/config.json" ]]; then
                log "SKIP (exists): $out_dir"
                continue
            fi

            log "Quantizing: $tag / $method / w${bits}"
            run_cmd "$QUANT_ENV_PYTHON ${PROJECT_DIR}/scripts/quantize_models.py \
                --model $hf_name \
                --method $method \
                --bits $bits \
                --group-size 128 \
                --output $out_dir"

            # Free GPU between quantization jobs
            run_cmd "$QUANT_ENV_PYTHON -c 'import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None'"
        done
    done

    log "Quantization complete. Models in: $QUANT_MODELS_DIR"
}

# ========================== PHASE 2: FP16 BASELINE ==========================
phase2_fp16_inference() {
    log "=============================================="
    log "PHASE 2: FP16 Baseline Inference"
    log "=============================================="

    local sample_flag=$(get_sample_flag)

    for model_spec in "${MODELS[@]}"; do
        IFS='|' read -r hf_name tag vram notes <<< "$model_spec"

        if ! can_run_fp16 "$vram"; then
            log "SKIP FP16 for $tag (needs ${vram}GB > 24GB VRAM)"
            continue
        fi

        for bench in "${BENCHMARKS[@]}"; do
            local out_dir="${RESULTS_DIR}/inference/fp16/${tag}"
            local out_file="${out_dir}/${bench}_run0.jsonl"

            if [[ -f "$out_file" ]]; then
                log "SKIP (exists): $out_file"
                continue
            fi

            log "Running FP16 inference: $tag / $bench"
            for run_idx in $(seq 0 $((NUM_RUNS - 1))); do
                run_cmd "python ${PROJECT_DIR}/scripts/run_inference.py \
                    --model $hf_name \
                    --benchmark $bench \
                    --output $out_dir \
                    --max-tokens $MAX_TOKENS \
                    --num-runs 1 \
                    $sample_flag"
            done
        done

        # Free GPU memory between models
        run_cmd "python -c 'import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None'"
    done
}

# ========================== PHASE 3: QUANTIZED INFERENCE ==========================
phase3_quantized_inference() {
    log "=============================================="
    log "PHASE 3: Quantized Inference"
    log "=============================================="

    local sample_flag=$(get_sample_flag)

    for model_spec in "${MODELS[@]}"; do
        IFS='|' read -r hf_name tag vram notes <<< "$model_spec"

        for quant_spec in "${QUANT_CONFIGS[@]}"; do
            IFS='|' read -r method bits <<< "$quant_spec"
            local quant_tag="${method}_w${bits}"

            # Skip 3-bit and 2-bit for very large models (too slow / unstable)
            if [[ $vram -ge 28 && $bits -lt 4 ]]; then
                log "SKIP $quant_tag for $tag (large model + low bit)"
                continue
            fi

            for bench in "${BENCHMARKS[@]}"; do
                local out_dir="${RESULTS_DIR}/inference/${quant_tag}/${tag}"
                local out_file="${out_dir}/${bench}_run0.jsonl"

                if [[ -f "$out_file" ]]; then
                    log "SKIP (exists): $out_file"
                    continue
                fi

                local model_path=$(resolve_model_path "$hf_name" "$tag" "$method" "$bits")

                # For awq/gptq, the local dir must exist (from phase1b)
                if [[ "$method" == "awq" || "$method" == "gptq" ]] && [[ ! -f "${model_path}/config.json" ]]; then
                    log "SKIP $quant_tag / $tag / $bench: quantized model not found at $model_path"
                    continue
                fi

                log "Running $quant_tag inference: $tag / $bench (from $model_path)"
                run_cmd "python ${PROJECT_DIR}/scripts/run_inference.py \
                    --model $model_path \
                    --quant $method \
                    --bits $bits \
                    --benchmark $bench \
                    --output $out_dir \
                    --max-tokens $MAX_TOKENS \
                    --num-runs 1 \
                    $sample_flag"
            done

            # Free GPU
            run_cmd "python -c 'import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None'"
        done
    done
}

# ========================== PHASE 4: SEGMENTATION ==========================
phase4_segment() {
    log "=============================================="
    log "PHASE 4: CoT Step Segmentation"
    log "=============================================="

    # Segment all inference outputs
    for inf_dir in "${RESULTS_DIR}"/inference/*/; do
        local quant_tag=$(basename "$inf_dir")

        for model_dir in "${inf_dir}"*/; do
            [[ -d "$model_dir" ]] || continue
            local model_tag=$(basename "$model_dir")
            local seg_dir="${RESULTS_DIR}/segmented/${quant_tag}/${model_tag}"

            for jsonl_file in "${model_dir}"*.jsonl; do
                [[ -f "$jsonl_file" ]] || continue
                local basename_f=$(basename "$jsonl_file")
                local out_file="${seg_dir}/${basename_f}"

                if [[ -f "$out_file" ]]; then
                    log "SKIP (exists): $out_file"
                    continue
                fi

                log "Segmenting: ${quant_tag}/${model_tag}/${basename_f}"
                mkdir -p "$seg_dir"
                run_cmd "python -m stepprobe.segment \
                    --input $(dirname $jsonl_file) \
                    --output $seg_dir \
                    --model $model_tag \
                    --quant $quant_tag"
            done
        done
    done
}

# ========================== PHASE 5: DIAGNOSIS ==========================
phase5_diagnose() {
    log "=============================================="
    log "PHASE 5: Step-Level Error Diagnosis"
    log "=============================================="

    local judge_flags=""
    if $USE_LLM_JUDGE; then
        judge_flags="--judge $JUDGE_PROVIDER --judge-model gpt-4o"
    fi

    for model_spec in "${MODELS[@]}"; do
        IFS='|' read -r hf_name tag vram notes <<< "$model_spec"

        # Find FP16 reference (use own FP16 if available, else skip)
        local ref_dir="${RESULTS_DIR}/segmented/fp16/${tag}"
        if [[ ! -d "$ref_dir" ]]; then
            log "WARN: No FP16 reference for $tag. Using closest available."
            # For models too large for FP16, use 8-bit as reference
            ref_dir="${RESULTS_DIR}/segmented/bnb_nf4/${tag}"
            if [[ ! -d "$ref_dir" ]]; then
                log "SKIP diagnosis for $tag (no reference traces)"
                continue
            fi
        fi

        for quant_spec in "${QUANT_CONFIGS[@]}"; do
            IFS='|' read -r method bits <<< "$quant_spec"
            local quant_tag="${method}_w${bits}"
            local hyp_dir="${RESULTS_DIR}/segmented/${quant_tag}/${tag}"

            [[ -d "$hyp_dir" ]] || continue

            local diag_dir="${RESULTS_DIR}/diagnosis/${quant_tag}/${tag}"

            # Check if already done
            local any_missing=false
            for jsonl_file in "${hyp_dir}"/*.jsonl; do
                [[ -f "$jsonl_file" ]] || continue
                local basename_f=$(basename "$jsonl_file")
                [[ -f "${diag_dir}/${basename_f}" ]] || any_missing=true
            done

            if ! $any_missing && [[ -d "$diag_dir" ]]; then
                log "SKIP (exists): diagnosis for ${quant_tag}/${tag}"
                continue
            fi

            log "Diagnosing: ${quant_tag} / ${tag}"
            mkdir -p "$diag_dir"
            run_cmd "python -m stepprobe.diagnose \
                --ref $ref_dir \
                --hyp $hyp_dir \
                --output $diag_dir \
                --alignment dtw \
                $judge_flags"
        done
    done
}

# ========================== PHASE 6: METRICS ==========================
phase6_metrics() {
    log "=============================================="
    log "PHASE 6: Compute StepProbe Metrics"
    log "=============================================="

    local metrics_dir="${RESULTS_DIR}/metrics"
    mkdir -p "$metrics_dir"

    for model_spec in "${MODELS[@]}"; do
        IFS='|' read -r hf_name tag vram notes <<< "$model_spec"

        # Compute FP16 accuracy first (for deltas)
        local fp16_acc=""
        local fp16_diag="${RESULTS_DIR}/diagnosis/fp16/${tag}"
        # (FP16 doesn't have diagnosis, compute from inference)

        for quant_spec in "${QUANT_CONFIGS[@]}"; do
            IFS='|' read -r method bits <<< "$quant_spec"
            local quant_tag="${method}_w${bits}"
            local diag_dir="${RESULTS_DIR}/diagnosis/${quant_tag}/${tag}"

            [[ -d "$diag_dir" ]] || continue

            local out_prefix="${metrics_dir}/${tag}_${quant_tag}"

            log "Computing metrics: ${tag} / ${quant_tag}"
            run_cmd "python -m stepprobe.metrics \
                --diagnosis $diag_dir \
                --output $metrics_dir \
                --model $tag \
                --quant $quant_tag"
        done
    done
}

# ========================== PHASE 7: RESTORATION ==========================
phase7_restore() {
    log "=============================================="
    log "PHASE 7: Targeted Restoration (QLoRA + DPO)"
    log "=============================================="

    for model_spec in "${MODELS[@]}"; do
        IFS='|' read -r hf_name tag vram notes <<< "$model_spec"

        # Only restore models that fit for QLoRA (need FP16 ref + 4bit base)
        if [[ $vram -gt 16 ]]; then
            log "SKIP restoration for $tag (too large for QLoRA on 24GB)"
            continue
        fi

        local ref_dir="${RESULTS_DIR}/segmented/fp16/${tag}"
        [[ -d "$ref_dir" ]] || continue

        # Restore for each quantization method
        for quant_spec in "${QUANT_CONFIGS[@]}"; do
            IFS='|' read -r method bits <<< "$quant_spec"
            local quant_tag="${method}_w${bits}"
            local diag_dir="${RESULTS_DIR}/diagnosis/${quant_tag}/${tag}"

            [[ -d "$diag_dir" ]] || continue

            local restore_dir="${RESULTS_DIR}/restored/${quant_tag}/${tag}"

            if is_complete_adapter "${restore_dir}/qlora/adapter"; then
                log "SKIP (exists): QLoRA restoration for ${quant_tag}/${tag}"
            else
                # Partial state from an interrupted run? HF Trainer will
                # overwrite, but make it loud so stale checkpoints aren't mistaken for success.
                if [[ -d "${restore_dir}/qlora" ]]; then
                    log "WARN: partial QLoRA state found at ${restore_dir}/qlora — restarting training (will overwrite)"
                fi
                log "QLoRA restoration: ${tag} / ${quant_tag}"
                run_cmd "python -m stepprobe.restore \
                    --model $hf_name \
                    --diagnosis $diag_dir \
                    --ref $ref_dir \
                    --output $restore_dir \
                    --method qlora \
                    --max-samples 500 \
                    --epochs 3 \
                    --lr 2e-4 \
                    --batch-size 4"
            fi

            # Also try DPO. NOTE: we write DPO output to "${restore_dir}_dpo"
            # (suffixed tag dir) so QLoRA and DPO don't collide — the skip
            # check must therefore look at "${restore_dir}_dpo/dpo/adapter",
            # not "${restore_dir}/dpo/adapter".
            if is_complete_adapter "${restore_dir}_dpo/dpo/adapter"; then
                log "SKIP (exists): DPO restoration for ${quant_tag}/${tag}"
            else
                if [[ -d "${restore_dir}_dpo/dpo" ]]; then
                    log "WARN: partial DPO state found at ${restore_dir}_dpo/dpo — restarting training (will overwrite)"
                fi
                log "DPO restoration: ${tag} / ${quant_tag}"
                run_cmd "python -m stepprobe.restore \
                    --model $hf_name \
                    --diagnosis $diag_dir \
                    --ref $ref_dir \
                    --output ${restore_dir}_dpo \
                    --method dpo \
                    --max-samples 300 \
                    --epochs 1 \
                    --lr 5e-5 \
                    --batch-size 2"
            fi

            # Free GPU
            run_cmd "python -c 'import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None'"
        done
    done
}

# ========================== PHASE 8: RE-EVALUATE RESTORED ==========================
phase8_reeval() {
    log "=============================================="
    log "PHASE 8: Re-evaluate Restored Models"
    log "=============================================="

    local sample_flag=$(get_sample_flag)

    # Fast restored-inference path:
    #   1. Merge the LoRA adapter into an FP16 copy of the base model (one-time
    #      per (model, quant_tag)). Merging in FP16 is lossless; merging into
    #      4-bit weights — as the old path did — triggers PEFT's rounding-error
    #      warning.
    #   2. Run vLLM on the merged model with --quant bnb_nf4 so it re-quantizes
    #      to NF4 at load. Same deployment target as before, with vLLM's batched
    #      generation instead of HF's one-sample-at-a-time loop.
    #   3. Delete the merged-FP16 dir once all benchmarks for that config are
    #      done, so disk usage stays bounded to ~one model at a time.
    for model_spec in "${MODELS[@]}"; do
        IFS='|' read -r hf_name tag vram notes <<< "$model_spec"

        for quant_spec in "${QUANT_CONFIGS[@]}"; do
            IFS='|' read -r method bits <<< "$quant_spec"
            local quant_tag="${method}_w${bits}"
            local adapter_dir="${RESULTS_DIR}/restored/${quant_tag}/${tag}/qlora/adapter"
            local merged_dir="${RESULTS_DIR}/restored/${quant_tag}/${tag}/qlora/merged_fp16"

            [[ -d "$adapter_dir" ]] || continue

            # Determine which benchmarks still need to run for this config.
            local pending_benches=()
            for bench in "${BENCHMARKS[@]}"; do
                local out_file="${RESULTS_DIR}/inference/${quant_tag}_restored/${tag}/${bench}_run0.jsonl"
                if [[ -f "$out_file" ]]; then
                    log "SKIP (exists): $out_file"
                else
                    pending_benches+=("$bench")
                fi
            done

            if [[ ${#pending_benches[@]} -eq 0 ]]; then
                continue
            fi

            # Merge adapter → FP16 once (cached on disk if re-run).
            if [[ ! -f "${merged_dir}/config.json" ]]; then
                log "Merging adapter into FP16: ${tag} / ${quant_tag}"
                run_cmd "python ${PROJECT_DIR}/scripts/merge_adapter.py \
                    --model $hf_name \
                    --adapter $adapter_dir \
                    --output $merged_dir"
                run_cmd "python -c 'import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None'"
            fi

            for bench in "${pending_benches[@]}"; do
                local out_dir="${RESULTS_DIR}/inference/${quant_tag}_restored/${tag}"
                mkdir -p "$out_dir"

                log "Re-evaluating restored (vLLM+NF4): ${tag} / ${quant_tag} / ${bench}"
                run_cmd "python ${PROJECT_DIR}/scripts/run_inference.py \
                    --model $merged_dir \
                    --quant bnb_nf4 \
                    --bits $bits \
                    --benchmark $bench \
                    --output $out_dir \
                    --max-tokens $MAX_TOKENS \
                    --num-runs 1 \
                    $sample_flag"
            done

            # Disk hygiene: the merged FP16 dir is ~3-16 GB and is only needed
            # during inference. Once all 3 benchmarks are done, drop it.
            if [[ -d "$merged_dir" ]] && ! $DRY_RUN; then
                log "Cleaning up merged FP16 dir: $merged_dir"
                rm -rf "$merged_dir"
            fi

            run_cmd "python -c 'import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None'"
        done
    done

    # Re-run segment + diagnose + metrics on restored outputs. `stepprobe.segment`
    # reads every jsonl in the input dir in one invocation, so we call it once
    # per (quant_tag, model_tag) — not once per jsonl.
    log "Segmenting + diagnosing restored model outputs..."
    shopt -s nullglob
    for inf_dir in "${RESULTS_DIR}"/inference/*_restored/; do
        [[ -d "$inf_dir" ]] || continue
        local quant_tag=$(basename "$inf_dir")

        for model_dir in "${inf_dir}"*/; do
            [[ -d "$model_dir" ]] || continue
            local model_tag=$(basename "$model_dir")
            local jsonls=("${model_dir}"*.jsonl)
            [[ ${#jsonls[@]} -gt 0 ]] || continue

            local seg_dir="${RESULTS_DIR}/segmented/${quant_tag}/${model_tag}"
            mkdir -p "$seg_dir"
            run_cmd "python -m stepprobe.segment --input $model_dir --output $seg_dir --quant ${quant_tag}"

            # Diagnose vs FP16 reference.
            local ref_dir="${RESULTS_DIR}/segmented/fp16/${model_tag}"
            [[ -d "$ref_dir" ]] || continue
            local diag_dir="${RESULTS_DIR}/diagnosis/${quant_tag}/${model_tag}"
            mkdir -p "$diag_dir"
            run_cmd "python -m stepprobe.diagnose --ref $ref_dir --hyp $seg_dir --output $diag_dir --alignment dtw"

            # Metrics — tagged so per-(model, quant) files don't clobber.
            run_cmd "python -m stepprobe.metrics --diagnosis $diag_dir --output ${RESULTS_DIR}/metrics --model $model_tag --quant $quant_tag"
        done
    done
    shopt -u nullglob
}

# ========================== PHASE 9: FIGURES & SUMMARY ==========================
phase9_figures() {
    log "=============================================="
    log "PHASE 9: Generate Figures & Summary"
    log "=============================================="

    # Exploratory per-(model, benchmark) figures — useful while iterating;
    # end up as supplementary material in the paper.
    log "Generating exploratory figures (per model × benchmark)..."
    run_cmd "python ${PROJECT_DIR}/scripts/make_figures.py \
        --metrics ${RESULTS_DIR}/metrics \
        --output $FIGURES_DIR"

    # Bootstrap confidence intervals and paired significance tests on the
    # per-problem diagnosis data. Writes *_ci.json and *_sig.json alongside
    # the *_metrics.json files; paper figures consume them for CI bands and
    # significance stars. Needs no GPU — pure numpy resampling.
    log "Computing bootstrap CIs + paired significance tests..."
    run_cmd "python ${PROJECT_DIR}/scripts/compute_ci.py \
        --diagnosis ${RESULTS_DIR}/diagnosis \
        --output ${RESULTS_DIR}/metrics \
        --n-boot 5000"

    # Paper-ready headline figures + LaTeX numerics table.
    # Produces 6 figures: pipeline schematic, SSR (with CI bands), error mix,
    # forest plot with CIs + sig stars, FFS distribution, qualitative trace
    # example. Reads metrics/ (point estimates + CIs + sig) plus diagnosis/
    # and segmented/ (for the per-problem data behind figs 4 and 5).
    log "Generating paper figures + LaTeX table..."
    run_cmd "python ${PROJECT_DIR}/scripts/make_paper_figures.py \
        --metrics ${RESULTS_DIR}/metrics \
        --diagnosis ${RESULTS_DIR}/diagnosis \
        --segmented ${RESULTS_DIR}/segmented \
        --output ${FIGURES_DIR}/paper"

    # Auto-populated supplementary tables (ablation / baselines / interventions).
    # Safe to call even before those experiments have run — placeholders fill
    # in and the paper still compiles.
    log "Generating supplementary LaTeX tables..."
    run_cmd "python ${PROJECT_DIR}/scripts/make_tables.py \
        --metrics-dir ${RESULTS_DIR}/metrics \
        --output-dir ${FIGURES_DIR}/paper"

    # Terminal summary table (for the log).
    log "Generating summary table..."
    run_cmd "python ${PROJECT_DIR}/scripts/summary_table.py --metrics ${RESULTS_DIR}/metrics"

    log "All figures saved to: $FIGURES_DIR"
}

# ========================== MAIN ==========================
main() {
    log "=============================================="
    log "StepProbe — Full Experiment Pipeline"
    log "Started: $(date)"
    log "Config: models=$MODEL_SET, samples=${MAX_SAMPLES:-all}, runs=$NUM_RUNS"
    log "=============================================="

    cd "$PROJECT_DIR"

    [[ $START_PHASE -le 0 ]] && phase0_setup
    [[ $START_PHASE -le 1 ]] && phase1_download
    [[ $START_PHASE -le 1 ]] && phase1b_quantize
    [[ $START_PHASE -le 2 ]] && phase2_fp16_inference
    [[ $START_PHASE -le 3 ]] && phase3_quantized_inference
    [[ $START_PHASE -le 4 ]] && phase4_segment
    [[ $START_PHASE -le 5 ]] && phase5_diagnose
    [[ $START_PHASE -le 6 ]] && phase6_metrics
    [[ $START_PHASE -le 7 ]] && phase7_restore
    [[ $START_PHASE -le 8 ]] && phase8_reeval
    [[ $START_PHASE -le 9 ]] && phase9_figures

    log ""
    log "=============================================="
    log "ALL PHASES COMPLETE"
    log "Finished: $(date)"
    log "Results:  $RESULTS_DIR"
    log "Figures:  $FIGURES_DIR"
    log "Log:      $LOG_FILE"
    log "=============================================="
}

main