#!/usr/bin/env bash # Full batch test for ALL CTA ablation variants × multiple checkpoints × 4 datasets. # # What this script does # --------------------- # For each ablation variant V: # 1. Pick the MOST-RECENT training run dir (outputs/cta_ablation_V_/), # ignoring older duplicates. # 2. Pick 4 checkpoints to test: # * top-3 best epoch ckpts under /checkpoints (filename order # encodes valauc, e.g. epoch08-valauc1.0000.ckpt — we sort lexicographically # DESC and take the first 3), # * plus last.ckpt. # 3. For each ckpt × dataset in {ours, thb, ff++, mmdf}: # - run python3 src/train.py method=cta_ablation method.ablation_variant=V # data= +test_only=true +test_ckpt= +test_predictions_csv=... # - parse test/acc, test/auc from stdout # - run scripts/compute_extra_metrics.py on the per-sample predictions CSV # to obtain ap and acc_at_eer # - if dataset == "ours", read the auto-generated *_fairness.csv and # extract F_FPR / F_OAE / F_DP / F_MEO # 4. Append one row per (variant, ckpt, dataset) to the summary CSV. # # Output schema (long format, one row per (variant, ckpt, dataset)) # ----------------------------------------------------------------- # variant, group, dataset, ckpt_name, ckpt_kind, # test_acc, test_auc, test_ap, test_acc_at_eer, # F_FPR, F_OAE, F_DP, F_MEO, # run_dir, predictions_csv, timestamp # # - ckpt_kind ∈ {top1, top2, top3, last} # - F_* columns blank for non-"ours" rows. # - All numeric fields use the natural sklearn / Lightning float representation. # # Usage # ----- # bash scripts/batch_test_cta_ablation_full.sh # all variants, all 4 datasets # bash scripts/batch_test_cta_ablation_full.sh --group M # only Group M # bash scripts/batch_test_cta_ablation_full.sh M1_video_only # one explicit variant # bash scripts/batch_test_cta_ablation_full.sh --datasets ours mmdf # bash scripts/batch_test_cta_ablation_full.sh --num-top 1 # only best + last per variant # bash scripts/batch_test_cta_ablation_full.sh --dry-run # plan only set -eo pipefail cd "$(dirname "$0")/.." # load .env if present [ -f .env ] && set -a && . ./.env && set +a # ---- python interpreter resolution ----------------------------------------- # The project's deps (hydra, pytorch_lightning, ...) live in a specific conda # env (typically 'av' on this server). The user's default shell may activate a # different env (e.g. 'pytorch') that does NOT have these deps, in which case # `python3 src/train.py` fails with `ModuleNotFoundError: No module named 'hydra'`. # # Resolution order: # 1. $PY override from caller # 2. current `python3` if it can import hydra # 3. /opt/conda/envs/av/bin/python3 if it can import hydra # 4. abort with a clear message resolve_python() { if [[ -n "${PY:-}" ]] && "$PY" -c 'import hydra' >/dev/null 2>&1; then echo "$PY"; return fi if command -v python3 >/dev/null 2>&1 && python3 -c 'import hydra' >/dev/null 2>&1; then command -v python3; return fi if [[ -x /opt/conda/envs/av/bin/python3 ]] && \ /opt/conda/envs/av/bin/python3 -c 'import hydra' >/dev/null 2>&1; then echo "/opt/conda/envs/av/bin/python3"; return fi cat <<'EOF' >&2 [batch_test_full] FATAL: cannot find a Python interpreter with `hydra` installed. Options: 1. Activate the project's conda env, e.g. `conda activate av`, then re-run. 2. Pass an explicit interpreter: PY=/path/to/python3 bash scripts/batch_test_cta_ablation_full.sh ... EOF exit 1 } PY="$(resolve_python)" echo "[batch_test_full] using python: $PY" OUTPUT_DIR="outputs" TIMESTAMP="$(date +%Y%m%d_%H%M%S)" # All test products are isolated under outputs/cta_test_result// # so they don't pollute the training run dirs and don't litter outputs/. TEST_RESULT_ROOT="outputs/cta_test_result" BATCH_DIR="${TEST_RESULT_ROOT}/batch_${TIMESTAMP}" RESULTS_CSV="${BATCH_DIR}/results.csv" LOG_DIR="${BATCH_DIR}/logs" RUNS_DIR="${BATCH_DIR}/runs" mkdir -p "$LOG_DIR" "$RUNS_DIR" # ---- variant universe (mirror of run_all_ablations.sh) --------------------- ALL_VARIANTS=( A1_full A2_no_asym A3_no_ltotal A4_asym_only A5_pooled_only B1_real_only B2_all_samples B3_no_predictor C1_no_loss_asym C2_no_loss_aux C3_no_loss_av C4_no_loss_va C5_no_detach D1_depth_1 D2_depth_4 D3_depth_8 D4_mlp_predictor D5_shared_predictor E1_video_freeze_0 E2_video_freeze_07 E3_video_freeze_10 F1_audio_freeze_0 F2_audio_freeze_08 G2_random_crop M1_video_only M2_audio_only M3_intra_modal M4_noise_target M5_shuffle_pair M6_drop_audio_infer M7_drop_video_infer ) declare -A GROUP_VARIANTS GROUP_VARIANTS[A]="A1_full A2_no_asym A3_no_ltotal A4_asym_only A5_pooled_only" GROUP_VARIANTS[B]="B1_real_only B2_all_samples B3_no_predictor" GROUP_VARIANTS[C]="C1_no_loss_asym C2_no_loss_aux C3_no_loss_av C4_no_loss_va C5_no_detach" GROUP_VARIANTS[D]="D1_depth_1 D2_depth_4 D3_depth_8 D4_mlp_predictor D5_shared_predictor" GROUP_VARIANTS[E]="E1_video_freeze_0 E2_video_freeze_07 E3_video_freeze_10" GROUP_VARIANTS[F]="F1_audio_freeze_0 F2_audio_freeze_08" GROUP_VARIANTS[G]="G2_random_crop" GROUP_VARIANTS[M]="M1_video_only M2_audio_only M3_intra_modal M4_noise_target M5_shuffle_pair M6_drop_audio_infer M7_drop_video_infer" # ---- args ----------------------------------------------------------------- VARIANTS=() DATASETS=("ours" "thb" "ff++" "mmdf") GROUP="" DRY_RUN=false NUM_TOP=3 while [[ $# -gt 0 ]]; do case "$1" in --group) GROUP="$2"; shift 2 ;; --datasets) shift DATASETS=() while [[ $# -gt 0 && "$1" != --* ]]; do DATASETS+=("$1"); shift done ;; --num-top) NUM_TOP="$2"; shift 2 ;; --dry-run) DRY_RUN=true; shift ;; -h|--help) grep -E '^#( |$)' "$0" | sed 's/^# \?//' exit 0 ;; --*) echo "Unknown flag: $1"; exit 1 ;; *) VARIANTS+=("$1"); shift ;; esac done if [[ -n "$GROUP" ]]; then if [[ -z "${GROUP_VARIANTS[$GROUP]+_}" ]]; then echo "Unknown group: $GROUP. Valid: A B C D E F G M"; exit 1 fi for v in ${GROUP_VARIANTS[$GROUP]}; do VARIANTS+=("$v"); done fi if [[ ${#VARIANTS[@]} -eq 0 ]]; then VARIANTS=("${ALL_VARIANTS[@]}") fi echo "============================================================" echo "[batch_test_full] start: $(date '+%Y-%m-%d %H:%M:%S')" echo "[batch_test_full] timestamp: $TIMESTAMP" echo "[batch_test_full] results CSV: $RESULTS_CSV" echo "[batch_test_full] per-run logs: $LOG_DIR/" echo "[batch_test_full] variants: ${VARIANTS[*]}" echo "[batch_test_full] datasets: ${DATASETS[*]}" echo "[batch_test_full] num_top: $NUM_TOP (+ last.ckpt)" $DRY_RUN && echo "[batch_test_full] DRY RUN: will only show what would be tested" echo "============================================================" # ---- summary CSV header --------------------------------------------------- echo "variant,group,dataset,ckpt_name,ckpt_kind,test_acc,test_auc,test_ap,test_acc_at_eer,F_FPR,F_OAE,F_DP,F_MEO,run_dir,test_out_dir,predictions_csv,timestamp" > "$RESULTS_CSV" # ---- helpers -------------------------------------------------------------- group_of() { case "$1" in A*) echo A ;; B*) echo B ;; C*) echo C ;; D*) echo D ;; E*) echo E ;; F*) echo F ;; G*) echo G ;; M*) echo M ;; *) echo "?" ;; esac } # Find the most-recent training run dir for a variant. We accept either: # outputs/cta_ablation_/ (no timestamp) # outputs/cta_ablation__/ (timestamped) # When duplicates exist, we keep ONLY the latest timestamped one. # We also DEFENSIVELY exclude any dir that looks like our own test output # (e.g. cta_ablation__test___/) — those would otherwise # be greedily matched by the trailing wildcard and confuse the latest-run pick. find_latest_run_dir() { local variant="$1" local match # Only accept dirs whose suffix after "_" is a pure timestamp # (8 digits + underscore + 6 digits). This rejects "_test_*_*" pollution. match=$(ls -d "$OUTPUT_DIR"/cta_ablation_${variant}_* 2>/dev/null \ | grep -E "/cta_ablation_${variant}_[0-9]{8}_[0-9]{6}$" \ | sort -r | head -1 || true) if [[ -n "$match" ]]; then echo "$match"; return fi local exact="$OUTPUT_DIR/cta_ablation_${variant}" if [[ -d "$exact" ]]; then echo "$exact"; return; fi echo "" } # Map dataset name -> hydra data config data_cfg_for() { case "$1" in ours) echo "fairtalking" ;; thb) echo "fairtalking_thb" ;; ff++) echo "fairtalking_ffpp" ;; mmdf) echo "fairtalking_mmdf" ;; hdtf) echo "fairtalking_hdtf_paired" ;; *) echo ""; return 1 ;; esac } # Extract a metric line from Lightning's stdout. Lightning prints e.g. # ┃ test/auc 0.8932 ┃ (with various box characters) # We grep the key, take the last hit, and pull the last whitespace-delimited # numeric token. Strip \r at the end as defense in depth. extract_metric() { local key="$1" output="$2" echo "$output" \ | grep -E "${key}[[:space:]]" \ | tail -1 \ | awk '{ for (i = NF; i >= 1; i--) { if ($i ~ /^-?[0-9.]+$/) { print $i; exit } } }' \ | tr -d '\r' } # Pull a single key's value from the `key=value key=value ...` output of # scripts/compute_extra_metrics.py. extract_kv() { local out="$1" key="$2" echo "$out" | tr ' ' '\n' | awk -F= -v k="$key" '$1==k {print $2; exit}' | tr -d '\r' } # Pull a fairness scalar out of the *_fairness.csv. Schema: # section,group,n,n_real,n_fake,acc,fpr,tpr,tnr,ppr,npr,metric,value # IMPORTANT: Python's csv.DictWriter writes \r\n line endings (RFC 4180), # but awk's default RS is \n, so the last field of a record arrives with a # trailing \r. We strip that \r before returning, otherwise the bare \r # corrupts results.csv (each field after it appears on a new visual line). extract_fairness() { local csv="$1" key="$2" [[ -f "$csv" ]] || { echo ""; return; } awk -F, -v k="$key" '$1=="summary" && $(NF-1)==k {print $NF; exit}' "$csv" | tr -d '\r' } # Pick checkpoints for a run dir: top-N (by lexicographic filename DESC, # which tracks valauc when checkpoint_callback uses the canonical filename # template "epochXX-valaucY.YYYY.ckpt") + last.ckpt. Echos ":" # pairs, one per line. pick_ckpts() { local run_dir="$1" num_top="$2" local ckpt_dir="$run_dir/checkpoints" [[ -d "$ckpt_dir" ]] || return 0 # top-N (excluding last.ckpt) local top top=$(ls -1 "$ckpt_dir"/*.ckpt 2>/dev/null | grep -v '/last\.ckpt$' | sort -r || true) if [[ -n "$top" ]]; then local i=1 while IFS= read -r p; do [[ -z "$p" ]] && continue echo "top${i}:$p" i=$((i + 1)) if (( i > num_top )); then break; fi done <<< "$top" fi # last.ckpt if [[ -f "$ckpt_dir/last.ckpt" ]]; then echo "last:$ckpt_dir/last.ckpt" fi } # Run a single (variant, ckpt, dataset) test. Echos a comma-joined CSV row. run_one_test() { local variant="$1" ckpt="$2" ckpt_kind="$3" dataset="$4" run_dir="$5" local data_cfg ts log_path pred_csv test_out_dir out rc grp acc auc extra ap acc_eer local f_fpr f_oae f_dp f_meo grp=$(group_of "$variant") data_cfg=$(data_cfg_for "$dataset") || true if [[ -z "$data_cfg" ]]; then echo "$variant,$grp,$dataset,$(basename "$ckpt"),$ckpt_kind,UNKNOWN_DATASET,N/A,N/A,N/A,,,,,$run_dir,,,$TIMESTAMP" return fi ts="$(date +%Y%m%d_%H%M%S)" # All test artifacts (predictions CSV, hydra cruft, tb / wandb noise) go # under outputs/cta_test_result/batch_/runs//____/ # so they don't pollute the training run dirs and don't litter outputs/. test_out_dir="${RUNS_DIR}/${variant}/${ckpt_kind}__${dataset}__${ts}" mkdir -p "$test_out_dir" pred_csv="${test_out_dir}/test_predictions.csv" log_path="$LOG_DIR/${variant}__${ckpt_kind}__${dataset}.log" if $DRY_RUN; then echo "$variant,$grp,$dataset,$(basename "$ckpt"),$ckpt_kind,DRY,DRY,DRY,DRY,,,,,$run_dir,$test_out_dir,$pred_csv,$ts" return fi # `output_dir=...` overrides the hydra-resolved output dir in train.py so # TensorBoard / wandb / hydra subdirs all live in test_out_dir, not in the # training run dir or under outputs/_/. set +e out=$("$PY" src/train.py \ method=cta_ablation \ method.ablation_variant="$variant" \ data="$data_cfg" \ trainer=ddp \ backbone=timesformer \ +test_only=true \ +test_ckpt="$ckpt" \ +test_predictions_csv="$pred_csv" \ output_dir="$test_out_dir" \ hydra.run.dir="$test_out_dir/hydra" \ experiment_name="cta_ablation_${variant}_test_${dataset}_${ckpt_kind}" \ 2>&1) rc=$? set -e echo "$out" > "$log_path" if [[ $rc -ne 0 ]]; then echo "$variant,$grp,$dataset,$(basename "$ckpt"),$ckpt_kind,ERROR_RC${rc},ERROR_RC${rc},ERROR_RC${rc},ERROR_RC${rc},,,,,$run_dir,$test_out_dir,$pred_csv,$ts" return fi acc=$(extract_metric "test/acc" "$out"); acc=${acc:-N/A} auc=$(extract_metric "test/auc" "$out"); auc=${auc:-N/A} # Post-hoc AP / Acc@EER from the predictions CSV ap="N/A"; acc_eer="N/A" if [[ -f "$pred_csv" ]]; then set +e extra=$("$PY" scripts/compute_extra_metrics.py "$pred_csv" 2>/dev/null) if [[ $? -eq 0 ]]; then ap=$(extract_kv "$extra" "ap"); ap=${ap:-N/A} acc_eer=$(extract_kv "$extra" "acc_at_eer"); acc_eer=${acc_eer:-N/A} fi set -e fi # Fairness (only ours has race4 annotations) f_fpr=""; f_oae=""; f_dp=""; f_meo="" if [[ "$dataset" == "ours" ]]; then local fairness_csv="${pred_csv%.csv}_fairness.csv" f_fpr=$(extract_fairness "$fairness_csv" "F_FPR") f_oae=$(extract_fairness "$fairness_csv" "F_OAE") f_dp=$(extract_fairness "$fairness_csv" "F_DP") f_meo=$(extract_fairness "$fairness_csv" "F_MEO") fi echo "$variant,$grp,$dataset,$(basename "$ckpt"),$ckpt_kind,$acc,$auc,$ap,$acc_eer,$f_fpr,$f_oae,$f_dp,$f_meo,$run_dir,$test_out_dir,$pred_csv,$ts" } # ---- main loop ------------------------------------------------------------ for variant in "${VARIANTS[@]}"; do grp=$(group_of "$variant") run_dir=$(find_latest_run_dir "$variant") if [[ -z "$run_dir" ]]; then echo "" echo "[$variant] NO run dir; skipping all combos" for ds in "${DATASETS[@]}"; do echo "$variant,$grp,$ds,NO_RUN_DIR,N/A,N/A,N/A,N/A,N/A,,,,,,,,$TIMESTAMP" >> "$RESULTS_CSV" done continue fi # mapfile -t works in bash >=4 mapfile -t CKPTS < <(pick_ckpts "$run_dir" "$NUM_TOP") if [[ ${#CKPTS[@]} -eq 0 ]]; then echo "" echo "[$variant] NO checkpoints in $run_dir/checkpoints; skipping" for ds in "${DATASETS[@]}"; do echo "$variant,$grp,$ds,NO_CKPT,N/A,N/A,N/A,N/A,N/A,,,,,$run_dir,,,$TIMESTAMP" >> "$RESULTS_CSV" done continue fi echo "" echo "============================================================" echo "[$variant] run dir: $run_dir" echo "[$variant] checkpoints to test (kind:path):" for kp in "${CKPTS[@]}"; do echo " - $kp"; done echo "============================================================" for kp in "${CKPTS[@]}"; do ckpt_kind="${kp%%:*}" ckpt_path="${kp#*:}" for ds in "${DATASETS[@]}"; do echo "" echo "[$(date '+%H:%M:%S')] [$variant] [$ckpt_kind] [$ds] -> $(basename "$ckpt_path")" row=$(run_one_test "$variant" "$ckpt_path" "$ckpt_kind" "$ds" "$run_dir") echo " -> $row" echo "$row" >> "$RESULTS_CSV" done done done echo "" echo "============================================================" echo "[batch_test_full] end: $(date '+%Y-%m-%d %H:%M:%S')" echo "[batch_test_full] CSV: $RESULTS_CSV" echo "[batch_test_full] logs: $LOG_DIR/" echo "============================================================" echo "" echo "Quick preview (first 30 rows):" if command -v column >/dev/null 2>&1; then head -30 "$RESULTS_CSV" | column -t -s, else head -30 "$RESULTS_CSV" fi