okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1# Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). 2# Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. 3"""tools/ds4/requant_gguf.py - a DeepSeek-V4.1 GGUF requantized by a recipe (the routed experts in ggml's low-bit types, 4the dense matrices in Q8_0), through ggml's own quantizers (libggml-base, ctypes) - a quick test model for maya-ds4's 5low-bit expert kernels until the real Maya quants exist. 6 7python tools/ds4/requant_gguf.py --src ~/models/DeepSeek-V4.1-Flash-1017-GGUF/UD-Q8_K_XL \\ 8--out ~/ds4test/Maya-S-test --recipe recipe.json --lib ~/llama.cpp/build/bin/libggml-base.so --jobs 10 9 10The recipe (JSON): 11{"experts": {"gate": "IQ2_XXS", "up": "IQ2_XXS", "down": "IQ3_XXS"}, 12"layers": [{"layers": "0-1,38-39", "gate": "IQ2_S", "up": "IQ2_S", "down": "IQ3_S"}], 13"dense": "Q8_0", 14"dense_keep": ["hc_", "engram", "norm", "attn_sinks", "exp_probs_b", "ffn_gate_inp"], 15"engram": "skip"} 16- experts: each role's type (gate = ffn_gate_exps, up = ffn_up_exps, down = ffn_down_exps); "layers" entries override it 17for the listed blocks (later entries win). A role's type may be "keep". 18- dense: the type of the other float matrices (2-D or more, F32 / F16 / BF16, rows a multiple of 32), except names 19containing a dense_keep string, which stay as they are; "keep" keeps them all. 20- engram: "keep" copies the Engram tables (engram_*) into the output, "skip" leaves them out (a shared Engram shard set 21beside the quant: pack_gguf.py reads <model>/Engram/*.gguf or <model>/../Engram/*.gguf); --engram-link then links the 22source's shards there as that set. 23 24The output has one shard a source shard (the same tensors in the same order, the metadata copied; split.tensors.count 25updated), tensors at the source's alignment. Workers (processes) read the source with O_DIRECT, so the page cache that 26running engines rely on is neither evicted nor filled, and drop what they wrote from it; they run at SCHED_IDLE. 27 28IQ2_XXS / IQ2_XS / IQ1_* need an importance matrix: --imatrix (llama.cpp's legacy .dat) or all ones. 29""" 30from __future__import annotations 31 32import argparse 33import ctypes 34import json 35import mmap 36import multiprocessing as mp 37import os 38import pathlib 39import re 40import shutil 41import struct 42import sys 43import time 44 45import numpy as np 46 47# ggml type id -> (name, values a block, bytes a block) 48GT = {0 : ("F32" ,1 ,4 ),1 : ("F16" ,1 ,2 ),8 : ("Q8_0" ,32 ,34 ),10 : ("Q2_K" ,256 ,84 ),11 : ("Q3_K" ,256 ,110 ), 4912 : ("Q4_K" ,256 ,144 ),13 : ("Q5_K" ,256 ,176 ),14 : ("Q6_K" ,256 ,210 ),16 : ("IQ2_XXS" ,256 ,66 ), 5017 : ("IQ2_XS" ,256 ,74 ),18 : ("IQ3_XXS" ,256 ,98 ),19 : ("IQ1_S" ,256 ,50 ),20 : ("IQ4_NL" ,32 ,18 ), 5121 : ("IQ3_S" ,256 ,110 ),22 : ("IQ2_S" ,256 ,82 ),23 : ("IQ4_XS" ,256 ,136 ),29 : ("IQ1_M" ,256 ,56 ), 5230 : ("BF16" ,1 ,2 ),39 : ("MXFP4" ,32 ,17 ),43 : ("MXFP8" ,32 ,33 ),67 : ("MXFP8" ,32 ,33 )} 53BYNAME = {v [0 ]:k for k ,v in GT .items ()} 54NEED_IMATRIX = {16 ,17 ,19 ,29 } 55ROLE = {"ffn_gate_exps.weight" :"gate" ,"ffn_up_exps.weight" :"up" ,"ffn_down_exps.weight" :"down" } 56ALIGN_IO = 4096 57 58 59def nbytes_of (typ :int ,dims :list [int ])-> int : 60_ ,per ,bpb = GT [typ ] 61n = 1 62for d in dims : 63n *= d 64return n // per * bpb 65 66 67class Shard : 68"""A GGUF shard: its KV records (raw bytes each, in order) and tensor infos (absolute data offsets).""" 69 70def __init__ (self ,path :pathlib .Path ): 71self .path = path 72with path .open ("rb" )as f : 73hdr = f .read (24 ) 74if hdr [:4 ]!= b"GGUF" : 75raise SystemExit ("%s: not a GGUF file" % path ) 76self .version ,nt ,nkv = struct .unpack ("<IQQ" ,hdr [4 :]) 77buf = f .read (64 << 20 )# (the metadata: the vocabulary is a few MB) 78pos = 0 79 80def take (n ): 81nonlocal pos ,buf 82while pos + n > len (buf ): 83more = f .read (64 << 20 ) 84if not more : 85raise SystemExit ("%s: truncated metadata" % path ) 86buf += more 87v = buf [pos :pos + n ] 88pos += n 89return v 90 91def s (): 92return take (struct .unpack ("<Q" ,take (8 ))[0 ]).decode ("utf-8" ,"replace" ) 93 94fmt = {0 :"B" ,1 :"b" ,2 :"H" ,3 :"h" ,4 :"I" ,5 :"i" ,6 :"f" ,7 :"?" ,10 :"Q" ,11 :"q" ,12 :"d" } 95 96def val (t ): 97if t in fmt : 98return struct .unpack ("<" + fmt [t ],take (struct .calcsize (fmt [t ])))[0 ] 99if t == 8 : 100return s () 101if t == 9 : 102at ,n = struct .unpack ("<IQ" ,take (12 )) 103if at in fmt : 104return list (struct .unpack ("<%d%s" % (n ,fmt [at ]),take (n * struct .calcsize (fmt [at ])))) 105return [val (at )for _ in range (n )] 106raise SystemExit ("%s: metadata type %d" % (path ,t )) 107 108self .kv ,self .kv_raw = {}, [] 109for _ in range (nkv ): 110p0 = pos 111k = s () 112self .kv [k ]= val (struct .unpack ("<I" ,take (4 ))[0 ]) 113self .kv_raw .append ((k ,bytes (buf [p0 :pos ]))) 114self .tensors = [] 115for _ in range (nt ): 116name = s () 117nd = struct .unpack ("<I" ,take (4 ))[0 ] 118dims = list (struct .unpack ("<%dQ" % nd ,take (8 * nd ))) 119typ ,off = struct .unpack ("<IQ" ,take (12 )) 120self .tensors .append ([name ,typ ,dims ,off ]) 121self .align = int (self .kv .get ("general.alignment" ,32 )) 122start = 24 + pos 123self .data_start = (start + self .align - 1 )// self .align * self .align 124for t in self .tensors : 125if t [1 ]not in GT : 126raise SystemExit ("%s: %s has ggml type %d, which this tool does not read" % (path .name ,t [0 ],t [1 ])) 127t [3 ]+= self .data_start 128 129 130def kv_int (raw :bytes ,v :int )-> bytes : 131"""An integer KV record with a new value, in its own type.""" 132kl = struct .unpack ("<Q" ,raw [:8 ])[0 ] 133t = struct .unpack ("<I" ,raw [8 + kl :12 + kl ])[0 ] 134fmt = {0 :"B" ,1 :"b" ,2 :"H" ,3 :"h" ,4 :"I" ,5 :"i" ,10 :"Q" ,11 :"q" }[t ] 135return raw [:12 + kl ]+ struct .pack ("<" + fmt ,v ) 136 137 138def layer_set (spec :str )-> set [int ]: 139out = set () 140for part in str (spec ).split ("," ): 141part = part .strip () 142if not part : 143continue 144if "-" in part : 145a ,b = part .split ("-" ) 146out .update (range (int (a ),int (b )+ 1 )) 147else : 148out .add (int (part )) 149return out 150 151 152def plan_type (recipe :dict ,name :str ,typ :int ,dims :list [int ])-> int | None : 153"""The output type of a tensor (None: copied as it is, -1: left out).""" 154m = re .match (r"blk\.(\d+)\.(.+)$" ,name ) 155short = m .group (2 )if m else name 156if short .startswith ("engram_" )or short .startswith ("per_layer_token_embd" ): 157return None if recipe .get ("engram" ,"skip" )== "keep" else - 1 158if m and short in ROLE : 159role = ROLE [short ] 160t = recipe .get ("experts" , {}).get (role ,"keep" ) 161for ov in recipe .get ("layers" , []): 162if int (m .group (1 ))in layer_set (ov ["layers" ])and role in ov : 163t = ov [role ] 164if t == "keep" : 165return None 166if t not in BYNAME : 167raise SystemExit ("recipe: unknown type %r" % t ) 168q = BYNAME [t ] 169if dims [0 ]% GT [q ][1 ]: 170raise SystemExit ("%s: rows of %d are not whole %s blocks" % (name ,dims [0 ],t )) 171return q 172dense = recipe .get ("dense" ,"keep" ) 173if dense == "keep" or typ not in (1 ,30 )or len (dims )< 2 or dims [0 ]% 32 :# (F32: the router, mHC - kept) 174return None 175if any (k in short for k in recipe .get ("dense_keep" , [])): 176return None 177q = BYNAME [dense ] 178if dims [0 ]% GT [q ][1 ]: 179return None 180return q 181 182 183# ---------------------------------------------------------------- workers 184_lib = None 185_fds = {} 186_imat = None 187 188 189def _init (lib_path :str ,imatrix :str | None ): 190global _lib ,_imat 191try : 192os .sched_setscheduler (0 ,os .SCHED_IDLE ,os .sched_param (0 )) 193except (AttributeError ,OSError ): 194try : 195os .nice (19 ) 196except OSError : 197pass 198_lib = ctypes .CDLL (lib_path ) 199_lib .ggml_quantize_chunk .restype = ctypes .c_size_t 200_lib .ggml_quantize_chunk .argtypes = [ctypes .c_int ,ctypes .c_void_p ,ctypes .c_void_p ,ctypes .c_int64 ,ctypes .c_int64 , 201ctypes .c_int64 ,ctypes .c_void_p ] 202_lib .ggml_quantize_init .argtypes = [ctypes .c_int ] 203_imat = load_imatrix (imatrix )if imatrix else None 204 205 206def load_imatrix (path :str )-> dict : 207"""llama.cpp's legacy imatrix .dat: {tensor name: float32 values (ne0, or ne0 * n_expert for experts)}.""" 208out = {} 209with open (path ,"rb" )as f : 210n = struct .unpack ("<i" ,f .read (4 ))[0 ] 211for _ in range (n ): 212ln = struct .unpack ("<i" ,f .read (4 ))[0 ] 213name = f .read (ln ).decode () 214ncall ,nval = struct .unpack ("<ii" ,f .read (8 )) 215v = np .frombuffer (f .read (4 * nval ),dtype = np .float32 ).copy () 216out [name ]= v / max (1 ,ncall ) 217return out 218 219 220def _fd (path :str ,direct :bool ): 221key = (path ,direct ) 222if key not in _fds : 223flags = os .O_RDONLY | (getattr (os ,"O_DIRECT" ,0 )if direct else 0 ) 224try : 225_fds [key ]= os .open (path ,flags ) 226except OSError : 227_fds [key ]= os .open (path ,os .O_RDONLY ) 228return _fds [key ] 229 230 231def read_src (path :str ,off :int ,n :int )-> memoryview : 232a0 = off // ALIGN_IO * ALIGN_IO 233a1 = (off + n + ALIGN_IO - 1 )// ALIGN_IO * ALIGN_IO 234buf = mmap .mmap (- 1 ,a1 - a0 ) 235try : 236got = os .preadv (_fd (path ,True ), [buf ],a0 ) 237except OSError :# (no O_DIRECT here: a plain read) 238got = os .preadv (_fd (path ,False ), [buf ],a0 ) 239if got < off - a0 + n : 240raise IOError ("%s: short read at %d" % (path ,off )) 241return memoryview (buf )[off - a0 :off - a0 + n ] 242 243 244E2M1 = np .array ([0 ,1 ,2 ,3 ,4 ,6 ,8 ,12 ,0 ,- 1 ,- 2 ,- 3 ,- 4 ,- 6 ,- 8 ,- 12 ],dtype = np .float32 ) 245 246 247def to_f32 (typ :int ,raw :memoryview ,n :int )-> np .ndarray : 248b = np .frombuffer (raw ,dtype = np .uint8 ) 249if typ == 0 : 250return np .frombuffer (raw ,dtype = np .float32 ).copy () 251if typ == 1 : 252return np .frombuffer (raw ,dtype = np .float16 ).astype (np .float32 ) 253if typ == 30 : 254return (np .frombuffer (raw ,dtype = np .uint16 ).astype (np .uint32 )<< 16 ).view (np .float32 ) 255if typ == 8 : 256blk = b .reshape (- 1 ,34 ) 257d = blk [:, :2 ].copy ().view (np .float16 ).astype (np .float32 ) 258q = blk [:,2 :].view (np .int8 ).astype (np .float32 ) 259return (q * d ).reshape (- 1 ) 260if typ == 39 :# ggml's MXFP4: [e8m0][16 code bytes], value j = kvalues[code] * 2^(e - 128) 261blk = b .reshape (- 1 ,17 ) 262e = blk [:,0 ].astype (np .int32 ) 263d = np .ldexp (np .float32 (1.0 ),e - 128 ).astype (np .float32 ) 264q = blk [:,1 :] 265v = np .empty ((blk .shape [0 ],32 ),dtype = np .float32 ) 266v [:, :16 ]= E2M1 [q & 15 ] 267v [:,16 :]= E2M1 [q >> 4 ] 268return (v * d [:,None ]).reshape (- 1 ) 269raise ValueError ("source type %d" % typ ) 270 271 272def _job (j :dict ): 273"""One piece of a tensor: rows [r0, r1) (of ne0 values each) quantized, or bytes copied; written in place.""" 274t0 = time .time () 275out_fd = os .open (j ["out" ],os .O_WRONLY ) 276try : 277if j ["q" ]is None :# a copy, in pieces of 256 MB 278n ,done = j ["n" ],0 279while done < n : 280k = min (256 << 20 ,n - done ) 281os .pwrite (out_fd ,read_src (j ["src" ],j ["src_off" ]+ done ,k ),j ["out_off" ]+ done ) 282done += k 283else : 284ne0 ,r0 ,r1 ,st ,q = j ["ne0" ],j ["r0" ],j ["r1" ],j ["typ" ],j ["q" ] 285srb = GT [st ][2 ]* ne0 // GT [st ][1 ] 286raw = read_src (j ["src" ],j ["src_off" ]+ r0 * srb , (r1 - r0 )* srb ) 287x = np .ascontiguousarray (to_f32 (st ,raw , (r1 - r0 )* ne0 ),dtype = np .float32 ) 288del raw 289qrb = GT [q ][2 ]* ne0 // GT [q ][1 ] 290dst = np .empty ((r1 - r0 )* qrb ,dtype = np .uint8 ) 291imat = None 292if q in NEED_IMATRIX or (_imat is not None and j ["iname" ]in _imat ): 293w = _imat .get (j ["iname" ])if _imat is not None else None 294if w is None or w .size % ne0 : 295w = np .ones (ne0 ,dtype = np .float32 ) 296imat = w 297rows_per = j ["rows_per_expert" ] 298r = r0 299while r < r1 :# (one expert's rows at a time: an expert's own importance row) 300n = min (r1 - r ,rows_per - r % rows_per if rows_per else r1 - r ) 301im = None 302if imat is not None : 303e = r // rows_per if rows_per else 0 304im = imat [e * ne0 :(e + 1 )* ne0 ]if imat .size >= (e + 1 )* ne0 else imat [:ne0 ] 305im = np .ascontiguousarray (im ,dtype = np .float32 ) 306got = _lib .ggml_quantize_chunk (q ,x [(r - r0 )* ne0 :].ctypes .data ,dst [(r - r0 )* qrb :].ctypes .data , 3070 ,n ,ne0 ,im .ctypes .data if im is not None else None ) 308if got != n * qrb : 309raise RuntimeError ("%s: ggml_quantize_chunk wrote %d bytes, expected %d" % (j ["name" ],got ,n * qrb )) 310r += n 311os .pwrite (out_fd ,memoryview (dst ),j ["out_off" ]+ r0 * qrb ) 312j ["n" ]= (r1 - r0 )* qrb 313j ["out_off" ]+= r0 * qrb 314os .fdatasync (out_fd ) 315try : 316os .posix_fadvise (out_fd ,j ["out_off" ],j ["n" ],os .POSIX_FADV_DONTNEED ) 317except (AttributeError ,OSError ): 318pass 319finally : 320os .close (out_fd ) 321return j ["name" ],j ["n" ],time .time ()- t0 322 323 324# ---------------------------------------------------------------- main 325def main ()-> int : 326ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 327ap .add_argument ("--src" ,required = True ,help = "the source GGUF's shards (a directory)" ) 328ap .add_argument ("--out" ,required = True ,help = "the output directory" ) 329ap .add_argument ("--recipe" ,required = True ,help = "the recipe (JSON file)" ) 330ap .add_argument ("--lib" ,default = os .path .expanduser ("~/llama.cpp/build/bin/libggml-base.so" ), 331help = "libggml-base (ggml_quantize_chunk)" ) 332ap .add_argument ("--imatrix" ,help = "llama.cpp's legacy imatrix .dat (default: all ones where a type needs one)" ) 333ap .add_argument ("--jobs" ,type = int ,default = max (1 , (os .cpu_count ()or 2 )- 2 )) 334ap .add_argument ("--experts-per-job" ,type = int ,default = 4 ) 335ap .add_argument ("--engram-link" ,action = "store_true" , 336help = "(engram skip) link the source's shards as <out>/Engram/, the shared Engram set" ) 337ap .add_argument ("--dry-run" ,action = "store_true" ,help = "print the plan and the output size" ) 338ap .add_argument ("--only" ,help = "regex: quantize only the matching tensors (the rest zero-filled: tests)" ) 339ap .add_argument ("--first" ,help = "regex: the matching tensors' pieces first (e.g. a few layers for a quick test)" ) 340ap .add_argument ("--resume" ,action = "store_true" , 341help = "keep the output files of an earlier run (same plan) and skip the pieces already written" ) 342a = ap .parse_args () 343 344src = pathlib .Path (a .src ).expanduser ().resolve () 345out = pathlib .Path (a .out ).expanduser () 346recipe = json .loads (pathlib .Path (a .recipe ).read_text ()) 347shards = sorted (src .glob ("*.gguf" )) 348if not shards : 349raise SystemExit ("%s: no .gguf files" % src ) 350ss = [Shard (p )for p in shards ] 351 352jobs ,plan_sizes ,outs = [], {}, [] 353for si ,sh in enumerate (ss ): 354kept = [] 355for name ,typ ,dims ,off in sh .tensors : 356q = plan_type (recipe ,name ,typ ,dims ) 357if q == - 1 : 358continue 359kept .append ((name ,typ ,dims ,off ,typ if q is None else q ,q )) 360# the output's layout: the KV records (split.tensors.count updated), the tensor infos, the data 361kv = [] 362for k ,raw in sh .kv_raw : 363if k == "split.tensors.count" : 364total = sum (1 for s2 in ss for t in s2 .tensors if plan_type (recipe ,t [0 ],t [1 ],t [2 ])!= - 1 ) 365raw = kv_int (raw ,total ) 366kv .append (raw ) 367tinfo ,data_off = [],0 368for name ,typ ,dims ,off ,otyp ,q in kept : 369nb = nbytes_of (otyp ,dims ) 370tinfo .append ((name ,dims ,otyp ,data_off ,nb )) 371data_off += (nb + sh .align - 1 )// sh .align * sh .align 372plan_sizes [GT [otyp ][0 ]]= plan_sizes .get (GT [otyp ][0 ],0 )+ nb 373head = struct .pack ("<4sIQQ" ,b"GGUF" ,sh .version ,len (tinfo ),len (kv ))+ b"" .join (kv ) 374for name ,dims ,otyp ,doff ,nb in tinfo : 375nm = name .encode () 376head += struct .pack ("<Q" ,len (nm ))+ nm + struct .pack ("<I" ,len (dims )) 377head += struct .pack ("<%dQ" % len (dims ),* dims )+ struct .pack ("<IQ" ,otyp ,doff ) 378dstart = (len (head )+ sh .align - 1 )// sh .align * sh .align 379opath = out / sh .path .name .replace ("UD-Q8_K_XL" ,"requant" ) 380outs .append ((opath ,head ,dstart + data_off )) 381for (name ,typ ,dims ,off ,otyp ,q ), (_ ,_ ,_ ,doff ,nb )in zip (kept ,tinfo ): 382if a .only and not re .search (a .only ,name ): 383continue 384base = {"name" :name ,"src" :str (sh .path ),"src_off" :off ,"out" :str (opath ),"out_off" :dstart + doff } 385if q is None : 386jobs .append (dict (base ,q = None ,n = nb )) 387continue 388ne0 = dims [0 ] 389rows = 1 390for d in dims [1 :]: 391rows *= d 392rpe = dims [1 ]if len (dims )== 3 else 0 # rows an expert (3-D: [n_exp][rows][ne0]) 393step = rpe * a .experts_per_job if rpe else max (1 , (64 << 20 )// (4 * ne0 )) 394m = re .match (r"blk\.(\d+)\.(.+)$" ,name ) 395iname = name 396for r0 in range (0 ,rows ,step ): 397jobs .append (dict (base ,q = q ,typ = typ ,ne0 = ne0 ,r0 = r0 ,r1 = min (rows ,r0 + step ),rows_per_expert = rpe , 398iname = iname ,n = 0 )) 399total = sum (o [2 ]for o in outs ) 400"plan: %d shards, %.1f GB (%s), %d jobs" % (len (outs ),total / 1e9 , 401", " .join ("%s %.1f GB" % (k ,v / 1e9 )for k ,v in sorted (plan_sizes .items ())),len (jobs )),flush = True ) 402# the free-space check the release runbook promises (DEEPSEEK-RELEASE.MD 9.6 item 5): the plan's bytes against what 403# the output's filesystem has, with 2% of headroom. It runs in --dry-run too, so the operator sees the verdict 404# before committing hours of CPU. 405probe = out if out .exists ()else next ((p for p in [out .parent ,pathlib .Path ("/" )]if p .exists ()),pathlib .Path ("/" )) 406du = shutil .disk_usage (probe ) 407"space: %.1f GB planned, %.1f GB free on %s%s" % (total / 1e9 ,du .free / 1e9 ,probe , 408"" if du .free * 0.98 >= total else " <- NOT ENOUGH" ),flush = True ) 409if a .dry_run :# nothing is written: report the verdict, and 3 when the space is short (so `--dry-run && requant` works) 410return 0 if du .free * 0.98 >= total else 3 411if a .resume : 412have = sum (p .stat ().st_size for p in out .glob ("*.gguf" )if p .is_file ())if out .exists ()else 0 413need = max (0 ,total - have ) 414if du .free * 0.98 < need : 415raise SystemExit ("%s: %d GB free, %d GB more needed (%d GB already written) - free space first" 416% (out ,du .free / 1e9 ,need / 1e9 ,have / 1e9 )) 417elif du .free * 0.98 < total : 418raise SystemExit ("%s: %d GB free, %d GB needed - free space first (or --out elsewhere)" 419% (out ,du .free / 1e9 ,total / 1e9 )) 420out .mkdir (parents = True ,exist_ok = True ) 421for opath ,head ,size in outs : 422if a .resume and opath .is_file ()and opath .stat ().st_size == size : 423with open (opath ,"r+b" )as f : 424if f .read (len (head ))!= head : 425raise SystemExit ("%s: not this plan's file (--resume)" % opath ) 426continue 427with open (opath ,"wb" )as f : 428f .write (head ) 429f .truncate (size ) 430if a .resume :# a piece is written when the first and last 256 bytes of its output are not all zero 431def written (j ): 432n = j ["n" ]if j ["q" ]is None else (j ["r1" ]- j ["r0" ])* GT [j ["q" ]][2 ]* j ["ne0" ]// GT [j ["q" ]][1 ] 433o = j ["out_off" ]+ (0 if j ["q" ]is None else j ["r0" ]* GT [j ["q" ]][2 ]* j ["ne0" ]// GT [j ["q" ]][1 ]) 434with open (j ["out" ],"rb" )as f : 435f .seek (o ) 436h = f .read (min (256 ,n )) 437f .seek (o + max (0 ,n - 256 )) 438t = f .read (min (256 ,n )) 439return any (h )and any (t ) 440before = len (jobs ) 441jobs = [j for j in jobs if not written (j )] 442"resume: %d of %d pieces already written" % (before - len (jobs ),before ),flush = True ) 443if a .engram_link and recipe .get ("engram" ,"skip" )== "skip" : 444eg = out / "Engram" 445eg .mkdir (exist_ok = True ) 446for p in shards : 447link = eg / p .name 448if not link .exists (): 449link .symlink_to (p ) 450# the biggest pieces first (the experts), so the last minutes are not one long tensor 451jobs .sort (key = lambda j :- (j .get ("r1" ,0 )- j .get ("r0" ,0 ))* j .get ("ne0" ,0 )if j ["q" ]is not None else 0 ) 452if a .first : 453jobs .sort (key = lambda j :0 if re .search (a .first ,j ["name" ])else 1 ) 454t0 ,done_b ,done_j = time .time (),0 ,0 455with mp .get_context ("fork" ).Pool (a .jobs ,initializer = _init ,initargs = (os .path .expanduser (a .lib ),a .imatrix ))as pool : 456for name ,nb ,dt in pool .imap_unordered (_job ,jobs ): 457done_b += nb 458done_j += 1 459if done_j % 50 == 0 or done_j == len (jobs ): 460el = time .time ()- t0 461"%d / %d jobs, %.1f GB written, %.0f s (%.0f min left)" % 462 (done_j ,len (jobs ),done_b / 1e9 ,el ,el / done_j * (len (jobs )- done_j )/ 60 ),flush = True ) 463"done: %s (%.1f GB) in %.1f min" % (out ,total / 1e9 , (time .time ()- t0 )/ 60 )) 464return 0 465 466 467if __name__ == "__main__" : 468sys .exit (main ())