#!/bin/bash
# Start a plain vLLM baseline server for DeepSeek-V4-Flash on H200.
set -e

cd /data/user1/yy
mkdir -p logs

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
source "${SCRIPT_DIR}/config.env"

VENV="${VENV_SERVER}"
export PATH="$VENV/bin:$PATH"
VLLM="$VENV/bin/vllm"

TP=4
LOG="/data/user1/yy/logs/dsv4_h200_vllm_tp${TP}_$(date +%Y%m%d_%H%M%S).log"
PID_FILE="/data/user1/yy/dsv4_h200_vllm.pid"

export TMPDIR=/data/user1/yy/tmp
export CUDA_VISIBLE_DEVICES=4,5,6,7

echo "=== Starting DeepSeek-V4-Flash vLLM baseline (TP=$TP) ==="
echo "Model: $MODEL_PATH"
echo "Port: $PORT"
echo "Log: $LOG"

rm -f "$PID_FILE"
nohup "$VLLM" serve "$MODEL_PATH" \
    --trust-remote-code \
    --tensor-parallel-size "$TP" \
    --kv-cache-dtype fp8 \
    --block-size 256 \
    --max-model-len auto \
    --max-num-seqs 256 \
    --gpu-memory-utilization 0.90 \
    --tokenizer-mode deepseek_v4 \
    --reasoning-parser deepseek_v4 \
    --no-disable-hybrid-kv-cache-manager \
    --disable-uvicorn-access-log \
    --port "$PORT" \
    > "$LOG" 2>&1 &
PID=$!
echo $PID > "$PID_FILE"
echo "PID: $PID"
echo "Waiting for health..."

for i in $(seq 1 240); do
    if curl -s "http://127.0.0.1:$PORT/health" > /dev/null 2>&1; then
        echo "Server is ready at http://127.0.0.1:$PORT"
        echo "Log: $LOG"
        exit 0
    fi
    if ! kill -0 $PID 2>/dev/null; then
        echo "ERROR: Server exited early"
        tail -200 "$LOG"
        exit 1
    fi
    echo "Waiting... ($i/240)"
    sleep 5
done

echo "ERROR: Server not healthy after 240 retries"
tail -200 "$LOG"
exit 1
