okami.mom/strata

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

Niko1221Terminal Overview: the ASCII look has no U+00B7 (a redirected stdout in cp852, cp874, cp932 or ascii raised UnicodeEncodeError); test_speed_average decodes node's output as UTF-8 instead of the locale code page568127b7a

main
12.3 KiB231 linesraw
1"""The monitor's Overview (view 1): numbers from /metrics, the drawing, glyph fallbacks, and the monitor showing it."""
2
3from __future__ import annotations
4
5import asyncio
6import io
7import time
8import unittest
9
10from rich.console import Console
11
12from strata_cli import overview
13from strata_cli.monitor import MonitorApp
14
15GIB = 2 ** 30
16
17
18def metrics(state="reading", **over):
19    now = time.time()
20    hist = lambda base, amp: [base + amp * ((i * 7) % 5) / 4 for i in range(60)]     # noqa: E731
21    m = {"time": now,
22         "engine": {"model": "IQ3_S", "max_context": 131072, "expert_slots": 1644, "experts": 5120, "expert_cache_mib": 3280},
23         "live": {"state": state, "queued": 0, "prompt_read": 35610 if state == "reading" else None, "prompt_total": 36742 if state == "reading" else None,
24                  "prompt_tokens": 36742, "generated": 120 if state == "generating" else 0, "max_tokens": 4096,
25                  "tok_s": 50.4 if state == "generating" else None, "prefill_tok_s_mean": 820.0},
26         "hardware": {"gpu_util": 88, "gpu_mem_used": 11.2 * GIB, "gpu_mem_total": 12 * GIB, "gpu_temp": 54, "gpu_power": 114, "gpu_power_limit": 250,
27                      "gpu_pcie_rx_mb": 18237, "gpu_pcie_gen": 4, "gpu_pcie_width": 16, "cpu": 14, "ram_used": 58.5 * GIB, "ram_total": 63 * GIB,
28                      "disk_read_mb": 0.1, "disk_write_mb": 0.0},
29         "hardware_static": {"gpu_name": "RTX 5070", "gpu_count": 1, "cores": 6, "threads": 12},
30         "history": {"tok_s": hist(40, 10), "gpu_util": hist(80, 10), "gpu_mem_used": [11.2 * GIB] * 60, "gpu_temp": [54] * 60,
31                     "gpu_power": hist(110, 10), "gpu_pcie_rx_mb": hist(10000, 9000), "cpu": hist(10, 8), "disk_read_mb": hist(0, 3)},
32         "requests": [{"id": "a", "time": now - 5, "duration_s": 429.8, "finish_reason": "stop", "prompt_tokens": 17183, "reused": 0,
33                       "output_tokens": 19511, "decode_ms": 386000},
34                      {"id": "b", "time": now - 9, "duration_s": 4.0, "finish_reason": "stop", "prompt_tokens": 626, "reused": 0,
35                       "output_tokens": 11, "decode_ms": 410}],
36          "totals": {"requests": 12, "prompt_tokens": 90000, "reused": 5000, "output_tokens": 40000,
37                     "prompt_ms": 120000.0, "decode_ms": 1000000.0}}
38    m.update(over)
39    return m
40
41
42def draw(model, width=110, height=30, **kw) -> str:
43    c = Console(width=width + 2, record=True, file=io.StringIO(), force_terminal=False, legacy_windows=False)
44    c.print(overview.render(model, width=width, height=height, connection="http://127.0.0.1:8080", **kw))
45    return c.export_text()
46
47
48class AsciiLook(unittest.TestCase):
49    """The ASCII look is pure ASCII: written to a stdout that cannot encode U+00B7 (cp852, cp874, cp932, ascii) it must not raise UnicodeEncodeError."""
50
51    def test_the_ascii_look_has_no_middle_dot(self):
52        for state in ("idle", "reading", "generating"):
53            text = draw(overview.build(metrics(state)), glyphs="ascii")
54            self.assertNotIn("·", text, state)      # (the box lines are rich's: it swaps them for + - | on a stream that cannot encode them)
55        self.assertIn("·", draw(overview.build(metrics("reading")), glyphs="unicode"), "the Unicode look keeps it")
56
57    def test_it_writes_to_strict_streams_of_the_legacy_code_pages(self):
58        from rich.console import Console as C
59        for enc in ("cp437", "cp852", "cp874", "cp932", "ascii"):
60            raw = io.BytesIO()
61            f = io.TextIOWrapper(raw, encoding=enc, errors="strict")
62            c = C(file=f, width=112, force_terminal=False, legacy_windows=False)
63            for state in ("idle", "reading", "generating"):
64                c.print(overview.render(overview.build(metrics(state)), width=110, height=30, connection="http://127.0.0.1:8080", glyphs="ascii"))
65            f.flush()
66            self.assertGreater(len(raw.getvalue()), 1000, enc)
67
68
69class Build(unittest.TestCase):
70    def test_reading_state_and_progress(self):
71        m = overview.build(metrics("reading"))
72        self.assertEqual(m["state"], "Reading")
73        self.assertEqual(m["progress"], (35610.0, 36742.0))
74        self.assertEqual(m["context"], (36742.0, 131072.0))
75        self.assertEqual(m["speed"][:2], (820.0, "reading the prompt"))
76
77    def test_generating_uses_the_live_rate_and_prompt_plus_generated_for_context(self):
78        m = overview.build(metrics("generating"))
79        self.assertEqual(m["state"], "Generating")
80        self.assertEqual(m["speed"][:2], (50.4, "now"))
81        self.assertEqual(m["context"][0], 36742 + 120)
82        self.assertEqual(m["progress"], (120.0, 4096.0))
83
84    def test_idle_shows_the_run_average(self):
85        m = overview.build(metrics("idle"))
86        self.assertEqual(m["state"], "Idle")
87        self.assertEqual(m["speed"][1], "average of the run")
88        self.assertAlmostEqual(m["speed"][0], 40.0, places=1)               # totals: 40000 tokens in 1000 s, not the last request's 50.5
89        self.assertEqual(m["context"][0], 17183 + 19511)
90        self.assertEqual(m["progress"], (None, None))
91
92    def test_the_run_average_is_token_weighted_and_never_invented(self):
93        """Community patch (keinebenutzer/STRATA-average-patch, MIT): the idle tile is every token over the run's decode time, from the server's totals."""
94        self.assertEqual(overview.run_average_speed({"totals": {"output_tokens": 40000, "decode_ms": 1000000.0}}), 40.0)
95        # a long request and a short one: the long one counts for what it is (a plain mean of the two would be 30.3)
96        self.assertEqual(overview.run_average_speed({"totals": {"output_tokens": 19522, "decode_ms": 386410.0}}), 50.5)
97        for totals in (None, {}, {"output_tokens": 0, "decode_ms": 100.0}, {"output_tokens": 1, "decode_ms": 100.0}, {"output_tokens": 500, "decode_ms": 0},
98                       {"output_tokens": 500}, {"decode_ms": 500.0}, {"output_tokens": True, "decode_ms": 5.0}, {"output_tokens": "9", "decode_ms": 3.0},
99                       {"output_tokens": float("nan"), "decode_ms": 3.0}):
100            self.assertIsNone(overview.run_average_speed({"totals": totals}), totals)
101        self.assertIsNone(overview.run_average_speed({}))
102
103    def test_without_totals_idle_falls_back_to_the_last_request(self):
104        m = metrics("idle")
105        del m["totals"]
106        built = overview.build(m)
107        self.assertEqual(built["speed"][1], "last request")
108        self.assertAlmostEqual(built["speed"][0], 50.5, places=1)
109        m = metrics("idle", totals={"requests": 0, "output_tokens": 0, "decode_ms": 0.0})
110        self.assertEqual(overview.build(m)["speed"][1], "last request", "an empty run is not an average of zero")
111
112    def test_live_values_stay_live(self):
113        """Only the idle value is an average: generating and reading are what they were."""
114        self.assertEqual(overview.build(metrics("generating"))["speed"][:2], (50.4, "now"))
115        self.assertEqual(overview.build(metrics("reading"))["speed"][:2], (820.0, "reading the prompt"))
116        self.assertIn("average of the run", draw(overview.build(metrics("idle"))))
117
118    def test_queued_and_error(self):
119        self.assertEqual(overview.build(metrics("idle", live={"state": "idle", "queued": 3}))["state"], "Queued")
120        self.assertEqual(overview.build(metrics("idle", engine={"model": "x", "error": "boom"}))["state"], "Error")
121
122    def test_hardware_in_gb(self):
123        m = overview.build(metrics())
124        self.assertAlmostEqual(m["gpu"]["vram_used"], 11.2)
125        self.assertEqual(m["gpu"]["vram_total"], 12.0)
126        self.assertAlmostEqual(m["ram"][0], 58.5)
127        self.assertEqual(m["experts"], {"slots": 1644.0, "total": 5120.0, "gb": 3280 / 1024.0})
128
129    def test_missing_numbers_stay_missing(self):
130        m = overview.build({"live": {"state": "idle"}, "engine": {}, "hardware": {}, "requests": []})
131        self.assertIsNone(m["gpu"]["util"])
132        self.assertIsNone(m["speed"][0])
133        text = draw(m)
134        self.assertIn("-- tok/s", text)
135        self.assertIn("No requests yet", text)
136        self.assertNotIn("0 %", text.replace("-- %", ""))                    # no invented zero
137
138    def test_a_server_without_metrics_gives_none(self):
139        self.assertIsNone(overview.build(None))
140        self.assertIsNone(overview.build({"engine": {}}))
141
142
143class Draw(unittest.TestCase):
144    def test_the_approved_layout(self):
145        text = draw(overview.build(metrics("reading")), connect=True)
146        for part in ("STRATA  Overview", "IQ3_S 128K", "Reading prompt · 97%", "[LIVE]", "[1 Overview]", "7 Connect",
147                     "Model state", "[Reading]", "35,610 / 36,742 tokens · 97%",
148                     "Speed", "GPU load", "VRAM", "GPU temp", "Power", "PCIe", "CPU", "Disk read",
149                     "88 %", "RTX 5070", "11.2 / 12 GB", "1,644 experts cached", "54 °C", "114 W", "of 250 W limit", "Gen4 x16",
150                     "to GPU 18,237 MB/s", "6 cores · 12 threads", "0.1 MB/s", "write 0.0 MB/s",
151                     "Context fill", "36K / 128K", "Experts in VRAM", "1,644 · 3.2 GB", "System RAM", "58.5 / 63 GB",
152                     "Recent requests", "TIME", "STATUS", "PROMPT", "REUSED", "OUTPUT", "TOK/S", "DURATION", "17,183", "19,511", "429.8 s",
153                     "1-7 views", "b open in browser", "q quit"):
154            self.assertIn(part, text, part)
155
156    def test_without_connect_the_hint_says_six_views(self):
157        text = draw(overview.build(metrics()), connect=False)
158        self.assertIn("1-6 views", text)
159        self.assertNotIn("7 Connect", text)
160
161    def test_ascii_mode_has_no_glyphs_the_classic_windows_console_font_lacks(self):
162        text = draw(overview.build(metrics()), glyphs="ascii", color=False)
163        for bad in "▁▂▃▄▅▆▇█░╭╮╰╯✓●":
164            self.assertNotIn(bad, text, bad)
165        self.assertIn("#", text)
166        self.assertIn("54 C", text)
167
168    def test_fits_the_width_it_is_given(self):
169        for w in (80, 100, 120):
170            text = draw(overview.build(metrics()), width=w - 2)
171            self.assertTrue(all(len(line) <= w for line in text.splitlines()), w)
172
173    def test_spark(self):
174        self.assertEqual(len(overview.spark([1, 2, 3], 8, "unicode")), 8)
175        self.assertEqual(overview.spark([None, None], 4, "unicode"), "    ")
176        self.assertEqual(overview.spark([0, 100], 2, "unicode", lo=0, hi=100), "▁█")
177        self.assertEqual(overview.spark([0, 100], 2, "ascii", lo=0, hi=100), ".@")
178
179
180class Source:
181    root = "http://127.0.0.1:8095"
182
183    def __init__(self, raw):
184        self.raw = raw
185        self.base_url = self.root
186
187    def get(self, path):
188        if path == "/metrics":
189            return self.raw
190        raise AssertionError(path)
191
192    def snapshot(self):
193        return {"source": "fixture", "sampled_at": time.time(), "schema_version": 1, "instance": {"id": "x"},
194                "model": {"id": "IQ3_S", "loaded": True}, "work": {}, "rates": {}, "devices": [], "recent": [], "totals": {},
195                "topology": {}, "quality": {}}
196
197
198class InTheMonitor(unittest.TestCase):
199    def test_view_one_is_the_new_overview_and_the_others_stay(self):
200        async def go():
201            app = MonitorApp(Source(metrics("generating")), None, interval=30)
202            async with app.run_test(size=(120, 36)) as pilot:
203                await pilot.pause(0.5)
204                shown = "\n".join(s.text for s in app.screen._compositor.render_strips())
205                self.assertIn("Model state", shown)
206                self.assertIn("Generating", shown)
207                await pilot.press("2")
208                await pilot.pause(0.2)
209                shown = "\n".join(s.text for s in app.screen._compositor.render_strips())
210                self.assertNotIn("Model state", shown)
211                self.assertIn("Serving", shown)
212        asyncio.run(go())
213
214    def test_an_older_server_without_metrics_keeps_the_earlier_overview(self):
215        class Old(Source):
216            def get(self, path):
217                from strata_cli.client import ClientError
218                raise ClientError("not found", http_status=404)
219
220        async def go():
221            app = MonitorApp(Old(None), None, interval=30)
222            async with app.run_test(size=(120, 36)) as pilot:
223                await pilot.pause(0.5)
224                shown = "\n".join(s.text for s in app.screen._compositor.render_strips())
225                self.assertNotIn("Model state", shown)
226                self.assertIn("MONITOR", shown)
227        asyncio.run(go())
228
229
230if __name__ == "__main__":
231    unittest.main()