okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
736266e87
main
1"""tools/image/gate/test_safetensors_lite.py - TEST-ONLY: src/image/vae/safetensors_lite.hpp (the VAE decoder's file 2reader) on files written here: names, dtypes, shapes, offsets, the bytes of a tensor, __metadata__ skipped, escaped 3strings, and the refusals (bad length, broken JSON). Builds a small C++ program with the host compiler; skipped when 4there is none. 5 6python -m pytest tools/image/gate/test_safetensors_lite.py""" 7import json 8import shutil 9import struct 10import subprocess 11import tempfile 12import unittest 13from pathlib import Path 14 15ROOT = Path (__file__ ).resolve ().parents [3 ] 16CXX = shutil .which ("g++" )or shutil .which ("clang++" ) 17 18PROGRAM = r''' 19#include "safetensors_lite.hpp" 20#include <cstring> 21#include <cstdio> 22int main(int argc, char** argv) { 23strata::image::StFile f; 24std::string err = strata::image::st_read_header(argv[1], f); 25if (!err.empty()) { std::printf("ERR %s\n", err.c_str()); return 1; } 26for (auto& kv : f.tensors) { 27std::printf("T %s %s", kv.first.c_str(), kv.second.dtype.c_str()); 28for (auto s : kv.second.shape) std::printf(" %lld", (long long) s); 29std::vector<unsigned char> b; 30err = strata::image::st_read_tensor(argv[1], f, kv.second, b); 31if (!err.empty()) { std::printf(" READERR %s\n", err.c_str()); return 1; } 32std::printf(" |"); 33for (auto c : b) std::printf(" %02x", c); 34std::printf("\n"); 35} 36for (int th : {1, 3, 16}) { // the whole data section in parallel parts: the same bytes as the tensor reads 37std::unique_ptr<unsigned char[]> all; 38size_t size = 0; 39err = strata::image::st_read_all_parallel(argv[1], f, all, size, th); 40if (!err.empty()) { std::printf("PARERR %s\n", err.c_str()); return 1; } 41for (auto& kv : f.tensors) { 42std::vector<unsigned char> b; 43strata::image::st_read_tensor(argv[1], f, kv.second, b); 44if (b.size() && std::memcmp(b.data(), all.get() + kv.second.begin, b.size()) != 0) { std::printf("PARDIFF\n"); return 1; } 45} 46} 47return 0; 48} 49''' 50 51 52def write_st (path :Path ,header :dict ,data :bytes ,raw_header :bytes = None ): 53h = raw_header if raw_header is not None else json .dumps (header ).encode () 54path .write_bytes (struct .pack ("<Q" ,len (h ))+ h + data ) 55 56 57@ unittest . skipUnless ( CXX , "no host C++ compiler" ) 58class SafetensorsLite (unittest .TestCase ): 59@classmethod 60def setUpClass (cls ): 61cls .tmp = tempfile .TemporaryDirectory () 62d = Path (cls .tmp .name ) 63 (d / "t.cpp" ).write_text (PROGRAM ) 64cls .exe = d / "st_test" 65subprocess .run ([CXX ,"-std=c++17" ,"-O1" ,"-pthread" ,"-I" ,str (ROOT / "src" / "image" / "vae" ),str (d / "t.cpp" ),"-o" , 66str (cls .exe )],check = True ) 67 68@classmethod 69def tearDownClass (cls ): 70cls .tmp .cleanup () 71 72def run_on (self ,header ,data ,raw_header = None ): 73p = Path (self .tmp .name )/ "m.safetensors" 74write_st (p ,header ,data ,raw_header ) 75r = subprocess .run ([str (self .exe ),str (p )],capture_output = True ,text = True ) 76return r .returncode ,r .stdout 77 78def test_tensors_and_metadata (self ): 79hdr = {"__metadata__" : {"format" :"pt" ,"nested" : {"a" : [1 ,2 , {"b" :"c}" }]}}, 80"decoder.conv_in.weight" : {"dtype" :"BF16" ,"shape" : [2 ,1 ,1 ,1 ],"data_offsets" : [0 ,4 ]}, 81"x\\\"y" : {"dtype" :"F32" ,"shape" : [1 ],"data_offsets" : [4 ,8 ]}} 82rc ,out = self .run_on (hdr ,bytes ([1 ,2 ,3 ,4 ,0 ,0 ,128 ,63 ])) 83self .assertEqual (rc ,0 ,out ) 84lines = sorted (out .splitlines ()) 85self .assertIn ("T decoder.conv_in.weight BF16 2 1 1 1 | 01 02 03 04" ,lines ) 86self .assertIn ('T x\\"y F32 1 | 00 00 80 3f' ,lines ) 87self .assertEqual (len (lines ),2 ) 88 89def test_empty_shape_scalar (self ): 90rc ,out = self .run_on ({"s" : {"dtype" :"F32" ,"shape" : [],"data_offsets" : [0 ,4 ]}},bytes (4 )) 91self .assertEqual ((rc ,out .strip ()), (0 ,"T s F32 | 00 00 00 00" )) 92 93def test_refusals (self ): 94rc ,out = self .run_on (None ,b"" ,raw_header = b'{"a": {"dtype": "F32", "shape": [1], "data_offsets": [4, 0]}}' ) 95self .assertEqual (rc ,1 ) 96self .assertIn ("bad data_offsets" ,out ) 97rc ,out = self .run_on (None ,b"" ,raw_header = b'{"a": {"dtype": "F32"' ) 98self .assertEqual (rc ,1 ) 99self .assertTrue (out .startswith ("ERR header" ),out ) 100rc ,out = self .run_on ({"a" : {"dtype" :"F32" ,"shape" : [2 ],"data_offsets" : [0 ,8 ]}},bytes (4 )) 101self .assertEqual (rc ,1 ) 102self .assertIn ("short read" ,out ) 103 104 105if __name__ == "__main__" : 106unittest .main ()