okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6360274c8
main
1#!/usr/bin/env python3 2"""tools/dflash2_pack.py reads a .safetensors file with numpy alone (the person's PC has neither torch nor the safetensors package) and writes 3the same runtime file the torch-based version wrote. 4 5python tools/test_dflash2_pack.py 6""" 7import importlib .util 8import json 9import struct 10import subprocess 11import sys 12import tempfile 13import unittest 14from pathlib import Path 15 16import numpy as np 17 18HERE = Path (__file__ ).resolve ().parent 19sys .path .insert (0 ,str (HERE )) 20import dflash2_pack as new # noqa: E402 21 22L ,H ,INTER ,HEADS ,KV ,HD ,RANK ,VOCAB = 2 ,64 ,96 ,2 ,1 ,32 ,32 ,128 23CFG = {"num_hidden_layers" :L ,"hidden_size" :H ,"num_attention_heads" :HEADS ,"num_key_value_heads" :KV ,"head_dim" :HD , 24"intermediate_size" :INTER ,"sliding_window" :128 ,"rope_parameters" : {"rope_theta" :1000000.0 },"rms_norm_eps" :1e-6 ,"vocab_size" :VOCAB , 25"dflash_config" : {"block_size" :8 ,"conv_group_size" :16 ,"conv_kernel_size" :2 ,"mask_token_id" :7 ,"selector_rank" :RANK ,"selector_top_k" :4 , 26"target_layer_ids" : [1 ,2 ,3 ]}} 27 28 29def bf16 (a ): 30"""float32 -> BF16 bytes by truncation (what torch's .to(bfloat16) does for these values up to rounding; the test only needs a valid BF16 file).""" 31return (np .ascontiguousarray (a ,np .float32 ).view (np .uint32 )>> 16 ).astype (np .uint16 ) 32 33 34def tensors (): 35rng = np .random .default_rng (7 ) 36r = lambda * shape :rng .standard_normal (shape ).astype (np .float32 )* 0.1 37t = {"fc.weight" :r (H ,H * 3 ),"hidden_norm.weight" :r (H ),"norm.weight" :r (H )} 38for l in range (L ): 39p = "layers.%d." % l 40t [p + "self_attn.q_proj.weight" ]= r (HEADS * HD ,H ) 41t [p + "self_attn.k_proj.weight" ]= r (KV * HD ,H ) 42t [p + "self_attn.v_proj.weight" ]= r (KV * HD ,H ) 43t [p + "self_attn.o_proj.weight" ]= r (H ,HEADS * HD ) 44t [p + "mlp.gate_proj.weight" ]= r (INTER ,H ) 45t [p + "mlp.up_proj.weight" ]= r (INTER ,H ) 46t [p + "mlp.down_proj.weight" ]= r (H ,INTER ) 47t [p + "attention_conv.kernel_projection.weight" ]= r (32 ,H ) 48t [p + "mlp_conv.kernel_projection.weight" ]= r (32 ,H ) 49for n in ("input_layernorm" ,"post_attention_layernorm" ,"self_attn.q_norm" ,"self_attn.k_norm" ): 50t [p + n + ".weight" ]= r (HD if "_norm" in n else H ) 51t [p + "attention_conv.base_kernel" ]= r (2 ,16 ) 52t [p + "mlp_conv.base_kernel" ]= r (2 ,16 ) 53t ["candidate_selector.hidden_projection.weight" ]= r (RANK ,H ) 54t ["candidate_selector.predecessor_codebook" ]= r (VOCAB ,RANK ) 55t ["candidate_selector.successor_codebook" ]= r (VOCAB ,RANK ) 56return t 57 58 59def write_safetensors (path ,arrays ): 60"""A BF16 safetensors file written by hand (the format is documented: u64 header length, JSON header, raw data).""" 61header ,blobs ,at = {}, [],0 62for name ,a in arrays .items (): 63data = bf16 (a ).tobytes () 64header [name ]= {"dtype" :"BF16" ,"shape" :list (a .shape ),"data_offsets" : [at ,at + len (data )]} 65blobs .append (data ) 66at += len (data ) 67js = json .dumps (header ).encode () 68js += b" " * ((8 - len (js )% 8 )% 8 ) 69with open (path ,"wb" )as fh : 70fh .write (struct .pack ("<Q" ,len (js ))+ js + b"" .join (blobs )) 71 72 73class PackWithoutTorch (unittest .TestCase ): 74@classmethod 75def setUpClass (cls ): 76cls .tmp = tempfile .TemporaryDirectory () 77cls .dir = Path (cls .tmp .name ) 78cls .arrays = tensors () 79write_safetensors (cls .dir / "model.safetensors" ,cls .arrays ) 80 (cls .dir / "config.json" ).write_text (json .dumps (CFG )) 81 82@classmethod 83def tearDownClass (cls ): 84cls .tmp .cleanup () 85 86def pack (self ,out ): 87return new .pack (str (self .dir / "model.safetensors" ),str (self .dir / "config.json" ),str (out ),say = lambda * _ :None ) 88 89def test_reader_widens_bf16_exactly (self ): 90f = new .SafeTensors (str (self .dir / "model.safetensors" )) 91got = f .get_float32 ("fc.weight" ) 92want = (bf16 (self .arrays ["fc.weight" ]).astype (np .uint32 )<< 16 ).view (np .float32 ) 93self .assertTrue (np .array_equal (got ,want )) 94self .assertEqual (f .get_bf16_bits ("candidate_selector.predecessor_codebook" ).dtype ,np .uint16 ) 95self .assertEqual (f .raw ("norm.weight" )[0 ],"BF16" ) 96 97def test_the_file_has_the_header_the_engine_reads (self ): 98out = self .dir / "out.pack" 99size = self .pack (out ) 100data = out .read_bytes () 101self .assertEqual (data [:4 ],b"DF2P" ) 102version ,index_len = struct .unpack ("<II" ,data [4 :12 ]) 103self .assertEqual (version ,1 ) 104self .assertEqual ((12 + index_len )% 4096 ,0 ,"the data starts on a 4096 multiple" ) 105index = data [12 :12 + index_len ].decode ().splitlines () 106self .assertTrue (any (l .startswith ("cfg hidden %d" % H )for l in index )) 107self .assertIn ("end" , [l .strip ()for l in index ]) 108names = [l .split ()[1 ]for l in index if l .startswith ("t " )] 109self .assertIn ("fc.weight" ,names ) 110self .assertIn ("candidate_selector.successor_codebook" ,names ) 111self .assertEqual (len (data ),size ) 112 113def test_a_matrix_is_ggml_q8_0_of_the_widened_values (self ): 114out = self .dir / "q8.pack" 115self .pack (out ) 116data = out .read_bytes () 117index_len = struct .unpack ("<I" ,data [8 :12 ])[0 ] 118base = 12 + index_len 119row = next (l .split ()for l in data [12 :base ].decode ().splitlines ()if l .startswith ("t fc.weight " )) 120_t ,_name ,dtype ,rows ,cols ,off ,nbytes = row 121self .assertEqual (dtype ,"q8_0" ) 122got = data [base + int (off ):base + int (off )+ int (nbytes )] 123widened = (bf16 (self .arrays ["fc.weight" ]).astype (np .uint32 )<< 16 ).view (np .float32 ) 124self .assertEqual (got ,new .quant_q8_0 (widened )) 125 126def test_q4_0_blocks_are_ggml_q4_0_and_only_the_matrices_change (self ): 127q8 ,q4 = self .dir / "q8b.pack" ,self .dir / "q4.pack" 128self .pack (q8 ) 129new .pack (str (self .dir / "model.safetensors" ),str (self .dir / "config.json" ),str (q4 ),say = lambda * _ :None ,q4 = True ) 130rows = {} 131for path in (q8 ,q4 ): 132data = path .read_bytes () 133index_len = struct .unpack ("<I" ,data [8 :12 ])[0 ] 134rows [path ]= (data ,12 + index_len , {l .split ()[1 ]:l .split ()for l in data [12 :12 + index_len ].decode ().splitlines ()if l .startswith ("t " )}) 135d8 ,b8 ,t8 = rows [q8 ] 136d4 ,b4 ,t4 = rows [q4 ] 137self .assertEqual (set (t8 ),set (t4 )) 138for name ,r in t4 .items (): 139dtype4 ,nbytes4 = r [2 ],int (r [6 ]) 140if t8 [name ][2 ]== "q8_0" : 141self .assertEqual (dtype4 ,"q4_0" ,name ) 142self .assertEqual (nbytes4 ,int (r [3 ])* int (r [4 ])// 32 * 18 ,name ) 143else :# norms, conv kernels and the codebooks are byte for byte the same 144self .assertEqual (d4 [b4 + int (r [5 ]):b4 + int (r [5 ])+ nbytes4 ],d8 [b8 + int (t8 [name ][5 ]):b8 + int (t8 [name ][5 ])+ int (t8 [name ][6 ])],name ) 145# one matrix: dequantize the blocks and check the error is within one step of each block scale (the +8 end is clamped to 7) 146w = (bf16 (self .arrays ["fc.weight" ]).astype (np .uint32 )<< 16 ).view (np .float32 ) 147r = t4 ["fc.weight" ] 148blocks = np .frombuffer (d4 [b4 + int (r [5 ]):b4 + int (r [5 ])+ int (r [6 ])],np .uint8 ).reshape (w .shape [0 ],w .shape [1 ]// 32 ,18 ) 149d = blocks [..., :2 ].copy ().view (np .float16 )[...,0 ].astype (np .float32 ) 150q = np .concatenate ([blocks [...,2 :]& 15 ,blocks [...,2 :]>> 4 ],axis =- 1 ).astype (np .float32 )- 8 151deq = (q * d [...,None ]).reshape (w .shape ) 152step = np .abs (d )[...,None ].repeat (32 ,- 1 ).reshape (w .shape ) 153self .assertTrue (np .all (np .abs (deq - w )<= 1.01 * step + 1e-6 )) 154 155def test_it_matches_the_torch_version_when_torch_is_here (self ): 156try : 157import torch # noqa: F401 158import safetensors # noqa: F401 159except ImportError : 160self .skipTest ("torch or safetensors is not installed here (the point of the change)" ) 161old_src = subprocess .run (["git" ,"show" ,"f1b6a2144:tools/dflash2_pack.py" ],cwd = HERE ,capture_output = True ,text = True ) 162if old_src .returncode != 0 : 163self .skipTest ("the earlier version is not in this clone" ) 164old_path = self .dir / "old_pack.py" 165old_path .write_text (old_src .stdout ) 166spec = importlib .util .spec_from_file_location ("old_pack" ,old_path ) 167old = importlib .util .module_from_spec (spec ) 168spec .loader .exec_module (old ) 169a ,b = self .dir / "a.pack" ,self .dir / "b.pack" 170sys .argv = ["x" ,str (self .dir / "model.safetensors" ),str (self .dir / "config.json" ),str (a )] 171old .main () 172self .pack (b ) 173self .assertEqual (a .read_bytes (),b .read_bytes (),"byte for byte the same file" ) 174 175 176if __name__ == "__main__" : 177unittest .main ()