File size: 12,792 Bytes
3ccaf5a | 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 | #!/usr/bin/env bash
###############################################################################
# StepProbe — Ablation Study Runner
#
# Runs all ablation experiments:
# A1: Dataset size ablation (50, 100, 200, 500 samples for restoration)
# A2: Error-type targeted ablation (restore only one error type at a time)
# A3: LoRA rank ablation (r=4, 8, 16, 32)
# A4: Quantization method comparison (AWQ vs GPTQ vs NF4 at same bit-width)
# A5: Model size scaling (1.5B, 7B, 14B, 32B)
#
# Usage:
# bash scripts/run_ablations.sh # all ablations
# bash scripts/run_ablations.sh --ablation A1 # single ablation
# bash scripts/run_ablations.sh --quick # small sample size
###############################################################################
set -euo pipefail
PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
RESULTS_DIR="${PROJECT_DIR}/results"
ABLATION_DIR="${RESULTS_DIR}/ablations"
LOG_FILE="${PROJECT_DIR}/logs/ablations_$(date +%Y%m%d_%H%M%S).log"
# Defaults
TARGET_ABLATION="all"
BASE_MODEL="deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
BASE_TAG="r1-qwen-7b"
QUICK=false
while [[ $# -gt 0 ]]; do
case $1 in
--ablation) TARGET_ABLATION=$2; shift 2 ;;
--quick) QUICK=true; shift ;;
--model) BASE_MODEL=$2; shift 2 ;;
*) shift ;;
esac
done
mkdir -p "$ABLATION_DIR" "$(dirname $LOG_FILE)"
log() { echo "[$(date '+%H:%M:%S')] $1" | tee -a "$LOG_FILE"; }
# ==================================================================
# A1: Dataset Size Ablation
# How many Silver Bullet samples do you actually need?
# ==================================================================
ablation_a1() {
log "========== A1: Dataset Size Ablation =========="
local sizes=(50 100 200 500)
if $QUICK; then sizes=(50 100); fi
local diag_dir="${RESULTS_DIR}/diagnosis/bnb_nf4/${BASE_TAG}"
local ref_dir="${RESULTS_DIR}/segmented/fp16/${BASE_TAG}"
[[ -d "$diag_dir" ]] || { log "SKIP A1: No diagnosis data. Run main pipeline first."; return; }
for n in "${sizes[@]}"; do
local out_dir="${ABLATION_DIR}/A1_dataset_size/n${n}"
if [[ -d "${out_dir}/qlora/adapter" ]]; then
log "SKIP: A1 n=$n already done"
continue
fi
log "A1: Restoring with n=$n samples"
python -m stepprobe.restore \
--model "$BASE_MODEL" \
--diagnosis "$diag_dir" \
--ref "$ref_dir" \
--output "$out_dir" \
--method qlora \
--max-samples "$n" \
--epochs 3 \
--lr 2e-4 \
--batch-size 4 \
2>&1 | tee -a "$LOG_FILE"
# Re-evaluate
log "A1: Evaluating restored model (n=$n)"
python "${PROJECT_DIR}/scripts/run_inference_restored.py" \
--model "$BASE_MODEL" \
--adapter "${out_dir}/qlora/adapter" \
--benchmark gsm8k \
--output "${out_dir}/eval" \
--max-samples 200 \
2>&1 | tee -a "$LOG_FILE"
python -c "import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None"
done
log "A1 complete."
}
# ==================================================================
# A2: Error-Type Targeted Ablation
# Does fixing one error type help with others?
# ==================================================================
ablation_a2() {
log "========== A2: Error-Type Targeted Ablation =========="
local error_types=("conceptual" "methodological" "executional" "logical")
local diag_dir="${RESULTS_DIR}/diagnosis/bnb_nf4/${BASE_TAG}"
local ref_dir="${RESULTS_DIR}/segmented/fp16/${BASE_TAG}"
[[ -d "$diag_dir" ]] || { log "SKIP A2: No diagnosis data."; return; }
for etype in "${error_types[@]}"; do
local out_dir="${ABLATION_DIR}/A2_error_type/${etype}"
if [[ -d "${out_dir}/qlora/adapter" ]]; then
log "SKIP: A2 $etype already done"
continue
fi
log "A2: Restoring with only $etype errors"
python -m stepprobe.restore \
--model "$BASE_MODEL" \
--diagnosis "$diag_dir" \
--ref "$ref_dir" \
--output "$out_dir" \
--method qlora \
--max-samples 500 \
--target-errors "$etype" \
--epochs 3 \
--lr 2e-4 \
--batch-size 4 \
2>&1 | tee -a "$LOG_FILE"
# Evaluate
python "${PROJECT_DIR}/scripts/run_inference_restored.py" \
--model "$BASE_MODEL" \
--adapter "${out_dir}/qlora/adapter" \
--benchmark gsm8k \
--output "${out_dir}/eval" \
--max-samples 200 \
2>&1 | tee -a "$LOG_FILE"
python -c "import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None"
done
log "A2 complete."
}
# ==================================================================
# A3: LoRA Rank Ablation
# ==================================================================
ablation_a3() {
log "========== A3: LoRA Rank Ablation =========="
local ranks=(4 8 16 32)
if $QUICK; then ranks=(8 16); fi
local diag_dir="${RESULTS_DIR}/diagnosis/bnb_nf4/${BASE_TAG}"
local ref_dir="${RESULTS_DIR}/segmented/fp16/${BASE_TAG}"
[[ -d "$diag_dir" ]] || { log "SKIP A3: No diagnosis data."; return; }
for r in "${ranks[@]}"; do
local out_dir="${ABLATION_DIR}/A3_lora_rank/r${r}"
if [[ -d "${out_dir}/qlora/adapter" ]]; then
log "SKIP: A3 r=$r already done"
continue
fi
log "A3: Restoring with LoRA r=$r"
python -c "
import sys, os
sys.path.insert(0, '${PROJECT_DIR}')
from stepprobe.restore import build_silver_bullet_dataset, format_for_sft, run_qlora_restoration
from stepprobe.utils import load_jsonl
import glob
diag = []
for f in sorted(glob.glob('${diag_dir}/*.jsonl')):
diag.extend(load_jsonl(f))
ref = []
for f in sorted(glob.glob('${ref_dir}/*.jsonl')):
ref.extend(load_jsonl(f))
samples, stats = build_silver_bullet_dataset(diag, ref, [], max_samples=500)
if samples:
train_data = format_for_sft(samples)
run_qlora_restoration(
model_name='${BASE_MODEL}',
train_data=train_data,
output_dir='${out_dir}/qlora',
r=${r},
lora_alpha=$((r * 2)),
num_epochs=3,
)
" 2>&1 | tee -a "$LOG_FILE"
# Evaluate
if [[ -d "${out_dir}/qlora/adapter" ]]; then
python "${PROJECT_DIR}/scripts/run_inference_restored.py" \
--model "$BASE_MODEL" \
--adapter "${out_dir}/qlora/adapter" \
--benchmark gsm8k \
--output "${out_dir}/eval" \
--max-samples 200 \
2>&1 | tee -a "$LOG_FILE"
fi
python -c "import torch; torch.cuda.empty_cache() if torch.cuda.is_available() else None"
done
log "A3 complete."
}
# ==================================================================
# A4: Quantization Method Comparison (at same bit-width)
# Already handled by main pipeline, this generates the comparison
# ==================================================================
ablation_a4() {
log "========== A4: Quant Method Comparison (metrics only) =========="
local metrics_dir="${RESULTS_DIR}/metrics"
[[ -d "$metrics_dir" ]] || { log "SKIP A4: No metrics data."; return; }
python -c "
import glob, json, os
files = sorted(glob.glob('${metrics_dir}/*_metrics.json'))
if not files:
print('No metrics found')
exit()
# Group by bit-width
by_bits = {}
for f in files:
with open(f) as fp:
m = json.load(fp)
quant = m.get('quantization', '')
if '_w' not in quant:
continue
parts = quant.split('_w')
method = parts[0]
bits = parts[1].split('_')[0]
by_bits.setdefault(bits, []).append(m)
for bits, metrics_list in sorted(by_bits.items()):
print(f'\\n=== {bits}-bit comparison ===')
print(f'{\"Method\":<15} {\"Acc\":<8} {\"FFS\":<8} {\"ECR\":<8}')
print('-' * 40)
for m in sorted(metrics_list, key=lambda x: -x.get('accuracy', 0)):
print(f'{m[\"quantization\"]:<15} {m.get(\"accuracy\",0):.1%} {m.get(\"avg_ffs\",0):.1f} {m.get(\"ecr\",0):.1%}')
" 2>&1 | tee -a "$LOG_FILE"
log "A4 complete."
}
# ==================================================================
# A5: Model Size Scaling
# Already handled by main pipeline, this generates the scaling plot
# ==================================================================
ablation_a5() {
log "========== A5: Model Size Scaling (figure only) =========="
local metrics_dir="${RESULTS_DIR}/metrics"
python -c "
import glob, json, os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
files = sorted(glob.glob('${metrics_dir}/*_metrics.json'))
if not files:
print('No metrics found')
exit()
# Group by model size
by_model = {}
for f in files:
with open(f) as fp:
m = json.load(fp)
model = m.get('model', '')
quant = m.get('quantization', '')
if 'bnb_nf4' not in quant:
continue
by_model[model] = m
if len(by_model) < 2:
print('Need at least 2 model sizes for scaling plot')
exit()
# Extract sizes from model names
sizes = {'1.5b': 1.5, '7b': 7, '8b': 8, '14b': 14, '32b': 32}
data = []
for model, m in by_model.items():
for s, v in sizes.items():
if s.lower() in model.lower():
data.append((v, m.get('accuracy', 0), m.get('avg_ffs', 0), m.get('ecr', 0)))
break
data.sort()
if data:
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
x = [d[0] for d in data]
axes[0].plot(x, [d[1] for d in data], 'o-', color='#2E86AB', linewidth=2, markersize=8)
axes[0].set_xlabel('Model size (B params)'); axes[0].set_ylabel('Accuracy (4-bit NF4)')
axes[0].set_title('Accuracy vs model size')
axes[1].plot(x, [d[2] for d in data], 's-', color='#A23B72', linewidth=2, markersize=8)
axes[1].set_xlabel('Model size (B params)'); axes[1].set_ylabel('Avg FFS')
axes[1].set_title('First failure step vs model size')
axes[2].plot(x, [d[3] for d in data], 'D-', color='#F18F01', linewidth=2, markersize=8)
axes[2].set_xlabel('Model size (B params)'); axes[2].set_ylabel('ECR')
axes[2].set_title('Error cascade rate vs model size')
for ax in axes:
ax.grid(True, alpha=0.3)
ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
plt.tight_layout()
out = '${ABLATION_DIR}/A5_model_scaling.pdf'
os.makedirs(os.path.dirname(out), exist_ok=True)
plt.savefig(out, dpi=300, bbox_inches='tight')
print(f'Scaling plot saved: {out}')
" 2>&1 | tee -a "$LOG_FILE"
log "A5 complete."
}
# ==================================================================
# Summary: collect all ablation results
# ==================================================================
collect_ablation_results() {
log "========== Collecting Ablation Results =========="
python -c "
import glob, json, os
abl_dir = '${ABLATION_DIR}'
results = {}
# A1: dataset size
for d in sorted(glob.glob(os.path.join(abl_dir, 'A1_dataset_size/n*/eval/*.jsonl'))):
n = d.split('/n')[1].split('/')[0]
lines = open(d).readlines()
results.setdefault('A1', []).append({'n': int(n), 'n_samples': len(lines)})
# A2: error type
for d in sorted(glob.glob(os.path.join(abl_dir, 'A2_error_type/*/eval/*.jsonl'))):
etype = d.split('A2_error_type/')[1].split('/')[0]
lines = open(d).readlines()
results.setdefault('A2', []).append({'error_type': etype, 'n_samples': len(lines)})
# A3: LoRA rank
for d in sorted(glob.glob(os.path.join(abl_dir, 'A3_lora_rank/r*/eval/*.jsonl'))):
r = d.split('/r')[1].split('/')[0]
lines = open(d).readlines()
results.setdefault('A3', []).append({'rank': int(r), 'n_samples': len(lines)})
out = os.path.join(abl_dir, 'ablation_summary.json')
with open(out, 'w') as f:
json.dump(results, f, indent=2)
print(f'Ablation summary: {out}')
print(json.dumps(results, indent=2))
" 2>&1 | tee -a "$LOG_FILE"
}
# ==================================================================
# MAIN
# ==================================================================
log "StepProbe Ablation Runner — Started $(date)"
case $TARGET_ABLATION in
A1|a1) ablation_a1 ;;
A2|a2) ablation_a2 ;;
A3|a3) ablation_a3 ;;
A4|a4) ablation_a4 ;;
A5|a5) ablation_a5 ;;
all)
ablation_a1
ablation_a2
ablation_a3
ablation_a4
ablation_a5
collect_ablation_results
;;
*) echo "Unknown ablation: $TARGET_ABLATION"; exit 1 ;;
esac
log "Ablation runner complete."
|