okami.mom/strata

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

Niko1221Merge main c1ff07f1a into f-own-intfefaa985c

main
8.5 KiB164 linesraw
1"""The plan's Main card is the run's Main card: `strata launch --plan` (strata_cli/launch/cmd.py roles_line -> gpu_roles.from_legacy) and the start
2(runner.apply_cards -> serve/server.py ordered_gpus) take the card order from ONE function, gpu_roles.speed_stage_order (5% rule #1760, faster card last
3#1352, VRAM guard #1576).  Faked cards, nothing is started or probed.
4
5Card sets (speed = multiprocessors x max clock):
6  control  four Tesla V100 (32, 32, 16, 16 GB), equal speed
7  A        card 0 = 16 GB, speed 171 (sm_120); card 1 = 24 GB, speed 150 (sm_89): the FASTER card has LESS memory
8  B        card 0 = 16 GB, speed 150; card 1 = 24 GB, speed 171: the faster card has MORE memory
9  C        card 0 = 12 GB, card 1 = 16 GB, both speed 150: equal speed, different memory
10Before the fix the plan named card 0 in A typed 0,1 while the start ended on card 1 (the #1576 guard lives only in the start).
11A typed --gpu after an earlier launch with roles (a saved "gpu_order": "as_given") means the same as on a fresh home: the engine decides
12(owner 11-11, "Ok for --gpu list"; before, apply_cards kept the old key and the start kept the typed order where the plan re-sorted).
13"""
14
15from __future__ import annotations
16
17import contextlib
18import io
19import os
20import re
21import unittest
22from unittest import mock
23
24from serve import server
25from strata_cli.launch import cmd as launch_cmd
26from strata_cli.launch import runner
27from strata_cli.launch import settings as S
28from strata_control import gpu_roles
29from tests.terminal.launch_support import HW_12, Home, catalog
30
31
32def card(i, name, gb, speed):
33    return {"index": i, "name": name, "vram_gb": float(gb), "speed": speed, "usable": True, "vendor": "nvidia"}
34
35
36SETS = {
37    "control": [card(0, "Tesla V100-SXM2-32GB", 32, 122.4), card(1, "Tesla V100-SXM2-32GB", 32, 122.4),
38                card(2, "Tesla V100-SXM2-16GB", 16, 122.4), card(3, "Tesla V100-SXM2-16GB", 16, 122.4)],
39    "A": [card(0, "NVIDIA GeForce RTX 5070 Ti", 16, 171.0), card(1, "NVIDIA RTX 4500 Ada Generation", 24, 150.0)],
40    "B": [card(0, "NVIDIA RTX 4000 Ada Generation", 16, 150.0), card(1, "NVIDIA GeForce RTX 5090 D", 24, 171.0)],
41    "C": [card(0, "NVIDIA GeForce RTX 4070", 12, 150.0), card(1, "NVIDIA GeForce RTX 4070 Ti SUPER", 16, 150.0)],
42}
43# (set, typed --gpu order) -> the card (nvidia-smi number) the run makes Main, pinned
44START_MAIN = {
45    ("control", (0, 1, 2, 3)): 3,
46    ("A", (0, 1)): 1,       # the faster 16 GB card would go last, the guard keeps the typed order: the 24 GB card is Main
47    ("A", (1, 0)): 0,
48    ("B", (0, 1)): 1,
49    ("B", (1, 0)): 1,       # reordered: the faster card last
50    ("C", (0, 1)): 1,
51    ("C", (1, 0)): 0,
52}
53
54
55def plan_main(cards, typed):
56    s = S.LaunchSettings(family="qwen", model="UD-Q4_K_XL", gpus=list(typed))
57    c = catalog({**HW_12, "engine_vendor": "nvidia", "gpus": cards})
58    with mock.patch.dict(os.environ, {}):
59        os.environ.pop("CUDA_VISIBLE_DEVICES", None)
60        line = launch_cmd.roles_line(s, c)
61    m = re.search(r"Main: GPU \d+ \(--gpu (\d+)\)", line or "")
62    assert m, line
63    return int(m.group(1)), line
64
65
66def start_main(cards, typed, base=None):
67    """The saved config of a typed --gpu on a fresh home (no earlier gpu_order) or on `base` (a config an earlier launch saved), then the
68    order the engine stages the cards in."""
69    cfg = dict(base) if base else {"layer_split": "auto"}
70    runner.apply_cards(cfg, list(typed))
71    scores = {c["index"]: c["speed"] for c in cards}
72    vrams = {c["index"]: int(c["vram_gb"] * 1024) for c in cards}
73    buf = io.StringIO()
74    with contextlib.redirect_stdout(buf):
75        order = server.ordered_gpus(cfg, scores=scores, vrams=vrams)
76    return order[-1], order, buf.getvalue().strip()
77
78
79class PlanNamesTheRunsMain(unittest.TestCase):
80    def setUp(self):
81        self.home = Home().__enter__()                  # a private install / data / home folder (STRATA_INSTALL_DIR ...), as the other launch tests
82        self.addCleanup(self.home.__exit__, None, None, None)
83
84    def test_every_row_the_plan_equals_the_start(self):
85        for (name, typed), want in START_MAIN.items():
86            with self.subTest(cards=name, typed=typed):
87                p, line = plan_main(SETS[name], typed)
88                s, order, _ = start_main(SETS[name], typed)
89                self.assertEqual(s, want, f"the start's Main changed ({order})")
90                self.assertEqual(p, s, f"the plan says '{line}', the start ends on card {s} ({order})")
91
92    def test_a_typed_list_after_a_roles_launch_means_the_same_as_on_a_fresh_home(self):
93        for (name, typed), want in START_MAIN.items():
94            n = len(SETS[name])
95            roles = {"gpu": list(range(n)), "gpu_order": "as_given", "layer_split": "auto",
96                     "gpu_roles": {str(i): ("main" if i == n - 1 else "helper") for i in range(n)}}
97            with self.subTest(cards=name, typed=typed):
98                s, order, _ = start_main(SETS[name], typed, base=roles)
99                p, line = plan_main(SETS[name], typed)
100                self.assertEqual(s, want, f"the start's Main after a roles launch ({order})")
101                self.assertEqual(p, s, f"the plan says '{line}', the start ends on card {s} ({order})")
102        cfg = {"gpu": [0, 1], "gpu_order": "as_given", "gpu_roles": {"0": "helper", "1": "main"}}
103        runner.apply_cards(cfg, [1, 0])
104        self.assertNotIn("gpu_order", cfg)
105        self.assertNotIn("gpu_roles", cfg)
106
107    def test_roles_still_keep_their_order(self):
108        cfg = {"gpu": [1, 0]}
109        runner.apply_cards(cfg, {"gpu": [1, 0], "gpu_order": "as_given", "gpu_roles": {"0": "main", "1": "helper"}})
110        self.assertEqual(cfg.get("gpu_order"), "as_given")
111
112    def test_the_help_line_says_who_picks_the_main_card(self):
113        import argparse
114        parsers = launch_cmd.add_parsers(argparse.ArgumentParser().add_subparsers())
115        helps = [a.help for p in parsers for a in p._actions if "--gpu" in a.option_strings]
116        self.assertTrue(helps)
117        text = helps[0]
118        self.assertEqual(text, "graphics card numbers to use, e.g. 0 or 0,1 (default: the engine's choice). With more than one card the engine "
119                               "decides which is the Main card; --gpu-roles (instead of --gpu) sets the roles yourself.")
120
121    def test_the_vram_guard_message_is_unchanged(self):
122        _, order, said = start_main(SETS["A"], (0, 1))
123        self.assertEqual(order, [0, 1])
124        self.assertEqual(said, "[strata] layer split: keeping card order 0,1 - the faster card has less VRAM than the one the split ends on (16384 vs 24576 MiB, #1576)")
125
126    def test_the_reorder_message_is_unchanged(self):
127        _, order, said = start_main(SETS["B"], (1, 0))
128        self.assertEqual(order, [0, 1])
129        self.assertEqual(said, '[strata] layer split: card order 0,1 (the faster card last; "gpu_order": "as_given" keeps 1,0, #1352)')
130
131    def test_equal_cards_print_nothing_and_keep_the_typed_order(self):
132        for name, typed in (("control", (0, 1, 2, 3)), ("C", (0, 1)), ("C", (1, 0))):
133            _, order, said = start_main(SETS[name], typed)
134            self.assertEqual((order, said), (list(typed), ""))
135
136
137class SpeedStageOrder(unittest.TestCase):
138    def f(self, *a):
139        return gpu_roles.speed_stage_order(*a)
140
141    def test_why(self):
142        self.assertEqual(self.f([0, 1], {0: 100.0, 1: 104.9}), ([0, 1], "same", None))                    # within 5%
143        self.assertEqual(self.f([0, 1], {0: 100.0, 1: 105.0}), ([0, 1], "kept", None))                    # already faster last
144        self.assertEqual(self.f([1, 0], {0: 100.0, 1: 105.0}, {0: 8192, 1: 8192}), ([0, 1], "faster-last", None))
145        self.assertEqual(self.f([0, 1], {0: 105.0, 1: 100.0}, {0: 8192, 1: 16384}), ([0, 1], "kept-vram", (8192, 16384)))
146        self.assertEqual(self.f([0, 1], {0: 105.0, 1: 100.0}, {0: 16384, 1: 8192}), ([1, 0], "faster-last", None))
147        self.assertEqual(self.f([0, 1], {0: 105.0, 1: 100.0}, {0: 8192}), ([1, 0], "faster-last", None))   # a card without a VRAM figure: no guard
148        self.assertEqual(self.f([3], {3: 1.0}), ([3], "same", None))
149
150    def test_the_vram_figures_are_asked_only_when_a_reorder_is_on_the_table(self):
151        asked = []
152
153        def vram():
154            asked.append(1)
155            return {0: 8192, 1: 8192}
156        self.f([0, 1], {0: 100.0, 1: 101.0}, vram)                  # same speed: no question
157        self.f([0, 1], {0: 100.0, 1: 150.0}, vram)                  # already faster last: no question
158        self.assertEqual(asked, [])
159        self.f([1, 0], {0: 100.0, 1: 150.0}, vram)                  # a reorder: asked once
160        self.assertEqual(asked, [1])
161
162
163if __name__ == "__main__":
164    unittest.main()