okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
870ea9763
main
1// tools/vision/own/own_reader.cpp - see own_reader.h 2#include "own_reader.h" 3 4#include "cpu_caps.h" 5#include "vit_cpu.h" 6#include "vit_ref.h" 7#ifdef STRATA_VIT_GPU 8#include "vit_gpu.h" 9#endif 10 11#include <algorithm> 12#include <chrono> 13#include <cstdint> 14#include <cstdio> 15#include <cstdlib> 16#include <iostream> 17#include <memory> 18#include <thread> 19 20namespace strata_vit { 21 22namespace { 23 24// "ENC <image> <out>": the image path ends at the last space before the output path (a path of the image may hold spaces) 25bool parse_enc (const std::string & line , std::string & img , std::string & out ) { 26if (line .rfind ("ENC " ,0 )!= 0 )return false; 27const std::string rest = line .substr (4 ); 28const size_t sp = rest .rfind (' ' ); 29if (sp == std::string::npos || sp == 0 )return false; 30img = rest .substr (0 ,sp ); 31out = rest .substr (sp + 1 ); 32return !img .empty ()&& !out .empty (); 33} 34 35}// namespace 36 37std::string vision_tower_default (const char * env , std::string & note ) { 38const std::string v = env ?env :"" ; 39if (v == "mtmd" || v == "own" || v == "auto" )return v ; 40if (!v .empty ())note = "STRATA_VISION_TOWER=" + v + " is not mtmd, own or auto; using auto" ; 41return "auto" ; 42} 43 44bool own_reader_inject_failure (const char * point ) { 45const char * v = std::getenv ("STRATA_VIT_TEST_FAIL" ); 46return v && point && std::string (v )== point ; 47} 48 49bool own_reader_supported (const std::string & mmproj ,bool gpu ,int max_tokens , std::string & why ) { 50if (gpu ) { 51#ifdef STRATA_VIT_GPU 52bool bf16 = false;// the layer matrices' type decides on Pascal (vit_gpu.h) 53 { 54Gguf g0 ; 55 std::string e0 ; 56if (g0 .open (mmproj ,e0 )) 57if (const GgufTensorInfo * t = g0 .tensor ("v.blk.0.attn_qkv.weight" ))bf16 = t -> type == GT_BF16 ; 58 } 59if (!VitGpu ::available (why )|| VitGpu ::prefer_mtmd (bf16 ,max_tokens ,why ))return false; 60#else 61why = "this build has no GPU backend for the own tower" ; 62return false; 63#endif 64 } 65// (an MSVC x86 build kept mtmd here until 11-11; since 54f9cc3c0 it is 0.986 of mtmd-CPU's time at 1,024 tokens, RESULTS-OWN-3V.md D2, so that rule is gone) 66Gguf gg ; 67VitGeometry g ; 68if (!gg .open (mmproj ,why )|| !vit_geometry_from_gguf (gg ,g ,why ))return false; 69if (!gpu )return own_cpu_reader_supported (g , quant::best_isa (),why ); 70if (!vit_geometry_supported (g ,why ))return false; 71if (g .head_dim > 96 ) {why = "a head size above 96 is not handled by the GPU attention" ;return false; }// `auto` then reads with mtmd 72return true; 73} 74 75bool own_cpu_reader_supported (const VitGeometry & g , quant::Isa isa , std::string & why ) { 76// Every CPU tier is allowed (owner 11-11, "make ours the default" below AVX2 too). Until then an x86 CPU whose best tier was scalar, sse41 or avx kept mtmd under 77// `auto`; the tiers were gated since (RESULTS-OWN-3V.md PART H: rule 1 on both reader files, byte-identical repeats, no instruction above the CPU's tier outside the 78// CPU-checked kernels, timed against llama.cpp's reader built for the same CPU class: 0.05 to 0.35 of its time, one cell 1.04). `isa` stays an argument so a 79// per-tier rule is one line here and has a test. 80 (void )isa ; 81return vit_geometry_supported (g ,why ); 82} 83 84std::string vision_tower_resolve (const std::string & tower ,bool own_ok ) { 85if (tower == "mtmd" || tower == "own" )return tower ;// an explicit choice is never overruled, either way 86return own_ok ?"own" :"mtmd" ;// auto 87} 88 89int own_reader_run (const OwnReaderOptions & o ) { 90using clock = std::chrono::steady_clock ; 91const auto load_t0 = clock::now (); 92// every return before READY goes through here: under `auto` the reason goes back to strata-vision, which starts mtmd's reader (nothing on stdout yet) 93auto fail = [& o ](const std::string & msg ,int code ) { 94if (o .start_error ) { 95* o .start_error = msg ; 96return kOwnStartFailed ; 97 } 98 std::printf ("ERR %s\n" ,msg .c_str ()); 99 std::fflush (stdout ); 100return code ; 101 }; 102const std::string injected = " (injected for a test: STRATA_VIT_TEST_FAIL)" ; 103#ifndef STRATA_VIT_GPU 104if (o .gpu )return fail ("this build has no GPU backend for the own tower (use --tower mtmd)" ,3 ); 105#endif 106Gguf gg ; 107VitGeometry geo ; 108 std::string err ; 109if (!gg .open (o .mmproj ,err )|| !vit_geometry_from_gguf (gg ,geo ,err )|| !vit_geometry_supported (geo ,err )) 110return fail ("cannot load the vision encoder " + o .mmproj + " (" + err + ")" ,1 ); 111int threads = o .threads ; 112 std::unique_ptr < VitRef > cpu ; 113 std::unique_ptr < VitCpu > fast ; 114#ifdef STRATA_VIT_GPU 115 std::unique_ptr < VitGpu > gpu ; 116if (o .gpu ) { 117 std::string why ; 118if (own_reader_inject_failure ("gpu" ))return fail ("this picture reader found no GPU" + injected ,3 ); 119if (!VitGpu ::available (why ))return fail ("this picture reader found no GPU (" + why + ")" ,3 ); 120gpu .reset (new VitGpu ()); 121// buffers for the warm-up picture below (2048 x 2048: 4,096 tokens at most, fewer under a lower limit): claimed now, before READY. A larger limit 122// (the app allows up to 16,384 image tokens) grows them when such a picture comes: slower for that picture, never an error. 123const int tokens = std::min (o .max_tokens > 0 ?o .max_tokens :geo .max_tokens ,4096 ); 124if (!gpu -> load (gg ,geo ,0 ,tokens * 4 ,err ))return fail ("cannot load the vision encoder " + o .mmproj + " (" + err + ")" ,1 ); 125if (own_reader_inject_failure ("load" ))return fail ("cannot load the vision encoder " + o .mmproj + injected ,1 );// after the load: its memory is freed on return 126 } 127#endif 128if (!o .gpu ) { 129// the CPU path of the own tower is the fast tower (VitCpu); STRATA_VIT_CPU=ref selects the float32 reference (VitRef: the oracle, for tests) 130const char * sel = std::getenv ("STRATA_VIT_CPU" ); 131if (!(sel && std::string (sel )== "ref" )) { 132fast .reset (new VitCpu ()); 133if (!fast -> load (gg ,geo ,err ))return fail ("cannot load the vision encoder " + o .mmproj + " (" + err + ")" ,1 ); 134 }else { 135cpu .reset (new VitRef ()); 136if (!cpu -> load (gg ,geo ,err ))return fail ("cannot load the vision encoder " + o .mmproj + " (" + err + ")" ,1 ); 137 } 138if (own_reader_inject_failure ("load" ))return fail ("cannot load the vision encoder " + o .mmproj + injected ,1 ); 139if (threads <=0 )threads = (int ) std::max (1u , std::min (16u , std::thread::hardware_concurrency () /2 )); 140 } 141 std::fprintf (stderr ,"strata-vision: own tower (%s, %d layers, width %d) loaded in %.1f s, %s\n" ,geo .projector .c_str (),geo .layers ,geo .width , 142 std::chrono::duration < double > (clock::now ()- load_t0 ).count (),o .gpu ?"on the GPU" : ("on the CPU, " + std::to_string (threads )+ " threads" ).c_str ()); 143auto encode = [& ](const PreparedImage & prep , std::vector < float >& rows ,int & nx ,int & ny , std::string & e ) { 144#ifdef STRATA_VIT_GPU 145if (gpu )return gpu -> encode (prep ,rows ,nx ,ny ,e ); 146#endif 147if (fast )return fast -> encode (prep ,threads ,rows ,nx ,ny ,e ); 148return cpu -> encode (prep ,threads ,rows ,nx ,ny ,e ); 149 }; 150#ifdef STRATA_VIT_GPU 151if (gpu ) {// warm up at the largest picture before READY: the work buffers are taken now, not at the first real picture 152const auto w0 = clock::now (); 153ImageU8 gray ; 154gray .w = gray .h = 2048 ; 155gray .rgb .assign ((size_t )2048 * 2048 * 3 ,128 ); 156PreparedImage wp ; 157 std::vector < float > rows ; 158int nx = 0 ,ny = 0 ; 159err .clear (); 160if (own_reader_inject_failure ("warmup" ))err = "out of GPU memory" + injected ; 161if (err .empty ()&& prepare_image (gray ,geo ,o .min_tokens ,o .max_tokens ,wp ,err )&& encode (wp ,rows ,nx ,ny ,err )) 162 std::fprintf (stderr ,"strata-vision: warmed up at %d image tokens in %.1f s, %.0f MiB of GPU memory\n" ,nx * ny , 163 std::chrono::duration < double > (clock::now ()- w0 ).count (), (double )gpu -> device_bytes () /1048576.0 ); 164else 165return fail ("the vision encoder failed its warm-up (" + err + ")" ,1 ); 166 } 167#endif 168 std::printf ("READY %d own\n" ,geo .out_dim );// the third word names the reader (a server reads only the start: "READY") 169 std::fflush (stdout ); 170 171 std::string line ; 172while (std::getline (std::cin ,line )) { 173while (!line .empty ()&& (line .back ()== '\r' || line .back ()== '\n' ))line .pop_back (); 174if (line == "QUIT" )break ; 175 std::string img ,out ; 176if (!parse_enc (line ,img ,out )) { std::printf ("ERR expected: ENC <image> <output>\n" ); std::fflush (stdout );continue ; } 177const auto t0 = clock::now (); 178ImageU8 src ; 179PreparedImage prep ; 180if (!image_load_file (img ,src ,err )) { std::printf ("ERR cannot read the image %s\n" ,img .c_str ()); std::fflush (stdout );continue ; } 181if (!prepare_image (src ,geo ,o .min_tokens ,o .max_tokens ,prep ,err )) { std::printf ("ERR the image could not be preprocessed (%s)\n" ,err .c_str ()); std::fflush (stdout );continue ; } 182const int n_expect = (prep .w /geo .align ())* (prep .h /geo .align ()); 183// never silently produce many times the budget (I7, #3690): over the limit (a rounding margin of an eighth) the picture is refused 184if (o .max_tokens > 0 && n_expect > o .max_tokens + o .max_tokens /8 ) { 185 std::printf ("ERR the picture became %d image tokens, over the limit of %d (vision.max_tokens); send a smaller picture or raise the limit\n" ,n_expect , 186o .max_tokens ); 187 std::fflush (stdout ); 188continue ; 189 } 190 std::vector < float > rows ; 191int nx = 0 ,ny = 0 ; 192if (std::getenv ("STRATA_VIT_PROF" )) 193 std::fprintf (stderr ,"vit-prof: read + decode + prepare %.2f ms\n" , std::chrono::duration < double , std::milli > (clock::now ()- t0 ).count ()); 194if (!encode (prep ,rows ,nx ,ny ,err )) { std::printf ("ERR the vision encoder failed (%s)\n" ,err .c_str ()); std::fflush (stdout );continue ; } 195const int n = nx * ny ; 196FILE * f = std::fopen (out .c_str (),"wb" ); 197if (!f ) { std::printf ("ERR cannot write %s\n" ,out .c_str ()); std::fflush (stdout );continue ; } 198const int32_t hdr [5 ]= {0x31455653 ,n ,nx ,ny ,geo .out_dim }; 199const bool ok = std::fwrite (hdr ,sizeof hdr ,1 ,f )== 1 && std::fwrite (rows .data (),sizeof (float )* (size_t )geo .out_dim , (size_t )n ,f )== (size_t )n ; 200 std::fclose (f ); 201if (!ok ) { std::printf ("ERR short write to %s\n" ,out .c_str ()); std::fflush (stdout );continue ; } 202const double ms = std::chrono::duration < double , std::milli > (clock::now ()- t0 ).count (); 203 std::printf ("OK %d %d %d %.0f\n" ,n ,nx ,ny ,ms ); 204 std::fflush (stdout ); 205 } 206return 0 ; 207} 208 209}// namespace strata_vit