#!/bin/bash
# Start vLLM with MTP speculative decoding for the comparison experiment.
set -e

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

cd /data/user1/yy
mkdir -p logs tmp

VENV="${VENV_VLLM}"
export PATH="$VENV/bin:$PATH"
export PYTHONUNBUFFERED=1
export TMPDIR=/data/user1/yy/tmp
export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES}"

LOG="/data/user1/yy/logs/dsv4_h200_vllm_mtp_vs_default_mtp_$(date +%Y%m%d_%H%M%S).log"
PID_FILE="/data/user1/yy/dsv4_h200_vllm_mtp_vs_default_mtp.pid"

rm -f "$PID_FILE"

echo "=== Starting vLLM+MTP server (TP=$TP, spec_method=$SPEC_METHOD, spec_tokens=$SPEC_TOKENS) ==="
echo "Model: $MODEL_PATH"
echo "Port: $MTP_PORT"
echo "Log: $LOG"

nohup vllm serve "$MODEL_PATH" \
    --trust-remote-code \
    --tensor-parallel-size "$TP" \
    --kv-cache-dtype fp8 \
    --max-model-len "$MAX_MODEL_LEN" \
    --max-num-seqs "$MAX_NUM_SEQS" \
    --block-size 256 \
    --gpu-memory-utilization 0.90 \
    --tokenizer-mode deepseek_v4 \
    --reasoning-parser deepseek_v4 \
    --speculative-config "{\"method\":\"mtp\",\"num_speculative_tokens\":$SPEC_TOKENS}" \
    --no-disable-hybrid-kv-cache-manager \
    --disable-uvicorn-access-log \
    --port "$MTP_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 --fail --silent --show-error --max-time 5 "http://127.0.0.1:${MTP_PORT}/health" >/dev/null 2>&1; then
        echo "vLLM+MTP server is ready at http://127.0.0.1:${MTP_PORT}"
        echo "Log: $LOG"
        exit 0
    fi
    if ! kill -0 $PID 2>/dev/null; then
        echo "ERROR: vLLM+MTP server exited early"
        tail -200 "$LOG"
        exit 1
    fi
    echo "Waiting... ($i/240)"
    sleep 5
done

echo "ERROR: vLLM+MTP server not healthy after 240 retries"
tail -200 "$LOG"
exit 1
