import shlex
import subprocess
import sys
import time

MODEL = "/content/models/Qwen3.8-Flash-Next-NVFP4"
BASE = [
    "vllm", "serve", MODEL,
    "--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",
]


def gpu_used():
    out = subprocess.run(
        "nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits",
        shell=True, capture_output=True, text=True).stdout.strip()
    return int(out.splitlines()[0]) if out else 999999


def stop():
    subprocess.run("pkill -f 'vllm serve /content/models/Qwen3.8-Flash-Next-NVFP4'", shell=True)
    for _ in range(120):
        if gpu_used() < 2000:
            print("GPU released", gpu_used(), "MiB")
            return
        time.sleep(1)
    print("WARNING GPU still used", gpu_used(), "MiB")


def start(arm):
    stop()
    cmd = list(BASE)
    if arm == "mtp1":
        cmd += ["--speculative-config", '{"method":"mtp","num_speculative_tokens":1}']
    elif arm == "mtp3":
        cmd += ["--speculative-config", '{"method":"mtp","num_speculative_tokens":3}']
    log = f"/content/vllm_{arm}.log"
    full = "nohup " + " ".join(shlex.quote(x) for x in cmd) + f" > {log} 2>&1 & echo $!"
    r = subprocess.run(full, shell=True, text=True, capture_output=True)
    print("started", arm, "pid", r.stdout.strip(), "log", log)


if __name__ == "__main__":
    action = sys.argv[1]
    if action == "stop":
        stop()
    elif action == "start":
        start(sys.argv[2])
