okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/nvfp4_local_pack.py - NVIDIA's Qwen3.8-Flash-Next-FP4-Local (ModelOpt, QAD) -> files Strata can pack. 2 3python tools/nvfp4_local_pack.py convert --model <nvidia/Qwen3.8-Flash-Next-FP4-Local dir> --outfile <model.gguf> 4python tools/nvfp4_local_pack.py ple --model <same dir> --out <ple-nvfp4.gguf> 5python tools/nvfp4_local_pack.py mtp --model <same dir> --out <mtp src dir> (then tools/mtp_pack.py, tools/mtp_rt.py) 6python tools/nvfp4_local_pack.py pack --model <same dir> --dense-gguf <dense.gguf> --out <pack dir> (instead of iq_pack on a full GGUF) 7python tools/nvfp4_local_pack.py verify --model <same dir> --gguf <model.gguf> [--experts 6] 8python tools/iq_pack.py --gguf <model.gguf> --out <pack dir> 9 10Nothing of NVIDIA's weights is shipped: the user downloads the checkpoint from NVIDIA's repository and this runs 11locally. What the checkpoint stores, and what is done with it: 12 13* routed experts: NVFP4 (E2M1 codes, E4M3 scale per 16 values, F32 weight_scale_2). The block scales are stored 14in NVIDIA's "CSF" form (config `weight_scale_encoding: "csf"`, codec byte-window4-fixed-stream-u24-exceptions/1): 15per tensor a `.nvfp4_csf_fixed` U8 stream and a `.nvfp4_csf_exceptions` U32 stream. They are decoded here to the 16plain E4M3 matrix (the format is documented by vLLM's loader, PR 60646, and flashinfer's b12x decoder, both 17Apache-2.0; this is a fresh implementation of that description), and from there the ordinary ModelOpt NVFP4 18repack of tools/nvfp4_convert.py applies, bit for bit. 19* attention, GDN projections, shared experts, indexer: MXFP8 (E4M3 values, E8M0 scale per 32 values). They are 20dequantized exactly to BF16 and then take the type policy of tools/nvfp4_convert.py (Q8_0 for the big ones, 21BF16 for the small projections the BF16 kernels read). Q8_0 has the same 32-value blocks; the added error is 22~0.6% RMS against MXFP8's own ~3%. 23* the 26.8 GiB n-gram (PLE) table is NVFP4 too (160 values a row: 80 B of codes, 10 E4M3 scales, one F32 for the 24whole table). `ple` copies it row by row into a one-tensor GGUF of 90-byte rows. 25* the MTP head (NVFP4 experts, BF16 rest) is dequantized by `mtp` into the folder form tools/mtp_pack.py reads. 26The vision tower is not written (text first). 27""" 28from __future__import annotations 29 30import argparse 31import json 32import pathlib 33import struct 34import sys 35import time 36 37import numpy as np 38 39HERE = pathlib .Path (__file__ ).resolve ().parent 40sys .path .insert (0 ,str (HERE )) 41 42# #3227: llama.cpp's converter (conversion/base.py: `from transformers import AutoConfig`) and the MXFP8 / NVFP4 decoding below need 43# these; setup installs them from requirements-nvfp4-local.txt before a prepare, and a run by hand says which one is missing. 44NEEDED_PACKAGES = ("torch" ,"transformers" ,"safetensors" ) 45MARKS = ("ple-nvfp4.gguf.done" ,"dense.gguf.done" ,"pack.done" ,"draft.done" ) 46 47 48def require_packages ()-> None : 49import importlib .util 50missing = [m for m in NEEDED_PACKAGES if importlib .util .find_spec (m )is None ] 51if missing : 52req = HERE .parent / "requirements-nvfp4-local.txt" 53sys .exit ("tools/nvfp4_local_pack.py needs the Python package%s %s, which %s not installed for %s.\n" 54"Install %s with: %s -m pip install -r %s" % ("s" if len (missing )> 1 else "" ,", " .join (missing ), 55"are" if len (missing )> 1 else "is" ,sys .executable , 56"them" if len (missing )> 1 else "it" ,sys .executable ,req )) 57 58 59CSF_FIXED = ".nvfp4_csf_fixed" 60CSF_EXC = ".nvfp4_csf_exceptions" 61PLE_ROW_BYTES = 90 # 80 B of E2M1 codes + 10 E4M3 block scales, per 160-value row 62 63 64# --------------------------------------------------------------------------------------------- safetensors access 65class Checkpoint : 66"""Header-indexed, buffered access to a checkpoint's safetensors shards (raw bytes, any dtype). 67 68Reads go through a cached file handle into a fresh buffer instead of a process-lifetime np.memmap: 69a memmap sweep of the ~64 GB of expert bytes charges every faulted page to the PROCESS WORKING 70SET, which Windows (and every free-RAM observer reading GlobalMemoryStatusEx) counts as used 71until the OS trims it - the pack step then looks like a ~64 GB RAM demand while its real 72committed need is a few GB, and under memory pressure it is the pack run itself that pays 73(issue: the silent exit-1 mid-pack failure). 74A cached sequential read puts the same pages in the system file cache (standby: counted as 75available). The returned array is a fresh WRITABLE buffer - no consumer writes (a mutator would 76previously have hit the read-only memmap) - and reads share one handle per shard, so raw() is 77not thread-safe, unlike the memmap it replaces. Each shard is read as three ascending streams 78(exceptions, weights, CSF-fixed) walked expert-ascending.""" 79 80def __init__ (self ,folder ,partial_ok = False ): 81self .dir = pathlib .Path (folder ) 82index = self .dir / "model.safetensors.index.json" 83if index .exists (): 84wmap = json .loads (index .read_text (encoding = "utf-8" ))["weight_map" ] 85files = sorted (set (wmap .values ())) 86else : 87files = sorted (p .name for p in self .dir .glob ("*.safetensors" )) 88if not files : 89raise FileNotFoundError ("no .safetensors files in " + str (self .dir )) 90self .meta :dict [str ,tuple [str ,str ,list [int ],int ,int ]]= {} 91self ._fh :dict [str ,"object" ]= {} 92for fn in files : 93path = self .dir / fn 94if not path .exists ()and partial_ok : 95continue # a subset of the shards (the MTP head is in two) 96with open (path ,"rb" )as f : 97n = struct .unpack ("<Q" ,f .read (8 ))[0 ] 98hdr = json .loads (f .read (n )) 99for k ,v in hdr .items (): 100if k != "__metadata__" : 101a ,b = v ["data_offsets" ] 102self .meta [k ]= (fn ,v ["dtype" ],v ["shape" ],8 + n + a ,8 + n + b ) 103 104def __contains__ (self ,name ): 105return name in self .meta 106 107def dtype (self ,name ): 108return self .meta [name ][1 ] 109 110def shape (self ,name ): 111return self .meta [name ][2 ] 112 113def raw (self ,name )-> np .ndarray : 114fn ,_ ,_ ,a ,b = self .meta [name ] 115f = self ._fh .get (fn ) 116if f is None : 117f = self ._fh [fn ]= open (self .dir / fn ,"rb" ) 118buf = np .empty (b - a ,dtype = np .uint8 ) 119f .seek (a ) 120if f .readinto (buf )!= b - a : 121raise EOFError ("%s: shard %s ended early at %d" % (name ,fn ,a )) 122return buf 123 124def array (self ,name ,np_dtype )-> np .ndarray : 125return self .raw (name ).view (np_dtype ).reshape (self .shape (name )) 126 127 128# ----------------------------------------------------------------------------------------------------- CSF decoding 129def csf_decode (fixed :np .ndarray ,exceptions :np .ndarray )-> np .ndarray : 130"""The CSF stream pair -> the plain E4M3 block-scale matrix as uint8 [rows, cols] (cols = K / 16). 131 132fixed: uint8 [rows / 16, 16 * (1 + cols / 2)]. Per slab of 16 rows: the 16 rows' base bytes, then each 133row's cols 4-bit codes (two to a byte, low nibble first). A scale byte is base + code. 134exceptions: uint32 words, low 24 bits = flat row * cols + col, high 8 bits = the scale byte there. 135""" 136if fixed .dtype != np .uint8 or fixed .ndim != 2 or fixed .shape [1 ]% 16 or fixed .shape [1 ]< 32 : 137raise ValueError ("invalid CSF fixed stream %s %s" % (fixed .dtype ,fixed .shape )) 138if exceptions .dtype != np .uint32 : 139raise ValueError ("invalid CSF exceptions dtype %s" % exceptions .dtype ) 140rows = fixed .shape [0 ]* 16 141cols = (fixed .shape [1 ]// 16 - 1 )* 2 142bases = fixed [:, :16 ].reshape (rows ,1 ).astype (np .int16 ) 143if (bases > 240 ).any (): 144raise ValueError ("CSF row bases must be in 0..240" ) 145packed = fixed [:,16 :].reshape (rows ,cols // 2 ) 146codes = np .stack ((packed & 0xF ,packed >> 4 ),axis =- 1 ).reshape (rows ,cols ) 147out = (bases + codes ).reshape (- 1 ) 148words = exceptions .reshape (- 1 ).astype (np .int64 ) 149pos = words & 0xFFFFFF 150if pos .size and int (pos .max ())>= rows * cols : 151raise ValueError ("CSF exception position out of range" ) 152out [pos ]= words >> 24 153return out .astype (np .uint8 ).reshape (rows ,cols ) 154 155 156def csf_encode (scales :np .ndarray )-> tuple [np .ndarray ,np .ndarray ]: 157"""The inverse, for the tests: uint8 [rows, cols] -> (fixed, exceptions). Base = the row's most common 158window start; whatever falls outside base..base+15 is an exception.""" 159rows ,cols = scales .shape 160assert rows % 16 == 0 and cols % 2 == 0 161base = np .zeros (rows ,np .int16 ) 162for r in range (rows ): 163v = scales [r ].astype (np .int16 ) 164best = (- 1 ,0 ) 165for b in range (max (0 ,int (v .min ())- 0 ),int (v .max ())+ 1 ): 166c = int (((v >= b )& (v <= b + 15 )).sum ()) 167if c > best [0 ]: 168best = (c ,b ) 169base [r ]= min (best [1 ],240 ) 170code = scales .astype (np .int16 )- base [:,None ] 171exc = (code < 0 )| (code > 15 ) 172code = np .where (exc ,0 ,code ).astype (np .uint8 ) 173pk = (code [:,0 ::2 ]| (code [:,1 ::2 ]<< 4 )).astype (np .uint8 ) 174fixed = np .empty ((rows // 16 ,16 * (1 + cols // 2 )),np .uint8 ) 175for s in range (rows // 16 ): 176fixed [s , :16 ]= base [s * 16 :(s + 1 )* 16 ].astype (np .uint8 ) 177fixed [s ,16 :]= pk [s * 16 :(s + 1 )* 16 ].reshape (- 1 ) 178pos = np .flatnonzero (exc .reshape (- 1 )) 179words = (pos .astype (np .uint64 )| (scales .reshape (- 1 )[pos ].astype (np .uint64 )<< 24 )).astype (np .uint32 ) 180return fixed ,words 181 182 183# --------------------------------------------------------------------------------------------- MXFP8 dequantizing 184def mxfp8_dequant (values_u8 :np .ndarray ,scales_u8 :np .ndarray ): 185"""MXFP8 (E4M3 values [R, K], E8M0 scale bytes [R, K/32]) -> float32 [R, K]. Exact (4-bit significands).""" 186import torch 187R ,K = values_u8 .shape 188if scales_u8 .shape != (R ,K // 32 )or K % 32 : 189raise ValueError ("MXFP8 shapes %s / %s" % (values_u8 .shape ,scales_u8 .shape )) 190if (scales_u8 == 255 ).any (): 191raise ValueError ("MXFP8 scale byte 255 (NaN) in a weight" ) 192v = torch .from_numpy (np .ascontiguousarray (values_u8 )).view (torch .float8_e4m3fn ).to (torch .float32 ) 193s = torch .from_numpy (np .exp2 (scales_u8 .astype (np .float32 )- 127.0 )) 194return (v .reshape (R ,K // 32 ,32 )* s [:, :,None ]).reshape (R ,K ) 195 196 197# --------------------------------------------------------------------------- the overlay on llama.cpp's tensor index 198def _orig_name (ck :Checkpoint ,name :str ): 199"""The converter strips `language_model.`; find the checkpoint's own name.""" 200if name in ck : 201return name 202for cand in (name .replace ("model." ,"model.language_model." ,1 ),"model.language_model." + name ): 203if cand in ck : 204return cand 205return None 206 207 208def overlay (tensors :dict ,ck :Checkpoint ,stats :dict ,dense_only :bool = False )-> dict : 209"""Replace the CSF stream pairs by plain `weight_scale` tensors, the MXFP8 weights by BF16, and drop what 210the PLE writer and the MTP packer own.""" 211import torch 212out = dict (tensors ) 213if dense_only :# the GGUF the engine reads the dense weights from: no experts in it 214out = {k :v for k ,v in out .items ()if ".mlp.experts." not in k } 215for name in list (out ): 216if name not in out : 217continue 218if name .endswith (CSF_FIXED ): 219base = name [:- len (CSF_FIXED )]# ...weight_scale 220o_fix = _orig_name (ck ,name ) 221o_exc = _orig_name (ck ,base + CSF_EXC ) 222if o_fix is None or o_exc is None : 223raise ValueError ("CSF fixed stream without its exceptions: " + name ) 224 225def gen (o_fix = o_fix ,o_exc = o_exc ): 226dec = csf_decode (ck .array (o_fix ,np .uint8 ),ck .array (o_exc ,np .uint32 )) 227return torch .from_numpy (dec ).view (torch .float8_e4m3fn ) 228del out [name ] 229out .pop (base + CSF_EXC ,None ) 230out [base ]= gen 231stats ["csf" ]= stats .get ("csf" ,0 )+ 1 232elif ".ngram_embedding." in name and (name .endswith (".weight_scale" )or name .endswith (".weight_scale_2" )): 233del out [name ]# the PLE table has its own writer (`ple`) 234for name in list (out ): 235if not name .endswith (".weight" )or ".ngram_embedding." in name : 236continue 237sname = name [:- len (".weight" )]+ ".weight_scale" 238o_w ,o_s = _orig_name (ck ,name ),_orig_name (ck ,sname ) 239if o_w is None or o_s is None or sname not in out : 240continue 241if ck .dtype (o_w )== "F8_E4M3" and ck .dtype (o_s )== "U8" :# MXFP8 242def gen (o_w = o_w ,o_s = o_s ): 243f = mxfp8_dequant (np .asarray (ck .raw (o_w )).reshape (ck .shape (o_w )),np .asarray (ck .raw (o_s )).reshape (ck .shape (o_s ))) 244return f .to (torch .bfloat16 ) 245out [name ]= gen 246del out [sname ] 247stats ["mxfp8" ]= stats .get ("mxfp8" ,0 )+ 1 248return out 249 250 251def install (ck :Checkpoint ,stats :dict ,dense_only :bool = False ): 252"""Import the converter, give it nvfp4_convert's type policy, and hook the tensor index.""" 253import nvfp4_convert as base 254base .install_policy () 255from conversion .base import ModelBase 256from conversion import qwen4exp as Q4 257orig_index = ModelBase .index_tensors 258 259def index_tensors (self ,remote_hf_model_id = None ): 260return overlay (orig_index (self ,remote_hf_model_id ),ck ,stats ,dense_only ) 261ModelBase .index_tensors = index_tensors 262 263# NVIDIA's repo keeps the shards in a `tensors/` folder that its index names; the converter only lists the top level 264orig_parts = ModelBase .get_model_part_names 265 266def get_model_part_names (dir_model ,prefix ,suffix ): 267names = orig_parts (dir_model ,prefix ,suffix ) 268sub = pathlib .Path (dir_model )/ "tensors" 269if not names and suffix == ".safetensors" and prefix == "model" and sub .is_dir (): 270names = sorted ("tensors/" + p .name for p in sub .glob ("model*.safetensors" )) 271return names 272ModelBase .get_model_part_names = staticmethod (get_model_part_names ) 273 274cls = Q4 .Qwen4ExpTextModel 275 276def place_ple_shard (self ,data_torch ,name ): 277# the shards are NVFP4 here: two values a byte, so a row of 160 values is 80 bytes 278idx = int (name .rsplit ("shard_" ,1 )[1 ].split ("." ,1 )[0 ]) 279self ._ple_shards [idx ]= name 280self ._ple_row_dim = int (data_torch .shape [- 1 ])* 2 281base .dropped_ple .append (name ) 282return [] 283cls ._place_ple_shard = place_ple_shard 284return base 285 286 287def cmd_convert (a )-> int : 288require_packages () 289model = pathlib .Path (a .model ) 290ck = Checkpoint (model ) 291stats :dict = {} 292base = install (ck ,stats ,a .dense_only ) 293import convert_hf_to_gguf as C 294out = pathlib .Path (a .outfile ) 295out .parent .mkdir (parents = True ,exist_ok = True ) 296argv = [str (model ),"--outtype" ,"q8_0" ,"--outfile" ,str (out )]+ (["--dry-run" ]if a .dry_run else []) 297sys .argv = ["convert_hf_to_gguf.py" ]+ argv 298t0 = time .time () 299rc = C .main () 300took = time .time ()- t0 301"nvfp4_local_pack: done in %.0f s; CSF scale tensors decoded %d, MXFP8 weights dequantized %d, PLE shards dropped %d" 302% (took ,stats .get ("csf" ,0 ),stats .get ("mxfp8" ,0 ),len (base .dropped_ple ))) 303if not a .dry_run : 304out .with_suffix (".manifest.json" ).write_text (json .dumps ({ 305"source" :str (model ),"csf_decoded" :stats .get ("csf" ,0 ),"mxfp8_dequantized" :stats .get ("mxfp8" ,0 ), 306"ple_table" :"written separately: nvfp4_local_pack.py ple" ,"mtp" :"not written" ,"seconds" :round (took ,1 )}, 307indent = 2 )+ "\n" ,encoding = "utf-8" ) 308return rc or 0 309 310 311# ------------------------------------------------------------------------------------------------- the PLE table 312GGUF_TYPE_STRING ,GGUF_TYPE_F32 = 8 ,6 313GGML_TYPE_I8 = 24 314ALIGN = 32 315 316 317def _gs (s ): 318b = s .encode ("utf-8" ) 319return struct .pack ("<Q" ,len (b ))+ b 320 321 322def interleave_rows (codes :np .ndarray ,scales :np .ndarray )-> np .ndarray : 323"""[n, 80] codes + [n, 10] E4M3 scale bytes -> [n, 90]: the codes, then the scales.""" 324return np .concatenate ([codes ,scales ],axis = 1 ) 325 326 327def cmd_ple (a )-> int : 328model ,out = pathlib .Path (a .model ),pathlib .Path (a .out ) 329ck = Checkpoint (model ,partial_ok = True )# the table is in six of the shards; a folder with only those works 330shards = {} 331for name in ck .meta : 332if ".ngram_embedding.shard_" in name and name .endswith (".weight" ): 333shards [int (name .rsplit (".shard_" ,1 )[1 ].split ("." )[0 ])]= name 334if not shards or sorted (shards )!= list (range (len (shards ))): 335sys .exit ("the n-gram shards are missing or not numbered 0..N-1" ) 336g = [k for k in ck .meta if k .endswith (".ngram_embedding.weight_scale_2" )] 337if len (g )!= 1 : 338sys .exit ("expected one ngram_embedding.weight_scale_2" ) 339scale2 = float (ck .array (g [0 ],np .float32 ).reshape (- 1 )[0 ]) 340rows ,dim = 0 ,None 341for k in range (len (shards )): 342n = shards [k ] 343r ,c = ck .shape (n ) 344if ck .dtype (n )!= "U8" or c != 80 or ck .shape (n [:- 6 ]+ "weight_scale" )!= [r ,10 ]: 345sys .exit ("%s: not an NVFP4 160-value row table" % n ) 346rows += r 347"%d shards, %d rows x 160, global scale %.9g, %.2f GB" % (len (shards ),rows ,scale2 ,rows * PLE_ROW_BYTES / 1e9 ),flush = True ) 348kvs = (_gs ("general.architecture" )+ struct .pack ("<I" ,GGUF_TYPE_STRING )+ _gs ("strata-ple" ) 349+ _gs ("general.name" )+ struct .pack ("<I" ,GGUF_TYPE_STRING )+ _gs ("PLE n-gram table, NVFP4 as shipped" ) 350+ _gs ("strata.ple.format" )+ struct .pack ("<I" ,GGUF_TYPE_STRING )+ _gs ("nvfp4x16" ) 351+ _gs ("strata.ple.scale" )+ struct .pack ("<I" ,GGUF_TYPE_F32 )+ struct .pack ("<f" ,scale2 ) 352+ _gs ("strata.ple.source" )+ struct .pack ("<I" ,GGUF_TYPE_STRING )+ _gs (model .name )) 353# the tensor is [90, rows] I8 so one row is 90 contiguous bytes; the engine reads it by the format key 354head = b"GGUF" + struct .pack ("<IQQ" ,3 ,1 ,5 )+ kvs 355head += _gs ("per_layer_token_embd.weight" )+ struct .pack ("<I" ,2 )+ struct .pack ("<QQ" ,PLE_ROW_BYTES ,rows ) 356head += struct .pack ("<I" ,GGML_TYPE_I8 )+ struct .pack ("<Q" ,0 ) 357head += b"\0" * ((- len (head ))% ALIGN ) 358out .parent .mkdir (parents = True ,exist_ok = True ) 359tmp = out .with_suffix (out .suffix + ".part" ) 360CH = 1 << 20 361with open (tmp ,"wb" )as w : 362w .write (head ) 363for k in range (len (shards )): 364n = shards [k ] 365codes = ck .array (n ,np .uint8 ) 366sc = ck .array (n [:- 6 ]+ "weight_scale" ,np .uint8 ) 367for i in range (0 ,codes .shape [0 ],CH ): 368w .write (np .ascontiguousarray (interleave_rows (codes [i :i + CH ],sc [i :i + CH ])).tobytes ()) 369if k % 16 == 15 or k == len (shards )- 1 : 370" %3d/%d shards" % (k + 1 ,len (shards )),flush = True ) 371if tmp .stat ().st_size != len (head )+ rows * PLE_ROW_BYTES : 372sys .exit ("size check failed" ) 373tmp .replace (out ) 374"wrote %s (%d rows x %d B)" % (out ,rows ,PLE_ROW_BYTES )) 375return 0 376 377 378# ------------------------------------------------------------------------------------------------------- the MTP head 379E2M1 = np .array ([0 ,.5 ,1 ,1.5 ,2 ,3 ,4 ,6 ,- 0. ,- .5 ,- 1 ,- 1.5 ,- 2 ,- 3 ,- 4 ,- 6 ],np .float32 ) 380 381 382def e4m3_table ()-> np .ndarray : 383x = np .arange (256 ) 384s ,e ,m = x >> 7 , (x >> 3 )& 15 ,x & 7 385f = np .where (e == 0 ,np .ldexp (m / 8.0 ,- 6 ),np .ldexp (1.0 + m / 8.0 ,e .astype (np .int32 )- 7 )) 386f = np .where ((e == 15 )& (m == 7 ),np .nan ,f ) 387return np .where (s == 1 ,- f ,f ).astype (np .float32 ) 388 389 390def nvfp4_dequant (codes :np .ndarray ,scales_u8 :np .ndarray ,scale2 :float )-> np .ndarray : 391"""ModelOpt NVFP4 -> float32: codes [R, K/2] (low nibble first), E4M3 scale bytes [R, K/16], one F32.""" 392R = codes .shape [0 ] 393lo ,hi = codes & 15 ,codes >> 4 394v = E2M1 [np .stack ([lo ,hi ],axis =- 1 ).reshape (R ,- 1 )] 395sc = e4m3_table ()[scales_u8 ] 396return (v .reshape (R ,- 1 ,16 )* sc [:, :,None ]* np .float32 (scale2 )).reshape (R ,- 1 ) 397 398 399def f32_to_bf16_bits (x :np .ndarray )-> np .ndarray : 400u = np .ascontiguousarray (x ,np .float32 ).view (np .uint32 ) 401r = u + 0x7FFF + ((u >> 16 )& 1 )# round to nearest even 402return (r >> 16 ).astype (np .uint16 ) 403 404 405def cmd_mtp (a )-> int : 406"""The MTP head in tools/mtp_fetch.py's folder form (raw BF16 files + mtp-manifest.json), so tools/mtp_pack.py and 407tools/mtp_rt.py take it as they take Qwen's own: the 31 tensors, experts fused as gate_up_proj / down_proj.""" 408import hashlib 409ck = Checkpoint (a .model ,partial_ok = True ) 410out = pathlib .Path (a .out ) 411out .mkdir (parents = True ,exist_ok = True ) 412manifest = [] 413 414def put (name ,bits ,shape ): 415fn = name .replace ("/" ,"_" )+ ".bin" 416data = np .ascontiguousarray (bits ,np .uint16 ) 417 (out / fn ).write_bytes (data .tobytes ()) 418manifest .append ({"name" :name ,"dtype" :"BF16" ,"shape" :list (shape ),"file" :fn , 419"sha256" :hashlib .sha256 (data .tobytes ()).hexdigest ()}) 420 421for name in sorted (k for k in ck .meta if k .startswith ("mtp." )and ".experts." not in k ): 422if ck .dtype (name )!= "BF16" : 423sys .exit ("%s is %s, expected BF16" % (name ,ck .dtype (name ))) 424put (name ,ck .array (name ,np .uint16 ),ck .shape (name )) 425n_exp = 512 426for fused ,parts in (("mtp.layers.0.mlp.experts.gate_up_proj" , ("gate_proj" ,"up_proj" )), 427 ("mtp.layers.0.mlp.experts.down_proj" , ("down_proj" ,))): 428rows = [ck .shape ("mtp.layers.0.mlp.experts.0.%s.weight" % p )[0 ]for p in parts ] 429cols = ck .shape ("mtp.layers.0.mlp.experts.0.%s.weight" % parts [0 ])[1 ]* 2 430shape = [n_exp ,sum (rows ),cols ] 431fn = fused + ".bin" 432with open (out / fn ,"wb" )as f : 433h = hashlib .sha256 () 434for e in range (n_exp ): 435mats = [] 436for p in parts : 437b = "mtp.layers.0.mlp.experts.%d.%s." % (e ,p ) 438mats .append (nvfp4_dequant (np .asarray (ck .array (b + "weight" ,np .uint8 )), 439np .asarray (ck .array (b + "weight_scale" ,np .uint8 )), 440float (ck .array (b + "weight_scale_2" ,np .float32 ).reshape (- 1 )[0 ]))) 441blob = f32_to_bf16_bits (np .concatenate (mats ,axis = 0 )).tobytes () 442f .write (blob ) 443h .update (blob ) 444manifest .append ({"name" :fused ,"dtype" :"BF16" ,"shape" :shape ,"file" :fn ,"sha256" :h .hexdigest ()}) 445" %s %s" % (fused ,shape ),flush = True ) 446 (out / "mtp-manifest.json" ).write_text (json .dumps (manifest ,indent = 1 ),encoding = "utf-8" ) 447"wrote %d MTP tensors to %s" % (len (manifest ),out )) 448return 0 449 450 451# ------------------------------------------------------------------------------------------------------ the slim GGUF 452def cmd_slim (a )-> int : 453"""Copy a converted GGUF without its routed experts (and their .scale / .input_scale tensors): the file the engine 454reads the dense weights from (--native / --native-dense-gguf), ~9 GB instead of ~74 GB, once experts.bin is cut.""" 455from _paths import gguf_lib 456gguf = gguf_lib () 457GGUFReader ,GGUFWriter ,VT = gguf .GGUFReader ,gguf .GGUFWriter ,gguf .GGUFValueType 458rd = GGUFReader (a .gguf ) 459arch = rd .fields ["general.architecture" ].contents () 460w = GGUFWriter (a .out ,arch ) 461for key ,f in rd .fields .items (): 462if key .startswith ("GGUF." )or key == "general.architecture" : 463continue 464vt = f .types [0 ] 465w .add_key_value (key ,f .contents (),vt ,sub_type = f .types [- 1 ]if vt == VT .ARRAY else None ) 466kept = skipped = 0 467for t in rd .tensors : 468if "_exps." in t .name : 469skipped += 1 470continue 471data = np .asarray (t .data ) 472qt = t .tensor_type 473if qt in (gguf .GGMLQuantizationType .F32 ,gguf .GGMLQuantizationType .F16 ): 474w .add_tensor (t .name ,data ) 475else :# raw bytes with the type: the quantized blocks (BF16 rides as uint16) 476raw = np .ascontiguousarray (data ).view (np .uint8 ) 477w .add_tensor (t .name ,raw ,raw_dtype = qt ,raw_shape = [int (x )for x in raw .shape ]) 478kept += 1 479w .write_header_to_file () 480w .write_kv_data_to_file () 481w .write_tensors_to_file () 482w .close () 483"slim: %d tensors kept, %d expert tensors left out -> %s" % (kept ,skipped ,a .out )) 484return 0 485 486 487# ------------------------------------------------------------------------------------------- the pack, without a big GGUF 488def nvfp4_blocks (weight_u8 :np .ndarray ,scale_u8 :np .ndarray )-> np .ndarray : 489"""ModelOpt NVFP4 rows -> ggml's block_nvfp4 rows: weight [R, K/2] (two E2M1 codes a byte, element 2i low), scale [R, K/16] 490E4M3 bytes -> [R, K/64 * 36] bytes of super-blocks `[4 UE4M3 scales | 32 code bytes]`. The same bits as llama.cpp's 491ModelBase._nvfp4_pack (the scale's sign bit is dropped; it is 0 in every scale of this checkpoint).""" 492R ,nb = scale_u8 .shape 493w = weight_u8 .reshape (R ,nb ,8 ) 494vals = np .stack ([w & 0x0F ,w >> 4 ],axis =- 1 ).reshape (R ,nb ,16 ) 495qs = (vals [:, :, :8 ]| (vals [:, :,8 :]<< 4 )).astype (np .uint8 ) 496d = (scale_u8 & 0x7F ).reshape (R ,nb // 4 ,4 ) 497qs = qs .reshape (R ,nb // 4 ,32 ) 498return np .concatenate ([d ,qs ],axis =- 1 ).reshape (R , (nb // 4 )* 36 ) 499 500 501class _VTensor : 502"""A tensor info for iq_pack: an expert tensor (or its scale) whose bytes come from the checkpoint.""" 503 504def __init__ (self ,name ,shape ,type_id ,type_name ,nbytes ): 505self .name ,self .shape ,self .type_id ,self .type_name ,self .offset = name ,shape ,type_id ,type_name ,0 506self ._n = nbytes 507 508def expected_bytes (self ): 509return self ._n 510 511 512class _VGguf : 513data_start = 0 514 515 516def experts_from_checkpoint (model ,ck :Checkpoint ,n_layers :int = 48 ,n_exp :int = 512 ): 517"""Give an iq_pack.Model of the dense-only GGUF the routed experts of the checkpoint as virtual tensors.""" 518from _paths import gguf_lib 519Q = gguf_lib ().GGMLQuantizationType 520src = next (iter (model .where .values ()))[3 ] 521cache :dict = {} 522base = "model.language_model.layers.%d.mlp.experts.%d.%s_proj." 523 524def layer_role (l ,role ): 525key = (l ,role ) 526if key not in cache : 527cache .clear () 528rows = [] 529for e in range (n_exp ): 530b = base % (l ,e ,role ) 531dec = csf_decode (np .asarray (ck .array (b + "weight_scale" + CSF_FIXED ,np .uint8 )), 532np .asarray (ck .array (b + "weight_scale" + CSF_EXC ,np .uint32 ))) 533rows .append (nvfp4_blocks (np .asarray (ck .array (b + "weight" ,np .uint8 )),dec ).reshape (- 1 )) 534cache [key ]= (np .stack (rows ),) 535return cache [key ] 536 537# shapes in ggml order (ne0 = K, ne1 = rows, ne2 = experts) 538geo = {"gate" : (2560 ,640 ),"up" : (2560 ,640 ),"down" : (640 ,2560 )} 539 540class _Mem (_VGguf ):# a tiny tensor held in memory: iq_pack reads it like any dense one 541pass 542 543for l in range (n_layers ): 544for role , (k ,rows )in geo .items (): 545n = "blk.%d.ffn_%s_exps.weight" % (l ,role ) 546vt = _VTensor (n , [k ,rows ,n_exp ],Q .NVFP4 .value ,"NVFP4" ,n_exp * rows * (k // 64 )* 36 ) 547model .where [n ]= (_VGguf (),vt ,None ,src ) 548# the per-expert F32 scales (weight_scale_2 -> .scale, input_scale -> .input_scale), as the converter writes them 549for suffix ,key in ((".scale" ,"weight_scale_2" ), (".input_scale" ,"input_scale" )): 550vals = np .array ([ck .array (base % (l ,e ,role )+ key ,np .float32 ).reshape (- 1 )[0 ]for e in range (n_exp )],np .float32 ) 551sn = "blk.%d.ffn_%s_exps%s" % (l ,role ,suffix ) 552raw = vals .view (np .uint8 ) 553model .where [sn ]= (_Mem (),_VTensor (sn , [n_exp ],Q .F32 .value ,"F32" ,n_exp * 4 ),raw ,src ) 554orig_bytes = type (model ).bytes 555 556def bytes_ (name ): 557if name .startswith ("blk." )and "_exps." in name : 558if not name .endswith (".weight" ):# the small F32 scale tensors are in memory 559return model .where [name ][2 ] 560l = int (name .split ("." )[1 ]);role = name .split ("ffn_" )[1 ].split ("_exps" )[0 ] 561return layer_role (l ,role )[0 ].reshape (- 1 ) 562return orig_bytes (model ,name ) 563model .bytes = bytes_ 564return model 565 566 567def cmd_pack (a )-> int : 568"""tools/iq_pack.py on the dense-only GGUF, with the experts read from the checkpoint: experts.bin, native_experts.txt, 569dense.bin, index.txt and the tokenizer, with no 74 GB GGUF in between.""" 570import iq_pack 571ck = Checkpoint (a .model ) 572orig_model = iq_pack .Model 573 574class M (orig_model ): 575def __init__ (self ,first ): 576super ().__init__ (first ) 577experts_from_checkpoint (self ,ck ) 578iq_pack .Model = M 579sys .argv = ["iq_pack.py" ,"--gguf" ,a .dense_gguf ,"--out" ,a .out ,"--experts-bin" ] 580return iq_pack .main () 581 582 583# ------------------------------------------------------------------------------------------------------- prepare (setup) 584def cmd_prepare (a )-> int : 585"""Everything setup needs from the downloaded checkpoint, each step skipped when its mark is there: 586<out>/ple-nvfp4.gguf the n-gram table <out>/dense.gguf the dense weights (no experts) 587<out>/pack/ index.txt, dense.bin, experts.bin, native_experts.txt, tokenizer/ 588<out>/mtp/rt/ the draft layer (a Q2_0 copy of NVIDIA's MTP experts) 589The checkpoint is read, never changed; it can be deleted afterwards (the pack and the two GGUFs hold everything).""" 590import subprocess 591model ,out = pathlib .Path (a .model ),pathlib .Path (a .out ) 592if not all ((out / m ).is_file ()for m in MARKS ): 593require_packages ()# before the 20 minutes of the n-gram table, not after them (#3227) 594out .mkdir (parents = True ,exist_ok = True ) 595me = [sys .executable ,str (pathlib .Path (__file__ ).resolve ())] 596tools = pathlib .Path (__file__ ).resolve ().parent 597 598def run (cmd ): 599r = subprocess .run (cmd ) 600if r .returncode : 601sys .exit ("prepare: %s failed (exit %d)" % (cmd [1 ]if len (cmd )> 1 else cmd [0 ],r .returncode )) 602 603def step (name ,mark ,fn ): 604if mark .exists (): 605"prepare: %s already done" % name ,flush = True ) 606return 607"prepare: %s ..." % name ,flush = True ) 608t0 = time .time () 609fn () 610mark .write_text ("done %.0f s\n" % (time .time ()- t0 )) 611 612step ("the n-gram table" ,out / "ple-nvfp4.gguf.done" , 613lambda :run (me + ["ple" ,"--model" ,str (model ),"--out" ,str (out / "ple-nvfp4.gguf" )])) 614step ("the dense weights" ,out / "dense.gguf.done" , 615lambda :run (me + ["convert" ,"--dense-only" ,"--model" ,str (model ),"--outfile" ,str (out / "dense.gguf" )])) 616step ("the experts and the pack" ,out / "pack.done" ,# (native_experts.txt is the pack's own marker, not ours) 617lambda :run (me + ["pack" ,"--model" ,str (model ),"--dense-gguf" ,str (out / "dense.gguf" ),"--out" ,str (out / "pack" )])) 618 619mtp = out / "mtp" 620 621def draft_layer (): 622src = mtp / "src" 623run (me + ["mtp" ,"--model" ,str (model ),"--out" ,str (src )]) 624run ([sys .executable ,str (tools / "mtp_pack.py" ),"--src" ,str (src ),"--experts" ,"q2_0" , 625"--out" ,str (mtp / "mtp-q2_0.gguf" )]) 626run ([sys .executable ,str (tools / "mtp_rt.py" ),"--gguf" ,str (mtp / "mtp-q2_0.gguf" ),"--out" ,str (mtp / "rt" )]) 627import shutil 628shutil .rmtree (src ,ignore_errors = True ) 629step ("the draft layer" ,out / "draft.done" ,draft_layer ) 630"prepare: done -> %s" % out ) 631return 0 632 633# ------------------------------------------------------------------------------------------------------ verifying 634def cmd_verify (a )-> int : 635"""Experts: decode the checkpoint (CSF + ModelOpt definition) and compare with tools/strata_quants.py's dequantization of the 636GGUF's NVFP4 blocks times the scale tensor, bit for bit (zeros normalised: ggml has one zero).""" 637import torch 638import nvfp4_verify as V 639from _paths import gguf_lib 640gguf = gguf_lib () 641GGUFReader ,Q ,quants = gguf .GGUFReader ,gguf .GGMLQuantizationType ,gguf .quants 642ck = Checkpoint (a .model ) 643rd = GGUFReader (a .gguf ) 644T = {t .name :t for t in rd .tensors } 645bad = 0 646rng = np .random .default_rng (1 ) 647layers = sorted ({int (k .split (".layers." )[1 ].split ("." )[0 ])for k in ck .meta if ".mlp.experts." in k and k .startswith ("model.language_model" )}) 648for _ in range (a .experts ): 649L = int (rng .choice (layers ));e = int (rng .integers (0 ,512 )) 650for proj ,gname in (("gate_proj" ,"ffn_gate_exps" ), ("up_proj" ,"ffn_up_exps" ), ("down_proj" ,"ffn_down_exps" )): 651b = "model.language_model.layers.%d.mlp.experts.%d.%s." % (L ,e ,proj ) 652w = torch .from_numpy (np .array (ck .array (b + "weight" ,np .uint8 ))) 653sc = csf_decode (ck .array (b + "weight_scale" + CSF_FIXED ,np .uint8 ),ck .array (b + "weight_scale" + CSF_EXC ,np .uint32 )) 654s = torch .from_numpy (sc ).view (torch .float8_e4m3fn ) 655s2 = torch .from_numpy (np .array (ck .array (b + "weight_scale_2" ,np .float32 ))).reshape (()) 656ref = V .modelopt_dequant (w ,s ,s2 ) 657t = T ["blk.%d.%s.weight" % (L ,gname )] 658blob = np .asarray (t .data )# [512, rows, bytes] of NVFP4 blocks 659got = quants .dequantize (np .ascontiguousarray (blob [e ]),Q .NVFP4 ).astype (np .float32 ) 660sct = T ["blk.%d.%s.scale" % (L ,gname )] 661got = got * np .float32 (np .asarray (sct .data )[e ]) 662same = np .array_equal ((ref + np .float32 (0 )).view (np .uint32 ), (got .reshape (ref .shape )+ np .float32 (0 )).view (np .uint32 )) 663" layer %2d expert %3d %-9s bitwise %s" % (L ,e ,proj ,"OK" if same else "NO" ),flush = True ) 664bad += not same 665"RESULT:" ,"lossless" if not bad else "MISMATCH" ) 666return 1 if bad else 0 667 668 669def main ()-> int : 670ap = argparse .ArgumentParser (description = __doc__ .split ("\n\n" )[0 ]) 671sub = ap .add_subparsers (dest = "cmd" ,required = True ) 672c = sub .add_parser ("convert" ) 673c .add_argument ("--model" ,required = True ) 674c .add_argument ("--outfile" ,required = True ) 675c .add_argument ("--dry-run" ,action = "store_true" ) 676c .add_argument ("--dense-only" ,action = "store_true" , 677help = "leave the routed experts out: the GGUF that --native-dense-gguf reads (~9 GB) beside an experts.bin" ) 678p = sub .add_parser ("ple" ) 679p .add_argument ("--model" ,required = True ) 680p .add_argument ("--out" ,required = True ) 681m = sub .add_parser ("mtp" ) 682m .add_argument ("--model" ,required = True ) 683m .add_argument ("--out" ,required = True ) 684pk = sub .add_parser ("pack" ) 685pk .add_argument ("--model" ,required = True ) 686pk .add_argument ("--dense-gguf" ,required = True ,help = "the output of `convert --dense-only` (or `slim`)" ) 687pk .add_argument ("--out" ,required = True ) 688pr = sub .add_parser ("prepare" ) 689pr .add_argument ("--model" ,required = True ) 690pr .add_argument ("--out" ,required = True ) 691sl = sub .add_parser ("slim" ) 692sl .add_argument ("--gguf" ,required = True ) 693sl .add_argument ("--out" ,required = True ) 694v = sub .add_parser ("verify" ) 695v .add_argument ("--model" ,required = True ) 696v .add_argument ("--gguf" ,required = True ) 697v .add_argument ("--experts" ,type = int ,default = 4 ) 698a = ap .parse_args () 699return {"convert" :cmd_convert ,"ple" :cmd_ple ,"mtp" :cmd_mtp ,"slim" :cmd_slim ,"pack" :cmd_pack ,"prepare" :cmd_prepare ,"verify" :cmd_verify }[a .cmd ](a ) 700 701 702if __name__ == "__main__" : 703raise SystemExit (main ())