#!/bin/bash

# 定义参数
GPU_NUM=$1
BASE_OUTPUT_DIR=$2

# 定义任务和相应的配置文件
tasks=(
    "/root/Open-GroundingDino-main/config/datasets_mixed_odvg_5.json"
     /root/Open-GroundingDino-main/config/datasets_mixed_odvg_10.json
     /root/Open-GroundingDino-main/config/datasets_mixed_odvg_20.json
)

# 定义适应性掩码参数
masks=("None" "random_mask" "radiation_mask")

# 最大重试次数
MAX_RETRIES=3
# START_MASK_INDEX=2
# 循环每个JSONL 文件
for task_index in "${!tasks[@]}"; do
   task=${tasks[$task_index]}

   if [[ $task_index -eq 0 ]]; then
        start_mask_index=2  # 第一个任务只从第三个掩码开始
    else
        start_mask_index=0  # 其他任务从第一个掩码开始
    fi

    
    for mask_index in "${!masks[@]}"; do
        # 跳过掩码索引在start_mask_index之前的掩码
        if (( mask_index < start_mask_index )); then
            continue
        fi

        mask=${masks[$mask_index]}
        CFG="config/cfg_coco.py"  # 替换为你的配置文件路径
        
        # 创建输出目录
        OUTPUT_DIR="${BASE_OUTPUT_DIR}/task_${task_index}/mask_${mask}"
        mkdir -p "$OUTPUT_DIR"

        # 重试逻辑
        for (( retry=0; retry<MAX_RETRIES; retry++ )); do
            echo "Executing: bash my_bash.sh --datasets $task --adaptive_mask $mask (Attempt: $((retry + 1)))"
            nohup bash -c "CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python -m torch.distributed.launch \
                --nproc_per_node=${GPU_NUM} main.py \
                --output_dir ${OUTPUT_DIR} \
                -c ${CFG} \
                --datasets ${task} \
                --adaptive_mask ${mask} \
                --options text_encoder_type=bert-base-uncased" > "${OUTPUT_DIR}/output.log" 2>&1 &
            
            # 等待进程完成
            wait $!

            # 检查退出状态
            if [[ $? -eq 0 ]]; then
                echo "Execution succeeded for task $task with mask $mask."
                break
            else
                echo "Execution failed for task $task with mask $mask. Retrying..."
            fi
            
            # 如果已经重试了 MAX_RETRIES 次，退出
            if [[ $retry -eq $((MAX_RETRIES - 1)) ]]; then
                echo "Failed $MAX_RETRIES times for task $task with mask $mask. Exiting."
                exit 1
            fi
        done
    done
done

echo "All tasks submitted."
