#!/bin/bash
#
# Copyright 2022 Skycloud Software
#
# This script is a wrapper for DeepSpeed
# it generates the machine file based on the hosts
# given to it by AIP.
#

MYARGS=$*
host=$(hostname -I | awk {'print $1}')

if [ "$CB_DOCKER_IMAGE" != "" ]; then
  WORKDIR="/tmp"
else
  WORKDIR=`dirname ${CB_JOBFILENAME}`
  rm -f ${WORKDIR}/ds_machines.*
fi

MACHFILE=${WORKDIR}/ds_machines.${CB_JOBID}

T=`echo "${MYARGS}" | grep -- -hostfile |wc -l`
if [ $T -gt 0 ]; then
    echo "Error:  Do not provide the hostfile for deepspeed."
    echo "        It is generated automatically for you."
    exit -3
fi

# Make the DeepSpeed machine file
/opt/skyformai/bin/hostlist -o > ${MACHFILE}
if [ $? != 0 ]; then
    echo "DeepSpeed is used. The CPU requirement is incorrect"
    exit 1
fi

if [ "$CB_DOCKER_IMAGE" != "" ]; then
  export CB_TASK_DOCKER_IMAGE=$CB_DOCKER_IMAGE
  export CB_TASK_DOCKER_OPTIONS=$CB_DOCKER_OPTIONS
  export OMPI_ALLOW_RUN_AS_ROOT=1
  export OMPI_ALLOW_RUN_AS_ROOT_CONFIRM=1
  deepspeed --launcher OpenMPI \
      --launcher_args "--mca plm_rsh_agent /opt/skyformai/bin/rsh -x GPU_ALLOCATION -x OMP_NUM_THREADS -x OMPI_ALLOW_RUN_AS_ROOT -x OMPI_ALLOW_RUN_AS_ROOT_CONFIRM -x CB_ENVDIR -x LSB_MCPU_HOSTS -x CB_TASK_DOCKER_IMAGE -x CB_TASK_DOCKER_OPTIONS" \
      --hostfile $MACHFILE \
      --master_port $CB_PORT \
      --no_ssh_check \
      --master_addr $host \
      $MYARGS
else
  export MACHFILE=$MACHFILE
  export MASTER_PORT=$CB_PORT
  exec ${MYARGS}
fi

