diff --git a/setup.py b/setup.py index eac1f554..d8e112f8 100644 --- a/setup.py +++ b/setup.py @@ -597,6 +597,13 @@ def free_gb(path): # ------------------------------------------------------------------------------------------------ downloads +def drop_archive(z: Path) -> None: + """An unpacked or refused engine archive and its .done mark go: a refused one kept them, and every later run + reused it ("already downloaded") instead of the published one (PR #324).""" + z.unlink(missing_ok=True) + z.with_name(z.name + ".done").unlink(missing_ok=True) + + def download(url, dst: Path, what=None): """Resumable HTTP(S) download with a progress line; `file://` and plain paths are copied (tests, mirrors). A finished file gets a .done mark, so a later run skips it without asking the server.""" @@ -1083,6 +1090,7 @@ def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None: warn(f"the ready-made engine at {base} is version {meta.get('version')}; this setup needs " f"{need}: compiling instead") shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) return None archs = [int(a) for a in meta.get("archs", [])] miss = [int(x) for x in gpu.get("archs", [gpu["arch"]]) @@ -1091,6 +1099,7 @@ def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None: warn(f"the ready-made engine is built for {', '.join(str(a) for a in archs)}; your GPU is " f"{', '.join(str(x) for x in miss)}" + ("" if updating else ": compiling instead")) shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) return None for p in tmp.iterdir(): dst = eng / p.name @@ -1098,8 +1107,7 @@ def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None: shutil.rmtree(dst) if dst.is_dir() else dst.unlink() p.replace(dst) shutil.rmtree(tmp, ignore_errors=True) - z.unlink(missing_ok=True) - z.with_name(z.name + ".done").unlink(missing_ok=True) + drop_archive(z) if not (eng / EXE).exists(): fail("the ready-made engine archive has no " + EXE) if not WIN: @@ -1814,6 +1822,17 @@ OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced959 DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin"} +def mtp_corrupt(mtp: Path, env=None) -> bool: + """#327: True when the MTP tensors an install fetched are not the pinned checkpoint's (tools/mtp_fetch.py verify, + which hashes only files that changed since they last checked out). A mirror that ignored range requests left the + shards' starts there instead, and the draft layer built from them accepted nothing - with no error anywhere.""" + if not (mtp / "tensors").is_dir(): + return False + r = subprocess.run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "verify", "--out", str(mtp)], env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + return r.returncode == 3 + + def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137) or `en` (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster). @@ -2381,7 +2400,11 @@ def main() -> int: ok(f"model prepared: {pack}") mtp = (find_in(roots, "mtp/rt/experts.bin") or data / "mtp/rt/experts.bin").parent.parent rt = mtp / "rt" - if not (rt / "experts.bin").exists(): + corrupt = (rt / "experts.bin").exists() and mtp_corrupt(mtp, env) + if corrupt: + warn("some MTP tensors are not the checkpoint's (a download mirror that ignored range requests, #327): " + "fetching them again and rebuilding the draft layer") + 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) diff --git a/tools/mtp_fetch.py b/tools/mtp_fetch.py index b5454fe6..1893e607 100644 --- a/tools/mtp_fetch.py +++ b/tools/mtp_fetch.py @@ -6,9 +6,15 @@ at the start of each shard, so HTTP range requests can read the headers and then python tools/mtp_fetch.py inventory --out DIR # headers only (a few KB per shard) python tools/mtp_fetch.py fetch --out DIR [--only SUBSTR] # the MTP tensors themselves, resumable + python tools/mtp_fetch.py verify --out DIR # the fetched tensors against SHA256 (exit 3: bad ones) `fetch` writes one raw file per tensor plus `mtp-manifest.json` (dtype, shape, source shard, byte range, sha256). It never downloads anything but the ranges named in the headers. Nothing here runs a model. + +#327: a mirror or proxy that ignores the Range header answers 200 with the whole shard - its JSON header and +unrelated tensors - and a proxy may cut that to the requested length, so neither the size nor a hash of what was +downloaded catches it (the drafter then accepts nothing, silently). A range read therefore needs a 206 whose +Content-Range is the range asked for, and every tensor of the pinned revision is checked against SHA256 below. """ import argparse import hashlib @@ -23,9 +29,80 @@ import urllib.request # #214: a fixed commit of the checkpoint (its `sha` from https://huggingface.co/api/models/Qwen/Qwen3.8-Flash-Next # on 2026-09-30), so every install reads the same tensors; STRATA_MTP_REVISION overrides it (e.g. main). When the # repository no longer has it, the current files are read instead, with a message (resolve_repo). -REVISION = os.environ.get("STRATA_MTP_REVISION") or "de4b8e4d43b917e7706784d8bb445c9af86a3540" +PINNED_REVISION = "de4b8e4d43b917e7706784d8bb445c9af86a3540" +REVISION = os.environ.get("STRATA_MTP_REVISION") or PINNED_REVISION REPO = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % REVISION +PINNED = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % PINNED_REVISION # SHA256's revision 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 + +# #327: sha256 of every MTP tensor's bytes at PINNED_REVISION (two independent fetches agree, and 29 of them were read +# again from that revision; the two expert tensors' first and last 16 MiB), so a mirror that ignored the +# Range header (it sent the shard's start: its JSON header) is caught, and an install it corrupted is fetched again. +SHA256 = { + "mtp.fc_embedding.weight": + "241d6e87ded317a61b1aeb3ca4e28c53f1caba09ad5be66092e91fe5e3e14751", + "mtp.fc_hidden.weight": + "97c8e427ad0177e2c713ed24a397d815b523eda15ef453f1ae6463f6c70a8f96", + "mtp.hyper_connection_mixer.hc_norm.weight": + "ce948a398e15aeaa403c424cda34e6eed296ab2570d591bb5ff3da642b255d64", + "mtp.hyper_connection_mixer.input_mix_weight_down.weight": + "c633d2841fda463e82045e0b93fb8cb8d511ec0c9eda616020f01aca18d71947", + "mtp.hyper_connection_mixer.input_mix_weight_up.weight": + "6565285f0ba2923703252763cfc11d8a9bda40ab42e7548e12464b04dbdbec13", + "mtp.layers.0.attn_hyper_connection.block_inject_weight.weight": + "c8afff64e7f54412d02120097c4255033c55245e1c1eed84cc630d428ccb864c", + "mtp.layers.0.attn_hyper_connection.hc_norm.weight": + "1fb619aeaaf637ccd70f46f1f8f8116e6a46448cb43026b246de8ee8286ed809", + "mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight": + "e80ac8bf3e270e9d5a949ec7c913329dc8de017d69851334820fae7b8c86a7f5", + "mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight": + "f80f1fd44e1183e7764ea496b11ff89ead9dd758f861d4e79a770bf54956b1a5", + "mtp.layers.0.mlp.experts.down_proj": + "539c46234f73bac70450f731f40e715f77ac32faf77def0f3f800e58aaabbbc0", + "mtp.layers.0.mlp.experts.gate_up_proj": + "839e98f9642ebc884b178abd2090b6dc8b0bcd81ed92d7f7a08314c6a68f96d5", + "mtp.layers.0.mlp.gate.weight": + "f0d35fa41b360a08bc0c5b1e5766aa42df960291716ee189208b5d2599462c20", + "mtp.layers.0.mlp.shared_expert.down_proj.weight": + "d2ced8c81367cc494599d1a8cdc279c3dd6579b628ded05acd7495e99cee01d8", + "mtp.layers.0.mlp.shared_expert.gate_proj.weight": + "f4a81109165853b3b64f36d809f98094b599763364070f5fa079200e1c386d4c", + "mtp.layers.0.mlp.shared_expert.up_proj.weight": + "172586861eea53efbff10afc43ded5b6e49c83879e9efc01e089c652bbb0a156", + "mtp.layers.0.mlp.shared_expert_gate.weight": + "acdd306d9996d356e4667a16ff63af6fef086fc7f570f1bc00bbe882a2a93f6e", + "mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight": + "c5782dd92b479a1f8ef43d683fe9c917fd9e8fba81f23c1aae8817bfe4b476a6", + "mtp.layers.0.mlp_hyper_connection.hc_norm.weight": + "21a504876b5e7b788301557c68dfb757999430eba36c66ec8ab96a63604dbfd1", + "mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight": + "b71240036dea954e034d5ae04e097bcd7ac51cb28a44e4c93d198af3447278a1", + "mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight": + "40756866bf2a5e82c28e407f717b6fa07614d593f78e79c7ceb2cd4ffe6dda94", + "mtp.layers.0.self_attn.indexer.index_qk_proj.weight": + "2befafae6e944c1fc651fd73d4d527eb6f138a6c1679065b003128ee3150e859", + "mtp.layers.0.self_attn.indexer.k_layernorm.weight": + "2db621f6a08b4085756fc69d60a4a1bd1d7fbf5d406456d2477075842efaae54", + "mtp.layers.0.self_attn.indexer.q_layernorm.weight": + "afaf59f68e251939970ffdeacad0667dffc657a522bea62cdc44a52816fc49d6", + "mtp.layers.0.self_attn.k_norm.weight": + "8f924b0357cf936e14fc34518205d000e1423aa60626827df81b0804fae8cdfd", + "mtp.layers.0.self_attn.k_proj.weight": + "1a295dc2d6e633e808aeb19e00c97856a1817bbfcc83f5b610e2bfcacfcb8c38", + "mtp.layers.0.self_attn.o_proj.weight": + "9d2fcf0ac6ac19de87f638f710cfd1af6ad14141e75b7d3d5d29fbd06f374219", + "mtp.layers.0.self_attn.q_norm.weight": + "57957aa1e7c5a3ac628bff0ec5522ad55a39b8c0b8bd2d324ae640e3771617ef", + "mtp.layers.0.self_attn.q_proj.weight": + "5220aef3d288f40759f7356af9ef453e5ac0256a38749a9bb803a4e9db58150d", + "mtp.layers.0.self_attn.v_proj.weight": + "39cb12f5424e965fa71fb81db0ee230c701b7b1e0b72c36641fde7e0e41bff41", + "mtp.pre_fc_norm_embedding.weight": + "04c4a570850e06f2d8913da8220d54d4c7f87db6eb6d45480b938e8ba41d6a86", + "mtp.pre_fc_norm_hidden.weight": + "b933b44559879449b1baf2af8385c5c237347307e3fd452394870cb53e6eab6d", +} def get(url, start=None, end=None, retries=4): @@ -35,6 +112,8 @@ def get(url, start=None, end=None, retries=4): if start is not None: req.add_header("Range", "bytes=%d-%d" % (start, end)) with urllib.request.urlopen(req, timeout=120) as r: + if start is not None: + check_range(r.status, r.headers.get("Content-Range"), start, end) data = r.read() if start is not None and len(data) != end - start + 1: raise IOError("short range read: %d of %d" % (len(data), end - start + 1)) @@ -46,6 +125,29 @@ def get(url, start=None, end=None, retries=4): print("retry %s: %s" % (url, e), file=sys.stderr) +def check_range(status, content_range, start, end): + """#327: a range read is only what was asked for when the server says so: 206 and `bytes START-END/...`.""" + if status != 206: + raise IOError("range request not honoured: HTTP %s instead of 206 (a mirror or proxy that ignores the Range " + "header sends the whole file)" % status) + want = "bytes %d-%d/" % (start, end) + if not (content_range or "").strip().startswith(want): + raise IOError("range request answered with Content-Range %r, not %s..." % (content_range, want)) + + +def pinned(): + """The tensors' hashes are the pinned revision's: they apply when this run reads that revision.""" + return REPO == PINNED + + +def sha256_of(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 24), b""): + h.update(block) + return h.hexdigest() + + def resolve_repo(): """REPO, or the repository's current files when the pinned revision is gone from it (a 404 on its index).""" global REPO @@ -102,8 +204,18 @@ def inventory(out): def fetch(out, only): inv_path = os.path.join(out, "mtp-inventory.json") - rows = json.load(open(inv_path))["tensors"] if os.path.exists(inv_path) else inventory(out) tdir = os.path.join(out, "tensors") + inv = None + if os.path.exists(inv_path): + try: + with open(inv_path, encoding="utf-8") as f: + inv = json.load(f) + except ValueError: + inv = None + # The byte ranges belong to one revision: an inventory read from another repository or revision is read again, + # and a tensor fetched from there is not resumed - it is kept only when it is the pinned revision's (sha256). + same = isinstance(inv, dict) and inv.get("repo") == REPO + rows = inv["tensors"] if same else inventory(out) os.makedirs(tdir, exist_ok=True) manifest = [] chunk = 64 << 20 @@ -111,31 +223,81 @@ def fetch(out, only): if only and only not in r["name"]: continue path = os.path.join(tdir, r["name"] + ".bin") - have = os.path.getsize(path) if os.path.exists(path) else 0 - with open(path, "ab") as f: - pos = r["start"] + have - while pos <= r["end"]: - end = min(pos + chunk - 1, r["end"]) - f.write(get(REPO + r["shard"], pos, end)) - pos = end + 1 - print("%s %.0f%%" % (r["name"], 100 * (pos - r["start"]) / r["bytes"]), file=sys.stderr) - h = hashlib.sha256() - with open(path, "rb") as f: - for block in iter(lambda: f.read(1 << 24), b""): - h.update(block) - if os.path.getsize(path) != r["bytes"]: - sys.exit("%s: size %d != %d" % (path, os.path.getsize(path), r["bytes"])) - manifest.append(dict(r, file=os.path.relpath(path, out), sha256=h.hexdigest())) + want = SHA256.get(r["name"]) if pinned() else None + if os.path.exists(path) and not same and ( + want is None or os.path.getsize(path) != r["bytes"] or sha256_of(path) != want): + os.remove(path) + for attempt in range(2): + have = os.path.getsize(path) if os.path.exists(path) else 0 + if have > r["bytes"]: + os.remove(path) + have = 0 + with open(path, "ab") as f: + pos = r["start"] + have + while pos <= r["end"]: + end = min(pos + chunk - 1, r["end"]) + f.write(get(REPO + r["shard"], pos, end)) + pos = end + 1 + print("%s %.0f%%" % (r["name"], 100 * (pos - r["start"]) / r["bytes"]), file=sys.stderr) + if os.path.getsize(path) != r["bytes"]: + sys.exit("%s: size %d != %d" % (path, os.path.getsize(path), r["bytes"])) + digest = sha256_of(path) + if want is None or digest == want: + break + os.remove(path) # wrong bytes (#327): the whole tensor again, once + if attempt: + sys.exit("%s: sha256 %s is not the checkpoint's %s - the download source sends wrong data (a mirror " + "that ignores Range requests?)" % (r["name"], digest, want)) + print("%s: wrong bytes (sha256 %s...), fetching it again" % (r["name"], digest[:12]), file=sys.stderr) + manifest.append(dict(r, file=os.path.relpath(path, out), sha256=digest)) with open(os.path.join(out, "mtp-manifest.json"), "w", encoding="utf-8") as f: json.dump(manifest, f, indent=1) +def verify(out): + """#327: the fetched tensors against SHA256 -> the names that are missing or wrong. [] when they are right, or + when there is nothing to check (no tensors/, or STRATA_MTP_REVISION names another revision). A tensor's verdict + is kept in tensors/verified.json by size and mtime, so a later run hashes only what changed.""" + tdir = os.path.join(out, "tensors") + if not pinned() or not os.path.isdir(tdir): + return [] + stamp_path = os.path.join(tdir, "verified.json") + try: + with open(stamp_path, encoding="utf-8") as f: + stamps = json.load(f) + except (OSError, ValueError): + stamps = {} + bad, good = [], {} + for name, want in sorted(SHA256.items()): + path = os.path.join(tdir, name + ".bin") + if not os.path.exists(path): + bad.append(name) + continue + st = os.stat(path) + key = [st.st_size, st.st_mtime_ns, want] + if stamps.get(name) != key and sha256_of(path) != want: + bad.append(name) + continue + good[name] = key + try: + with open(stamp_path, "w", encoding="utf-8") as f: + json.dump(good, f, indent=1) + except OSError: + pass + return bad + + def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("cmd", choices=["inventory", "fetch"]) + ap.add_argument("cmd", choices=["inventory", "fetch", "verify"]) ap.add_argument("--out", required=True) ap.add_argument("--only") a = ap.parse_args() + if a.cmd == "verify": # offline: the hashes are the pinned revision's + bad = verify(a.out) + for name in bad: + print("MTP tensor missing or corrupt: %s" % name, file=sys.stderr) + sys.exit(BAD if bad else 0) resolve_repo() inventory(a.out) if a.cmd == "inventory" else fetch(a.out, a.only) diff --git a/tools/test_mtp_fetch.py b/tools/test_mtp_fetch.py new file mode 100644 index 00000000..f6c442fa --- /dev/null +++ b/tools/test_mtp_fetch.py @@ -0,0 +1,201 @@ +"""Tests for tools/mtp_fetch.py (#327): a range read needs a 206 with the asked Content-Range, the pinned revision's +tensors are checked against their sha256 (a wrong one is fetched again; a corrupt install is found by `verify` and +setup fetches it again), and an inventory from another revision is read again. A fake checkpoint behind a mocked +urlopen - nothing is downloaded. + + python -m unittest tools.test_mtp_fetch +""" +from __future__ import annotations + +import contextlib +import hashlib +import io +import json +import os +import struct +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import mtp_fetch as M # noqa: E402 + + +def shard(tensors): + """A safetensors file: [u64 header length][JSON header][data].""" + header, data = {}, b"" + for name, blob in tensors: + header[name] = {"dtype": "BF16", "shape": [len(blob) // 2], "data_offsets": [len(data), len(data) + len(blob)]} + data += blob + h = json.dumps(header).encode() + return struct.pack("