diff --git a/docs/INSTALL.md b/docs/INSTALL.md index fb1f32fd..13c32f42 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -265,5 +265,15 @@ point setup at them with `--gguf-dir`. To let setup download from a Hugging Face first (Windows: `set HF_ENDPOINT=https://hf-mirror.com`, Linux: `export HF_ENDPOINT=https://hf-mirror.com`): the same pinned revisions and checks apply, and the MTP draft layer comes from there too. +**From ModelScope (mainland China):** every repository setup downloads from (the GSQ-RCO models, Swift 1.5, the +Coder, Unsloth's files, and the original checkpoint the MTP draft layer is taken from) is on +[ModelScope](https://www.modelscope.cn) under the same name, with the same files. Setup never switches to it by +itself (a download that fails says how): use `--source modelscope` (`STRATA_SOURCE=modelscope`). ModelScope serves a +repository's current files (no pinned revision), so each file is checked against the SHA-256 ModelScope publishes for +it (self-attested: a changed upstream repository would carry its own hash), and the MTP tensors against the +pinned checkpoint's own hashes, as from Hugging Face; setup says so when you choose it. Measured on a PC in mainland +China on 2026-10-05: 11-14 MB/s; the Q2_0 and IQ3_S files matched their published SHA-256, and Q2_0's shard 1 matched +the copy from hf-mirror.com. + On Linux the same options go to `./setup.sh`. `START-HERE.bat --help` lists them all. The server's own settings (sharing the GPU with games, MCP tools, CORS, API keys, the API itself) are in the [details](DETAILS.md#using-it). diff --git a/setup.py b/setup.py index ed441d76..924f58bb 100644 --- a/setup.py +++ b/setup.py @@ -89,6 +89,78 @@ def hf_unpinned(url: str) -> str: return re.sub(r"^(https?://[^/]+/.+?/resolve/)[0-9a-f]{40}/", r"\1main/", url, count=1) +# ModelScope (www.modelscope.cn) hosts every repository above under the same name, with the same file paths and +# sizes, and is reachable from mainland China where huggingface.co often is not. It serves a repository's current +# files (no pinned revision), so a file from it is checked against the SHA-256 ModelScope publishes for it, and the +# MTP tensors against the pinned checkpoint's own hashes (tools/mtp_fetch.py). +# --source / STRATA_SOURCE: huggingface (what auto means), or modelscope: only when asked for (a different host +# serving current files, not our pinned revision: setup never switches to it by itself, it recommends it, #908). +MS_DEFAULT = "https://www.modelscope.cn" +SOURCES = ("auto", "modelscope", "huggingface") +HF_FILE = re.compile(r"^https?://[^/]+/(?P[^/]+/[^/]+)/resolve/[^/]+/(?P.+)$") +_sources = {} # model_source()'s answer per (STRATA_SOURCE, HF_ENDPOINT, host) +_ms_files = {} + + +def ms_endpoint() -> str: + return (os.environ.get("MODELSCOPE_ENDPOINT") or "").strip().rstrip("/") or MS_DEFAULT + + +def reachable(url: str, timeout: float = 5.0) -> bool: + """Whether `url` answers a HEAD request with success (2xx, after redirects) within `timeout` seconds.""" + try: + urllib.request.urlopen(urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"}), + timeout=timeout).close() + return True + except OSError: # HTTPError too: an error page is not the file + return False + + +def model_source() -> str: + """"modelscope" or "huggingface". ModelScope only when --source modelscope / STRATA_SOURCE=modelscope asks for it; + everything else (auto, a HF_ENDPOINT mirror chosen on purpose, #495) is Hugging Face. Setup does not switch hosts + by itself (#908): ModelScope serves a repository's current files, not our pinned revision.""" + want = (os.environ.get("STRATA_SOURCE") or "auto").strip().lower() + key = (want, os.environ.get("HF_ENDPOINT") or "", ms_endpoint()) + if key not in _sources: + _sources[key] = "modelscope" if want in ("ms", "modelscope") else "huggingface" + return _sources[key] + + +def source_hint(url: str) -> str: + """The recommendation that goes with a failed download from Hugging Face: ModelScope, by an explicit choice.""" + if "huggingface" in url or "hf-mirror" in url: + return ("; if huggingface.co does not reach you (mainland China), the same files are on ModelScope: run setup " + "with --source modelscope (docs/INSTALL.md)") + return "" + + +def ms_file(url: str): + """(repo, path) when `url` is a Hugging Face file of a repository setup knows (HF_REVISIONS), else None.""" + m = HF_FILE.match(url) + if m is None or m.group("repo") not in HF_REVISIONS: + return None + return m.group("repo"), m.group("path") + + +def ms_url(repo: str, path: str) -> str: + return f"{ms_endpoint()}/models/{repo}/resolve/master/{path}" + + +def ms_meta(repo: str, path: str): + """(size, sha256) ModelScope publishes for a file, or None when it cannot be asked.""" + if repo not in _ms_files: + try: + api = f"{ms_endpoint()}/api/v1/models/{repo}/repo/files?Recursive=true" + with urllib.request.urlopen(urllib.request.Request(api, headers={"User-Agent": "strata-setup"}), + timeout=60) as r: + files = json.loads(r.read())["Data"]["Files"] + _ms_files[repo] = {f["Path"]: (int(f.get("Size") or 0), (f.get("Sha256") or "").lower()) for f in files} + except (OSError, ValueError, KeyError, TypeError): + return None + return _ms_files[repo].get(path) + + HF = hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF") LLAMA_CPP_COMMIT = "3cf03257f219afbe7334045ff7c6a06ac68c627d" LLAMA_CPP_ZIP = f"https://github.com/ggml-org/llama.cpp/archive/{LLAMA_CPP_COMMIT}.zip" @@ -1209,6 +1281,13 @@ def download(url, dst: Path, what=None): mark(dst) ok(f"{what or dst.name} copied") return + ms = ms_file(url) if model_source() == "modelscope" else None + if ms is not None: + if reachable(ms_url(*ms), timeout=30): + url = ms_url(*ms) + else: + warn(f"{what or dst.name}: ModelScope does not answer; downloading it from {hf_endpoint()}") + ms = None part = dst.with_name(dst.name + ".part") total = 0 for attempt in range(5): @@ -1223,11 +1302,13 @@ def download(url, dst: Path, what=None): url = hf_unpinned(url) continue if attempt == 4: - fail(f"cannot reach {url.split('/')[2]} ({e})", "check your internet connection and run it again") + fail(f"cannot reach {url.split('/')[2]} ({e})", + "check your internet connection and run it again" + source_hint(url)) time.sleep(5) except OSError as e: if attempt == 4: - fail(f"cannot reach {url.split('/')[2]} ({e})", "check your internet connection and run it again") + fail(f"cannot reach {url.split('/')[2]} ({e})", + "check your internet connection and run it again" + source_hint(url)) time.sleep(5) if dst.exists() and total and dst.stat().st_size == total: # finished by an older setup (no mark yet) mark(dst) @@ -1267,7 +1348,13 @@ def download(url, dst: Path, what=None): fail(f"could not finish downloading {dst.name}: {part.stat().st_size:,} bytes on disk, the server says {total:,}", "check your internet connection and run it again (the download resumes where it stopped)") part.replace(dst) - mark(dst) + meta = ms_meta(*ms) if ms is not None else None + if meta is not None and meta[1]: + verify_sha256(dst, meta[0], meta[1]) # ModelScope's published hash; kept in the finish mark + else: + if ms is not None: + warn(f"{what or dst.name}: ModelScope publishes no SHA-256 for it: the file is not verified") + mark(dst) ok(f"{what or dst.name} downloaded") @@ -4133,6 +4220,10 @@ def main() -> int: ap.add_argument("--rollback-engine", action="store_true", help="put back the engine an update replaced (kept in engine/.previous), and keep the current one there") ap.add_argument("--build", action="store_true", help="compile the engine instead of using the ready-made one") + ap.add_argument("--source", choices=SOURCES, default=None, + help="where the model files come from: auto (default: Hugging Face), huggingface or modelscope " + "(mainland China: the same files, checked against ModelScope's published SHA-256; " + "STRATA_SOURCE)") ap.add_argument("--cuda", choices=["12", "13", "auto"], default=os.environ.get("STRATA_CUDA") or None, help="NVIDIA: the CUDA toolkit of this model's engine. auto (default): CUDA 13, the ready-made " "engine; CUDA 12 (experimental) when a chosen card is older than CUDA 13 supports (Pascal, " @@ -4170,6 +4261,8 @@ def main() -> int: "sycl = Intel Arc, EXPERIMENTAL: Linux, built from source (docs/INTEL_ARC.md)") ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) a = ap.parse_args() + if a.source: + os.environ["STRATA_SOURCE"] = a.source if a.backend == "sycl": # Intel Arc: the SYCL port's own setup (sycl/setup_intel.py) return sycl_setup(sys.argv[1:]) if a.resident_budget_gib is not None and not a.resident_budget_gib > 0: @@ -4743,7 +4836,12 @@ def main() -> int: say(f" The model files go in {models_dir}") say(f" Files you already have: put them here with their original names ({', '.join(missing)}), or use " "--gguf-dir .") - if hf_endpoint() != HF_DEFAULT: + if model_source() == "modelscope": + say(f" Downloading from ModelScope ({ms_endpoint()}); --source huggingface downloads from Hugging Face") + warn("ModelScope serves the repositories' current files, not the pinned revisions: each file is checked " + "against the SHA-256 ModelScope itself publishes (self-attested); the MTP tensors against the " + "pinned checkpoint's own hashes") + elif hf_endpoint() != HF_DEFAULT: say(f" Downloading from {hf_endpoint()} (HF_ENDPOINT)") for s in shards: if s.exists() and done(s): @@ -4811,7 +4909,8 @@ def main() -> int: if corrupt or not (rt / "experts.bin").exists(): say(" The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:") say(" only its ~5 GB of MTP tensors are downloaded.") - run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "fetch", "--out", str(mtp)], env=env) + run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "fetch", "--out", str(mtp)], + env={**env, "STRATA_SOURCE": model_source()}) run([sys.executable, str(ROOT / "tools" / "mtp_pack.py"), "--src", str(mtp), "--experts", "q2_0", "--out", str(mtp / "mtp-q2_0.gguf")], env=env) run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], diff --git a/tools/mtp_fetch.py b/tools/mtp_fetch.py index eb1b7ce6..ea74b1c8 100644 --- a/tools/mtp_fetch.py +++ b/tools/mtp_fetch.py @@ -35,6 +35,12 @@ REVISION = os.environ.get("STRATA_MTP_REVISION") or PINNED_REVISION HF_ENDPOINT = (os.environ.get("HF_ENDPOINT") or "").strip().rstrip("/") or "https://huggingface.co" REPO = HF_ENDPOINT + "/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % REVISION PINNED = HF_ENDPOINT + "/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % PINNED_REVISION # SHA256's revision +# STRATA_SOURCE=modelscope (setup's --source): the same checkpoint from ModelScope. It serves the repository's current +# files, not a pinned revision, so REPO and PINNED are one URL here: every tensor is still checked against the pinned +# revision's SHA256 below, so a tensor that differs from it is caught, not used. +if (os.environ.get("STRATA_SOURCE") or "").strip().lower() in ("ms", "modelscope"): + MS_ENDPOINT = (os.environ.get("MODELSCOPE_ENDPOINT") or "").strip().rstrip("/") or "https://www.modelscope.cn" + REPO = PINNED = MS_ENDPOINT + "/models/Qwen/Qwen3.8-Flash-Next/resolve/master/" DTYPE_BYTES = {"BF16": 2, "F16": 2, "F32": 4, "F8_E4M3": 1, "I64": 8, "I32": 4} BAD = 3 # `verify`'s exit code: a tensor is missing or corrupt diff --git a/tools/test_setup_modelscope.py b/tools/test_setup_modelscope.py new file mode 100644 index 00000000..cf1cdf23 --- /dev/null +++ b/tools/test_setup_modelscope.py @@ -0,0 +1,139 @@ +"""ModelScope as a download source (--source / STRATA_SOURCE): which source is used, the URL mapping, and that a file +from ModelScope is checked against the SHA-256 ModelScope publishes (a wrong one is deleted). No network: a local +HTTP server plays ModelScope. + + python -m unittest tools.test_setup_modelscope +""" +from __future__ import annotations + +import hashlib +import http.server +import json +import os +import sys +import tempfile +import threading +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + +REPO = "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" +PATH = "Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" +HF_URL = setup.hf(REPO) + PATH + + +class Quiet(http.server.SimpleHTTPRequestHandler): + def log_message(self, *a): + pass + + +class Base(unittest.TestCase): + def setUp(self): + for name in ("say", "ok", "warn"): + p = mock.patch.object(setup, name, lambda *a, **k: None) + p.start() + self.addCleanup(p.stop) + env = mock.patch.dict(os.environ, {}, clear=False) + env.start() + self.addCleanup(env.stop) + for k in ("STRATA_SOURCE", "HF_ENDPOINT", "MODELSCOPE_ENDPOINT"): + os.environ.pop(k, None) + setup._sources.clear() + setup._ms_files.clear() + self.addCleanup(setup._sources.clear) + + +class Source(Base): + def test_explicit(self): + for value, want in (("modelscope", "modelscope"), ("ms", "modelscope"), ("huggingface", "huggingface"), + ("hf", "huggingface")): + setup._sources.clear() + os.environ["STRATA_SOURCE"] = value + self.assertEqual(setup.model_source(), want, value) + + def test_auto_is_huggingface_and_never_asks_the_network(self): + """#908: setup does not switch hosts by itself, whatever answers.""" + with mock.patch.object(setup, "reachable", side_effect=AssertionError("no probe")): + self.assertEqual(setup.model_source(), "huggingface") + + def test_a_failed_download_recommends_modelscope(self): + self.assertIn("--source modelscope", setup.source_hint(HF_URL)) + self.assertEqual(setup.source_hint(setup.LLAMA_CPP_ZIP), "") + + def test_hf_endpoint_is_a_choice(self): + os.environ["HF_ENDPOINT"] = "https://hf-mirror.com" + with mock.patch.object(setup, "reachable", return_value=True) as r: + self.assertEqual(setup.model_source(), "huggingface") + r.assert_not_called() + + def test_mapping(self): + self.assertEqual(setup.ms_file(HF_URL), (REPO, PATH)) + self.assertEqual(setup.ms_url(REPO, PATH), + "https://www.modelscope.cn/models/" + REPO + "/resolve/master/" + PATH) + self.assertIsNone(setup.ms_file("https://huggingface.co/someone/other/resolve/main/x.gguf")) + self.assertIsNone(setup.ms_file(setup.LLAMA_CPP_ZIP)) + + +class Download(Base): + """download() through a local server laid out as ModelScope: /models//resolve/master/ and + /api/v1/models//repo/files (the query string is ignored by the test server).""" + + def setUp(self): + super().setUp() + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.www = Path(self.tmp.name) / "www" + self.data = os.urandom(300_000) + f = self.www / "models" / REPO / "resolve" / "master" / PATH + f.parent.mkdir(parents=True) + f.write_bytes(self.data) + self.server = http.server.ThreadingHTTPServer( + ("127.0.0.1", 0), lambda *a, **k: Quiet(*a, directory=str(self.www), **k)) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + os.environ["MODELSCOPE_ENDPOINT"] = "http://127.0.0.1:%d" % self.server.server_address[1] + os.environ["STRATA_SOURCE"] = "modelscope" + self.dst = Path(self.tmp.name) / "out" / Path(PATH).name + + def api(self, sha): + p = self.www / "api" / "v1" / "models" / REPO / "repo" / "files" + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(json.dumps({"Data": {"Files": [{"Path": PATH, "Size": len(self.data), "Sha256": sha}]}})) + + def test_right_hash_is_kept(self): + sha = hashlib.sha256(self.data).hexdigest() + self.api(sha) + setup.download(HF_URL, self.dst) + self.assertEqual(self.dst.read_bytes(), self.data) + self.assertIn("sha256 " + sha, self.dst.with_name(self.dst.name + ".done").read_text()) + + def test_wrong_hash_is_deleted(self): + self.api("0" * 64) + with mock.patch.object(setup, "say"), self.assertRaises(SystemExit): + setup.download(HF_URL, self.dst) + self.assertFalse(self.dst.exists()) + self.assertFalse(self.dst.with_name(self.dst.name + ".done").exists()) + + def test_no_hash_published(self): + setup.download(HF_URL, self.dst) # no API file: the download is kept, as from Hugging Face + self.assertEqual(self.dst.read_bytes(), self.data) + self.assertTrue(self.dst.with_name(self.dst.name + ".done").exists()) + + def test_falls_back_when_modelscope_is_silent(self): + calls = [] + with mock.patch.object(setup, "reachable", return_value=False), \ + mock.patch.object(setup.urllib.request, "urlopen", + side_effect=lambda req, timeout=0: calls.append(req.full_url) or (_ for _ in ()).throw( + OSError("offline"))), \ + mock.patch.object(setup.time, "sleep"), self.assertRaises(SystemExit): + setup.download(HF_URL, self.dst) + self.assertTrue(calls and all(u == HF_URL for u in calls), calls[:2]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_pins.py b/tools/test_setup_pins.py index 2d8a08af..bdcafb73 100644 --- a/tools/test_setup_pins.py +++ b/tools/test_setup_pins.py @@ -73,7 +73,9 @@ class HuggingFacePins(unittest.TestCase): raise not_found(req.full_url) return Response(b"model bytes", status=200) - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen): + # the pinned Hugging Face path itself (setup's --source huggingface; auto may pick ModelScope) + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ + mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface"}): dst = Path(d) / "m.gguf" _, out = quiet(setup.download, setup.FAMILIES["qwen"]["mmproj_hf"] + "m.gguf", dst) self.assertEqual(dst.read_bytes(), b"model bytes")