mtp_fetch: a range read needs 206 + its Content-Range; pinned per-tensor sha256, corrupt installs fetched again (#327)
A mirror that ignores the Range header answers 200 with the shard's start (its JSON header); cut to the asked length it passed the size check and the manifest hashed the wrong bytes, so the drafter accepted nothing. get() now requires HTTP 206 with the requested Content-Range. The 31 MTP tensors' sha256 at the pinned revision (de4b8e4) ship in SHA256 (two independent fetches agree; 29 re-read from the revision, the two expert tensors' first/last 16 MiB): a wrong tensor is fetched again once, then refused. An inventory read from another repository/revision is read again and its tensors are kept only when they hash right. `mtp_fetch.py verify` (offline, cached by size/mtime) finds a corrupt install; setup then fetches the bad tensors again and rebuilds the draft layer. From PR #324: a refused engine archive no longer keeps its zip and .done mark. Tests: tools/test_mtp_fetch.py (fake checkpoint behind a mocked urlopen, a mirror that ignores Range), test_setup_pins (refused archive).
This commit is contained in:
1 parent
40eaa123d4
commit
75780af235
4 files changed
+427
-21
No files matched your search
@@ -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 <name>.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)
|
||||
|
||||
+180
-18
@@ -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)
|
||||
|
||||
|
||||
@@ -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("<Q", len(h)) + h + data
|
||||
|
||||
|
||||
A, B, X = bytes(range(64)), bytes(range(100, 164)) * 2, b"\x07" * 48
|
||||
FILES = {"model-1.safetensors": shard([("model.x", X), ("mtp.a", A)]), "model-2.safetensors": shard([("mtp.b", B)])}
|
||||
INDEX = json.dumps({"weight_map": {"model.x": "model-1.safetensors", "mtp.a": "model-1.safetensors",
|
||||
"mtp.b": "model-2.safetensors"}}).encode()
|
||||
HASHES = {"mtp.a": hashlib.sha256(A).hexdigest(), "mtp.b": hashlib.sha256(B).hexdigest()}
|
||||
|
||||
|
||||
class Response(io.BytesIO):
|
||||
def __init__(self, body, status, headers):
|
||||
super().__init__(body)
|
||||
self.status, self.headers = status, headers
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.close()
|
||||
|
||||
|
||||
class Mirror:
|
||||
"""urlopen for the fake checkpoint. `ignore_range`: 200 and the whole file (`cut`: cut to the asked length, as
|
||||
the proxy in #327 did); `wrong`: the bytes of these tensors' ranges are flipped (a source that sends bad data)."""
|
||||
|
||||
def __init__(self, ignore_range=False, cut=False, wrong=()):
|
||||
self.ignore_range, self.cut, self.wrong, self.ranges = ignore_range, cut, set(wrong), []
|
||||
|
||||
def __call__(self, req, timeout=None):
|
||||
name = req.full_url.rsplit("/", 1)[1]
|
||||
body = INDEX if name == "model.safetensors.index.json" else FILES[name]
|
||||
rng = req.get_header("Range")
|
||||
if rng is None:
|
||||
return Response(body, 200, {"Content-Length": str(len(body))})
|
||||
a, b = map(int, rng.split("=")[1].split("-"))
|
||||
self.ranges.append((name, a, b))
|
||||
if self.ignore_range:
|
||||
return Response(body[:b - a + 1] if self.cut else body, 200, {})
|
||||
part = body[a:b + 1]
|
||||
if any(t in self.wrong and self.span(name, t) == (a, b) for t in ("mtp.a", "mtp.b")):
|
||||
part = bytes(x ^ 0xFF for x in part)
|
||||
return Response(part, 206, {"Content-Range": "bytes %d-%d/%d" % (a, b, len(body))})
|
||||
|
||||
@staticmethod
|
||||
def span(name, tensor):
|
||||
raw = FILES[name]
|
||||
n = struct.unpack("<Q", raw[:8])[0]
|
||||
meta = json.loads(raw[8:8 + n]).get(tensor)
|
||||
return (8 + n + meta["data_offsets"][0], 8 + n + meta["data_offsets"][1] - 1) if meta else None
|
||||
|
||||
|
||||
class FetchCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.out = Path(self.tmp.name)
|
||||
self.patches = [mock.patch.object(M, "SHA256", HASHES), mock.patch.object(M.time, "sleep", lambda s: None),
|
||||
mock.patch.object(M, "REPO", M.PINNED)]
|
||||
for p in self.patches:
|
||||
p.start()
|
||||
|
||||
def tearDown(self):
|
||||
for p in reversed(self.patches):
|
||||
p.stop()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def fetch(self, mirror):
|
||||
with mock.patch.object(M.urllib.request, "urlopen", mirror), contextlib.redirect_stdout(io.StringIO()), \
|
||||
contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
M.fetch(str(self.out), None)
|
||||
return err.getvalue()
|
||||
|
||||
def tensor(self, name):
|
||||
return (self.out / "tensors" / (name + ".bin")).read_bytes()
|
||||
|
||||
|
||||
class Ranges(FetchCase):
|
||||
def test_check_range(self):
|
||||
M.check_range(206, "bytes 10-19/100", 10, 19)
|
||||
for status, cr in ((200, None), (200, "bytes 10-19/100"), (206, "bytes 0-9/100"), (206, None)):
|
||||
with self.subTest(status=status, cr=cr), self.assertRaises(IOError):
|
||||
M.check_range(status, cr, 10, 19)
|
||||
|
||||
def test_a_mirror_that_ignores_range_is_refused(self):
|
||||
for cut in (False, True): # the whole file, or cut to the asked length (#327's proxy)
|
||||
with self.subTest(cut=cut), mock.patch.object(M.urllib.request, "urlopen", Mirror(True, cut)), \
|
||||
contextlib.redirect_stderr(io.StringIO()), self.assertRaisesRegex(IOError, "not honoured"):
|
||||
M.get(M.REPO + "model-1.safetensors", 8, 15)
|
||||
|
||||
def test_fetch_from_an_honest_mirror(self):
|
||||
self.fetch(Mirror())
|
||||
self.assertEqual((self.tensor("mtp.a"), self.tensor("mtp.b")), (A, B))
|
||||
manifest = json.loads((self.out / "mtp-manifest.json").read_text())
|
||||
self.assertEqual({r["name"]: r["sha256"] for r in manifest}, HASHES)
|
||||
self.assertEqual(M.verify(str(self.out)), [])
|
||||
|
||||
def test_wrong_bytes_are_fetched_again_once_then_refused(self):
|
||||
self.fetch(Mirror())
|
||||
bad = bytes(len(A)) # an install the #327 mirror corrupted: right size, wrong bytes
|
||||
(self.out / "tensors" / "mtp.a.bin").write_bytes(bad)
|
||||
self.assertEqual(M.verify(str(self.out)), ["mtp.a"])
|
||||
err = self.fetch(Mirror()) # setup runs fetch again: the bad one is fetched again
|
||||
self.assertIn("mtp.a: wrong bytes", err)
|
||||
self.assertEqual(self.tensor("mtp.a"), A)
|
||||
self.assertEqual(M.verify(str(self.out)), [])
|
||||
os.remove(self.out / "tensors" / "mtp.b.bin")
|
||||
with self.assertRaises(SystemExit) as cm:
|
||||
self.fetch(Mirror(wrong={"mtp.b"})) # a source that keeps sending wrong data
|
||||
self.assertIn("is not the checkpoint's", str(cm.exception))
|
||||
self.assertFalse((self.out / "tensors" / "mtp.b.bin").exists())
|
||||
|
||||
def test_an_inventory_from_another_revision_is_read_again(self):
|
||||
self.fetch(Mirror())
|
||||
inv = json.loads((self.out / "mtp-inventory.json").read_text())
|
||||
inv["repo"] = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/"
|
||||
for r in inv["tensors"]:
|
||||
r["start"] += 1 # that revision's ranges: not this one's
|
||||
r["end"] += 1
|
||||
(self.out / "mtp-inventory.json").write_text(json.dumps(inv))
|
||||
(self.out / "tensors" / "mtp.b.bin").write_bytes(B[:10]) # half a tensor from that revision
|
||||
mirror = Mirror()
|
||||
self.fetch(mirror)
|
||||
self.assertEqual(json.loads((self.out / "mtp-inventory.json").read_text())["repo"], M.REPO)
|
||||
self.assertEqual((self.tensor("mtp.a"), self.tensor("mtp.b")), (A, B))
|
||||
fetched = [r for r in mirror.ranges if r[2] - r[1] + 1 in (len(A), len(B))]
|
||||
self.assertEqual(fetched, [("model-2.safetensors",) + Mirror.span("model-2.safetensors", "mtp.b")],
|
||||
"mtp.a was right and is kept; mtp.b is fetched whole")
|
||||
|
||||
def test_verify_keeps_its_verdict_and_skips_other_revisions(self):
|
||||
self.fetch(Mirror())
|
||||
self.assertEqual(M.verify(str(self.out)), [])
|
||||
stamps = json.loads((self.out / "tensors" / "verified.json").read_text())
|
||||
self.assertEqual(sorted(stamps), ["mtp.a", "mtp.b"])
|
||||
with mock.patch.object(M, "sha256_of", side_effect=AssertionError("hashed an unchanged file")):
|
||||
self.assertEqual(M.verify(str(self.out)), [])
|
||||
with mock.patch.object(M, "REPO", "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/"):
|
||||
(self.out / "tensors" / "mtp.a.bin").write_bytes(b"x")
|
||||
self.assertEqual(M.verify(str(self.out)), []) # STRATA_MTP_REVISION: other hashes
|
||||
self.assertEqual(M.verify(str(self.out)), ["mtp.a"])
|
||||
self.assertEqual(M.verify(str(self.out / "nothing")), [])
|
||||
|
||||
|
||||
class Pinned(unittest.TestCase):
|
||||
def test_every_tensor_has_a_hash(self):
|
||||
self.assertEqual(len(M.SHA256), 31)
|
||||
for name, h in M.SHA256.items():
|
||||
self.assertTrue(name.startswith("mtp."))
|
||||
self.assertRegex(h, "^[0-9a-f]{64}$")
|
||||
self.assertIn(M.PINNED_REVISION, M.PINNED)
|
||||
|
||||
|
||||
class Setup(unittest.TestCase):
|
||||
def test_setup_rebuilds_a_corrupt_install(self):
|
||||
import setup
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
mtp = Path(d)
|
||||
self.assertFalse(setup.mtp_corrupt(mtp)) # no tensors kept: nothing to check
|
||||
(mtp / "tensors").mkdir()
|
||||
for code, want in ((0, False), (3, True), (1, False)):
|
||||
with self.subTest(code=code), mock.patch.object(
|
||||
setup.subprocess, "run", return_value=mock.Mock(returncode=code)) as run:
|
||||
self.assertEqual(setup.mtp_corrupt(mtp), want)
|
||||
self.assertIn("verify", run.call_args[0][0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -154,6 +154,26 @@ class Engine(unittest.TestCase):
|
||||
self.assertEqual(got, [setup.PREBUILT_URL + setup.PREBUILT_ASSET])
|
||||
self.assertIn("No ready-made engine for v0.1.31", out)
|
||||
|
||||
def test_a_refused_archive_is_not_kept(self):
|
||||
"""PR #324: a refused archive (too old, or no code for the GPU) kept its zip and .done mark, and every later
|
||||
run reused it ("already downloaded") instead of the published one."""
|
||||
for meta in ({"version": "0.1.0", "archs": [89]},
|
||||
{"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [120]}):
|
||||
with self.subTest(meta=meta):
|
||||
def download(url, dst, what=None):
|
||||
with zipfile.ZipFile(dst, "w") as z:
|
||||
z.writestr("BUILD.json", json.dumps(meta))
|
||||
z.writestr(setup.EXE, b"engine")
|
||||
setup.mark(dst)
|
||||
|
||||
with mock.patch.object(setup.urllib.request, "urlopen", lambda req, timeout=None: Response()), \
|
||||
mock.patch.object(setup, "download", download):
|
||||
eng, _ = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu")
|
||||
self.assertIsNone(eng)
|
||||
z = self.root / "engine" / setup.PREBUILT_ASSET
|
||||
self.assertFalse(z.exists())
|
||||
self.assertFalse(z.with_name(z.name + ".done").exists())
|
||||
|
||||
def test_an_installed_engine_is_kept(self):
|
||||
(self.root / "engine" / "BUILD.json").write_text(json.dumps(
|
||||
{"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]}))
|
||||
|
||||
Reference in new issue
Block a user