File size: 7,298 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
#!/usr/bin/env bash
###############################################################################
# StepProbe — Dataset-size ablation for the restoration step.
#
# Trains a QLoRA restoration adapter at several silver-bullet dataset sizes,
# evaluates each on a primary benchmark, then renders fig_paper_6_ablation.pdf.
#
# Why qwen25-7b + GPTQ w4 and not r1-qwen-7b?
#   The forest plot shows r1-qwen-7b does NOT respond to restoration on math500
#   (ΔAcc ≈ +1 pp, ns) — a flat ablation curve would be a weak paper story.
#   qwen25-7b + GPTQ on math500 is the cell with the strongest significant
#   positive response (+5.4 pp, p<.01), so the ablation curve should show a
#   meaningful upward trend as N grows. Override with env vars if you want
#   different config.
#
# Usage:
#   bash run_ablation.sh                       # defaults
#   MODEL_TAG=r1-qwen-1.5b bash run_ablation.sh  # override model
#   SAMPLE_SIZES='25 50 100 200' bash run_ablation.sh  # override sweep
#
# Expected runtime: ~90-120 min on a single 3090 Ti.
###############################################################################
set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$PROJECT_DIR"

export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-1}"
export HF_HUB_DOWNLOAD_TIMEOUT=300

# ====== Config (override via env) ==========================================
MODEL_HF="${MODEL_HF:-Qwen/Qwen2.5-7B-Instruct}"
MODEL_TAG="${MODEL_TAG:-qwen25-7b}"
QUANT_TAG="${QUANT_TAG:-gptq_w4}"
BENCHMARK="${BENCHMARK:-math500}"
SAMPLE_SIZES_STR="${SAMPLE_SIZES:-50 100 250 500}"
IFS=' ' read -r -a SAMPLE_SIZES <<< "$SAMPLE_SIZES_STR"

PY="${PY:-python}"
MAX_TOKENS="${MAX_TOKENS:-4096}"
# vLLM will OOM if another process (e.g. ollama) is already holding a chunk
# of the GPU. 0.55 gives a 7B NF4 model plenty while leaving ~11 GB free for
# anything else — override with GPU_MEM=... on GPUs where more is free.
GPU_MEM="${GPU_MEM:-0.55}"

# ====== Paths ==============================================================
ABLATION_ROOT="${PROJECT_DIR}/results/ablation/${MODEL_TAG}_${QUANT_TAG}"
DIAG_DIR="${PROJECT_DIR}/results/diagnosis/${QUANT_TAG}/${MODEL_TAG}"
REF_DIR="${PROJECT_DIR}/results/segmented/fp16/${MODEL_TAG}"
LOG_DIR="${PROJECT_DIR}/logs"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOG_FILE="${LOG_DIR}/ablation_${TIMESTAMP}.log"

mkdir -p "$ABLATION_ROOT" "$LOG_DIR"

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

run_or_skip() {
    local desc=$1
    local skip_check=$2
    local cmd=$3
    if eval "$skip_check"; then
        log "SKIP: $desc"
    else
        log "RUN: $desc"
        eval "$cmd" 2>&1 | tee -a "$LOG_FILE"
    fi
}

# ====== Preflight ==========================================================
log "=============================================="
log "StepProbe restoration ablation"
log "  Model:      $MODEL_HF ($MODEL_TAG)"
log "  Quant:      $QUANT_TAG"
log "  Benchmark:  $BENCHMARK"
log "  Sample Ns:  ${SAMPLE_SIZES[*]}"
log "  Output:     $ABLATION_ROOT"
log "  Log:        $LOG_FILE"
log "=============================================="

# Prerequisites: need diagnosis + FP16 reference segmentation for this config.
if [[ ! -d "$DIAG_DIR" ]]; then
    log "ERROR: missing diagnosis dir: $DIAG_DIR"
    log "       run 'bash run_all.sh --phase 5' to generate it first"
    exit 1
fi
if [[ ! -d "$REF_DIR" ]]; then
    log "ERROR: missing FP16 reference segmentation: $REF_DIR"
    log "       run 'bash run_all.sh --phase 4' to generate it first"
    exit 1
fi

# ====== Main sweep =========================================================
for N in "${SAMPLE_SIZES[@]}"; do
    log ""
    log "=============================================="
    log "Ablation N=$N"
    log "=============================================="

    CFG_DIR="${ABLATION_ROOT}/n${N}"
    ADAPTER="${CFG_DIR}/qlora/adapter"
    MERGED="${CFG_DIR}/qlora/merged_fp16"
    INF_DIR="${CFG_DIR}/inference"
    OUT_FILE="${INF_DIR}/${BENCHMARK}_run0.jsonl"

    # --- 1. Restoration training --------------------------------------------
    run_or_skip "QLoRA restoration (N=$N)" \
        "[[ -f '${ADAPTER}/adapter_model.safetensors' ]]" \
        "$PY -m stepprobe.restore \
            --model '$MODEL_HF' \
            --diagnosis '$DIAG_DIR' \
            --ref '$REF_DIR' \
            --output '$CFG_DIR' \
            --method qlora \
            --max-samples $N \
            --epochs 3 \
            --lr 2e-4 \
            --batch-size 4"

    # --- 2. Merge + inference (skip entirely if inference output already exists) ----
    if [[ -f "$OUT_FILE" ]]; then
        log "SKIP: vLLM inference on $BENCHMARK (N=$N) — $OUT_FILE exists"
    else
        run_or_skip "Merge adapter → FP16 (N=$N)" \
            "[[ -f '${MERGED}/config.json' ]]" \
            "$PY ${PROJECT_DIR}/scripts/merge_adapter.py \
                --model '$MODEL_HF' \
                --adapter '$ADAPTER' \
                --output '$MERGED'"

        $PY -c "import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None" 2>&1 | tee -a "$LOG_FILE"

        run_or_skip "vLLM inference on $BENCHMARK (N=$N)" \
            "[[ -f '$OUT_FILE' ]]" \
            "$PY ${PROJECT_DIR}/scripts/run_inference.py \
                --model '$MERGED' \
                --quant bnb_nf4 \
                --bits 4 \
                --benchmark $BENCHMARK \
                --output '$INF_DIR' \
                --max-tokens $MAX_TOKENS \
                --num-runs 1 \
                --gpu-memory-utilization $GPU_MEM"
    fi

    # --- 4. Segmentation + diagnosis on this ablation config ---------------
    SEG_DIR="${CFG_DIR}/segmented"
    DIAG_OUT="${CFG_DIR}/diagnosis"
    run_or_skip "Segment (N=$N)" \
        "[[ -f '${SEG_DIR}/${BENCHMARK}_run0.jsonl' ]]" \
        "$PY -m stepprobe.segment --input '$INF_DIR' --output '$SEG_DIR' --quant '${QUANT_TAG}_ablation_n${N}'"

    run_or_skip "Diagnose vs FP16 (N=$N)" \
        "[[ -f '${DIAG_OUT}/${BENCHMARK}_run0.jsonl' ]]" \
        "$PY -m stepprobe.diagnose --ref '$REF_DIR' --hyp '$SEG_DIR' --output '$DIAG_OUT' --alignment dtw"

    # --- 5. Free disk (merged FP16 is ~14 GB for a 7B model) ---------------
    if [[ -d "$MERGED" ]]; then
        log "Cleaning up merged FP16 dir: $MERGED"
        rm -rf "$MERGED"
    fi

    $PY -c "import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None" 2>&1 | tee -a "$LOG_FILE"
done

# ====== Build the ablation figure =========================================
log ""
log "=============================================="
log "Rendering fig_paper_6_ablation.pdf"
log "=============================================="
$PY ${PROJECT_DIR}/scripts/make_ablation_figure.py \
    --ablation-root "$ABLATION_ROOT" \
    --model "$MODEL_TAG" \
    --quant "$QUANT_TAG" \
    --benchmark "$BENCHMARK" \
    --metrics "${PROJECT_DIR}/results/metrics" \
    --output "${PROJECT_DIR}/figures/paper/fig_paper_6_ablation.pdf" 2>&1 | tee -a "$LOG_FILE"

log ""
log "=============================================="
log "DONE"
log "  Figure:   figures/paper/fig_paper_6_ablation.pdf"
log "  Log:      $LOG_FILE"
log "=============================================="