okami.mom/strata

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

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

main
8.9 KiB181 linesraw
1"""serve/test_prometheus.py - GET /metrics in the Prometheus text format (vLLM's names), against the mock engine.
2
3    python -m unittest serve.test_prometheus -v
4"""
5from __future__ import annotations
6
7import json
8import re
9import sys
10import threading
11import time
12import unittest
13import urllib.request
14from pathlib import Path
15
16sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
17from serve.frontend import ChatTemplate  # noqa: E402
18from serve.prometheus import BUCKETS, Latencies, render, wants_prometheus  # noqa: E402
19from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
20
21ROOT = Path(__file__).resolve().parents[1]
22
23
24def parse(text):
25    """{(name, labels): value} for every sample line; checks each family has HELP and TYPE first."""
26    out, typed = {}, set()
27    for line in text.splitlines():
28        if line.startswith("# TYPE "):
29            assert line.split()[2] not in typed, f"two # TYPE lines for {line.split()[2]}"
30            typed.add(line.split()[2])
31            continue
32        if line.startswith("#") or not line:
33            continue
34        m = re.fullmatch(r'([a-z0-9_:]+)\{([^}]*)\} (\S+)', line)
35        assert m, f"not a sample line: {line!r}"
36        name, labels, value = m.groups()
37        family = re.sub(r"_(bucket|sum|count)$", "", name)
38        assert name in typed or family in typed, f"{name} has no # TYPE"
39        out[(name, labels)] = float(value)
40    return out
41
42
43class Units(unittest.TestCase):
44    def test_who_gets_the_text(self):
45        self.assertTrue(wants_prometheus("text/plain;version=0.0.4", ""))
46        self.assertTrue(wants_prometheus("application/openmetrics-text;version=1.0.0", ""))
47        self.assertTrue(wants_prometheus("", "format=prometheus"))
48        self.assertFalse(wants_prometheus("application/json", ""))
49        self.assertFalse(wants_prometheus("*/*", "requests=all"))
50
51    def test_histograms_are_cumulative(self):
52        lat = Latencies()
53        lat.observe(0.3, 11, 1.0, 1.5)       # 10 gaps of 0.1 s
54        lat.observe(None, 1, 0.0, 0.2)       # no first token, one token: no gap
55        s = lat.snapshot()
56        counts, total, n = s["itl"]
57        self.assertEqual(n, 10)
58        self.assertAlmostEqual(total, 1.0)
59        self.assertEqual(counts[BUCKETS.index(0.1)], 10)
60        self.assertEqual(counts[BUCKETS.index(0.08)], 0)
61        self.assertEqual(s["ttft"][2], 1)
62        self.assertEqual(s["e2e"][2], 2)
63        self.assertEqual(counts, sorted(counts))
64
65    def test_render_reads_the_server_record(self):
66        m = {"engine": {"model": 'a "b"', "max_context": 1000},
67             "live": {"state": "generating", "queued": 2, "prompt_tokens": 400, "generated": 100},
68             "totals": {"requests": 3, "prompt_tokens": 900, "reused": 600, "output_tokens": 50,
69                        "drafts_offered": 40, "drafts_accepted": 30}}
70        got = parse(render(m, Latencies().snapshot()))
71        lab = 'model_name="a \\"b\\""'
72        self.assertEqual(got[("vllm:num_requests_running", lab)], 1)
73        self.assertEqual(got[("vllm:num_requests_waiting", lab)], 2)
74        self.assertEqual(got[("vllm:kv_cache_usage_perc", lab)], 0.5)
75        self.assertEqual(got[("vllm:prefix_cache_hits_total", lab)], 600)
76        self.assertEqual(got[("vllm:spec_decode_num_accepted_tokens_total", lab)], 30)
77        self.assertEqual(got[("vllm:time_to_first_token_seconds_count", lab)], 0)
78
79    def test_strata_names_follow_the_json(self):
80        m = {"engine": {"model": "m", "max_context": 1000},
81             "live": {"state": "reading", "queued": 0, "prompt_read": 300, "prefill_tok_s_mean": 2500.0},
82             "totals": {"requests": 1, "prompt_ms": 1500.0, "decode_ms": 2000.0},
83             "requests": [{"hit_rate": 0.97, "decode_tok_s": 101.5}],
84             "hardware": {"gpu_util": 40.0, "gpus": [{"index": 0, "util": 30.0, "mem_used": 1 << 30, "temp": 60},
85                                                     {"index": 1, "util": 50.0, "mem_used": 2 << 30, "temp": 65}],
86                          "cpu": 12.5, "ram_used": 8 << 30, "ram_total": 64 << 30}}
87        got = parse(render(m, Latencies().snapshot()))
88        lab = 'model_name="m"'
89        self.assertEqual(got[("strata:live_state", lab + ',state="reading"')], 1)
90        self.assertEqual(got[("strata:live_state", lab + ',state="generating"')], 0)
91        self.assertEqual(got[("strata:live_prompt_read", lab)], 300)
92        self.assertEqual(got[("strata:totals_decode_seconds_total", lab)], 2.0)
93        self.assertEqual(got[("strata:last_hit_rate", lab)], 0.97)
94        self.assertEqual(got[("strata:gpu_util", lab + ',gpu="1"')], 50)
95        self.assertEqual(got[("strata:gpu_mem_used_bytes", lab + ',gpu="0"')], 1 << 30)
96        self.assertNotIn(("strata:gpu_power_watts", lab + ',gpu="0"'), got)   # not measured: no sample
97        self.assertEqual(got[("strata:ram_total_bytes", lab)], 64 << 30)
98
99
100class Endpoint(unittest.TestCase):
101    @classmethod
102    def setUpClass(cls):
103        tok = ByteTokenizer()
104        cls.svc = Service(MockEngine(tok, "</think>\n\nhello there", max_context=4096), tok,
105                          ChatTemplate(ROOT / "serve/chat_template.jinja"))
106        cls.httpd = serve(cls.svc, port=0)
107        cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
108
109    @classmethod
110    def tearDownClass(cls):
111        cls.httpd.shutdown()
112        cls.httpd.server_close()
113
114    def get(self, path, accept):
115        req = urllib.request.Request(self.base + path, headers={"Accept": accept})
116        with urllib.request.urlopen(req, timeout=30) as r:
117            return r.headers.get("Content-Type"), r.read().decode()
118
119    def test_a_request_shows_in_both_formats(self):
120        body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 32}).encode()
121        req = urllib.request.Request(self.base + "/v1/chat/completions", data=body,
122                                     headers={"Content-Type": "application/json"})
123        with urllib.request.urlopen(req, timeout=30) as r:
124            usage = json.loads(r.read())["usage"]
125        ctype, text = self.get("/metrics", "text/plain")
126        self.assertTrue(ctype.startswith("text/plain"))
127        got = {k[0]: v for k, v in parse(text).items()}
128        self.assertGreaterEqual(got["vllm:request_success_total"], 1)
129        self.assertGreaterEqual(got["vllm:generation_tokens_total"], usage["completion_tokens"])
130        self.assertGreaterEqual(got["vllm:e2e_request_latency_seconds_count"], 1)
131        ctype, text = self.get("/metrics", "application/json")
132        self.assertTrue(ctype.startswith("application/json"))
133        self.assertGreaterEqual(json.loads(text)["totals"]["requests"], 1)
134        ctype, _ = self.get("/metrics?format=prometheus", "*/*")
135        self.assertTrue(ctype.startswith("text/plain"))
136
137
138class BatchEngine(MockEngine):
139    """--batch as the server sees it: several requests generate at once, none waits for the control lines."""
140    batch, waiting = 4, 0
141
142
143class Batched(unittest.TestCase):
144    def test_every_concurrent_request_is_counted(self):
145        tok = ByteTokenizer()
146        svc = Service(BatchEngine(tok, "</think>\n\n" + "y" * 40, max_context=4096, delay_s=0.02), tok,
147                      ChatTemplate(ROOT / "serve/chat_template.jinja"))
148        httpd = serve(svc, port=0)
149        base = f"http://127.0.0.1:{httpd.server_address[1]}"
150        try:
151            body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}],
152                               "max_tokens": 64}).encode()
153
154            def ask():
155                req = urllib.request.Request(base + "/v1/chat/completions", data=body,
156                                             headers={"Content-Type": "application/json"})
157                with urllib.request.urlopen(req, timeout=60) as r:
158                    r.read()
159
160            threads = [threading.Thread(target=ask) for _ in range(3)]
161            [t.start() for t in threads]
162            time.sleep(0.4)                              # the three are generating
163            req = urllib.request.Request(base + "/metrics", headers={"Accept": "text/plain"})
164            with urllib.request.urlopen(req, timeout=30) as r:
165                during = {k[0]: v for k, v in parse(r.read().decode()).items()}
166            [t.join() for t in threads]
167            with urllib.request.urlopen(req, timeout=30) as r:
168                after = {k[0]: v for k, v in parse(r.read().decode()).items()}
169        finally:
170            httpd.shutdown()
171            httpd.server_close()
172        self.assertEqual(during["vllm:num_requests_running"], 3)
173        self.assertEqual(after["vllm:num_requests_running"], 0)
174        self.assertEqual(after["vllm:request_success_total"], 3)      # each one, not only the last to finish
175        self.assertEqual(after["vllm:e2e_request_latency_seconds_count"], 3)
176        self.assertEqual(after["vllm:time_to_first_token_seconds_count"], 3)
177        self.assertEqual(svc.metrics()["totals"]["requests"], 3)          # the JSON agrees
178
179
180if __name__ == "__main__":
181    unittest.main()