okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
d4eac2ca3
main
1// src/image/qi21_image_main.cpp - test program strata-image (step 5; not shipped, not called by the server, in no build 2// that ships): prompt + size + seed -> PNG with Strata's own parts only, no stable-diffusion.cpp and no ggml in the 3// process. sd-cli stays the default and the fallback everywhere. 4// 5// strata-image --te <Qwen3-VL text encoder .gguf> --dit <qwen-image-2.1 DiT .gguf> --vae <VAE .safetensors> 6// --prompt TEXT -o OUT.png [--width 1024] [--height 1024] [--seed 42] [--steps 8] 7// [--dump DIR] [--report FILE.json] [--threads N] [--plan auto|resident|te-released] [--te-mode auto|resident|streamed] 8// 9// The pipeline, part by part (each a tested piece of its own): 10// tokens Qwen2Tok + qwen_image_tokens (src/image/te/qwen2_tok.cpp; ids identical to sd.cpp's) 11// condition qwen3vl_te_encode (src/image/te/qwen3vl_te.cu) + qi21_condition (token weights, system rows dropped) 12// noise qi21_noise (Philox, the x86 stream sd.cpp computes on a PC) -> qi21_initial_latent at sigma 1 13// 8 steps Turbo's sigmas (qi21_parse_sigmas(QI21_TURBO_SIGMAS)); per step qi21_dit_step at t = sigma x 1000 14// (src/image/dit/qi21_dit.cu), then qi21_euler_step (sd.cpp's bytes given the same velocity) 15// decode wan_vae_denormalize + wan_vae_decode (src/image/vae/wan_vae.cu, row bands) + qi21_picture_to_unit 16// PNG qi21_picture_to_u8 + png_write_file (stored deflate blocks, the "parameters" text chunk) 17// 18// Memory, decided by the card's TOTAL memory (never its free memory), as the STEP 5 DESIGN note plans it: 19// 24 GB and up "resident": the text encoder, the DiT and the VAE opened at the start and kept to the end; 20// under 24 GB "te-released": the text encoder opened, used and closed before the DiT and the VAE are opened 21// (under 14 GiB the text encoder itself streams its layers, its own auto mode). 22// --plan resident / te-released forces one plan (a measurement switch for the memory rows of smaller cards on a big 23// one; the pictures do not depend on it); --te-mode the text encoder's own mode (streamed = the under-14-GiB layout). 24// Only the GB10 row and the plans forced on one card are measured so far. 25// 26// Prints one line per stage (open, encode, steps, decode, png): wall time, the stage's own GPU time where a part 27// measures it, the parts' own device memory at the stage's end (each live part's peak so far), the device memory in 28// use as the driver reports it (sampled every 2 ms during the stage, largest value minus the value before the first 29// open), and the process's host peak (ru_maxrss). --report writes the same as JSON. --dump writes the stage tensors 30// with the names tools/image/gate/stage_hooks.py uses (tokens, cond, noise, dit_x_k, dit_t_k, vel_k, latent, vae_in, 31// vae_out; float32 / int32 with a .shape file) for the checks against sd.cpp's dumps. 32// 33// Build (CUDA; the noise table from `python tools/image/sdcpp_noise/apply.py --prepare NOISEINC`): 34// nvcc -O3 -std=c++17 -arch=native -Iinclude -Isrc/image/te -Isrc/image/vae -Itools/image/sdcpp_noise -INOISEINC 35// -Xcompiler -ffp-contract=off src/image/qi21_image_main.cpp src/image/pipeline/qi21_glue.cpp 36// src/image/te/qwen2_tok.cpp src/image/te/qwen3vl_te.cu src/image/te/te_dequant.cu src/image/te/te_dequant_host.cpp 37// src/image/dit/qi21_dit.cu src/image/dit/qi21_kernels.cu src/image/dit/dit_gemm.cu src/image/dit/qi21_rope.cpp 38// src/image/vae/wan_vae.cu src/image/vae/qi21_pixels.cpp src/image/noise/qi21_noise.cpp 39// src/image/sample/qi21_sampler.cpp src/image/png/png_write.cpp -lcublas -o strata-image 40// HIP: written against include/strata/hip_compat like the parts; not compiled yet (owed, p620). 41#include "strata/image/png_write.hpp" 42#include "strata/image/qi21_dit.hpp" 43#include "strata/image/qi21_image.hpp" 44#include "strata/image/qi21_noise.hpp" 45#include "strata/image/qi21_pixels.hpp" 46#include "strata/image/qi21_sampler.hpp" 47#include "strata/image/qwen2_tok.hpp" 48#include "strata/image/qwen3vl_te.hpp" 49#include "strata/image/wan_vae.hpp" 50 51#if defined(__HIP__ )|| defined(__HIPCC__ )|| defined(__HIP_PLATFORM_AMD__ ) 52#include "strata/hip_compat/cuda_runtime.h" 53#else 54#include <cuda_runtime.h> 55#endif 56 57#include <sys/resource.h> 58 59#include <algorithm> 60#include <atomic> 61#include <chrono> 62#include <cstdio> 63#include <cstdlib> 64#include <cstring> 65#include <filesystem> 66#include <fstream> 67#include <memory> 68#include <mutex> 69#include <string> 70#include <thread> 71#include <vector> 72 73namespace fs= std::filesystem; 74using namespace strata::image ; 75 76namespace { 77 78using clk = std::chrono::steady_clock ; 79 80double ms_since (clk::time_point t0 ) {return std::chrono::duration < double , std::milli > (clk::now ()- t0 ).count (); } 81 82double host_peak_gb () { 83struct rusage ru {}; 84getrusage (RUSAGE_SELF ,& ru ); 85return ru .ru_maxrss * 1024.0 /1e9 ;// Linux: KiB 86} 87 88// The driver's view of device memory in use (total - free), sampled on a thread; reset() starts a new stage. 89class MemSampler { 90public : 91MemSampler () { 92size_t f = 0 ,t = 0 ; 93cudaMemGetInfo (& f ,& t ); 94base_ = t - f ; 95total_ = t ; 96stage_max_ = base_ ; 97th_ = std::thread ([this ] { 98while (!stop_ ) { 99sample (); 100 std::this_thread::sleep_for (std::chrono::milliseconds (2 )); 101 } 102 }); 103 } 104 ~MemSampler () { 105stop_ = true; 106th_ .join (); 107 } 108void sample () { 109size_t f = 0 ,t = 0 ; 110if (cudaMemGetInfo (& f ,& t )!= cudaSuccess )return ; 111 std::lock_guard < std::mutex > g (mu_ ); 112stage_max_ = std::max (stage_max_ ,t - f ); 113 } 114// the stage's largest value above the start, then a new stage 115double take_stage_gb () { 116sample (); 117 std::lock_guard < std::mutex > g (mu_ ); 118const double r = stage_max_ > base_ ? (stage_max_ - base_ ) /1e9 :0.0 ; 119size_t f = 0 ,t = 0 ; 120cudaMemGetInfo (& f ,& t ); 121stage_max_ = t - f ; 122return r ; 123 } 124size_t total ()const {return total_ ; } 125 126private : 127size_t base_ = 0 ,total_ = 0 ,stage_max_ = 0 ; 128 std::mutex mu_ ; 129 std::atomic < bool > stop_ {false}; 130 std::thread th_ ; 131}; 132 133struct Stage { 134 std::string name ; 135double wall_ms = 0 ,gpu_ms = -1 ; 136double ours_gb = 0 ,driver_gb = 0 ,host_gb = 0 ; 137 std::string note ; 138}; 139 140bool write_bin (const fs::path & p ,const void * data ,size_t bytes ) { 141 std::ofstream f (p , std::ios::binary ); 142f .write (static_cast < const char *> (data ), (std::streamsize )bytes ); 143return (bool )f ; 144} 145 146void dump_f32 (const fs::path & dir ,const std::string & name ,const std::vector < float >& v ,const std::string & shape ) { 147if (dir .empty ())return ; 148write_bin (dir / (name + ".bin" ),v .data (),v .size ()* 4 ); 149 std::ofstream (dir / (name + ".shape" )) <<shape <<"\n" ; 150} 151 152std::string json_escape (const std::string & s ) { 153 std::string o ; 154for (char c :s ) { 155if (c == '"' || c == '\\' )o += '\\' ,o += c ; 156else if (c == '\n' )o += "\\n" ; 157else if ((unsigned char )c < 0x20 ) { 158char b [8 ]; 159 std::snprintf (b ,sizeof b ,"\\u%04x" ,c ); 160o += b ; 161 }else o += c ; 162 } 163return o ; 164} 165 166int usage () { 167 std::fprintf (stderr , 168"usage: strata-image --te TE.gguf --dit DIT.gguf --vae VAE.safetensors --prompt TEXT -o OUT.png\n" 169" [--width 1024] [--height 1024] [--seed 42] [--steps 8] [--dump DIR] [--report FILE]\n" 170" [--threads N] [--plan auto|resident|te-released] [--te-mode auto|resident|streamed]\n" ); 171return 2 ; 172} 173 174}// namespace 175 176int main (int argc ,char ** argv ) { 177 std::string te_path ,dit_path ,vae_path ,prompt ,out_png ,dump_dir ,report_path ,plan_arg = "auto" ; 178int width = 1024 ,height = 1024 ,steps = 8 ,threads = 8 ,te_mode = 0 ; 179uint64_t seed = 42 ; 180bool have_prompt = false; 181for (int i = 1 ;i < argc ;++ i ) { 182const std::string a = argv [i ]; 183auto next = [& ]()-> const char * {return i + 1 < argc ?argv [++ i ] :nullptr ; }; 184const char * v = nullptr ; 185if (a == "--te" && (v = next ()))te_path = v ; 186else if (a == "--dit" && (v = next ()))dit_path = v ; 187else if (a == "--vae" && (v = next ()))vae_path = v ; 188else if (a == "--prompt" && (v = next ()))prompt = v ,have_prompt = true; 189else if ((a == "-o" || a == "--output" )&& (v = next ()))out_png = v ; 190else if (a == "--width" && (v = next ()))width = std::atoi (v ); 191else if (a == "--height" && (v = next ()))height = std::atoi (v ); 192else if (a == "--seed" && (v = next ()))seed = std::strtoull (v ,nullptr ,10 ); 193else if (a == "--steps" && (v = next ()))steps = std::atoi (v ); 194else if (a == "--dump" && (v = next ()))dump_dir = v ; 195else if (a == "--report" && (v = next ()))report_path = v ; 196else if (a == "--threads" && (v = next ()))threads = std::max (1 , std::atoi (v )); 197else if (a == "--plan" && (v = next ()))plan_arg = v ; 198else if (a == "--te-mode" && (v = next ())) 199te_mode = !std::strcmp (v ,"resident" ) ?1 : !std::strcmp (v ,"streamed" ) ?2 : !std::strcmp (v ,"auto" ) ?0 :-1 ; 200else return usage (); 201 } 202if (te_path .empty ()|| dit_path .empty ()|| vae_path .empty ()|| !have_prompt || out_png .empty ())return usage (); 203if (steps != 8 ) { 204 std::fprintf (stderr ,"strata-image: --steps %d is not supported; this test program runs Turbo's 8-step " 205"schedule only\n" ,steps ); 206return 2 ; 207 } 208if (width < 16 || height < 16 || width %16 || height %16 ) { 209 std::fprintf (stderr ,"strata-image: width and height must be multiples of 16 (got %dx%d)\n" ,width ,height ); 210return 2 ; 211 } 212const std::vector < float > sigmas = qi21_parse_sigmas (QI21_TURBO_SIGMAS ); 213if ((int )sigmas .size ()!= steps + 1 ) { 214 std::fprintf (stderr ,"strata-image: the Turbo schedule did not parse\n" ); 215return 2 ; 216 } 217const fs::path dump (dump_dir ); 218if (!dump .empty ()) fs::create_directories (dump ); 219const int lw = width /16 ,lh = height /16 ;// the latent: [64][lh][lw] 220 221 std::vector < Stage > stages ; 222MemSampler mem ; 223const size_t total = mem .total (); 224if ((plan_arg != "auto" && plan_arg != "resident" && plan_arg != "te-released" )|| te_mode < 0 )return usage (); 225const bool resident = plan_arg == "auto" ?total >= (size_t )24 * 1000 * 1000 * 1000 :plan_arg == "resident" ; 226const char * plan = resident ?"resident" :"te-released" ; 227 std::printf ("strata-image: %dx%d, seed %llu, %d steps; device memory %.1f GB total -> plan %s%s\n" ,width ,height , 228 (unsigned long long )seed ,steps ,total /1e9 ,plan ,plan_arg == "auto" ?"" :" (forced by --plan)" ); 229 230 std::string err ; 231Qwen3VlTe * te = nullptr ; 232Qi21Dit * dit = nullptr ; 233WanVae * vae = nullptr ; 234Qwen3VlTeStats te_st ; 235Qi21DitStats dit_st ; 236WanVaeStats vae_st ; 237bool te_live = false,dit_live = false,vae_live = false; 238auto ours_gb = [& ]() { 239double s = 0 ; 240if (te_live )s += te_st .peak_bytes ; 241if (dit_live )s += dit_st .peak_bytes ; 242if (vae_live )s += vae_st .peak_bytes ; 243return s /1e9 ; 244 }; 245auto fail = [& ](const std::string & what ) { 246 std::fprintf (stderr ,"strata-image: %s\n" ,what .c_str ()); 247if (te )qwen3vl_te_close (te ); 248if (dit )qi21_dit_close (dit ); 249if (vae )wan_vae_close (vae ); 250 std::printf ("STRATA-IMAGE FAIL\n" ); 251return 1 ; 252 }; 253double open_ms = 0 ; 254 std::string open_note ; 255auto open_dit_vae = [& ]()-> bool { 256auto t0 = clk::now (); 257dit = qi21_dit_open (dit_path ,-1 ,& err ); 258if (!dit )return false; 259dit_live = true; 260vae = wan_vae_open (vae_path ,-1 ,& err ,threads ); 261if (!vae )return false; 262vae_live = true; 263wan_vae_set_streaming (vae , true); 264open_ms += ms_since (t0 ); 265open_note += "dit: " + qi21_dit_open_report (dit )+ "; vae: " + wan_vae_open_report (vae )+ "; " ; 266return true; 267 }; 268 269// ---- open 270auto t_open = clk::now (); 271 std::unique_ptr < Qwen2Tok > tok = Qwen2Tok ::from_gguf (te_path ,& err ); 272if (!tok )return fail ("tokenizer: " + err ); 273te = qwen3vl_te_open (te_path ,-1 ,& err ,te_mode ,threads ); 274if (!te )return fail ("text encoder: " + err ); 275te_live = true; 276open_ms += ms_since (t_open ); 277open_note += "te: " + qwen3vl_te_open_report (te )+ "; " ; 278if (resident && !open_dit_vae ())return fail ("open: " + err ); 279stages .push_back ({"open" ,open_ms ,-1 ,0 ,mem .take_stage_gb (),host_peak_gb (),open_note }); 280 281// ---- encode 282auto t_enc = clk::now (); 283QwenImageTokens toks ; 284err = qwen_image_tokens (* tok ,prompt ,& toks ); 285if (!err .empty ())return fail ("tokens: " + err ); 286const int n = (int )toks .ids .size (),C = qwen3vl_te_hidden (te ); 287 std::vector < float > hidden ((size_t )n * C ); 288err = qwen3vl_te_encode (te ,toks .ids .data (),n ,hidden .data (),& te_st ); 289if (!err .empty ())return fail ("encode: " + err ); 290const std::vector < float > cond = qi21_condition (std::move (hidden ),n ,C ,toks .weights ,toks .n_system ); 291const int L = n - toks .n_system ; 292stages .push_back ({"encode" ,ms_since (t_enc ),te_st .encode_ms ,ours_gb (),mem .take_stage_gb (),host_peak_gb (), 293 std::to_string (n )+ " tokens, " + std::to_string (L )+ " condition rows" + 294 (te_st .streamed ?", streamed" :", resident" )}); 295if (!dump .empty ()) { 296write_bin (dump /"tokens.bin" ,toks .ids .data (),toks .ids .size ()* 4 ); 297 std::ofstream (dump /"tokens.start" ) <<toks .n_system <<"\n" ; 298dump_f32 (dump ,"cond" ,cond , std::to_string (C )+ " " + std::to_string (L )); 299 } 300if (!resident ) { 301auto t0 = clk::now (); 302qwen3vl_te_close (te ); 303te = nullptr ; 304te_live = false; 305open_ms = 0 ; 306open_note .clear (); 307if (!open_dit_vae ())return fail ("open: " + err ); 308stages [0 ].wall_ms += ms_since (t0 ); 309stages [0 ].note += open_note ; 310 } 311 312// ---- 8 steps 313auto t_steps = clk::now (); 314const size_t nl = (size_t )64 * lh * lw ; 315if (qi21_dit_in_channels (dit )!= 64 || qi21_dit_out_channels (dit )!= 64 || qi21_dit_context_dim (dit )!= C ) 316return fail ("the DiT's channels do not match a 64-channel latent and the text encoder's width" ); 317const std::vector < float > noise = qi21_noise (seed , (uint32_t )nl ); 318const std::string lshape = std::to_string (lw )+ " " + std::to_string (lh )+ " 64 1" ; 319dump_f32 (dump ,"noise" ,noise ,lshape ); 320 std::vector < float > x = qi21_initial_latent (noise ,sigmas [0 ]),vel (nl ); 321double dit_gpu_ms = 0 ; 322 std::string step_ms ; 323for (int k = 0 ;k < steps ;++ k ) { 324const float t = qi21_timestep (sigmas [(size_t )k ]); 325dump_f32 (dump ,"dit_x_" + std::to_string (k ),x ,lshape ); 326dump_f32 (dump ,"dit_t_" + std::to_string (k ), std::vector < float > {t },"1" ); 327Qi21DitStats st ; 328err = qi21_dit_step (dit ,x .data (),lw ,lh ,cond .data (),L ,t ,vel .data (),& st ); 329if (!err .empty ())return fail ("step " + std::to_string (k )+ ": " + err ); 330dit_st .peak_bytes = std::max (dit_st .peak_bytes ,st .peak_bytes ); 331dit_st .weight_bytes = st .weight_bytes ; 332dit_gpu_ms += st .step_ms ; 333step_ms += (k ?" " :"" )+ std::to_string ((int ) (st .step_ms + 0.5 )); 334dump_f32 (dump ,"vel_" + std::to_string (k ),vel ,lshape ); 335qi21_euler_step (x .data (),vel .data (),nl ,sigmas [(size_t )k ],sigmas [(size_t )k + 1 ]); 336 } 337dump_f32 (dump ,"latent" ,x ,lshape ); 338stages .push_back ({"steps" ,ms_since (t_steps ),dit_gpu_ms ,ours_gb (),mem .take_stage_gb (),host_peak_gb (), 339"per step ms: " + step_ms }); 340 341// ---- decode 342auto t_dec = clk::now (); 343wan_vae_denormalize (x .data (),lh ,lw ); 344dump_f32 (dump ,"vae_in" ,x ,lshape ); 345const int W = 16 * lw ,H = 16 * lh ,PC = 4 ; 346 std::vector < float > pic ((size_t )PC * W * H ); 347err = wan_vae_decode (vae ,x .data (),lh ,lw ,pic .data (),& vae_st ); 348if (!err .empty ())return fail ("decode: " + err ); 349qi21_picture_to_unit (pic .data (),pic .size ()); 350dump_f32 (dump ,"vae_out" ,pic , std::to_string (W )+ " " + std::to_string (H )+ " " + std::to_string (PC )+ " 1" ); 351stages .push_back ({"decode" ,ms_since (t_dec ),vae_st .decode_ms ,ours_gb (),mem .take_stage_gb (),host_peak_gb (),"" }); 352 353// ---- PNG 354auto t_png = clk::now (); 355 std::vector < uint8_t > px ((size_t )W * H * PC ); 356qi21_picture_to_u8 (pic .data (),W ,H ,PC ,px .data ()); 357err = png_write_file (out_png ,px .data (),W ,H ,PC , 358qi21_parameters_text (prompt ,steps ,seed ,width ,height , fs::path (dit_path ).filename ().string ())); 359if (!err .empty ())return fail ("png: " + err ); 360stages .push_back ({"png" ,ms_since (t_png ),-1 ,ours_gb (),mem .take_stage_gb (),host_peak_gb (),out_png }); 361 362double total_ms = 0 ; 363for (const Stage & s :stages ) { 364total_ms += s .wall_ms ; 365 std::printf ("stage %-6s %9.1f ms" ,s .name .c_str (),s .wall_ms ); 366if (s .gpu_ms >=0 ) std::printf (" (gpu %.1f ms)" ,s .gpu_ms ); 367 std::printf (" | parts' own device memory %.3f GB | driver in use %.3f GB | host peak %.3f GB | %s\n" , 368s .ours_gb ,s .driver_gb ,s .host_gb ,s .note .c_str ()); 369 } 370 std::printf ("total %.1f ms; text encoder weights %.3f GB, DiT weights %.3f GB, VAE weights %.3f GB\n" ,total_ms , 371te_st .weight_bytes /1e9 ,dit_st .weight_bytes /1e9 ,vae_st .weight_bytes /1e9 ); 372if (!report_path .empty ()) { 373 std::ofstream r (report_path ); 374r <<"{\"width\": " <<width <<", \"height\": " <<height <<", \"seed\": " <<seed <<", \"steps\": " <<steps 375 <<", \"plan\": \"" <<plan <<"\", \"device_total_gb\": " <<total /1e9 <<", \"total_ms\": " <<total_ms 376 <<", \"te_weight_gb\": " <<te_st .weight_bytes /1e9 <<", \"dit_weight_gb\": " <<dit_st .weight_bytes /1e9 377 <<", \"vae_weight_gb\": " <<vae_st .weight_bytes /1e9 <<", \"stages\": [" ; 378for (size_t i = 0 ;i < stages .size ();++ i ) { 379const Stage & s = stages [i ]; 380r << (i ?", " :"" ) <<"{\"name\": \"" <<s .name <<"\", \"wall_ms\": " <<s .wall_ms <<", \"gpu_ms\": " 381 <<s .gpu_ms <<", \"ours_gb\": " <<s .ours_gb <<", \"driver_gb\": " <<s .driver_gb <<", \"host_gb\": " 382 <<s .host_gb <<", \"note\": \"" <<json_escape (s .note ) <<"\"}" ; 383 } 384r <<"]}\n" ; 385 } 386if (te )qwen3vl_te_close (te ); 387qi21_dit_close (dit ); 388wan_vae_close (vae ); 389 std::printf ("STRATA-IMAGE PASS %s\n" ,out_png .c_str ()); 390return 0 ; 391}