StepProbe / scripts /run_ablations.sh
Akiyue's picture
Add files using upload-large-folder tool
3ccaf5a verified
Raw
History Blame Contribute Delete
12.8 kB
#!/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."