okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1f0ace2d1
main
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 7python tools/mtp_fetch.py inventory --out DIR # headers only (a few KB per shard) 8python tools/mtp_fetch.py fetch --out DIR [--only SUBSTR] # the MTP tensors themselves, resumable 9python 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" ): 50MS_ENDPOINT = (os .environ .get ("MODELSCOPE_ENDPOINT" )or "" ).strip ().rstrip ("/" )or "https://www.modelscope.cn" 51REPO = 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 ): 135with _cdn_lock : 136hit = _cdn .get (url ) 137return 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" %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; 149a server that never answered in this run, or a computer that is offline, stops the fetch at once (NetFailure, with the plain sentence); 150after that a failed range is tried `retries` times.""" 151for attempt in range (retries ): 152try : 153used = _final (url ) 154req = urllib .request .Request (used ,headers = {"User-Agent" :"strata-mtp-fetch" }) 155if start is not None : 156req .add_header ("Range" ,"bytes=%d-%d" % (start ,end )) 157answer = netpolicy .open_url (netpolicy .urlopen ,req ,say = _say_waiting , 158check_memory =not _ANY_BYTES [0 ]) 159with answer as r : 160if start is not None : 161check_range (r .status ,r .headers .get ("Content-Range" ),start ,end ) 162data = r .read () 163landed = getattr (r ,"geturl" ,lambda :url )() 164if start is not None and len (data )!= end - start + 1 : 165raise IOError ("short range read: %d of %d" % (len (data ),end - start + 1 )) 166if used == url and landed and landed != url : 167with _cdn_lock : 168_cdn [url ]= (landed ,time .monotonic ()+ CDN_TTL ) 169_ANY_BYTES [0 ]= True 170return data 171except Exception as e :# network errors are retried, then surfaced 172with _cdn_lock : 173_cdn .pop (url ,None ) 174if isinstance (e ,netpolicy .NetFailure )and (e .kind == "offline" or not _ANY_BYTES [0 ]): 175raise # nothing came in this run, or no connection at all: say so now 176if attempt == retries - 1 : 177raise 178time .sleep (min (2 ** attempt ,16 )) 179"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 184progress parser (tools/strata_mcp.py install_progress) shows it. `done` counts what an earlier run already has.""" 185LABEL = "MTP draft layer" 186 187def __init__ (self ,total ,done = 0 ,every = 2.0 ,out = None ): 188self .total ,self .done ,self .every ,self .out = total ,done ,every ,out or sys .stderr 189self .last = 0.0 190self .lock = threading .Lock () 191 192def add (self ,n ): 193with self .lock : 194self .done += n 195self .show () 196 197def show (self ,force = False ): 198now = time .monotonic () 199if not force and now - self .last < self .every : 200return 201self .last = now 202if self .total > 0 : 203done = max (0 ,min (self .done ,self .total )) 204" %s: %6.2f / %.2f GB (%d%%)" % (self .LABEL ,done / 1e9 ,self .total / 1e9 ,100 * done // self .total ), 205file = 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 210its tensors done. Returns the open lock file (keep it open), or exits when the first does not end in `wait` seconds.""" 211os .makedirs (out ,exist_ok = True ) 212f = open (os .path .join (out ,".mtp_fetch.lock" ),"a+b" ) 213end = time .monotonic ()+ wait 214told = False 215while True : 216try : 217if os .name == "nt" : 218import msvcrt 219f .seek (0 ) 220msvcrt .locking (f .fileno (),msvcrt .LK_NBLCK ,1 ) 221else : 222import fcntl 223fcntl .flock (f .fileno (),fcntl .LOCK_EX | fcntl .LOCK_NB ) 224return f 225except OSError : 226if time .monotonic ()> end : 227sys .exit ("another MTP download is still writing %s: wait for it or end it (Task Manager: python.exe), then try again" % out ) 228if not told : 229"another MTP download is writing %s: waiting for it to end" % out ,file = sys .stderr ,flush = True ) 230told = True 231time .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 236or killed setup does not leave a download running on its own (#3257: taskkill /T does not reach a grandchild whose parent is gone).""" 237if (os .environ .get ("STRATA_EXIT_WITH_PARENT" )or "" ).strip ()!= "1" : 238return 239parent = os .getppid () 240if parent <= 1 : 241return 242if os .name == "nt" : 243import ctypes 244k32 = ctypes .windll .kernel32 245k32 .OpenProcess .restype = ctypes .c_void_p 246k32 .WaitForSingleObject .argtypes = (ctypes .c_void_p ,ctypes .c_ulong ) 247h = k32 .OpenProcess (0x00100000 ,False ,parent )# SYNCHRONIZE: a handle keeps the answer true if the id is reused 248if not h : 249return # no access (or already gone): nothing to watch 250gone = lambda :k32 .WaitForSingleObject (h ,0 )== 0 251else : 252gone = lambda :os .getppid ()!= parent 253 254def watch (): 255while not gone (): 256time .sleep (1.5 ) 257"the process that started this download has ended: stopping" ,file = sys .stderr ,flush = True ) 258os ._exit (1 ) 259threading .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.""" 264try : 265n = int ((os .environ .get ("STRATA_DL_CONNECTIONS" )or "" ).strip ()or 16 ) 266except ValueError : 267n = 16 268return 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 273checked by get() (a 206 with the range asked for), so a server that ignores Range still fails here.""" 274spans = [] 275pos = start 276while pos <= last : 277spans .append ((pos ,min (pos + chunk - 1 ,last ))) 278pos = spans [- 1 ][1 ]+ 1 279if workers <= 1 or len (spans )<= 1 : 280for a ,b in spans : 281yield get (url ,a ,b ) 282return 283todo = iter (spans ) 284window = 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 287depth = max (workers ,min (3 * workers , (512 << 20 )// max (chunk ,1 ))) 288with concurrent .futures .ThreadPoolExecutor (min (workers ,len (spans )))as ex : 289for a ,b in todo : 290window .append (ex .submit (get ,url ,a ,b )) 291if len (window )>= depth : 292break 293while window : 294data = window .popleft ().result () 295for a ,b in todo : 296window .append (ex .submit (get ,url ,a ,b )) 297break 298yield 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/...`.""" 303if status != 206 : 304raise 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 ) 306want = "bytes %d-%d/" % (start ,end ) 307if not (content_range or "" ).strip ().startswith (want ): 308raise 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.""" 313return REPO == PINNED 314 315 316def sha256_of (path ): 317h = hashlib .sha256 () 318with open (path ,"rb" )as f : 319for block in iter (lambda :f .read (1 << 24 ),b"" ): 320h .update (block ) 321return 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 326STRATA_ALLOW_UNPINNED=1: then the current files are read (their tensors are still checked against the pinned SHA256).""" 327global REPO 328try : 329req = urllib .request .Request (REPO + "model.safetensors.index.json" ,method = "HEAD" , 330headers = {"User-Agent" :"strata-mtp-fetch" }) 331netpolicy .open_url (netpolicy .urlopen ,req ,say = _say_waiting ).close () 332except urllib .error .HTTPError as e : 333if e .code == 404 and "/resolve/%s/" % REVISION in REPO : 334if (os .environ .get ("STRATA_ALLOW_UNPINNED" )or "" ).strip ()!= "1" : 335sys .exit ("the pinned version of the checkpoint (%s) is no longer on Hugging Face: update Strata" % REVISION ) 336"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 ) 338REPO = REPO .replace ("/resolve/%s/" % REVISION ,"/resolve/main/" ) 339except OSError : 340pass # no answer: get() retries and reports it 341return REPO 342 343 344def shard_header (shard ): 345url = REPO + shard 346n = struct .unpack ("<Q" ,get (url ,0 ,7 ))[0 ] 347header = json .loads (get (url ,8 ,8 + n - 1 )) 348return 8 + n ,header 349 350 351def inventory (out ): 352index = json .loads (get (REPO + "model.safetensors.index.json" ))["weight_map" ] 353mtp = {k :v for k ,v in index .items ()if k .startswith ("mtp." )} 354rows ,total = [],0 355shards = 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) 357with concurrent .futures .ThreadPoolExecutor (max (1 ,min (connections (),8 ,len (shards ))))as ex : 358headers = list (ex .map (shard_header ,shards )) 359for shard , (base ,header )in zip (shards ,headers ): 360for name ,meta in header .items (): 361if name in mtp and mtp [name ]== shard : 362a ,b = meta ["data_offsets" ] 363rows .append (dict (name = name ,shard = shard ,dtype = meta ["dtype" ],shape = meta ["shape" ], 364start = base + a ,end = base + b - 1 ,bytes = b - a )) 365total += b - a 366missing = sorted (set (mtp )- set (r ["name" ]for r in rows )) 367if missing : 368sys .exit ("tensors named in the index but absent from their shard headers: %s" % missing ) 369rows .sort (key = lambda r :r ["name" ]) 370os .makedirs (out ,exist_ok = True ) 371with open (os .path .join (out ,"mtp-inventory.json" ),"w" ,encoding = "utf-8" )as f : 372json .dump (dict (repo = REPO ,total_bytes = total ,tensors = rows ),f ,indent = 1 ) 373lines = ["# 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 |" ,"|---|---|---|---:|" ] 375for r in rows : 376lines .append ("| `%s` | %s | %s | %.1f |" % (r ["name" ],r ["dtype" ],"x" .join (map (str ,r ["shape" ])),r ["bytes" ]/ 1e6 )) 377text = "\n" .join (lines )+ "\n" 378with open (os .path .join (out ,"mtp-inventory.md" ),"w" ,encoding = "utf-8" )as f : 379f .write (text ) 380text ) 381return rows 382 383 384def fetch (out ,only ): 385inv_path = os .path .join (out ,"mtp-inventory.json" ) 386tdir = os .path .join (out ,"tensors" ) 387inv = None 388if os .path .exists (inv_path ): 389try : 390with open (inv_path ,encoding = "utf-8" )as f : 391inv = json .load (f ) 392except ValueError : 393inv = 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). 396same = isinstance (inv ,dict )and inv .get ("repo" )== REPO 397rows = inv ["tensors" ]if same else inventory (out ) 398os .makedirs (tdir ,exist_ok = True ) 399manifest = [] 400workers = connections () 401chunk = (16 if workers > 1 else 64 )<< 20 402todo = [r for r in rows if not only or only in r ["name" ]] 403have_all = 0 404for r in todo : 405tp = os .path .join (tdir ,r ["name" ]+ ".bin" ) 406if os .path .exists (tp ): 407have_all += min (os .path .getsize (tp ),r ["bytes" ]) 408progress = Progress (sum (r ["bytes" ]for r in todo ),have_all ) 409progress .show (force = True ) 410for r in todo : 411path = os .path .join (tdir ,r ["name" ]+ ".bin" ) 412want = SHA256 .get (r ["name" ])if pinned ()else None 413if os .path .exists (path )and not same and ( 414want is None or os .path .getsize (path )!= r ["bytes" ]or sha256_of (path )!= want ): 415os .remove (path ) 416attempt ,net_fails = 0 ,0 417while attempt < 2 : 418have = os .path .getsize (path )if os .path .exists (path )else 0 419if have > r ["bytes" ]: 420os .remove (path ) 421have = 0 422try : 423with open (path ,"ab" )as f : 424pos = r ["start" ]+ have 425for data in ranged (REPO + r ["shard" ],pos ,r ["end" ],chunk ,workers ): 426f .write (data ) 427pos += len (data ) 428progress .add (len (data )) 429except (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) 432net_fails += 1 433if net_fails > 3 : 434sys .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 )) 436workers = max (4 ,workers // 2 ) 437"%s: %s - continuing with %d connections (try %d)" % (r ["name" ],e ,workers ,net_fails + 1 ),file = sys .stderr ,flush = True ) 438time .sleep (min (5 * net_fails ,20 )) 439continue 440if os .path .getsize (path )!= r ["bytes" ]: 441sys .exit ("%s: size %d != %d" % (path ,os .path .getsize (path ),r ["bytes" ])) 442digest = sha256_of (path ) 443if want is None or digest == want : 444break 445progress .done -= os .path .getsize (path ) 446os .remove (path )# wrong bytes (#327): the whole tensor again, once 447attempt += 1 448if attempt > 1 : 449sys .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"%s: wrong bytes (sha256 %s...), fetching it again" % (r ["name" ],digest [:12 ]),file = sys .stderr ) 452manifest .append (dict (r ,file = os .path .relpath (path ,out ),sha256 = digest )) 453"%s done" % r ["name" ],file = sys .stderr ,flush = True ) 454progress .show (force = True ) 455with open (os .path .join (out ,"mtp-manifest.json" ),"w" ,encoding = "utf-8" )as f : 456json .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 461when there is nothing to check (no tensors/, or STRATA_MTP_REVISION names another revision). A tensor's verdict 462is kept in tensors/verified.json by size and mtime, so a later run hashes only what changed.""" 463tdir = os .path .join (out ,"tensors" ) 464if not pinned ()or not os .path .isdir (tdir ): 465return [] 466stamp_path = os .path .join (tdir ,"verified.json" ) 467try : 468with open (stamp_path ,encoding = "utf-8" )as f : 469stamps = json .load (f ) 470except (OSError ,ValueError ): 471stamps = {} 472bad ,good = [], {} 473for name ,want in sorted (SHA256 .items ()): 474path = os .path .join (tdir ,name + ".bin" ) 475if not os .path .exists (path ): 476bad .append (name ) 477continue 478st = os .stat (path ) 479key = [st .st_size ,st .st_mtime_ns ,want ] 480if stamps .get (name )!= key and sha256_of (path )!= want : 481bad .append (name ) 482continue 483good [name ]= key 484try : 485with open (stamp_path ,"w" ,encoding = "utf-8" )as f : 486json .dump (good ,f ,indent = 1 ) 487except OSError : 488pass 489return bad 490 491 492def main (): 493ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 494ap .add_argument ("cmd" ,choices = ["inventory" ,"fetch" ,"verify" ]) 495ap .add_argument ("--out" ,required = True ) 496ap .add_argument ("--only" ) 497a = ap .parse_args () 498if a .cmd == "verify" :# offline: the hashes are the pinned revision's 499bad = verify (a .out ) 500for name in bad : 501"MTP tensor missing or corrupt: %s" % name ,file = sys .stderr ) 502sys .exit (BAD if bad else 0 ) 503exit_with_parent () 504lock = lock_folder (a .out )if a .cmd == "fetch" else None 505try : 506resolve_repo () 507inventory (a .out )if a .cmd == "inventory" else fetch (a .out ,a .only ) 508except netpolicy .NetFailure as e :# the server did not answer, or no connection: one plain sentence, not a traceback 509" [X] " + e .headline ("the draft layer" ),file = sys .stderr ) 510" " + e .next_step (),file = sys .stderr ) 511sys .exit (OFFLINE if e .kind == "offline" else NO_ANSWER ) 512if lock : 513lock .close () 514 515 516if __name__ == "__main__" : 517main ()