#!/bin/bash

set -e

export N_GPUS=4
export BASE_MODEL=Qwen/Qwen2.5-1.5B-Instruct
# export BASE_MODEL=deepseek-ai/deepseek-math-7b-instruct
export DATA_DIR=data
export ROLLOUT_TP_SIZE=4
export EXPERIMENT_NAME=custom_calc_x_ray
export PROJECT_NAME=agentarium_ray
export VLLM_USE_V1=1

# Agent configuration
export AGENT_FILE=examples.mcp_calc_agent.calc_agent_ray
export AGENT_ROLLOUT=calcagent_rollout
export AGENT_NAME=calc_agent
echo "Starting Ray-based Agentarium training script..."

# Make sure Ray is available
python -c "import ray; print('Ray is available')" || { echo "Ray is not installed. Please install with: pip install ray"; exit 1; }

python -m agentarium.verl.agentarium_entrypoint \
    algorithm.adv_estimator=grpo \
    data.train_files=${DATA_DIR}/train.parquet \
    data.val_files=${DATA_DIR}/test.parquet \
    actor_rollout_ref.rollout.tensor_model_parallel_size=$ROLLOUT_TP_SIZE \
    trainer.n_gpus_per_node=${N_GPUS} \
    data.train_batch_size=32 \
    actor_rollout_ref.rollout.n=4 \
    actor_rollout_ref.actor.ppo_mini_batch_size=16 \
    actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=4 \
    actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=4 \
    actor_rollout_ref.rollout.multi_turn.format=hermes \
    actor_rollout_ref.model.path=${BASE_MODEL} \
    data.max_prompt_length=4096 \
    data.max_response_length=2048 \
    data.truncation='error' \
    trainer.val_before_train=True \
    actor_rollout_ref.actor.optim.lr=1e-6 \
    actor_rollout_ref.model.use_remove_padding=True \
    actor_rollout_ref.actor.use_kl_loss=True \
    actor_rollout_ref.actor.kl_loss_coef=0.0001 \
    actor_rollout_ref.actor.entropy_coeff=0.01 \
    actor_rollout_ref.actor.clip_ratio_low=0.2 \
    actor_rollout_ref.actor.clip_ratio_high=0.3 \
    actor_rollout_ref.model.enable_gradient_checkpointing=True \
    actor_rollout_ref.actor.fsdp_config.param_offload=True \
    actor_rollout_ref.actor.fsdp_config.optimizer_offload=True \
    actor_rollout_ref.rollout.name=vllm \
    actor_rollout_ref.rollout.gpu_memory_utilization=0.8 \
    actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=8 \
    actor_rollout_ref.ref.fsdp_config.param_offload=True \
    algorithm.use_kl_in_reward=False \
    trainer.critic_warmup=0 \
    trainer.logger=['console'] \
    trainer.project_name=${PROJECT_NAME} \
    trainer.experiment_name=${EXPERIMENT_NAME} \
    trainer.nnodes=1 \
    trainer.save_freq=128 \
    trainer.test_freq=32 \
    trainer.total_epochs=2 \
    agentarium.agent.agent_file=${AGENT_FILE} \
    agentarium.agent.agent_rollout=${AGENT_ROLLOUT} \
    agentarium.agent.agent_name=${AGENT_NAME} $@
