#!/usr/bin/env bash
# Last two BEATs blocks plus the 10 ms crackle residual and the pass-2 linear head.
# Tail LR 1e-5. Head and residual LR 2e-5. Earlier blocks, pass-1 head, and slots stay frozen.
# Official 60/40. Bounded: 8 epochs, early stop 6. Epoch 0 must match the 66.52 reload.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

TAG="${TAG:-frame_asd_F12_crackle_flux_tail}"
SEED="${SEED:-1}"
BATCH_SIZE="${BATCH_SIZE:-16}"
EPOCHS="${EPOCHS:-8}"
LR="${LR:-2e-5}"
TAIL_LR="${TAIL_LR:-1e-5}"
MIN_FREE_MB="${MIN_FREE_MB:-1500}"
RESUME="${RESUME:-$ROOT/save/icbhi_beats_frame_asd_frame_asd_F12_feedback_s2/best.pth}"
OUT="$ROOT/save/icbhi_beats_frame_asd_${TAG}"
PROTECTED="$ROOT/save/icbhi_beats_frame_asd_frame_asd_F12_feedback_s2"

[[ -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 feedback_s2 directory"
  exit 1
fi
if [[ -f "$OUT/best.pth" ]]; then
  echo "$OUT/best.pth already exists; pick another TAG"
  exit 1
fi
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 + last two BEATs blocks $TAG epochs=$EPOCHS head_lr=$LR tail_lr=$TAIL_LR ==="
python -u train_feedback.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_tail \
  --feedback_slots 4 --feedback_layers 2 --feedback_drop 0.2 \
  --reason_codes 16 \
  --crackle_flux --encoder_tail_layers 2 --tail_lr "$TAIL_LR" \
  --learning_rate "$LR" \
  --epochs "$EPOCHS" --eval_first \
  --resume "$RESUME" \
  --num_workers 4 \
  "$@" 2>&1 | tee "$OUT/train.log"
