StepProbe / run_all.sh
Akiyue's picture
Add files using upload-large-folder tool
1e59964 verified
Raw
History Blame Contribute Delete
31.6 kB
#!/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