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
7.1 KiB157 linesraw
1"""ModelScope as a download source (--source / STRATA_SOURCE): which source is used, the URL mapping, and that a file
2from ModelScope is checked against the SHA-256 ModelScope publishes (a wrong one is deleted).  No network: a local
3HTTP server plays ModelScope.
4
5    python -m unittest tools.test_setup_modelscope
6"""
7from __future__ import annotations
8
9import hashlib
10import http.server
11import json
12import os
13import sys
14import tempfile
15import threading
16import unittest
17from pathlib import Path
18from unittest import mock
19
20ROOT = Path(__file__).resolve().parents[1]
21sys.path.insert(0, str(ROOT))
22import setup  # noqa: E402
23
24REPO = "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"
25PATH = "Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"
26HF_URL = setup.hf(REPO) + PATH
27
28
29class Quiet(http.server.SimpleHTTPRequestHandler):
30    def log_message(self, *a):
31        pass
32
33
34class Base(unittest.TestCase):
35    def setUp(self):
36        for name in ("say", "ok", "warn"):
37            p = mock.patch.object(setup, name, lambda *a, **k: None)
38            p.start()
39            self.addCleanup(p.stop)
40        env = mock.patch.dict(os.environ, {}, clear=False)
41        env.start()
42        self.addCleanup(env.stop)
43        for k in ("STRATA_SOURCE", "HF_ENDPOINT", "MODELSCOPE_ENDPOINT"):
44            os.environ.pop(k, None)
45        setup._sources.clear()
46        setup._ms_files.clear()
47        self.addCleanup(setup._sources.clear)
48
49
50class Source(Base):
51    def test_explicit(self):
52        for value, want in (("modelscope", "modelscope"), ("ms", "modelscope"), ("huggingface", "huggingface"),
53                            ("hf", "huggingface")):
54            setup._sources.clear()
55            os.environ["STRATA_SOURCE"] = value
56            self.assertEqual(setup.model_source(), want, value)
57
58    def test_auto_is_huggingface_and_never_asks_the_network(self):
59        """#908: setup does not switch hosts by itself, whatever answers."""
60        with mock.patch.object(setup, "reachable", side_effect=AssertionError("no probe")):
61            self.assertEqual(setup.model_source(), "huggingface")
62
63    def test_a_failed_download_recommends_modelscope(self):
64        self.assertIn("--source modelscope", setup.source_hint(HF_URL))
65        self.assertEqual(setup.source_hint("https://github.com/example/repo/archive/main.zip"), "")
66
67    def test_hf_endpoint_is_a_choice(self):
68        os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
69        with mock.patch.object(setup, "reachable", return_value=True) as r:
70            self.assertEqual(setup.model_source(), "huggingface")
71            r.assert_not_called()
72
73    def test_mapping(self):
74        self.assertEqual(setup.ms_file(HF_URL), (REPO, PATH))
75        self.assertEqual(setup.ms_url(REPO, PATH),
76                         "https://www.modelscope.cn/models/" + REPO + "/resolve/master/" + PATH)
77        self.assertIsNone(setup.ms_file("https://huggingface.co/someone/other/resolve/main/x.gguf"))
78        self.assertIsNone(setup.ms_file("https://github.com/example/repo/archive/main.zip"))
79
80
81class Download(Base):
82    """download() through a local server laid out as ModelScope: /models/<repo>/resolve/master/<path> and
83    /api/v1/models/<repo>/repo/files (the query string is ignored by the test server)."""
84
85    def setUp(self):
86        super().setUp()
87        self.tmp = tempfile.TemporaryDirectory()
88        self.addCleanup(self.tmp.cleanup)
89        self.www = Path(self.tmp.name) / "www"
90        self.data = os.urandom(300_000)
91        f = self.www / "models" / REPO / "resolve" / "master" / PATH
92        f.parent.mkdir(parents=True)
93        f.write_bytes(self.data)
94        self.server = http.server.ThreadingHTTPServer(
95            ("127.0.0.1", 0), lambda *a, **k: Quiet(*a, directory=str(self.www), **k))
96        threading.Thread(target=self.server.serve_forever, daemon=True).start()
97        self.addCleanup(self.server.server_close)
98        self.addCleanup(self.server.shutdown)
99        os.environ["MODELSCOPE_ENDPOINT"] = "http://127.0.0.1:%d" % self.server.server_address[1]
100        os.environ["STRATA_SOURCE"] = "modelscope"
101        self.dst = Path(self.tmp.name) / "out" / Path(PATH).name
102        # a file with no pin of its own (the hash ModelScope publishes is the check); the pinned case is below
103        pins = {**setup.REPO_PINS, REPO: {k: v for k, v in setup.REPO_PINS[REPO].items() if k != Path(PATH).name}}
104        patch = mock.patch.object(setup, "REPO_PINS", pins)
105        patch.start()
106        self.addCleanup(patch.stop)
107
108    def api(self, sha):
109        p = self.www / "api" / "v1" / "models" / REPO / "repo" / "files"
110        p.parent.mkdir(parents=True, exist_ok=True)
111        p.write_text(json.dumps({"Data": {"Files": [{"Path": PATH, "Size": len(self.data), "Sha256": sha}]}}))
112
113    def test_right_hash_is_kept(self):
114        sha = hashlib.sha256(self.data).hexdigest()
115        self.api(sha)
116        setup.download(HF_URL, self.dst)
117        self.assertEqual(self.dst.read_bytes(), self.data)
118        self.assertIn("sha256 " + sha, self.dst.with_name(self.dst.name + ".done").read_text())
119
120    def test_wrong_hash_is_deleted(self):
121        self.api("0" * 64)
122        with mock.patch.object(setup, "say"), self.assertRaises(SystemExit):
123            setup.download(HF_URL, self.dst)
124        self.assertFalse(self.dst.exists())
125        self.assertFalse(self.dst.with_name(self.dst.name + ".done").exists())
126
127    def test_no_hash_published(self):
128        setup.download(HF_URL, self.dst)              # no API file: the download is kept, as from Hugging Face
129        self.assertEqual(self.dst.read_bytes(), self.data)
130        self.assertTrue(self.dst.with_name(self.dst.name + ".done").exists())
131
132    def test_the_pin_decides_over_what_modelscope_publishes(self):
133        """A pinned file is checked against its fixed SHA-256 whatever the host says: ModelScope serves current files."""
134        sha = hashlib.sha256(self.data).hexdigest()
135        self.api(sha)                                  # ModelScope vouches for its own copy ...
136        pins = {**setup.REPO_PINS, REPO: {**setup.REPO_PINS[REPO], Path(PATH).name: (len(self.data), "1" * 64)}}
137        with mock.patch.object(setup, "REPO_PINS", pins), mock.patch.object(setup, "say"),                 self.assertRaises(SystemExit):         # ... but it is not the pinned file
138            setup.download(HF_URL, self.dst)
139        self.assertFalse(self.dst.exists())
140        pins[REPO][Path(PATH).name] = (len(self.data), sha)
141        with mock.patch.object(setup, "REPO_PINS", pins):
142            setup.download(HF_URL, self.dst)
143        self.assertIn("sha256 " + sha, self.dst.with_name(self.dst.name + ".done").read_text())
144
145    def test_falls_back_when_modelscope_is_silent(self):
146        calls = []
147        with mock.patch.object(setup, "reachable", return_value=False), \
148                mock.patch.object(setup.netpolicy, "urlopen",
149                                  side_effect=lambda req, timeout=0: calls.append(req.full_url) or (_ for _ in ()).throw(
150                                      OSError("offline"))), \
151                mock.patch.object(setup.time, "sleep"), self.assertRaises(SystemExit):
152            setup.download(HF_URL, self.dst)
153        self.assertTrue(calls and all(u == HF_URL for u in calls), calls[:2])
154
155
156if __name__ == "__main__":
157    unittest.main()