#!/bin/bash
# Run ON the Colab G4 VM after setup_vm.sh has printed SETUP_DONE.
# Keeps the server bound to 127.0.0.1; reach it through an SSH local forward.
#
#   nohup bash /content/start_vllm.sh > /content/vllm.log 2>&1 &
#
# Default is the verified MTP3 configuration: 131,072-token context, one
# request at a time, FP8 KV cache, prefix caching off, MTP speculative
# decoding with 3 draft tokens. Measured single-stream decode on this
# configuration (thinking off, 3 repeats, medians):
#
#   MTP_TOKENS=3 (default)  44.6 / 49.8 / 68.7 tok/s  code / prose / reasoning
#   MTP_TOKENS=1            36.1 / 38.9 / 42.1 tok/s  (more conservative)
#   MTP_TOKENS=0            22.0 / 22.0 / 21.9 tok/s  (MTP off, same flags: the paired baseline)
#
# Startup lines observed with MTP_TOKENS=3 (model load 307.8 s on that boot;
# 596.7 s on another, it varies with page cache):
#   Resolved architecture: Qwen4ExpForConditionalGeneration
#   Resolved architecture: Qwen4ExpMTP
#   Model loading took 76.39 GiB memory and 307.778437 seconds
#   Available KV cache memory: 8.53 GiB
#   GPU KV cache size: 456,492 tokens, Maximum concurrency for 131,072 tokens per request: 3.48x
#   Application startup complete.
# With MTP_TOKENS=0 the same flags gave 73.6 GiB weights, 11.91 GiB KV,
# 870,094 pooled tokens, 6.64x.
#
# Earlier baseline configurations, kept for reference because the published
# no-MTP tables used them: BF16 KV cache (no --kv-cache-dtype), prefix caching
# on (vLLM default), --gpu-memory-utilization 0.95; the original 16K benchmark
# additionally used --max-model-len 16384 --max-num-seqs 8.
set -euo pipefail

MODEL_DIR="/content/models/Qwen3.8-Flash-Next-NVFP4"
MTP_TOKENS="${MTP_TOKENS:-3}"

SPEC_ARGS=()
if [ "$MTP_TOKENS" != "0" ]; then
  SPEC_ARGS=(--speculative-config "{\"method\":\"mtp\",\"num_speculative_tokens\":${MTP_TOKENS}}")
fi

exec env MAX_JOBS=1 vllm serve "$MODEL_DIR" \
  --host 127.0.0.1 --port 8000 \
  --served-model-name qwen3.8-flash-next \
  --quantization modelopt \
  --max-model-len 131072 \
  --gpu-memory-utilization 0.92 \
  --kv-cache-dtype fp8 \
  --language-model-only \
  --enforce-eager \
  --max-num-seqs 1 \
  --no-enable-prefix-caching \
  --no-enable-flashinfer-autotune \
  --reasoning-parser qwen3 \
  --trust-remote-code \
  "${SPEC_ARGS[@]}"
