okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
17.5 KiB384 linesraw
1"""Tests for tools/mtp_fetch.py (#327): a range read needs a 206 with the asked Content-Range, the pinned revision's
2tensors are checked against their sha256 (a wrong one is fetched again; a corrupt install is found by `verify` and
3setup fetches it again), and an inventory from another revision is read again.  A fake checkpoint behind a mocked
4urlopen - nothing is downloaded.
5
6    python -m unittest tools.test_mtp_fetch
7"""
8from __future__ import annotations
9
10import contextlib
11import hashlib
12import io
13import json
14import os
15import struct
16import sys
17import tempfile
18import unittest
19from pathlib import Path
20from unittest import mock
21
22ROOT = Path(__file__).resolve().parents[1]
23sys.path.insert(0, str(ROOT))
24sys.path.insert(0, str(ROOT / "tools"))
25import mtp_fetch as M  # noqa: E402
26
27
28def shard(tensors):
29    """A safetensors file: [u64 header length][JSON header][data]."""
30    header, data = {}, b""
31    for name, blob in tensors:
32        header[name] = {"dtype": "BF16", "shape": [len(blob) // 2], "data_offsets": [len(data), len(data) + len(blob)]}
33        data += blob
34    h = json.dumps(header).encode()
35    return struct.pack("<Q", len(h)) + h + data
36
37
38A, B, X = bytes(range(64)), bytes(range(100, 164)) * 2, b"\x07" * 48
39FILES = {"model-1.safetensors": shard([("model.x", X), ("mtp.a", A)]), "model-2.safetensors": shard([("mtp.b", B)])}
40INDEX = json.dumps({"weight_map": {"model.x": "model-1.safetensors", "mtp.a": "model-1.safetensors",
41                                   "mtp.b": "model-2.safetensors"}}).encode()
42HASHES = {"mtp.a": hashlib.sha256(A).hexdigest(), "mtp.b": hashlib.sha256(B).hexdigest()}
43
44
45class Response(io.BytesIO):
46    def __init__(self, body, status, headers):
47        super().__init__(body)
48        self.status, self.headers = status, headers
49
50    def __enter__(self):
51        return self
52
53    def __exit__(self, *exc):
54        self.close()
55
56
57class Mirror:
58    """urlopen for the fake checkpoint.  `ignore_range`: 200 and the whole file (`cut`: cut to the asked length, as
59    the proxy in #327 did); `wrong`: the bytes of these tensors' ranges are flipped (a source that sends bad data)."""
60
61    def __init__(self, ignore_range=False, cut=False, wrong=()):
62        self.ignore_range, self.cut, self.wrong, self.ranges = ignore_range, cut, set(wrong), []
63
64    def __call__(self, req, timeout=None):
65        name = req.full_url.rsplit("/", 1)[1]
66        body = INDEX if name == "model.safetensors.index.json" else FILES[name]
67        rng = req.get_header("Range")
68        if rng is None:
69            return Response(body, 200, {"Content-Length": str(len(body))})
70        a, b = map(int, rng.split("=")[1].split("-"))
71        self.ranges.append((name, a, b))
72        if self.ignore_range:
73            return Response(body[:b - a + 1] if self.cut else body, 200, {})
74        part = body[a:b + 1]
75        if any(t in self.wrong and self.span(name, t) == (a, b) for t in ("mtp.a", "mtp.b")):
76            part = bytes(x ^ 0xFF for x in part)
77        return Response(part, 206, {"Content-Range": "bytes %d-%d/%d" % (a, b, len(body))})
78
79    @staticmethod
80    def span(name, tensor):
81        raw = FILES[name]
82        n = struct.unpack("<Q", raw[:8])[0]
83        meta = json.loads(raw[8:8 + n]).get(tensor)
84        return (8 + n + meta["data_offsets"][0], 8 + n + meta["data_offsets"][1] - 1) if meta else None
85
86
87class FetchCase(unittest.TestCase):
88    def setUp(self):
89        self.tmp = tempfile.TemporaryDirectory()
90        self.out = Path(self.tmp.name)
91        self.patches = [mock.patch.object(M, "SHA256", HASHES), mock.patch.object(M.time, "sleep", lambda s: None),
92                        mock.patch.object(M, "REPO", M.PINNED)]
93        for p in self.patches:
94            p.start()
95
96    def tearDown(self):
97        for p in reversed(self.patches):
98            p.stop()
99        self.tmp.cleanup()
100
101    def fetch(self, mirror):
102        with mock.patch.object(M.netpolicy, "urlopen", mirror), contextlib.redirect_stdout(io.StringIO()), \
103                contextlib.redirect_stderr(io.StringIO()) as err:
104            M.fetch(str(self.out), None)
105        return err.getvalue()
106
107    def tensor(self, name):
108        return (self.out / "tensors" / (name + ".bin")).read_bytes()
109
110
111class Ranges(FetchCase):
112    def test_check_range(self):
113        M.check_range(206, "bytes 10-19/100", 10, 19)
114        for status, cr in ((200, None), (200, "bytes 10-19/100"), (206, "bytes 0-9/100"), (206, None)):
115            with self.subTest(status=status, cr=cr), self.assertRaises(IOError):
116                M.check_range(status, cr, 10, 19)
117
118    def test_a_mirror_that_ignores_range_is_refused(self):
119        for cut in (False, True):                 # the whole file, or cut to the asked length (#327's proxy)
120            with self.subTest(cut=cut), mock.patch.object(M.netpolicy, "urlopen", Mirror(True, cut)), \
121                    contextlib.redirect_stderr(io.StringIO()), self.assertRaisesRegex(IOError, "not honoured"):
122                M.get(M.REPO + "model-1.safetensors", 8, 15)
123
124    def test_fetch_from_an_honest_mirror(self):
125        self.fetch(Mirror())
126        self.assertEqual((self.tensor("mtp.a"), self.tensor("mtp.b")), (A, B))
127        manifest = json.loads((self.out / "mtp-manifest.json").read_text())
128        self.assertEqual({r["name"]: r["sha256"] for r in manifest}, HASHES)
129        self.assertEqual(M.verify(str(self.out)), [])
130
131    def test_ranges_are_read_in_parallel_and_come_back_in_order(self):
132        data = bytes(range(256)) * 40
133        seen = []
134
135        def get(url, a, b):
136            seen.append((a, b))
137            return data[a:b + 1]
138
139        for workers in (1, 4, 32):
140            seen.clear()
141            with self.subTest(workers=workers), mock.patch.object(M, "get", get):
142                got = b"".join(M.ranged("u", 100, len(data) - 1, 1000, workers))
143            self.assertEqual(got, data[100:])
144            self.assertEqual(sorted(seen)[0], (100, 1099))
145        with mock.patch.dict(M.os.environ, {"STRATA_DL_CONNECTIONS": "1"}):
146            self.assertEqual(M.connections(), 1)
147        with mock.patch.dict(M.os.environ, {"STRATA_DL_CONNECTIONS": ""}):
148            self.assertEqual(M.connections(), 16)
149
150    def test_the_cdn_address_is_reused_and_forgotten_after_an_error(self):
151        """HF redirects /resolve/ to a signed CDN address: only the first range goes through the redirect (the rest of a
152        tensor's ranges use the CDN address), and any error makes the next try ask the original address again."""
153        asked = []
154
155        def opener(req, timeout=None):
156            asked.append(req.full_url)
157            a, b = (int(x) for x in req.headers["Range"].split("=")[1].split("-"))
158            r = Response(bytes(b - a + 1), 206, {"Content-Range": "bytes %d-%d/1000" % (a, b)})
159            r.geturl = lambda: "https://cdn.example/x?sig=1"
160            return r
161
162        M._cdn.clear()
163        with mock.patch.object(M.netpolicy, "urlopen", opener):
164            for a in (0, 100, 200):
165                M.get("https://hf.example/f", a, a + 99)
166            self.assertEqual(asked, ["https://hf.example/f"] + ["https://cdn.example/x?sig=1"] * 2)
167            asked.clear()
168            fails = [True]
169
170            def flaky(req, timeout=None):
171                if fails.pop() if fails else False:
172                    raise IOError("expired")
173                return opener(req, timeout)
174
175            with mock.patch.object(M.netpolicy, "urlopen", flaky), mock.patch.object(M.time, "sleep", lambda s: None),                     contextlib.redirect_stderr(io.StringIO()):
176                M.get("https://hf.example/f", 300, 399)
177            self.assertEqual(asked, ["https://hf.example/f"])               # the cached address failed: the original is asked again
178        M._cdn.clear()
179
180    def test_a_slow_first_range_does_not_stop_the_ones_behind_it(self):
181        import threading
182        gate = threading.Event()
183        started = []
184
185        def get(url, a, b):
186            started.append(a)
187            if a == 0:
188                gate.wait(5)
189            return bytes(b - a + 1)
190
191        def release():                                   # lets the first range go once the later ones have been started
192            for _ in range(200):
193                if len(started) >= 9:
194                    break
195                M.time.sleep(0.01)
196            gate.set()
197
198        threading.Thread(target=release, daemon=True).start()
199        with mock.patch.object(M, "get", get):
200            list(M.ranged("u", 0, 40 * 1000 - 1, 1000, 4))
201        self.assertGreaterEqual(len(started), 9)                           # four connections, nine ranges started before range 0 ended
202
203    def test_a_failing_range_stops_the_parallel_read(self):
204        def get(url, a, b):
205            if a >= 2000:
206                raise IOError("boom")
207            return bytes(b - a + 1)
208
209        with mock.patch.object(M, "get", get), self.assertRaises(IOError):
210            list(M.ranged("u", 0, 9999, 1000, 4))
211
212    def test_wrong_bytes_are_fetched_again_once_then_refused(self):
213        self.fetch(Mirror())
214        bad = bytes(len(A))                       # an install the #327 mirror corrupted: right size, wrong bytes
215        (self.out / "tensors" / "mtp.a.bin").write_bytes(bad)
216        self.assertEqual(M.verify(str(self.out)), ["mtp.a"])
217        err = self.fetch(Mirror())                # setup runs fetch again: the bad one is fetched again
218        self.assertIn("mtp.a: wrong bytes", err)
219        self.assertEqual(self.tensor("mtp.a"), A)
220        self.assertEqual(M.verify(str(self.out)), [])
221        os.remove(self.out / "tensors" / "mtp.b.bin")
222        with self.assertRaises(SystemExit) as cm:
223            self.fetch(Mirror(wrong={"mtp.b"}))     # a source that keeps sending wrong data
224        self.assertIn("is not the checkpoint's", str(cm.exception))
225        self.assertFalse((self.out / "tensors" / "mtp.b.bin").exists())
226
227    def test_an_inventory_from_another_revision_is_read_again(self):
228        self.fetch(Mirror())
229        inv = json.loads((self.out / "mtp-inventory.json").read_text())
230        inv["repo"] = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/"
231        for r in inv["tensors"]:
232            r["start"] += 1                        # that revision's ranges: not this one's
233            r["end"] += 1
234        (self.out / "mtp-inventory.json").write_text(json.dumps(inv))
235        (self.out / "tensors" / "mtp.b.bin").write_bytes(B[:10])     # half a tensor from that revision
236        mirror = Mirror()
237        self.fetch(mirror)
238        self.assertEqual(json.loads((self.out / "mtp-inventory.json").read_text())["repo"], M.REPO)
239        self.assertEqual((self.tensor("mtp.a"), self.tensor("mtp.b")), (A, B))
240        fetched = [r for r in mirror.ranges if r[2] - r[1] + 1 in (len(A), len(B))]
241        self.assertEqual(fetched, [("model-2.safetensors",) + Mirror.span("model-2.safetensors", "mtp.b")],
242                         "mtp.a was right and is kept; mtp.b is fetched whole")
243
244    def test_verify_keeps_its_verdict_and_skips_other_revisions(self):
245        self.fetch(Mirror())
246        self.assertEqual(M.verify(str(self.out)), [])
247        stamps = json.loads((self.out / "tensors" / "verified.json").read_text())
248        self.assertEqual(sorted(stamps), ["mtp.a", "mtp.b"])
249        with mock.patch.object(M, "sha256_of", side_effect=AssertionError("hashed an unchanged file")):
250            self.assertEqual(M.verify(str(self.out)), [])
251        with mock.patch.object(M, "REPO", "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/"):
252            (self.out / "tensors" / "mtp.a.bin").write_bytes(b"x")
253            self.assertEqual(M.verify(str(self.out)), [])          # STRATA_MTP_REVISION: other hashes
254        self.assertEqual(M.verify(str(self.out)), ["mtp.a"])
255        self.assertEqual(M.verify(str(self.out / "nothing")), [])
256
257
258class Pinned(unittest.TestCase):
259    def test_every_tensor_has_a_hash(self):
260        self.assertEqual(len(M.SHA256), 31)
261        for name, h in M.SHA256.items():
262            self.assertTrue(name.startswith("mtp."))
263            self.assertRegex(h, "^[0-9a-f]{64}$")
264        self.assertIn(M.PINNED_REVISION, M.PINNED)
265
266
267class Setup(unittest.TestCase):
268    def test_setup_rebuilds_a_corrupt_install(self):
269        import setup
270        with tempfile.TemporaryDirectory() as d:
271            mtp = Path(d)
272            self.assertFalse(setup.mtp_corrupt(mtp))              # no tensors kept: nothing to check
273            (mtp / "tensors").mkdir()
274            for code, want in ((0, False), (3, True), (1, False)):
275                with self.subTest(code=code), mock.patch.object(
276                        setup.subprocess, "run", return_value=mock.Mock(returncode=code)) as run:
277                    self.assertEqual(setup.mtp_corrupt(mtp), want)
278                    self.assertIn("verify", run.call_args[0][0])
279
280
281
282
283class Progress(FetchCase):
284    """#3257: the fetch says how far it is in the form of setup's own download line, so the app can show it."""
285
286    def test_progress_lines_name_the_whole_download_and_end_at_100(self):
287        err = self.fetch(Mirror())
288        lines = [x for x in err.splitlines() if "MTP draft layer:" in x]
289        total = len(A) + len(B)
290        self.assertTrue(lines)
291        self.assertIn("/ %.2f GB" % (total / 1e9), lines[-1])
292        self.assertIn("(100%)", lines[-1])
293        import re
294        for x in lines:                                  # the shape tools/strata_mcp.py install_progress reads
295            self.assertTrue(re.match(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)", x), x)
296
297    def test_a_resumed_fetch_starts_from_what_is_already_there(self):
298        self.fetch(Mirror())
299        err = self.fetch(Mirror())
300        self.assertIn("(100%)", [x for x in err.splitlines() if "MTP draft layer:" in x][0])
301
302    def test_the_progress_figure_follows_the_job_in_strata_mcp(self):
303        import strata_mcp as MCP
304        got = MCP.install_progress(["=== Step 6: preparing the model for Strata ===",
305                                    "  MTP draft layer:   1.23 / 5.04 GB (24%)"])
306        self.assertEqual(got["download"], {"file": "MTP draft layer", "done_gb": 1.23, "total_gb": 5.04, "percent": 24})
307
308
309class Flaky(FetchCase):
310    def test_a_connection_that_drops_mid_tensor_does_not_end_the_run(self):
311        """#3214: every range of the tensor fails past get()'s own retries once: the tensor is tried again (fewer connections)."""
312        honest, fails = Mirror(), [0]
313
314        def mirror(req, timeout=None):
315            if req.get_header("Range") and req.full_url.endswith("model-2.safetensors") and fails[0] < 12:
316                a, b = map(int, req.get_header("Range").split("=")[1].split("-"))
317                if (a, b) == Mirror.span("model-2.safetensors", "mtp.b"):
318                    fails[0] += 1
319                    raise IOError("timed out")
320            return honest(req, timeout)
321
322        err = self.fetch(mirror)
323        self.assertEqual(self.tensor("mtp.b"), B)
324        self.assertIn("continuing with", err)
325
326    def test_a_link_that_never_works_ends_with_a_plain_sentence(self):
327        def mirror(req, timeout=None):
328            if req.get_header("Range") and req.full_url.endswith("model-2.safetensors"):
329                a, b = map(int, req.get_header("Range").split("=")[1].split("-"))
330                if (a, b) == Mirror.span("model-2.safetensors", "mtp.b"):
331                    raise IOError("timed out")
332            return Mirror()(req, timeout)
333
334        with self.assertRaisesRegex(SystemExit, "keeps failing"):
335            self.fetch(mirror)
336
337
338class OneAtATime(unittest.TestCase):
339    def test_a_second_fetch_in_the_same_folder_waits_for_the_first(self):
340        with tempfile.TemporaryDirectory() as d:
341            first = M.lock_folder(d)
342            told = io.StringIO()
343            with mock.patch.object(M.time, "sleep", lambda s: None), contextlib.redirect_stderr(told), \
344                    self.assertRaisesRegex(SystemExit, "another MTP download"):
345                M.lock_folder(d, wait=0.0)
346            first.close()
347            M.lock_folder(d).close()                     # free again once the first ends
348
349    def test_a_download_ends_with_the_process_that_started_it(self):
350        """#3257: setup killed, its child must not go on: a grandchild whose parent is gone."""
351        import subprocess
352        import time
353        child_code = ("import sys,time; sys.path.insert(0, %r); import mtp_fetch as M; M.exit_with_parent(); "
354                      "print('up', flush=True); time.sleep(60)" % str(ROOT / "tools"))
355        parent_code = ("import subprocess,sys,os; env=dict(os.environ, STRATA_EXIT_WITH_PARENT='1'); "
356                       "p=subprocess.Popen([sys.executable,'-c',%r], env=env, stdout=subprocess.PIPE, text=True); "
357                       "print(p.pid, flush=True); p.stdout.readline(); print('ready', flush=True); sys.stdout.flush(); os._exit(0)" % child_code)
358        r = subprocess.Popen([sys.executable, "-c", parent_code], stdout=subprocess.PIPE, text=True)
359        pid = int(r.stdout.readline())
360        r.stdout.readline()
361        r.wait(30)
362        end = time.time() + 15
363        alive = True
364        while time.time() < end and alive:
365            time.sleep(0.5)
366            if os.name == "nt":
367                out = subprocess.run(["tasklist", "/FI", "PID eq %d" % pid], capture_output=True, text=True).stdout
368                alive = str(pid) in out
369            else:
370                try:
371                    os.kill(pid, 0)
372                    alive = True
373                except OSError:
374                    alive = False
375        if alive:
376            if os.name == "nt":
377                subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True)
378            else:
379                os.kill(pid, 9)
380        self.assertFalse(alive, "the download kept running after its parent ended")
381
382
383if __name__ == "__main__":
384    unittest.main()