okami.mom/strata

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

Niko1221drafting: one drafter per install, never none unless Off was chosen1f0ace2d1

main
25.7 KiB517 linesraw
1"""tools/mtp_fetch.py - plan v0.3, P0.3/P6: the MTP block from the BF16 checkpoint, without the checkpoint.
2
3The GSQ-RCO GGUF ships no MTP head. The BF16 checkpoint (Qwen/Qwen3.8-Flash-Next, 360 GB in 131 shards) does:
431 `mtp.*` tensors scattered over 28 shards. Safetensors puts a JSON header (name -> dtype, shape, byte range)
5at the start of each shard, so HTTP range requests can read the headers and then only the MTP tensors.
6
7    python tools/mtp_fetch.py inventory --out DIR          # headers only (a few KB per shard)
8    python tools/mtp_fetch.py fetch --out DIR [--only SUBSTR]  # the MTP tensors themselves, resumable
9    python tools/mtp_fetch.py verify --out DIR             # the fetched tensors against SHA256 (exit 3: bad ones)
10
11`fetch` writes one raw file per tensor plus `mtp-manifest.json` (dtype, shape, source shard, byte range,
12sha256). It never downloads anything but the ranges named in the headers. Nothing here runs a model.
13
14#327: a mirror or proxy that ignores the Range header answers 200 with the whole shard - its JSON header and
15unrelated tensors - and a proxy may cut that to the requested length, so neither the size nor a hash of what was
16downloaded catches it (the drafter then accepts nothing, silently).  A range read therefore needs a 206 whose
17Content-Range is the range asked for, and every tensor of the pinned revision is checked against SHA256 below.
18"""
19import argparse
20import collections
21import concurrent.futures
22import hashlib
23import json
24import os
25import struct
26import sys
27import threading
28import time
29import urllib.error
30import urllib.request
31
32sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
33from strata_control import netpolicy, tls  # noqa: E402
34
35tls.install()       # #3722: the operating system's certificates
36
37# #214: a fixed commit of the checkpoint (its `sha` from https://huggingface.co/api/models/Qwen/Qwen3.8-Flash-Next
38# on 2026-09-30), so every install reads the same tensors; STRATA_MTP_REVISION overrides it (e.g. main).  When the
39# repository no longer has it, reading stops (resolve_repo) unless STRATA_ALLOW_UNPINNED=1.
40PINNED_REVISION = "de4b8e4d43b917e7706784d8bb445c9af86a3540"
41REVISION = os.environ.get("STRATA_MTP_REVISION") or PINNED_REVISION
42# #495: HF_ENDPOINT (a mirror, e.g. https://hf-mirror.com) serves the same revision; the SHA256 checks below still apply
43HF_ENDPOINT = (os.environ.get("HF_ENDPOINT") or "").strip().rstrip("/") or "https://huggingface.co"
44REPO = HF_ENDPOINT + "/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % REVISION
45PINNED = HF_ENDPOINT + "/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % PINNED_REVISION   # SHA256's revision
46# STRATA_SOURCE=modelscope (setup's --source): the same checkpoint from ModelScope.  It serves the repository's current
47# files, not a pinned revision, so REPO and PINNED are one URL here: every tensor is still checked against the pinned
48# revision's SHA256 below, so a tensor that differs from it is caught, not used.
49if (os.environ.get("STRATA_SOURCE") or "").strip().lower() in ("ms", "modelscope"):
50    MS_ENDPOINT = (os.environ.get("MODELSCOPE_ENDPOINT") or "").strip().rstrip("/") or "https://www.modelscope.cn"
51    REPO = PINNED = MS_ENDPOINT + "/models/Qwen/Qwen3.8-Flash-Next/resolve/master/"
52DTYPE_BYTES = {"BF16": 2, "F16": 2, "F32": 4, "F8_E4M3": 1, "I64": 8, "I32": 4}
53BAD = 3                                             # `verify`'s exit code: a tensor is missing or corrupt
54NO_ANSWER = 4                                       # the server did not answer (the [X] lines say so; setup does not run it again)
55OFFLINE = 5                                         # this computer has no connection at all: setup goes on without the draft layer, the model starts (offline users)
56
57# #327: sha256 of every MTP tensor's bytes at PINNED_REVISION (two independent fetches agree, and 29 of them were read
58# again from that revision; the two expert tensors' first and last 16 MiB), so a mirror that ignored the
59# Range header (it sent the shard's start: its JSON header) is caught, and an install it corrupted is fetched again.
60SHA256 = {
61    "mtp.fc_embedding.weight":
62        "241d6e87ded317a61b1aeb3ca4e28c53f1caba09ad5be66092e91fe5e3e14751",
63    "mtp.fc_hidden.weight":
64        "97c8e427ad0177e2c713ed24a397d815b523eda15ef453f1ae6463f6c70a8f96",
65    "mtp.hyper_connection_mixer.hc_norm.weight":
66        "ce948a398e15aeaa403c424cda34e6eed296ab2570d591bb5ff3da642b255d64",
67    "mtp.hyper_connection_mixer.input_mix_weight_down.weight":
68        "c633d2841fda463e82045e0b93fb8cb8d511ec0c9eda616020f01aca18d71947",
69    "mtp.hyper_connection_mixer.input_mix_weight_up.weight":
70        "6565285f0ba2923703252763cfc11d8a9bda40ab42e7548e12464b04dbdbec13",
71    "mtp.layers.0.attn_hyper_connection.block_inject_weight.weight":
72        "c8afff64e7f54412d02120097c4255033c55245e1c1eed84cc630d428ccb864c",
73    "mtp.layers.0.attn_hyper_connection.hc_norm.weight":
74        "1fb619aeaaf637ccd70f46f1f8f8116e6a46448cb43026b246de8ee8286ed809",
75    "mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight":
76        "e80ac8bf3e270e9d5a949ec7c913329dc8de017d69851334820fae7b8c86a7f5",
77    "mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight":
78        "f80f1fd44e1183e7764ea496b11ff89ead9dd758f861d4e79a770bf54956b1a5",
79    "mtp.layers.0.mlp.experts.down_proj":
80        "539c46234f73bac70450f731f40e715f77ac32faf77def0f3f800e58aaabbbc0",
81    "mtp.layers.0.mlp.experts.gate_up_proj":
82        "839e98f9642ebc884b178abd2090b6dc8b0bcd81ed92d7f7a08314c6a68f96d5",
83    "mtp.layers.0.mlp.gate.weight":
84        "f0d35fa41b360a08bc0c5b1e5766aa42df960291716ee189208b5d2599462c20",
85    "mtp.layers.0.mlp.shared_expert.down_proj.weight":
86        "d2ced8c81367cc494599d1a8cdc279c3dd6579b628ded05acd7495e99cee01d8",
87    "mtp.layers.0.mlp.shared_expert.gate_proj.weight":
88        "f4a81109165853b3b64f36d809f98094b599763364070f5fa079200e1c386d4c",
89    "mtp.layers.0.mlp.shared_expert.up_proj.weight":
90        "172586861eea53efbff10afc43ded5b6e49c83879e9efc01e089c652bbb0a156",
91    "mtp.layers.0.mlp.shared_expert_gate.weight":
92        "acdd306d9996d356e4667a16ff63af6fef086fc7f570f1bc00bbe882a2a93f6e",
93    "mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight":
94        "c5782dd92b479a1f8ef43d683fe9c917fd9e8fba81f23c1aae8817bfe4b476a6",
95    "mtp.layers.0.mlp_hyper_connection.hc_norm.weight":
96        "21a504876b5e7b788301557c68dfb757999430eba36c66ec8ab96a63604dbfd1",
97    "mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight":
98        "b71240036dea954e034d5ae04e097bcd7ac51cb28a44e4c93d198af3447278a1",
99    "mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight":
100        "40756866bf2a5e82c28e407f717b6fa07614d593f78e79c7ceb2cd4ffe6dda94",
101    "mtp.layers.0.self_attn.indexer.index_qk_proj.weight":
102        "2befafae6e944c1fc651fd73d4d527eb6f138a6c1679065b003128ee3150e859",
103    "mtp.layers.0.self_attn.indexer.k_layernorm.weight":
104        "2db621f6a08b4085756fc69d60a4a1bd1d7fbf5d406456d2477075842efaae54",
105    "mtp.layers.0.self_attn.indexer.q_layernorm.weight":
106        "afaf59f68e251939970ffdeacad0667dffc657a522bea62cdc44a52816fc49d6",
107    "mtp.layers.0.self_attn.k_norm.weight":
108        "8f924b0357cf936e14fc34518205d000e1423aa60626827df81b0804fae8cdfd",
109    "mtp.layers.0.self_attn.k_proj.weight":
110        "1a295dc2d6e633e808aeb19e00c97856a1817bbfcc83f5b610e2bfcacfcb8c38",
111    "mtp.layers.0.self_attn.o_proj.weight":
112        "9d2fcf0ac6ac19de87f638f710cfd1af6ad14141e75b7d3d5d29fbd06f374219",
113    "mtp.layers.0.self_attn.q_norm.weight":
114        "57957aa1e7c5a3ac628bff0ec5522ad55a39b8c0b8bd2d324ae640e3771617ef",
115    "mtp.layers.0.self_attn.q_proj.weight":
116        "5220aef3d288f40759f7356af9ef453e5ac0256a38749a9bb803a4e9db58150d",
117    "mtp.layers.0.self_attn.v_proj.weight":
118        "39cb12f5424e965fa71fb81db0ee230c701b7b1e0b72c36641fde7e0e41bff41",
119    "mtp.pre_fc_norm_embedding.weight":
120        "04c4a570850e06f2d8913da8220d54d4c7f87db6eb6d45480b938e8ba41d6a86",
121    "mtp.pre_fc_norm_hidden.weight":
122        "b933b44559879449b1baf2af8385c5c237347307e3fd452394870cb53e6eab6d",
123}
124
125
126# Hugging Face answers a /resolve/ address with a redirect to a signed CDN address (valid for about an hour).  Every range of a
127# tensor used to go through that redirect and a fresh connection to it; the CDN address of the first answer is reused now
128# (and forgotten after any error, so the next try asks again).
129CDN_TTL = 600
130_cdn = {}
131_cdn_lock = threading.Lock()
132
133
134def _final(url):
135    with _cdn_lock:
136        hit = _cdn.get(url)
137    return hit[0] if hit and hit[1] > time.monotonic() else url
138
139
140_ANY_BYTES = [False]        # an answer has come in this run: from then on a server that stops answering is retried, not given up at once
141
142
143def _say_waiting(line):
144    print("  %s ..." % line, file=sys.stderr, flush=True)
145
146
147def get(url, start=None, end=None, retries=6):
148    """One range under the network rule (strata_control/netpolicy.py): each try waits at most 12 s, then 30 s, for the server's answer;
149    a server that never answered in this run, or a computer that is offline, stops the fetch at once (NetFailure, with the plain sentence);
150    after that a failed range is tried `retries` times."""
151    for attempt in range(retries):
152        try:
153            used = _final(url)
154            req = urllib.request.Request(used, headers={"User-Agent": "strata-mtp-fetch"})
155            if start is not None:
156                req.add_header("Range", "bytes=%d-%d" % (start, end))
157            answer = netpolicy.open_url(netpolicy.urlopen, req, say=_say_waiting,
158                                        check_memory=not _ANY_BYTES[0])
159            with answer as r:
160                if start is not None:
161                    check_range(r.status, r.headers.get("Content-Range"), start, end)
162                data = r.read()
163                landed = getattr(r, "geturl", lambda: url)()
164            if start is not None and len(data) != end - start + 1:
165                raise IOError("short range read: %d of %d" % (len(data), end - start + 1))
166            if used == url and landed and landed != url:
167                with _cdn_lock:
168                    _cdn[url] = (landed, time.monotonic() + CDN_TTL)
169            _ANY_BYTES[0] = True
170            return data
171        except Exception as e:  # network errors are retried, then surfaced
172            with _cdn_lock:
173                _cdn.pop(url, None)
174            if isinstance(e, netpolicy.NetFailure) and (e.kind == "offline" or not _ANY_BYTES[0]):
175                raise                                   # nothing came in this run, or no connection at all: say so now
176            if attempt == retries - 1:
177                raise
178            time.sleep(min(2 ** attempt, 16))
179            print("retry %s: %s" % (url, e), file=sys.stderr)
180
181
182class Progress:
183    """One line a couple of seconds, `MTP draft layer: 1.23 / 5.04 GB (24%)`: the form of setup's own download line, so the app's
184    progress parser (tools/strata_mcp.py install_progress) shows it.  `done` counts what an earlier run already has."""
185    LABEL = "MTP draft layer"
186
187    def __init__(self, total, done=0, every=2.0, out=None):
188        self.total, self.done, self.every, self.out = total, done, every, out or sys.stderr
189        self.last = 0.0
190        self.lock = threading.Lock()
191
192    def add(self, n):
193        with self.lock:
194            self.done += n
195            self.show()
196
197    def show(self, force=False):
198        now = time.monotonic()
199        if not force and now - self.last < self.every:
200            return
201        self.last = now
202        if self.total > 0:
203            done = max(0, min(self.done, self.total))
204            print("  %s: %6.2f / %.2f GB (%d%%)" % (self.LABEL, done / 1e9, self.total / 1e9, 100 * done // self.total),
205                  file=self.out, flush=True)
206
207
208def lock_folder(out, wait=900.0):
209    """Only one fetch writes a folder: a second one (a retry while the first still runs, #3257) waits for the first and then finds
210    its tensors done.  Returns the open lock file (keep it open), or exits when the first does not end in `wait` seconds."""
211    os.makedirs(out, exist_ok=True)
212    f = open(os.path.join(out, ".mtp_fetch.lock"), "a+b")
213    end = time.monotonic() + wait
214    told = False
215    while True:
216        try:
217            if os.name == "nt":
218                import msvcrt
219                f.seek(0)
220                msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
221            else:
222                import fcntl
223                fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
224            return f
225        except OSError:
226            if time.monotonic() > end:
227                sys.exit("another MTP download is still writing %s: wait for it or end it (Task Manager: python.exe), then try again" % out)
228            if not told:
229                print("another MTP download is writing %s: waiting for it to end" % out, file=sys.stderr, flush=True)
230                told = True
231            time.sleep(2)
232
233
234def exit_with_parent():
235    """STRATA_EXIT_WITH_PARENT=1 (set by setup.py for the tools it runs): end when the process that started this one ends, so a cancelled
236    or killed setup does not leave a download running on its own (#3257: taskkill /T does not reach a grandchild whose parent is gone)."""
237    if (os.environ.get("STRATA_EXIT_WITH_PARENT") or "").strip() != "1":
238        return
239    parent = os.getppid()
240    if parent <= 1:
241        return
242    if os.name == "nt":
243        import ctypes
244        k32 = ctypes.windll.kernel32
245        k32.OpenProcess.restype = ctypes.c_void_p
246        k32.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_ulong)
247        h = k32.OpenProcess(0x00100000, False, parent)       # SYNCHRONIZE: a handle keeps the answer true if the id is reused
248        if not h:
249            return                                           # no access (or already gone): nothing to watch
250        gone = lambda: k32.WaitForSingleObject(h, 0) == 0
251    else:
252        gone = lambda: os.getppid() != parent
253
254    def watch():
255        while not gone():
256            time.sleep(1.5)
257        print("the process that started this download has ended: stopping", file=sys.stderr, flush=True)
258        os._exit(1)
259    threading.Thread(target=watch, daemon=True).start()
260
261
262def connections():
263    """Ranges read at once: STRATA_DL_CONNECTIONS (the setting of setup's downloads), else 16; 1 reads them one by one."""
264    try:
265        n = int((os.environ.get("STRATA_DL_CONNECTIONS") or "").strip() or 16)
266    except ValueError:
267        n = 16
268    return max(1, min(n, 32))
269
270
271def ranged(url, start, last, chunk, workers):
272    """The bytes start..last of `url` in order, read in `chunk`-sized ranges with `workers` of them in flight.  Each range is
273    checked by get() (a 206 with the range asked for), so a server that ignores Range still fails here."""
274    spans = []
275    pos = start
276    while pos <= last:
277        spans.append((pos, min(pos + chunk - 1, last)))
278        pos = spans[-1][1] + 1
279    if workers <= 1 or len(spans) <= 1:
280        for a, b in spans:
281            yield get(url, a, b)
282        return
283    todo = iter(spans)
284    window = collections.deque()
285    # the ranges are handed on in order, so one slow range holds the oldest slot; the connections that are done go on with
286    # the next ranges meanwhile (up to `depth` ahead, at most ~512 MiB in memory) instead of waiting for it
287    depth = max(workers, min(3 * workers, (512 << 20) // max(chunk, 1)))
288    with concurrent.futures.ThreadPoolExecutor(min(workers, len(spans))) as ex:
289        for a, b in todo:
290            window.append(ex.submit(get, url, a, b))
291            if len(window) >= depth:
292                break
293        while window:
294            data = window.popleft().result()
295            for a, b in todo:
296                window.append(ex.submit(get, url, a, b))
297                break
298            yield data
299
300
301def check_range(status, content_range, start, end):
302    """#327: a range read is only what was asked for when the server says so: 206 and `bytes START-END/...`."""
303    if status != 206:
304        raise IOError("range request not honoured: HTTP %s instead of 206 (a mirror or proxy that ignores the Range "
305                      "header sends the whole file)" % status)
306    want = "bytes %d-%d/" % (start, end)
307    if not (content_range or "").strip().startswith(want):
308        raise IOError("range request answered with Content-Range %r, not %s..." % (content_range, want))
309
310
311def pinned():
312    """The tensors' hashes are the pinned revision's: they apply when this run reads that revision."""
313    return REPO == PINNED
314
315
316def sha256_of(path):
317    h = hashlib.sha256()
318    with open(path, "rb") as f:
319        for block in iter(lambda: f.read(1 << 24), b""):
320            h.update(block)
321    return h.hexdigest()
322
323
324def resolve_repo():
325    """REPO.  When the pinned revision is gone from the repository (a 404 on its index) it stops, unless
326    STRATA_ALLOW_UNPINNED=1: then the current files are read (their tensors are still checked against the pinned SHA256)."""
327    global REPO
328    try:
329        req = urllib.request.Request(REPO + "model.safetensors.index.json", method="HEAD",
330                                     headers={"User-Agent": "strata-mtp-fetch"})
331        netpolicy.open_url(netpolicy.urlopen, req, say=_say_waiting).close()
332    except urllib.error.HTTPError as e:
333        if e.code == 404 and "/resolve/%s/" % REVISION in REPO:
334            if (os.environ.get("STRATA_ALLOW_UNPINNED") or "").strip() != "1":
335                sys.exit("the pinned version of the checkpoint (%s) is no longer on Hugging Face: update Strata" % REVISION)
336            print("STRATA_ALLOW_UNPINNED=1: the checkpoint's pinned revision %s is gone: reading its current files "
337                  "(main); every tensor is still checked against the pinned SHA256" % REVISION, file=sys.stderr)
338            REPO = REPO.replace("/resolve/%s/" % REVISION, "/resolve/main/")
339    except OSError:
340        pass                                        # no answer: get() retries and reports it
341    return REPO
342
343
344def shard_header(shard):
345    url = REPO + shard
346    n = struct.unpack("<Q", get(url, 0, 7))[0]
347    header = json.loads(get(url, 8, 8 + n - 1))
348    return 8 + n, header
349
350
351def inventory(out):
352    index = json.loads(get(REPO + "model.safetensors.index.json"))["weight_map"]
353    mtp = {k: v for k, v in index.items() if k.startswith("mtp.")}
354    rows, total = [], 0
355    shards = sorted(set(mtp.values()))
356    # one small request pair per shard (28 of them): side by side, not one after the other (28 s -> 4 s)
357    with concurrent.futures.ThreadPoolExecutor(max(1, min(connections(), 8, len(shards)))) as ex:
358        headers = list(ex.map(shard_header, shards))
359    for shard, (base, header) in zip(shards, headers):
360        for name, meta in header.items():
361            if name in mtp and mtp[name] == shard:
362                a, b = meta["data_offsets"]
363                rows.append(dict(name=name, shard=shard, dtype=meta["dtype"], shape=meta["shape"],
364                                 start=base + a, end=base + b - 1, bytes=b - a))
365                total += b - a
366    missing = sorted(set(mtp) - set(r["name"] for r in rows))
367    if missing:
368        sys.exit("tensors named in the index but absent from their shard headers: %s" % missing)
369    rows.sort(key=lambda r: r["name"])
370    os.makedirs(out, exist_ok=True)
371    with open(os.path.join(out, "mtp-inventory.json"), "w", encoding="utf-8") as f:
372        json.dump(dict(repo=REPO, total_bytes=total, tensors=rows), f, indent=1)
373    lines = ["# MTP block in the BF16 checkpoint", "", "%d tensors, %.3f GB, in %d shards." % (len(rows), total / 1e9, len(set(r["shard"] for r in rows))), "",
374             "| tensor | dtype | shape | MB |", "|---|---|---|---:|"]
375    for r in rows:
376        lines.append("| `%s` | %s | %s | %.1f |" % (r["name"], r["dtype"], "x".join(map(str, r["shape"])), r["bytes"] / 1e6))
377    text = "\n".join(lines) + "\n"
378    with open(os.path.join(out, "mtp-inventory.md"), "w", encoding="utf-8") as f:
379        f.write(text)
380    print(text)
381    return rows
382
383
384def fetch(out, only):
385    inv_path = os.path.join(out, "mtp-inventory.json")
386    tdir = os.path.join(out, "tensors")
387    inv = None
388    if os.path.exists(inv_path):
389        try:
390            with open(inv_path, encoding="utf-8") as f:
391                inv = json.load(f)
392        except ValueError:
393            inv = None
394    # The byte ranges belong to one revision: an inventory read from another repository or revision is read again,
395    # and a tensor fetched from there is not resumed - it is kept only when it is the pinned revision's (sha256).
396    same = isinstance(inv, dict) and inv.get("repo") == REPO
397    rows = inv["tensors"] if same else inventory(out)
398    os.makedirs(tdir, exist_ok=True)
399    manifest = []
400    workers = connections()
401    chunk = (16 if workers > 1 else 64) << 20
402    todo = [r for r in rows if not only or only in r["name"]]
403    have_all = 0
404    for r in todo:
405        tp = os.path.join(tdir, r["name"] + ".bin")
406        if os.path.exists(tp):
407            have_all += min(os.path.getsize(tp), r["bytes"])
408    progress = Progress(sum(r["bytes"] for r in todo), have_all)
409    progress.show(force=True)
410    for r in todo:
411        path = os.path.join(tdir, r["name"] + ".bin")
412        want = SHA256.get(r["name"]) if pinned() else None
413        if os.path.exists(path) and not same and (
414                want is None or os.path.getsize(path) != r["bytes"] or sha256_of(path) != want):
415            os.remove(path)
416        attempt, net_fails = 0, 0
417        while attempt < 2:
418            have = os.path.getsize(path) if os.path.exists(path) else 0
419            if have > r["bytes"]:
420                os.remove(path)
421                have = 0
422            try:
423                with open(path, "ab") as f:
424                    pos = r["start"] + have
425                    for data in ranged(REPO + r["shard"], pos, r["end"], chunk, workers):
426                        f.write(data)
427                        pos += len(data)
428                        progress.add(len(data))
429            except (OSError, urllib.error.URLError) as e:
430                # #3214: a timeout or a dropped connection mid-tensor ends only this try: what was written stays, the next try
431                # continues after it with fewer connections (a link that drops 16 at once often holds 4)
432                net_fails += 1
433                if net_fails > 3:
434                    sys.exit("%s: the download keeps failing (%s). Check the connection and try again - what is downloaded is kept; "
435                             "if Hugging Face is slow to reach, `--source modelscope` reads the same files elsewhere" % (r["name"], e))
436                workers = max(4, workers // 2)
437                print("%s: %s - continuing with %d connections (try %d)" % (r["name"], e, workers, net_fails + 1), file=sys.stderr, flush=True)
438                time.sleep(min(5 * net_fails, 20))
439                continue
440            if os.path.getsize(path) != r["bytes"]:
441                sys.exit("%s: size %d != %d" % (path, os.path.getsize(path), r["bytes"]))
442            digest = sha256_of(path)
443            if want is None or digest == want:
444                break
445            progress.done -= os.path.getsize(path)
446            os.remove(path)                         # wrong bytes (#327): the whole tensor again, once
447            attempt += 1
448            if attempt > 1:
449                sys.exit("%s: sha256 %s is not the checkpoint's %s - the download source sends wrong data (a mirror "
450                         "that ignores Range requests?)" % (r["name"], digest, want))
451            print("%s: wrong bytes (sha256 %s...), fetching it again" % (r["name"], digest[:12]), file=sys.stderr)
452        manifest.append(dict(r, file=os.path.relpath(path, out), sha256=digest))
453        print("%s done" % r["name"], file=sys.stderr, flush=True)
454    progress.show(force=True)
455    with open(os.path.join(out, "mtp-manifest.json"), "w", encoding="utf-8") as f:
456        json.dump(manifest, f, indent=1)
457
458
459def verify(out):
460    """#327: the fetched tensors against SHA256 -> the names that are missing or wrong.  [] when they are right, or
461    when there is nothing to check (no tensors/, or STRATA_MTP_REVISION names another revision).  A tensor's verdict
462    is kept in tensors/verified.json by size and mtime, so a later run hashes only what changed."""
463    tdir = os.path.join(out, "tensors")
464    if not pinned() or not os.path.isdir(tdir):
465        return []
466    stamp_path = os.path.join(tdir, "verified.json")
467    try:
468        with open(stamp_path, encoding="utf-8") as f:
469            stamps = json.load(f)
470    except (OSError, ValueError):
471        stamps = {}
472    bad, good = [], {}
473    for name, want in sorted(SHA256.items()):
474        path = os.path.join(tdir, name + ".bin")
475        if not os.path.exists(path):
476            bad.append(name)
477            continue
478        st = os.stat(path)
479        key = [st.st_size, st.st_mtime_ns, want]
480        if stamps.get(name) != key and sha256_of(path) != want:
481            bad.append(name)
482            continue
483        good[name] = key
484    try:
485        with open(stamp_path, "w", encoding="utf-8") as f:
486            json.dump(good, f, indent=1)
487    except OSError:
488        pass
489    return bad
490
491
492def main():
493    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
494    ap.add_argument("cmd", choices=["inventory", "fetch", "verify"])
495    ap.add_argument("--out", required=True)
496    ap.add_argument("--only")
497    a = ap.parse_args()
498    if a.cmd == "verify":                           # offline: the hashes are the pinned revision's
499        bad = verify(a.out)
500        for name in bad:
501            print("MTP tensor missing or corrupt: %s" % name, file=sys.stderr)
502        sys.exit(BAD if bad else 0)
503    exit_with_parent()
504    lock = lock_folder(a.out) if a.cmd == "fetch" else None
505    try:
506        resolve_repo()
507        inventory(a.out) if a.cmd == "inventory" else fetch(a.out, a.only)
508    except netpolicy.NetFailure as e:                # the server did not answer, or no connection: one plain sentence, not a traceback
509        print("  [X]  " + e.headline("the draft layer"), file=sys.stderr)
510        print("       " + e.next_step(), file=sys.stderr)
511        sys.exit(OFFLINE if e.kind == "offline" else NO_ANSWER)
512    if lock:
513        lock.close()
514
515
516if __name__ == "__main__":
517    main()