okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
736266e87
main
1// src/image/vae/safetensors_lite.hpp - read the tensor table of a .safetensors file (the format: an 8-byte little-endian 2// header length, a JSON object {name: {"dtype", "shape", "data_offsets": [begin, end]}, "__metadata__": {...}}, then the 3// data). Only what a model file of ours needs: string keys, the three fields above, numbers and arrays of numbers; the 4// "__metadata__" object is skipped. No third-party JSON code. Header-only, host-only. 5#pragma once 6 7#include <cstdint> 8#include <cstdio> 9#include <map> 10#include <memory> 11#include <thread> 12#include <string> 13#include <vector> 14 15namespace strata::image { 16 17struct StTensor { 18 std::string dtype ;// "BF16", "F16", "F32", ... 19 std::vector < int64_t > shape ; 20uint64_t begin = 0 ,end = 0 ;// byte offsets from the start of the data section 21}; 22 23struct StFile { 24 std::map < std::string ,StTensor > tensors ; 25uint64_t data_start = 0 ;// file offset of the data section 26}; 27 28namespace st_detail { 29struct Parser { 30const std::string & s ; 31size_t i = 0 ; 32 std::string err ; 33explicit Parser (const std::string & t ) :s (t ) {} 34void ws () {while (i < s .size ()&& (s [i ]== ' ' || s [i ]== '\n' || s [i ]== '\r' || s [i ]== '\t' ))++ i ; } 35bool eat (char c ) {ws ();if (i < s .size ()&& s [i ]== c ) {++ i ;return true; }return false; } 36bool str (std::string & out ) { 37ws (); 38if (i >=s .size ()|| s [i ]!= '"' )return fail ("string expected" ); 39++ i ; 40out .clear (); 41while (i < s .size ()&& s [i ]!= '"' ) { 42if (s [i ]== '\\' ) { 43if (i + 1 >=s .size ())return fail ("bad escape" ); 44char e = s [i + 1 ]; 45if (e == 'u' ) {// names are ASCII; keep \uXXXX as-is (never matched) 46out += s .substr (i ,6 ); 47i += 6 ; 48continue ; 49 } 50out += (e == 'n' ) ?'\n' : (e == 't' ) ?'\t' :e ; 51i += 2 ; 52continue ; 53 } 54out += s [i ++ ]; 55 } 56if (i >=s .size ())return fail ("unterminated string" ); 57++ i ; 58return true; 59 } 60bool num (int64_t & v ) { 61ws (); 62size_t j = i ; 63if (j < s .size ()&& s [j ]== '-' )++ j ; 64while (j < s .size ()&& s [j ] >='0' && s [j ] <='9' )++ j ; 65if (j == i )return fail ("number expected" ); 66v = std::stoll (s .substr (i ,j - i )); 67i = j ; 68return true; 69 } 70bool skip_value () {// any JSON value (for __metadata__ and unknown fields) 71ws (); 72if (i >=s .size ())return fail ("value expected" ); 73char c = s [i ]; 74if (c == '"' ) { std::string t ;return str (t ); } 75if (c == '{' || c == '[' ) { 76char close = c == '{' ?'}' :']' ; 77++ i ; 78if (eat (close ))return true; 79do { 80if (c == '{' ) { std::string k ;if (!str (k )|| !eat (':' ))return fail ("object" ); } 81if (!skip_value ())return false; 82 }while (eat (',' )); 83return eat (close )|| fail ("unterminated container" ); 84 } 85while (i < s .size ()&& s [i ]!= ',' && s [i ]!= '}' && s [i ]!= ']' )++ i ;// number, true, false, null 86return true; 87 } 88bool int_array (std::vector < int64_t >& out ) { 89out .clear (); 90if (!eat ('[' ))return fail ("[ expected" ); 91if (eat (']' ))return true; 92do {int64_t v ;if (!num (v ))return false;out .push_back (v ); }while (eat (',' )); 93return eat (']' )|| fail ("] expected" ); 94 } 95bool fail (const char * m ) {if (err .empty ())err = std::string (m )+ " at byte " + std::to_string (i );return false; } 96}; 97}// namespace st_detail 98 99// Parse the header of `path` into `out`. Returns an empty string on success, else the reason. 100inline std::string st_read_header (const std::string & path ,StFile & out ) { 101FILE * f = std::fopen (path .c_str (),"rb" ); 102if (!f )return "cannot open " + path ; 103unsigned char len8 [8 ]; 104if (std::fread (len8 ,1 ,8 ,f )!= 8 ) { std::fclose (f );return "short file " + path ; } 105uint64_t n = 0 ; 106for (int k = 7 ;k >=0 ;-- k )n = (n <<8 ) |len8 [k ]; 107if (n == 0 || n > (64u <<20 )) { std::fclose (f );return "implausible header length in " + path ; } 108 std::string text (n ,'\0' ); 109if (std::fread (& text [0 ],1 ,n ,f )!= n ) { std::fclose (f );return "short header in " + path ; } 110 std::fclose (f ); 111out = StFile {}; 112out .data_start = 8 + n ; 113 st_detail::Parser p (text ); 114if (!p .eat ('{' ))return "header is not a JSON object" ; 115if (p .eat ('}' ))return "" ; 116do { 117 std::string name ; 118if (!p .str (name )|| !p .eat (':' ))return "header: " + p .err ; 119if (name == "__metadata__" ) {if (!p .skip_value ())return "header: " + p .err ;continue ; } 120StTensor t ; 121if (!p .eat ('{' ))return "header: tensor entry is not an object" ; 122if (!p .eat ('}' )) { 123do { 124 std::string key ; 125if (!p .str (key )|| !p .eat (':' ))return "header: " + p .err ; 126if (key == "dtype" ) {if (!p .str (t .dtype ))return "header: " + p .err ; } 127else if (key == "shape" ) {if (!p .int_array (t .shape ))return "header: " + p .err ; } 128else if (key == "data_offsets" ) { 129 std::vector < int64_t > o ; 130if (!p .int_array (o )|| o .size ()!= 2 || o [0 ]< 0 || o [1 ]< o [0 ])return "header: bad data_offsets" ; 131t .begin = (uint64_t )o [0 ]; 132t .end = (uint64_t )o [1 ]; 133 }else if (!p .skip_value ())return "header: " + p .err ; 134 }while (p .eat (',' )); 135if (!p .eat ('}' ))return "header: } expected" ; 136 } 137out .tensors [name ]= t ; 138 }while (p .eat (',' )); 139if (!p .eat ('}' ))return "header: } expected at the end" ; 140return "" ; 141} 142 143// Read the whole data section (one sequential read; the decoder converts from memory). 144inline std::string st_read_all (const std::string & path ,const StFile & file , std::vector < unsigned char >& bytes ) { 145uint64_t end = 0 ; 146for (const auto & kv :file .tensors )end = kv .second .end > end ?kv .second .end :end ; 147FILE * f = std::fopen (path .c_str (),"rb" ); 148if (!f )return "cannot open " + path ; 149bytes .resize (end ); 150#if defined(_WIN32 ) 151int rc = _fseeki64 (f , (long long )file .data_start ,SEEK_SET ); 152#else 153int rc = fseeko (f , (off_t )file .data_start ,SEEK_SET ); 154#endif 155size_t got = rc == 0 ? std::fread (bytes .data (),1 ,bytes .size (),f ) :0 ; 156 std::fclose (f ); 157return got == bytes .size () ?"" :"short read in " + path ; 158} 159 160// The same into a buffer that is not zero-filled first, read in `threads` parts at once (each part its own file 161// handle). size = the data section's length. 162inline std::string st_read_all_parallel (const std::string & path ,const StFile & file , std::unique_ptr < unsigned char []>& buf , 163size_t & size ,int threads ) { 164uint64_t end = 0 ; 165for (const auto & kv :file .tensors )end = kv .second .end > end ?kv .second .end :end ; 166size = (size_t )end ; 167buf .reset (new unsigned char [size ?size :1 ]); 168const int parts = threads < 1 ?1 : (threads > 16 ?16 :threads ); 169const size_t step = (size + parts - 1 ) /parts ; 170 std::vector < std::string > errs ((size_t )parts ); 171 std::vector < std::thread > pool ; 172for (int p = 0 ;p < parts ;++ p ) { 173pool .emplace_back ([& ,p ]() { 174const size_t b = (size_t )p * step ,e = b + step < size ?b + step :size ; 175if (b >=e )return ; 176FILE * f = std::fopen (path .c_str (),"rb" ); 177if (!f ) {errs [(size_t )p ]= "cannot open " + path ;return ; } 178#if defined(_WIN32 ) 179int rc = _fseeki64 (f , (long long ) (file .data_start + b ),SEEK_SET ); 180#else 181int rc = fseeko (f , (off_t ) (file .data_start + b ),SEEK_SET ); 182#endif 183size_t got = rc == 0 ? std::fread (buf .get ()+ b ,1 ,e - b ,f ) :0 ; 184 std::fclose (f ); 185if (got != e - b )errs [(size_t )p ]= "short read in " + path ; 186 }); 187 } 188for (auto & t :pool )t .join (); 189for (const auto & e :errs ) 190if (!e .empty ())return e ; 191return "" ; 192} 193 194// Read the raw bytes of one tensor. 195inline std::string st_read_tensor (const std::string & path ,const StFile & file ,const StTensor & t , 196 std::vector < unsigned char >& bytes ) { 197FILE * f = std::fopen (path .c_str (),"rb" ); 198if (!f )return "cannot open " + path ; 199bytes .resize (t .end - t .begin ); 200#if defined(_WIN32 ) 201int rc = _fseeki64 (f , (long long ) (file .data_start + t .begin ),SEEK_SET ); 202#else 203int rc = fseeko (f , (off_t ) (file .data_start + t .begin ),SEEK_SET ); 204#endif 205size_t got = rc == 0 ? std::fread (bytes .data (),1 ,bytes .size (),f ) :0 ; 206 std::fclose (f ); 207return got == bytes .size () ?"" :"short read in " + path ; 208} 209 210}// namespace strata::image