okami.mom/strata

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

Niko1221drafting: one drafter per install, never none unless Off was chosen1f0ace2d1

main
8.5 KiB166 linesraw
1"""Setup's MTP download, the Gyro low-RAM pack and the FP4-Local conversion packages (#3193 #3214 #3257 #3227): the draft layer's download is run again when it stops, every tool
2setup runs ends with setup, and Gyro's low-RAM pack gets --compat-bf16 like its first pack.  Everything mocked; nothing downloaded.
3
4    python -m unittest tools.test_setup_dl_fix
5"""
6import os
7import pathlib
8import sys
9import unittest
10from unittest import mock
11
12ROOT = pathlib.Path(__file__).resolve().parent.parent
13sys.path.insert(0, str(ROOT))
14sys.path.insert(0, str(ROOT / "tools"))
15import setup  # noqa: E402
16import test_setup_unsloth as U  # noqa: E402
17
18
19class FetchMtp(unittest.TestCase):
20    def run_with(self, codes, grow=True):
21        """grow: each run writes a few bytes into the folder (a run that moved data); the network rule runs it again only then (lane NET)."""
22        import tempfile
23        calls = []
24        tmp = tempfile.TemporaryDirectory()
25        self.addCleanup(tmp.cleanup)
26        mtp = pathlib.Path(tmp.name) / "mtp"
27
28        def fake_run(cmd, cwd=None, env=None, check=True, quiet=False):
29            calls.append((cmd, env, check))
30            if grow:
31                mtp.mkdir(exist_ok=True)
32                (mtp / f"part{len(calls)}").write_bytes(b"x")
33            return mock.Mock(returncode=codes[min(len(calls) - 1, len(codes) - 1)])
34        with mock.patch.object(setup, "run", fake_run), mock.patch.object(setup.time, "sleep", lambda s: None), \
35                mock.patch.object(setup, "say", lambda *a, **k: None), mock.patch.object(setup, "warn", lambda *a, **k: None):
36            try:
37                setup.fetch_mtp(mtp, {"A": "1"})
38                result = "ok"
39            except SystemExit as e:
40                result = e.code
41        return result, calls
42
43    def test_a_run_that_moved_no_bytes_is_not_run_again(self):
44        out = []
45        with mock.patch.object(setup, "fail", lambda msg, hint=None: out.append((msg, hint)) or (_ for _ in ()).throw(SystemExit(1))):
46            result, calls = self.run_with([1], grow=False)
47        self.assertEqual((result, len(calls)), (1, 1))
48
49    def test_a_server_that_does_not_answer_stops_at_once_with_the_fetchs_own_reason(self):
50        result, calls = self.run_with([4])
51        self.assertEqual((result, len(calls)), (1, 1))
52
53    def test_offline_setup_goes_on_without_the_draft_layer(self):
54        # 0.2.14 real-use run, R9700 offline: a first Auto launch stopped with exit 6 at the draft layer; offline is never a stop (the model starts without it)
55        result, calls = self.run_with([5])
56        self.assertEqual((result, len(calls)), ("ok", 1))
57
58    def test_the_fetch_says_offline_with_its_own_exit_code(self):
59        import mtp_fetch
60        from strata_control import netpolicy
61        for kind, code in (("offline", mtp_fetch.OFFLINE), ("no_answer", mtp_fetch.NO_ANSWER)):
62            with self.subTest(kind=kind), mock.patch.object(sys, "argv", ["mtp_fetch.py", "inventory", "--out", "x"]), \
63                    mock.patch.object(mtp_fetch, "exit_with_parent", lambda: None), \
64                    mock.patch.object(mtp_fetch, "resolve_repo", mock.Mock(side_effect=netpolicy.NetFailure("huggingface.co", kind))), \
65                    mock.patch("sys.stderr", new=__import__("io").StringIO()):
66                with self.assertRaises(SystemExit) as got:
67                    mtp_fetch.main()
68                self.assertEqual(got.exception.code, code)
69
70    def test_a_stopped_download_is_run_again_and_continues(self):
71        result, calls = self.run_with([1, 1, 0])
72        self.assertEqual((result, len(calls)), ("ok", 3))
73        self.assertTrue(all(c[0][2] == "fetch" and c[1]["A"] == "1" and c[2] is False for c in calls))
74
75    def test_a_download_that_never_works_ends_setup_with_a_hint(self):
76        out = []
77        with mock.patch.object(setup, "fail", lambda msg, hint=None: out.append((msg, hint)) or (_ for _ in ()).throw(SystemExit(1))):
78            result, calls = self.run_with([1])
79        self.assertEqual((result, len(calls)), (1, 3))
80        self.assertIn("modelscope", out[0][1])
81
82    def test_the_source_reaches_the_fetch(self):
83        with mock.patch.object(setup, "model_source", lambda: "modelscope"):
84            _, calls = self.run_with([0])
85        self.assertEqual(calls[0][1]["STRATA_SOURCE"], "modelscope")
86
87
88class RunEndsWithSetup(unittest.TestCase):
89    def test_tools_are_told_to_end_when_setup_ends(self):
90        seen = {}
91
92        def fake_subprocess_run(cmd, **kw):
93            seen.update(kw)
94            return mock.Mock(returncode=0)
95        with mock.patch.object(setup.subprocess, "run", fake_subprocess_run), mock.patch.object(setup, "say", lambda *a, **k: None), \
96                mock.patch.object(setup.acquisition, "require", lambda *a, **k: None):
97            setup.run([sys.executable, "x.py"])
98            self.assertEqual(seen["env"]["STRATA_EXIT_WITH_PARENT"], "1")
99            self.assertIn("PATH", seen["env"] if os.name != "nt" else {k.upper(): v for k, v in seen["env"].items()})
100            setup.run([sys.executable, "x.py"], env={"B": "2", "STRATA_EXIT_WITH_PARENT": "0"})
101            self.assertEqual(seen["env"]["STRATA_EXIT_WITH_PARENT"], "0", "a value the caller set is kept")
102            self.assertEqual(seen["env"]["B"], "2")
103
104
105class GyroLowRam(U.Base):
106    def test_the_low_ram_pack_gets_compat_bf16_like_the_first_pack(self):
107        code, out, _ = self.main(["--family", "gyro", "--low-ram", "on", "--context", "8192"], m="Gyro-S", family=False, ram=31.9, version="0.1.45.1")
108        packs = [r for r in self.runs if any(x.endswith("iq_pack.py") for x in r)]
109        self.assertTrue(packs, (code, out[-1500:]))
110        self.assertTrue(all("--compat-bf16" in r for r in packs), packs)
111        self.assertTrue(any("--experts-bin" in r for r in packs), "the low-RAM pack ran")
112
113
114class Fp4LocalPackages(unittest.TestCase):
115    """#3227: torch, transformers and safetensors come from a pinned requirements file, right before a prepare that runs."""
116
117    def test_the_requirements_file_pins_what_the_converter_imports(self):
118        pkgs = setup.nvfp4_local_packages()
119        self.assertEqual(sorted({p.split("==")[0] for p in pkgs}), sorted(setup.NVFP4_LOCAL_MODULES))
120        self.assertTrue(all("==" in p for p in pkgs), pkgs)
121
122    def test_missing_packages_are_installed_once_with_the_pins(self):
123        calls = []
124        with mock.patch("importlib.util.find_spec", lambda name: None), mock.patch.object(setup, "CONTROL", False), \
125                mock.patch.object(setup, "say", lambda *a, **k: None), \
126                mock.patch.object(setup, "pip_install", lambda pkgs, what, extra=(): calls.append((list(pkgs), list(extra)))):
127            setup.ensure_nvfp4_local_packages()
128        self.assertEqual(len(calls), 1)
129        self.assertEqual(calls[0][0], setup.nvfp4_local_packages())
130        self.assertEqual(bool(calls[0][1]), not setup.WIN)               # the CPU wheel index only on Linux
131
132    def test_nothing_is_installed_when_they_are_there(self):
133        with mock.patch("importlib.util.find_spec", lambda name: object()), \
134                mock.patch.object(setup, "pip_install", side_effect=AssertionError("pip ran")):
135            setup.ensure_nvfp4_local_packages()
136
137    def test_the_app_says_so_instead_of_installing(self):
138        with mock.patch("importlib.util.find_spec", lambda name: None), mock.patch.object(setup, "CONTROL", True), \
139                mock.patch.object(setup, "say", lambda *a, **k: None), \
140                mock.patch.object(setup, "pip_install", side_effect=AssertionError("pip ran")), \
141                self.assertRaises(SystemExit):
142            setup.ensure_nvfp4_local_packages()
143
144    def test_the_tool_names_the_missing_package_when_run_by_hand(self):
145        import nvfp4_local_pack as P
146        with mock.patch("importlib.util.find_spec", lambda name: None if name == "transformers" else object()):
147            with self.assertRaises(SystemExit) as cm:
148                P.require_packages()
149        self.assertIn("transformers", str(cm.exception))
150        self.assertIn("requirements-nvfp4-local.txt", str(cm.exception))
151        self.assertNotIn("torch,", str(cm.exception))
152
153
154class Fp4LocalOrder(unittest.TestCase):
155    def test_the_packages_come_before_the_prepare_run(self):
156        import test_setup_golden as G
157        import test_setup_nvfp4 as N
158        events = []
159        with mock.patch.object(setup, "ensure_nvfp4_local_packages", lambda: events.append("packages")):
160            ram, found = G.PROFILES["128GB-1x24GB"]
161            _ = G.install(ram, found, ["--family", "nvfp4", "--no-start", "--model", "NVFP4-QAD"])
162        self.assertEqual(events, ["packages"])
163
164
165if __name__ == "__main__":
166    unittest.main()