#!/usr/bin/env bash
# Fine-time crackle residual on a frozen official-split F12 linear head.
# feedback_s2/best.pth cannot be resumed: its SelfFeedback stores attn.in_proj_*,
# and the current decoder uses separate q/k/v plus a timbre projection.
# Epoch 0 is only the zero-init identity check. It is not a trained Score.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

TAG="${TAG:-frame_asd_F12_crackle_flux}"
SEED="${SEED:-1}"
BATCH_SIZE="${BATCH_SIZE:-16}"
EPOCHS="${EPOCHS:-8}"
LR="${LR:-1e-3}"
MIN_FREE_MB="${MIN_FREE_MB:-1500}"
RESUME="${RESUME:-$ROOT/save/icbhi_beats_frame_asd_frame_asd_F12_sastruct_s1_rerun2/best.pth}"
OUT="$ROOT/save/icbhi_beats_frame_asd_${TAG}"
PROTECTED="$ROOT/save/icbhi_beats_frame_asd_frame_asd_F12_sastruct_s1_rerun2"

[[ -f "$RESUME" ]] || { echo "Missing resume checkpoint $RESUME"; exit 1; }
[[ -f "$ROOT/pretrained_models/BEATs_iter3_plus_AS2M.pt" ]] || { echo "Missing pretrained_models/BEATs_iter3_plus_AS2M.pt"; exit 1; }
if [[ "$OUT" == "$PROTECTED" ]]; then
  echo "Refusing to write the protected stage-1 directory"
  exit 1
fi
if [[ "$EPOCHS" != "0" && -f "$OUT/best.pth" ]]; then
  echo "$OUT/best.pth already exists; pick another TAG"
  exit 1
fi
mkdir -p "$ROOT/save"
FREE_MB=$(df --output=avail -BM "$ROOT/save" | tail -1 | tr -dc '0-9')
(( FREE_MB >= MIN_FREE_MB )) || { echo "Only ${FREE_MB}MB free (need >= ${MIN_FREE_MB}MB)"; exit 1; }
mkdir -p "$OUT"

echo "=== crackle flux $TAG epochs=$EPOCHS lr=$LR resume=$RESUME ==="
python -u train.py --tag "$TAG" \
  --method frame_asd --model beats --dataset icbhi --seed "$SEED" \
  --save_dir "$ROOT/save" \
  --class_split lungsound --n_cls 4 --batch_size "$BATCH_SIZE" \
  --desired_length 5 --optimizer adam --weight_decay 1e-6 \
  --cosine --test_fold official --pad_types repeat \
  --print_freq 50 \
  --min_se 48 --min_sp 72 --early_stop_patience 6 \
  --mil_pool topk --mil_topk 3 \
  --use_specaug --specaug_policy structured \
  --beats_wave_scale 32768 --threshold_n_points 41 \
  --ablation_stage F12_crackle_flux \
  --head_type linear \
  --crackle_flux --freeze_backbone \
  --epochs "$EPOCHS" --learning_rate "$LR" \
  --eval_first --reset_epoch_on_resume --reset_optimizer_on_resume \
  --resume "$RESUME" \
  --num_workers 4 \
  "$@" 2>&1 | tee "$OUT/train.log"
