okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-1402-d2' into f-14021be32e9c7

main
9.3 KiB160 linesraw
1"""GET /metrics in the Prometheus text format, with vLLM's metric names, so the dashboards and alerts written for a
2vLLM server read a Strata server unchanged.  Everything comes from the server's own record (Service.metrics(), the
3same dict the JSON /metrics returns) plus three latency histograms observed when a request finishes.
4
5What vLLM has no name for is the JSON's own facts under `strata:`, named after the JSON's keys (live.tok_s ->
6strata:live_tok_s, totals.decode_ms -> strata:totals_decode_seconds_total, hardware.gpu_util -> strata:gpu_util), so
7the two formats say the same thing and a panel can be moved from the Monitor tab to Grafana by its key."""
8import threading
9
10# vLLM's buckets for the request latencies (seconds)
11BUCKETS = (0.001, 0.005, 0.01, 0.02, 0.04, 0.06, 0.08, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, 20.0, 40.0,
12           80.0, 160.0, 640.0, 2560.0)
13CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8"
14
15
16def wants_prometheus(accept: str, query: str) -> bool:
17    """Prometheus asks with Accept: text/plain or application/openmetrics-text; a person can add ?format=prometheus.
18    Anything else (the Monitor tab, curl without a header) keeps the JSON."""
19    return "format=prometheus" in (query or "") or "openmetrics" in (accept or "") or "text/plain" in (accept or "")
20
21
22class Histogram:
23    def __init__(self):
24        self.counts = [0] * len(BUCKETS)
25        self.sum = 0.0
26        self.n = 0
27
28    def observe(self, v: float, times: int = 1):
29        if v is None or times <= 0:
30            return
31        for i, b in enumerate(BUCKETS):
32            if v <= b:
33                self.counts[i] += times
34        self.sum += v * times
35        self.n += times
36
37
38class Latencies:
39    """Time to first token, the time between tokens and the whole request, per finished request."""
40
41    def __init__(self):
42        self.lock = threading.Lock()
43        self.ttft, self.itl, self.e2e = Histogram(), Histogram(), Histogram()
44
45    def observe(self, ttft_s, output_tokens, decode_s, total_s):
46        with self.lock:
47            self.ttft.observe(ttft_s)
48            if output_tokens and output_tokens > 1 and decode_s:
49                # the mean gap, once per gap: the engine reports the decode time, not each token's
50                self.itl.observe(decode_s / (output_tokens - 1), output_tokens - 1)
51            self.e2e.observe(total_s)
52
53    def snapshot(self):
54        with self.lock:
55            return {k: (list(h.counts), h.sum, h.n) for k, h in
56                    (("ttft", self.ttft), ("itl", self.itl), ("e2e", self.e2e))}
57
58
59def _num(v, default=0):
60    return v if isinstance(v, (int, float)) and not isinstance(v, bool) else default
61
62
63def render(m: dict, lat: dict) -> str:
64    """The text for one scrape.  `m` is Service.metrics(), `lat` Latencies.snapshot()."""
65    model = str((m.get("engine") or {}).get("model") or "strata").replace("\\", "\\\\").replace('"', '\\"')
66    lab = f'model_name="{model}"'
67    live, totals = m.get("live") or {}, m.get("totals") or {}
68    out = []
69
70    def metric(name, kind, help_, value):
71        out.append(f"# HELP {name} {help_}\n# TYPE {name} {kind}\n{name}{{{lab}}} {value}")
72
73    busy = live.get("state") in ("reading", "generating")
74    ctx = _num((m.get("engine") or {}).get("max_context"), 0)
75    used = _num(live.get("prompt_tokens")) + _num(live.get("generated")) if busy else 0
76    # "parallel": live.running / live.waiting count the requests together (waiting: for a slot or the control lines)
77    metric("vllm:num_requests_running", "gauge", "Requests reading their prompt or generating.",
78           _num(live.get("running"), int(busy)))
79    metric("vllm:num_requests_waiting", "gauge", "Requests waiting for their turn.",
80           _num(live.get("queued")) + _num(live.get("waiting")))
81    metric("vllm:kv_cache_usage_perc", "gauge", "The running request's share of the context (1 = full).",
82           round(min(1.0, used / ctx), 4) if ctx else 0)
83    metric("vllm:prompt_tokens_total", "counter", "Prompt tokens of the finished requests.",
84           _num(totals.get("prompt_tokens")))
85    metric("vllm:generation_tokens_total", "counter", "Generated tokens.", _num(totals.get("output_tokens")))
86    metric("vllm:request_success_total", "counter", "Finished requests.", _num(totals.get("requests")))
87    metric("vllm:prefix_cache_queries_total", "counter", "Prompt tokens looked up in the prompt cache.",
88           _num(totals.get("prompt_tokens")))
89    metric("vllm:prefix_cache_hits_total", "counter", "Prompt tokens the prompt cache already held.",
90           _num(totals.get("reused")))
91    metric("vllm:spec_decode_num_draft_tokens_total", "counter", "MTP draft tokens offered.",
92           _num(totals.get("drafts_offered")))
93    metric("vllm:spec_decode_num_accepted_tokens_total", "counter", "MTP draft tokens accepted.",
94           _num(totals.get("drafts_accepted")))
95    metric("vllm:num_preemptions_total", "counter", "Preempted requests (Strata does not preempt).", 0)
96    for name, key, help_ in (("vllm:time_to_first_token_seconds", "ttft", "Time to the first token."),
97                             ("vllm:inter_token_latency_seconds", "itl", "Time between two tokens."),
98                             ("vllm:e2e_request_latency_seconds", "e2e", "A request from start to end.")):
99        counts, total, n = lat[key]
100        out.append(f"# HELP {name} {help_}\n# TYPE {name} histogram")
101        for b, c in zip(BUCKETS, counts):
102            out.append(f'{name}_bucket{{{lab},le="{b}"}} {c}')
103        out.append(f'{name}_bucket{{{lab},le="+Inf"}} {n}')
104        out.append(f"{name}_sum{{{lab}}} {round(total, 6)}\n{name}_count{{{lab}}} {n}")
105    strata(m, out, lab)
106    return "\n".join(out) + "\n"
107
108
109def strata(m: dict, out: list, lab: str):
110    """The JSON's facts vLLM has no name for, under `strata:` and the JSON's key."""
111    live, totals = m.get("live") or {}, m.get("totals") or {}
112    hw, eng = m.get("hardware") or {}, m.get("engine") or {}
113    reqs = m.get("requests") or []
114
115    typed = set()
116
117    def metric(name, kind, help_, value, labels=""):
118        if not isinstance(value, (int, float)) or isinstance(value, bool):
119            return                                       # unknown here (no GPU telemetry, an older engine): no sample
120        if name not in typed:                            # one HELP / TYPE per family, before its first sample
121            typed.add(name)
122            out.append(f"# HELP strata:{name} {help_}\n# TYPE strata:{name} {kind}")
123        out.append(f"strata:{name}{{{lab}{labels}}} {value}")
124
125    for state in ("unloaded", "idle", "reading", "generating"):
126        metric("live_state", "gauge", "1 for what the engine is doing (live.state).", int(live.get("state") == state),
127               f',state="{state}"')
128    metric("live_tok_s", "gauge", "Decode rate over the last seconds (live.tok_s).", live.get("tok_s") or 0)
129    metric("live_prefill_tok_s_mean", "gauge", "Prompt reading rate of the running request (live.prefill_tok_s_mean).",
130           live.get("prefill_tok_s_mean") or 0)
131    metric("live_prompt_read", "gauge", "Prompt tokens read so far by the running request (live.prompt_read).",
132           live.get("prompt_read") or 0)
133    for state in ("idle", "reading", "generating"):
134        slots = live.get("slots")
135        if isinstance(slots, list) and slots:
136            metric("live_slots", "gauge", "The batch slots in each state (live.slots).",
137                   sum(1 for x in slots if isinstance(x, dict) and x.get("state") == state), f',state="{state}"')
138    metric("engine_max_context", "gauge", "The engine's context (engine.max_context).", eng.get("max_context"))
139    metric("totals_prompt_seconds_total", "counter", "Time spent reading prompts (totals.prompt_ms).",
140           round((totals.get("prompt_ms") or 0) / 1000, 3))
141    metric("totals_decode_seconds_total", "counter", "Time spent generating (totals.decode_ms).",
142           round((totals.get("decode_ms") or 0) / 1000, 3))
143    last = reqs[0] if reqs else {}
144    metric("last_hit_rate", "gauge", "The last request's expert cache hit rate (requests[0].hit_rate).",
145           last.get("hit_rate"))
146    metric("last_decode_tok_s", "gauge", "The last request's decode rate (requests[0].decode_tok_s).",
147           last.get("decode_tok_s"))
148    gpus = hw.get("gpus") or ([{"index": 0, "util": hw.get("gpu_util"), "mem_used": hw.get("gpu_mem_used"),
149                                "mem_total": hw.get("gpu_mem_total"), "temp": hw.get("gpu_temp"),
150                                "power": hw.get("gpu_power")}] if hw.get("gpu_util") is not None else [])
151    for name, key, help_ in (("gpu_util", "util", "GPU busy, percent (hardware.gpu_util)."),
152                             ("gpu_mem_used_bytes", "mem_used", "GPU memory in use (hardware.gpu_mem_used)."),
153                             ("gpu_mem_total_bytes", "mem_total", "GPU memory (hardware.gpu_mem_total)."),
154                             ("gpu_temp_celsius", "temp", "GPU temperature (hardware.gpu_temp)."),
155                             ("gpu_power_watts", "power", "GPU power draw (hardware.gpu_power).")):
156        for g in gpus:                                   # a family's samples together, one per card
157            metric(name, "gauge", help_, g.get(key), f',gpu="{g.get("index")}"')
158    metric("cpu", "gauge", "CPU busy, percent (hardware.cpu).", hw.get("cpu"))
159    metric("ram_used_bytes", "gauge", "RAM in use (hardware.ram_used).", hw.get("ram_used"))
160    metric("ram_total_bytes", "gauge", "RAM (hardware.ram_total).", hw.get("ram_total"))