File size: 16,086 Bytes
7c2871f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
391
392
393
394
395
396
397
398
399
#!/usr/bin/env bash
# Batch evaluation for CTA ablation variants TRAINED on the diffusion+HDTF
# COMBINED split (produced by scripts/train_cta_combined_ablation.sh, which
# writes experiment_name=cta_ablation_diffusion_combined_<VARIANT>).
#
# This is the combined-split analogue of batch_test_cta_ablation_diffusion.sh.
# Only three things differ:
#   * run-dir discovery glob:   cta_ablation_diffusion_combined_<VARIANT>_<TS>
#   * variant extraction from --run-dir is done by matching against the known
#     variant list (naive `[^_]+` doesn't work — variant names contain
#     underscores, e.g. A2_no_asym, M6_drop_audio_infer).
#   * output subdir tag:        diffusion_combined_ablation_<TS>/
#
# For each variant, picks 4 ckpts (top-3 by valauc + last) and runs
# inference on 6 datasets:
#
#   ours_sadtalker — held-out 3DMM family from FairTalking test split (SadTalker)
#   ours_edtalk    — held-out AE/VAE family from FairTalking test split (EDTalk)
#   ours_float     — held-out Flow-Matching family from FairTalking test split
#   thb            — TalkingHeadBench (cross-source)
#   ff++           — FaceForensics++ (cross-source)
#   mmdf           — MMDF (cross-source)
#
# Fairness metrics (race4) are emitted only for the three `ours_*` datasets.
#
# Output layout:
#   outputs/cta_test_result/diffusion_combined_ablation_<TS>/
#     ├── results.csv                                      one row per (variant, ckpt, dataset)
#     ├── logs/<variant>__<kind>__<dataset>.log
#     └── runs/<variant>/<kind>__<dataset>__<ts>/          one subdir per inference run
#
# Usage:
#   bash scripts/batch_test_cta_ablation_diffusion_combined.sh
#   bash scripts/batch_test_cta_ablation_diffusion_combined.sh --group M
#   bash scripts/batch_test_cta_ablation_diffusion_combined.sh A1_full M3_intra_modal
#   bash scripts/batch_test_cta_ablation_diffusion_combined.sh --datasets ours_sadtalker ours_float
#   bash scripts/batch_test_cta_ablation_diffusion_combined.sh --num-top 1
#   bash scripts/batch_test_cta_ablation_diffusion_combined.sh --dry-run
#   bash scripts/batch_test_cta_ablation_diffusion_combined.sh --run-dir outputs/cta_ablation_diffusion_combined_A2_no_asym_20260708_141953
set -eo pipefail
cd "$(dirname "$0")/.."

[ -f .env ] && set -a && . ./.env && set +a

# ---- python interpreter resolution -----------------------------------------
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
[ablation-combined-test] FATAL: cannot find a python interpreter with hydra installed.
  Activate the project env (e.g. conda activate pytorch) or pass PY=/path/to/python3.
EOF
    exit 1
}
PY="$(resolve_python)"
echo "[ablation-combined-test] using python: $PY"

OUTPUT_DIR="outputs"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
TEST_RESULT_ROOT="outputs/cta_test_result"
BATCH_DIR="${TEST_RESULT_ROOT}/diffusion_combined_ablation_${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 -------------------------------------------------------
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_sadtalker" "ours_edtalk" "ours_float" "thb" "ff++" "mmdf")
GROUP=""
DRY_RUN=false
NUM_TOP=3
SKIP_LAST=false
SPECIFIC_RUN_DIR=""

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 ;;
        --no-last) SKIP_LAST=true; shift ;;
        --dry-run) DRY_RUN=true; shift ;;
        --run-dir) SPECIFIC_RUN_DIR="$2"; shift 2 ;;
        -h|--help) grep -E '^#( |$)' "$0" | sed 's/^# \?//'; exit 0 ;;
        --*) echo "Unknown flag: $1"; exit 1 ;;
        *) VARIANTS+=("$1"); shift ;;
    esac
done

if [[ -n "$SPECIFIC_RUN_DIR" ]]; then
    if [[ ! -d "$SPECIFIC_RUN_DIR" ]]; then
        echo "Error: Run directory does not exist: $SPECIFIC_RUN_DIR"; exit 1
    fi
    # Match against known variant names — variant names themselves contain
    # underscores, so a `[^_]+` regex would silently pick the wrong prefix.
    # Basename form: cta_ablation_diffusion_combined_<VARIANT>_YYYYMMDD_HHMMSS
    RUN_DIR_BASENAME=$(basename "$SPECIFIC_RUN_DIR")
    VARIANT_FROM_DIR=""
    for _v in "${ALL_VARIANTS[@]}"; do
        if [[ "$RUN_DIR_BASENAME" =~ _${_v}_[0-9]{8}_[0-9]{6}$ ]] || \
           [[ "$RUN_DIR_BASENAME" == *"_${_v}" ]]; then
            # Prefer the longest match so e.g. A1_full beats a hypothetical A1.
            if [[ ${#_v} -gt ${#VARIANT_FROM_DIR} ]]; then
                VARIANT_FROM_DIR="$_v"
            fi
        fi
    done
    if [[ -z "$VARIANT_FROM_DIR" ]]; then
        echo "Error: Could not extract a known variant name from run directory: $SPECIFIC_RUN_DIR"
        echo "  basename: $RUN_DIR_BASENAME"
        echo "  expected form: cta_ablation_diffusion_combined_<VARIANT>_YYYYMMDD_HHMMSS"
        exit 1
    fi
    echo "[ablation-combined-test] extracted variant '$VARIANT_FROM_DIR' from $RUN_DIR_BASENAME"
    VARIANTS=("$VARIANT_FROM_DIR")
elif [[ -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 "[ablation-combined-test] start:        $(date '+%Y-%m-%d %H:%M:%S')"
echo "[ablation-combined-test] timestamp:    $TIMESTAMP"
echo "[ablation-combined-test] results CSV:  $RESULTS_CSV"
echo "[ablation-combined-test] per-run logs: $LOG_DIR/"
echo "[ablation-combined-test] variants:     ${VARIANTS[*]}"
echo "[ablation-combined-test] datasets:     ${DATASETS[*]}"
echo "[ablation-combined-test] num_top:      $NUM_TOP  (+ last.ckpt)"
if [[ -n "$SPECIFIC_RUN_DIR" ]]; then
    echo "[ablation-combined-test] specific run dir: $SPECIFIC_RUN_DIR"
fi
$DRY_RUN && echo "[ablation-combined-test] DRY RUN: will only show what would be tested"
echo "============================================================"

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 combined-diffusion-trained run dir for a variant.
# Combined split writes cta_ablation_diffusion_combined_<VARIANT>_<TS>.
find_latest_run_dir() {
    local variant="$1"
    local match
    match=$(ls -d "$OUTPUT_DIR"/cta_ablation_diffusion_combined_${variant}_* 2>/dev/null \
            | grep -E "/cta_ablation_diffusion_combined_${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_diffusion_combined_${variant}"
    if [[ -d "$exact" ]]; then echo "$exact"; return; fi
    echo ""
}

# Map dataset name -> hydra data config.
data_cfg_for() {
    case "$1" in
        ours_sadtalker) echo "fairtalking_test_sadtalker" ;;
        ours_edtalk)    echo "fairtalking_test_edtalk" ;;
        ours_float)     echo "fairtalking_test_float" ;;
        thb)            echo "fairtalking_thb" ;;
        ff++)           echo "fairtalking_ffpp" ;;
        mmdf)           echo "fairtalking_mmdf" ;;
        hdtf)           echo "fairtalking_hdtf_paired" ;;
        *) echo ""; return 1 ;;
    esac
}

dataset_has_fairness() {
    case "$1" in
        ours_*) return 0 ;;
        *)      return 1 ;;
    esac
}

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'
}
extract_kv() {
    local out="$1" key="$2"
    echo "$out" | tr ' ' '\n' | awk -F= -v k="$key" '$1==k {print $2; exit}' | tr -d '\r'
}
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_ckpts() {
    local run_dir="$1" num_top="$2" skip_last="${3:-false}"
    local ckpt_dir="$run_dir/checkpoints"
    [[ -d "$ckpt_dir" ]] || return 0
    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
    if [[ "$skip_last" != "true" ]] && [[ -f "$ckpt_dir/last.ckpt" ]]; then
        echo "last:$ckpt_dir/last.ckpt"
    fi
}

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)"
    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

    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_diffusion_combined_${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}

    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

    f_fpr=""; f_oae=""; f_dp=""; f_meo=""
    if dataset_has_fairness "$dataset"; 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")

    if [[ -n "$SPECIFIC_RUN_DIR" ]]; then
        run_dir="$SPECIFIC_RUN_DIR"
        echo ""
        echo "============================================================"
        echo "[$variant] Using specific run dir: $run_dir"
        echo "============================================================"
    else
        run_dir=$(find_latest_run_dir "$variant")
        if [[ -z "$run_dir" ]]; then
            echo ""
            echo "[$variant] NO combined-diffusion-trained run dir found (looked for outputs/cta_ablation_diffusion_combined_${variant}_*); 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
    fi

    mapfile -t CKPTS < <(pick_ckpts "$run_dir" "$NUM_TOP" "$SKIP_LAST")
    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 "[ablation-combined-test] end:    $(date '+%Y-%m-%d %H:%M:%S')"
echo "[ablation-combined-test] CSV:    $RESULTS_CSV"
echo "[ablation-combined-test] 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