File size: 3,534 Bytes
a4822b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""vLLM server lifecycle for the SeqRoute build: replicas of one model on disjoint GPU groups, one model at a time."""
from __future__ import annotations

import json
import os
import signal
import subprocess
import time
import urllib.request
from pathlib import Path

ROOT = Path("/mnt/localssd/seqroute1m")
MODELS = Path("/mnt/localssd/models")
VLLM = "/mnt/localssd/venvs/main/bin/vllm"
LOGS = ROOT / "logs"
PIDS = LOGS / "servers.pids"
BASE_PORT = 18100
ENV = dict(os.environ, TMPDIR="/mnt/localssd/tmp", HF_HOME="/mnt/localssd/hf_cache", HF_HUB_OFFLINE="1", VLLM_CACHE_ROOT="/mnt/localssd/vllm_cache",
           TORCHINDUCTOR_CACHE_DIR="/mnt/localssd/torchinductor", XDG_CACHE_HOME="/mnt/localssd/xdg", VLLM_NO_USAGE_STATS="1", VLLM_USE_FLASHINFER_SAMPLER="0", DO_NOT_TRACK="1",
           TIKTOKEN_ENCODINGS_BASE="/mnt/localssd/tiktoken_encodings", TOKENIZERS_PARALLELISM="false")


def stop_servers() -> None:
    if PIDS.exists():
        for pid in json.loads(PIDS.read_text()):
            try:
                os.killpg(os.getpgid(pid), signal.SIGTERM)
            except (ProcessLookupError, PermissionError):
                pass
        time.sleep(5)
        for pid in json.loads(PIDS.read_text()):
            try:
                os.killpg(os.getpgid(pid), signal.SIGKILL)
            except (ProcessLookupError, PermissionError):
                pass
        PIDS.unlink()
    time.sleep(2)


def start_servers(spec: dict, n_gpus: int = 8, max_num_seqs: int = 128, max_model_len: int | None = None, mem_util: float = 0.92) -> list[int]:
    """spec: entry of manifests/models.json (id, tp, serve_args). One replica per group of `tp` GPUs."""
    tp = int(spec.get("tp", 1))
    groups = [list(range(i, i + tp)) for i in range(0, n_gpus - tp + 1, tp)]
    LOGS.mkdir(parents=True, exist_ok=True)
    ports, pids = [], []
    for gi, g in enumerate(groups):
        port = BASE_PORT + gi
        cmd = [VLLM, "serve", str(MODELS / spec["id"]), "--served-model-name", spec["id"], "--port", str(port), "--seed", "0", "--trust-remote-code",
               "--max-model-len", str(max_model_len or spec.get("max_model_len", 16384)), "--gpu-memory-utilization", str(mem_util), "--max-num-seqs", str(max_num_seqs),
               "--enable-prefix-caching", "--tensor-parallel-size", str(tp), *spec.get("serve_args", [])]
        log = open(LOGS / f"serve_{spec['id']}_{gi}.log", "w")
        p = subprocess.Popen(cmd, env=dict(ENV, CUDA_VISIBLE_DEVICES=",".join(map(str, g))), stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, start_new_session=True)
        ports.append(port)
        pids.append(p.pid)
    PIDS.write_text(json.dumps(pids))
    return ports


def wait_ready(ports: list[int], timeout: float = 1800) -> None:
    t0 = time.time()
    pending = set(ports)
    while pending:
        for p in list(pending):
            try:
                if urllib.request.urlopen(f"http://127.0.0.1:{p}/v1/models", timeout=3).status == 200:
                    pending.discard(p)
            except Exception:
                pass
        if pending:
            if time.time() - t0 > timeout:
                raise TimeoutError(f"servers not ready after {timeout}s: {sorted(pending)}")
            if PIDS.exists():
                for pid in json.loads(PIDS.read_text()):
                    try:
                        os.kill(pid, 0)
                    except ProcessLookupError:
                        raise RuntimeError("a vLLM server process died; see logs/serve_*.log")
            time.sleep(5)