diffuzamba-phase2-pipeline / run_pipeline.sh
ModhiSathvik's picture
Add run_pipeline.sh
45d5b40 verified
Raw History Blame Contribute Delete
10.7 kB
#!/bin/bash
# ========================================================================
# Automated multi-format synthetic data generation pipeline.
#
# For each format in the configured list:
# 1. Filter seeds (skip silently if format has no filter rule)
# 2. Run smoke test (50 samples)
# 3. Validate quality of the smoke test
# 4. If quality passes, run full generation
# 5. If anything fails, STOP and report the reason
#
# Usage:
# bash run_pipeline.sh javascript # default formats
# bash run_pipeline.sh javascript tier1 # autocomplete-focused only
# bash run_pipeline.sh python tier2 # broader coverage
#
# Resume: re-running the script picks up where it left off (each generator
# auto-resumes from existing output files).
#
# Stop conditions (script exits with error):
# - vLLM endpoint unreachable
# - Generator file missing
# - Smoke test produces 0 successful samples
# - Smoke test fail rate > 50%
# - Smoke test sample is empty or malformed JSON
#
# Logs:
# logs/<subject>_pipeline.log master pipeline log
# logs/<subject>_<format>.log per-format generation log
# ========================================================================
set -u # error on undefined vars (don't use -e; we want to handle errors explicitly)
# ===== Args =====
SUBJECT="${1:-python}"
TIER="${2:-tier1}"
# ===== Config =====
ROOT="/workspace/pluto_run"
VLLM_URL="http://localhost:8000/v1"
SMOKE_LIMIT=50
SMOKE_FAIL_THRESHOLD=50 # max % of failed samples in smoke test before we abort
# Format list per tier. Order matters: highest-value formats first so partial
# completions still leave you with the best data.
case "$TIER" in
tier1)
# Autocomplete-focused (~3 hours)
FORMATS=(
"infilling:128"
"code_exercise:128"
"infilling_long:96"
"infilling_class:128"
"infilling_real_libs:128"
)
;;
tier2)
# Broader coverage (Tier 1 + conceptual)
FORMATS=(
"infilling:128"
"code_exercise:128"
"infilling_long:96"
"infilling_class:128"
"infilling_real_libs:128"
"textbook:96"
"worked_example:128"
"refinement:96"
)
;;
all)
# Everything (~10 hours)
FORMATS=(
"infilling:128"
"code_exercise:128"
"infilling_long:96"
"infilling_class:128"
"infilling_real_libs:128"
"textbook:96"
"worked_example:128"
"refinement:96"
"debug_dialogue:96"
"instruction_reversal:128"
)
;;
*)
echo "ERROR: unknown tier '$TIER'. Use: tier1 | tier2 | all"
exit 1
;;
esac
# ===== Setup =====
cd "$ROOT" || { echo "ERROR: cannot cd to $ROOT"; exit 1; }
mkdir -p logs data/$SUBJECT
PIPELINE_LOG="logs/${SUBJECT}_pipeline.log"
log() {
local msg="$1"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $msg" | tee -a "$PIPELINE_LOG"
}
abort() {
local reason="$1"
log ""
log "================================================================"
log "PIPELINE ABORTED"
log "Reason: $reason"
log ""
log "Diagnose:"
log " - Master log: $PIPELINE_LOG"
log " - Format logs: logs/${SUBJECT}_*.log"
log " - Last format: ${LAST_FORMAT:-none}"
log "================================================================"
exit 1
}
# ===== Pre-flight checks =====
log "================================================================"
log "Pipeline starting: subject=$SUBJECT tier=$TIER"
log "Formats to run (${#FORMATS[@]}):"
for entry in "${FORMATS[@]}"; do
log " - $entry"
done
log "================================================================"
# 1. Seeds file exists
SEEDS_FILE="seeds/${SUBJECT}.json"
if [ ! -f "$SEEDS_FILE" ]; then
abort "Seeds file missing: $SEEDS_FILE. Run topic expansion first."
fi
SEED_COUNT=$(python -c "import json; print(len(json.load(open('$SEEDS_FILE'))))" 2>/dev/null) \
|| abort "Cannot parse seeds file: $SEEDS_FILE"
log "Seeds file: $SEEDS_FILE ($SEED_COUNT topics)"
# 2. vLLM endpoint reachable
if ! curl -sf "$VLLM_URL/models" > /dev/null; then
abort "vLLM endpoint unreachable at $VLLM_URL. Start vLLM first."
fi
MODEL=$(curl -s "$VLLM_URL/models" | python -c "import json,sys; print(json.load(sys.stdin)['data'][0]['id'])" 2>/dev/null)
log "vLLM up: model=$MODEL"
# 3. Generators exist
log "Checking generator files..."
for entry in "${FORMATS[@]}"; do
fmt="${entry%%:*}"
gen="generators/generate_${fmt}.py"
if [ ! -f "$gen" ]; then
abort "Generator missing: $gen"
fi
done
log "All generators present."
# 4. Filter utility
if [ ! -f "utils/filter_seeds.py" ]; then
log "WARNING: utils/filter_seeds.py missing - per-format seed filtering will be skipped"
fi
# ===== Quality validator =====
# Reads smoke output JSONL, counts successful samples, checks for obvious problems
validate_smoke() {
local fmt="$1"
local out_file="data/${SUBJECT}/${fmt}.jsonl"
if [ ! -f "$out_file" ]; then
echo "MISSING_FILE"
return
fi
python << PYEOF
import json
import sys
samples = []
malformed = 0
with open("$out_file") as f:
for line in f:
try:
samples.append(json.loads(line))
except Exception:
malformed += 1
n = len(samples)
if n == 0:
print("EMPTY")
sys.exit()
# Check for content-level issues
empty_text = 0
for s in samples:
text = s.get("messages", [{}, {}, {}])[2].get("content", "")
if not text or len(text) < 50:
empty_text += 1
# Token range
tokens = [s.get("tokens", 0) for s in samples]
min_tok = min(tokens)
max_tok = max(tokens)
median_tok = sorted(tokens)[len(tokens) // 2]
# Output structured result for the bash caller
empty_pct = empty_text / n * 100
print(f"OK n={n} malformed={malformed} empty={empty_text} empty_pct={empty_pct:.1f} "
f"tokens_min={min_tok} tokens_median={median_tok} tokens_max={max_tok}")
PYEOF
}
# ===== Per-format pipeline =====
LAST_FORMAT=""
TOTAL_SAMPLES_BEFORE=$(find data/$SUBJECT -name "*.jsonl" 2>/dev/null | xargs -r wc -l 2>/dev/null | tail -1 | awk '{print $1}' || echo 0)
log ""
log "Starting samples on disk: ${TOTAL_SAMPLES_BEFORE:-0}"
for entry in "${FORMATS[@]}"; do
fmt="${entry%%:*}"
conc="${entry##*:}"
LAST_FORMAT="$fmt"
log ""
log "================================================================"
log "FORMAT: $fmt (concurrency=$conc)"
log "================================================================"
# ---- Step 1: Filter seeds (best-effort, may not apply) ----
if [ -f "utils/filter_seeds.py" ]; then
log "[1/4] Filtering seeds for $fmt..."
python utils/filter_seeds.py --subject "$SUBJECT" --format "$fmt" \
>> "$PIPELINE_LOG" 2>&1 \
|| log " (filter step had warnings - format may use base seeds)"
fi
# ---- Step 2: Smoke test ----
log "[2/4] Smoke test ($SMOKE_LIMIT samples)..."
# Snapshot existing data so we can detect new samples cleanly
out_file="data/${SUBJECT}/${fmt}.jsonl"
before_count=0
[ -f "$out_file" ] && before_count=$(wc -l < "$out_file")
smoke_log="logs/${SUBJECT}_${fmt}_smoke.log"
python "generators/generate_${fmt}.py" \
--subject "$SUBJECT" \
--limit $SMOKE_LIMIT \
--concurrent "$conc" \
> "$smoke_log" 2>&1 &
smoke_pid=$!
# Wait for smoke test
wait $smoke_pid
smoke_exit=$?
if [ $smoke_exit -ne 0 ]; then
log " Smoke test exited with code $smoke_exit"
log " Last 20 lines of smoke log:"
tail -20 "$smoke_log" | sed 's/^/ /' | tee -a "$PIPELINE_LOG"
abort "Smoke test failed for $fmt (exit code $smoke_exit). See $smoke_log"
fi
# ---- Step 3: Validate smoke quality ----
log "[3/4] Validating smoke output..."
result=$(validate_smoke "$fmt")
log " $result"
case "$result" in
"MISSING_FILE")
abort "Smoke test for $fmt produced no output file"
;;
"EMPTY")
abort "Smoke test for $fmt produced 0 samples (output file empty)"
;;
OK*)
# Parse the metrics
after_count=$(wc -l < "$out_file")
new_samples=$((after_count - before_count))
if [ $new_samples -lt 5 ]; then
log " Last 30 lines of smoke log for diagnosis:"
tail -30 "$smoke_log" | sed 's/^/ /' | tee -a "$PIPELINE_LOG"
abort "Smoke test produced only $new_samples new samples (need at least 5). See $smoke_log"
fi
success_rate=$((new_samples * 100 / SMOKE_LIMIT))
log " Success rate: $new_samples/$SMOKE_LIMIT (${success_rate}%)"
if [ $success_rate -lt 30 ]; then
log " Last 30 lines of smoke log:"
tail -30 "$smoke_log" | sed 's/^/ /' | tee -a "$PIPELINE_LOG"
abort "Smoke success rate ${success_rate}% below 30% threshold for $fmt"
fi
log " Smoke test PASSED"
;;
*)
abort "Unknown validation result: $result"
;;
esac
# ---- Step 4: Full generation ----
log "[4/4] Full generation for $fmt..."
full_log="logs/${SUBJECT}_${fmt}.log"
python "generators/generate_${fmt}.py" \
--subject "$SUBJECT" \
--concurrent "$conc" \
> "$full_log" 2>&1 &
full_pid=$!
echo $full_pid > "logs/${SUBJECT}_${fmt}.pid"
# Show progress every minute while it runs
while kill -0 $full_pid 2>/dev/null; do
if [ -f "$out_file" ]; then
cur_count=$(wc -l < "$out_file")
tail_line=$(tail -1 "$full_log" 2>/dev/null | tr -d '\r' | tail -c 200)
log " in progress: $cur_count samples on disk | $tail_line"
fi
sleep 60
done
wait $full_pid
full_exit=$?
if [ $full_exit -ne 0 ]; then
log " Full generation exited with code $full_exit"
log " Last 20 lines of generation log:"
tail -20 "$full_log" | sed 's/^/ /' | tee -a "$PIPELINE_LOG"
abort "Full generation failed for $fmt (exit code $full_exit). See $full_log"
fi
# Final stats
final_count=$(wc -l < "$out_file")
final_tokens=$(python -c "
import json
total = 0
for line in open('$out_file'):
total += json.loads(line).get('tokens', 0)
print(f'{total:,}')
" 2>/dev/null || echo "?")
log " COMPLETED: $final_count samples, $final_tokens completion tokens"
done
# ===== Final summary =====
log ""
log "================================================================"
log "PIPELINE COMPLETE for subject=$SUBJECT tier=$TIER"
log "================================================================"
log ""
log "Final corpus state:"
for f in data/$SUBJECT/*.jsonl; do
if [ -f "$f" ]; then
fmt=$(basename "$f" .jsonl)
count=$(wc -l < "$f")
tokens=$(python -c "
import json
total = 0
for line in open('$f'):
total += json.loads(line).get('tokens', 0)
print(f'{total/1e6:.2f}M')
" 2>/dev/null || echo "?")
log " $(printf '%-25s' "$fmt") $(printf '%6d' "$count") samples $tokens tokens"
fi
done
log ""
log "Logs preserved in: logs/${SUBJECT}_*.log"
log "Done."