#!/bin/bash
set -e

export WANDB_MODE=offline
export TORCH_ELASTIC_RENDEZVOUS_TIMEOUT=10000

GPUS_PER_NODE=${SLURM_GPUS_ON_NODE:-1}
WORLD_SIZE=${SLURM_NNODES:-1}
RANK=${SLURM_PROCID:-0}
MASTER_ADDR="localhost"
MASTER_PORT=12345

DISTRIBUTED_ARGS="\
  --nproc_per_node $GPUS_PER_NODE \
  --nnodes $WORLD_SIZE \
  --node_rank $RANK \
  --master_addr $MASTER_ADDR \
  --master_port $MASTER_PORT"

echo "Launching with args:"
echo "$DISTRIBUTED_ARGS"

############### Pretrain ################

MODEL_SETTING="llava-uhd-qwen3-moonvit-so-400m-4-18-se-hirope2d-p10"
DATA_SETTING_STAGE_1="anyres-256-1560-4558k"
DATA_SETTING_STAGE_2="anyres-256-1560-ocr-inter"
DATA_SETTING_STAGE_3="anyres-256-1560-858k"

LLM_CKPT_DIR=/mnt/nfs_200T/optics/SHL/CKPT/Qwen3-8B
CLIP_CKPT_DIR=/mnt/nfs_200T/optics/SHL/CKPT/moonvit-so-400m-4-18-se-hirope2d-p10
projector=mlp

BASE_RUN_NAME_STAGE_1="$MODEL_SETTING-$DATA_SETTING_STAGE_1"

echo "BASE_RUN_NAME: ${BASE_RUN_NAME_STAGE_1}"

ACCELERATE_DISABLE_NUMA_AFFINITY=1 torchrun $DISTRIBUTED_ARGS llava/train/train_mem.py \
    --deepspeed $PWD/scripts/zero2_old.json \
    --model_name_or_path $LLM_CKPT_DIR \
    --version qwen_1_5 \
    --model_mode='uhd_v3' \
    --data_path /path/to/json_file/ \
    --image_folder /path/to/image_dir/ \
    --vision_tower $CLIP_CKPT_DIR \
    --mm_projector_type $projector \
    --mm_tunable_parts="mm_vision_tower,mm_mlp_adapter" \    --mm_vision_select_layer -2 \
    --mm_use_im_start_end False \
    --mm_use_im_patch_token False \
    --bf16 True \
    --output_dir ./${BASE_RUN_NAME_STAGE_1} \
    --num_train_epochs 1 \
    --per_device_train_batch_size 4 \
    --per_device_eval_batch_size 1 \
    --gradient_accumulation_steps 2 \
    --evaluation_strategy "no" \
    --save_strategy "steps" \
    --save_steps 6000 \
    --save_total_limit 1 \
    --mm_vision_tower_lr 1e-5 \
    --learning_rate 2e-4 \
    --weight_decay 0. \
    --warmup_ratio 0.03 \
    --lr_scheduler_type "cosine" \
    --logging_steps 1 \
    --tf32 True \
    --model_max_length 4096 \
    --gradient_checkpointing True \
    --dataloader_num_workers 4 \
    --lazy_preprocess True \
    --report_to wandb \
    --dataloader_drop_last True \
    --run_name ${BASE_RUN_NAME_STAGE_1} \
    --attn_implementation flash_attention_2 \
    --single True \
    --resolution 1560 \
    --any_res True \
    --split_patch_size 40 \
    --merger_from_prev False