okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fe57a0cb5
main
1// fnx_run MODEL.gguf check REF.bin OUT.bin [W] the reference prompt in windows of W rows, per-layer dumps to OUT.bin 2// fnx_run MODEL.gguf gen REF.bin N greedy: the reference prompt, then N tokens one row per window 3// fnx_run MODEL.gguf rows REF.bin T N N windows of T rows (the reference tokens, cycled): time per window 4// fnx_run MODEL.gguf bench REF.bin T N N verify windows of T rows, each committing one: wall and GPU time 5// fnx_run MODEL.gguf bench_step REF.bin L N C [step] verify windows of 1..MAXT rows, then batched windows of 1..L lanes, 6// at a context of C tokens: medians of N windows each 7// fnx_run MODEL.gguf mtp RT_DIR REF.bin N K [VOCAB [LK]] greedy decoding with the draft layer (data/mtp-rt), K drafts 8// per round (VOCAB: the draft vocabulary, default RT_DIR's; LK lookup drafts) 9// fnx_run MODEL.gguf spec REF.bin GEN.txt K [BAD%] speculative windows of K perfect drafts from gen's output, BAD% of 10// windows with one draft corrupted: the output must be gen's 11// fnx_run MODEL.gguf logits PROMPT.bin CONT.lgr T OUT.lgr the prompt, then CONT.lgr's steps in windows of T: top-64s 12// fnx_run MODEL.gguf exact|read|decode|batch|compare ... the lab's standard checks (lab_check below) 13#include <cmath> 14#include <numeric> 15#include <optional> 16#include <algorithm> 17#include <array> 18#include <chrono> 19#include <fstream> 20#include <random> 21#include <sstream> 22#include <cstdio> 23#include <cstdlib> 24#include <cstring> 25#include <string> 26#include <vector> 27 28#include <cerrno> 29#include <cinttypes> 30#include <climits> 31#include <cuda_runtime.h> 32#include <dlfcn.h> 33#include <sys/stat.h> 34#include <unistd.h> 35#include <iterator> 36#include <stdexcept> 37 38#include "../src/engine.hpp" 39#include "batch_check.hpp" 40#include "ref_tokens.hpp" 41#include "../src/env.hpp" 42 43// the draft layer's runtime: Flash-Next's files, or the 27B's own layer in its GGUF (Mtp's "nextn") 44#if FNX_27B 45#define MTP_RT "nextn" 46#else 47#define MTP_RT FNX_DIR "/data/mtp-rt" 48#endif 49 50// timings: the middle value, and the p-quantile at index p * (n - 1) 51static double pct (std::vector < double > v ,double p ) { 52if (v .empty ())throw std::runtime_error ("pct: no values" ); 53 std::sort (v .begin (),v .end ()); 54return v [(size_t ) (p * (v .size ()- 1 ))]; 55} 56static double median (std::vector < double > v ) { 57if (v .empty ())throw std::runtime_error ("median: no values" ); 58 std::sort (v .begin (),v .end ()); 59return v [v .size () /2 ]; 60} 61 62// the reference prompt (through the prompt path when prefill, else in windows of MAXT), then the continuation of 63// REF.lgr in windows of T: the top 64 logits of each step to OUT.lgr (fnx_logref's format) 64static int run_logits (fnx::Model & m , fnx::Engine & e ,const char * prompt_path ,const char * ref_path ,int T ,const char * out_path , 65bool prefill ) { 66const std::vector < int > prompt = ref_tokens (prompt_path ); 67if (T < 1 || T > fnx::MAXT ) { std::fprintf (stderr ,"T: 1..%d\n" , fnx::MAXT );return 2 ; } 68// the continuation's tokens (fnx_logref's records) 69 std::vector < int > cont ; 70 { 71 std::FILE * f = std::fopen (ref_path ,"rb" ); 72char magic [4 ]; 73uint32_t k = 0 ; 74int32_t np = 0 ,ns = 0 ; 75if (!f || std::fread (magic ,1 ,4 ,f )!= 4 || std::memcmp (magic ,"LGR1" ,4 )|| std::fread (& k ,4 ,1 ,f )!= 1 || 76 std::fread (& np ,4 ,1 ,f )!= 1 ) { std::fprintf (stderr ,"%s: not an .lgr file\n" ,ref_path );return 1 ; } 77 std::vector < int32_t > pr ((size_t )np ); 78if (std::fread (pr .data (),4 ,pr .size (),f )!= pr .size ()|| std::fread (& ns ,4 ,1 ,f )!= 1 )return 1 ; 79if (std::vector < int > (pr .begin (),pr .end ())!= prompt ) { std::fprintf (stderr ,"the .lgr file has another prompt\n" );return 1 ; } 80for (int i = 0 ;i < ns ;++ i ) { 81int32_t tok ; 82if (std::fread (& tok ,4 ,1 ,f )!= 1 )return 1 ; 83cont .push_back (tok ); 84 std::fseek (f ,4 + (long )k * 8 ,SEEK_CUR ); 85 } 86 std::fclose (f ); 87 } 88constexpr uint32_t K = 64 ; 89 std::FILE * out = std::fopen (out_path ,"wb" ); 90if (!out ) { std::perror (out_path );return 1 ; } 91const int32_t np = (int32_t )prompt .size (),ns = (int32_t )cont .size (); 92 std::fwrite ("LGR1" ,1 ,4 ,out ); 93 std::fwrite (& K ,4 ,1 ,out ); 94 std::fwrite (& np ,4 ,1 ,out ); 95for (int t :prompt ) { 96const int32_t v = t ; 97 std::fwrite (& v ,4 ,1 ,out ); 98 } 99 std::fwrite (& ns ,4 ,1 ,out ); 100int written = 0 ; 101auto put_rows = [& ](const std::vector < float >& lg ,int vocab ,int r0 ,int r1 ) { 102for (int r = r0 ;r < r1 && written < ns ;++ r ,++ written ) { 103const float * row = lg .data ()+ (size_t )r * vocab ; 104float mx = - INFINITY ; 105for (int i = 0 ;i < vocab ;++ i )mx = std::max (mx ,row [i ]); 106double s = 0 ; 107for (int i = 0 ;i < vocab ;++ i )s += std::exp ((double )row [i ]- mx ); 108const float lse = (float ) (mx + std::log (s )); 109 std::vector < int > idx ((size_t )vocab ); 110 std::iota (idx .begin (),idx .end (),0 ); 111 std::partial_sort (idx .begin (),idx .begin ()+ K ,idx .end (), 112 [& ](int a ,int b ) {return row [a ]> row [b ]|| (row [a ]== row [b ]&& a < b ); }); 113const int32_t taken = cont [(size_t )written ]; 114 std::fwrite (& taken ,4 ,1 ,out ); 115 std::fwrite (& lse ,4 ,1 ,out ); 116for (uint32_t k = 0 ;k < K ;++ k ) { 117const int32_t id = idx [k ]; 118 std::fwrite (& id ,4 ,1 ,out ); 119 std::fwrite (& row [id ],4 ,1 ,out ); 120 } 121 } 122 }; 123const int vocab = m .cards [fnx::NCARD - 1 ].v1 ; 124// FNX_IMAGES=FILE.sve (img_logref's): each run of image-pad tokens takes the file's next picture (its cells get 125// ids of their own, its rows and grid go to set_images) 126 std::vector < int > feed = prompt ; 127 std::vector < float > img_rows ; 128 std::vector < fnx::Engine ::Image > imgs ; 129if (const char * sv = std::getenv ("FNX_IMAGES" )) { 130 std::FILE * f = std::fopen (sv ,"rb" ); 131if (!f ) { std::perror (sv );return 1 ; } 132 std::vector < std::array < int ,4 >> recs ;// n, nx, ny, first row 133int32_t h [5 ]; 134while (std::fread (h ,4 ,5 ,f )== 5 ) { 135if (h [0 ]!= 0x31455653 || h [4 ]!= fnx::N ) { std::fprintf (stderr ,"%s: not strata-vision records of width %d\n" ,sv , fnx::N );return 1 ; } 136const size_t off = img_rows .size (); 137img_rows .resize (off + (size_t )h [1 ]* fnx::N ); 138if (std::fread (img_rows .data ()+ off ,4 , (size_t )h [1 ]* fnx::N ,f )!= (size_t )h [1 ]* fnx::N )return 1 ; 139recs .push_back ({h [1 ],h [2 ],h [3 ], (int ) (off / fnx::N )}); 140 } 141 std::fclose (f ); 142size_t k = 0 ; 143for (size_t i = 0 ;i < feed .size ();) { 144if (feed [i ]!= (int )m .ple_image ) {++ i ;continue ; } 145if (k >=recs .size ()) { std::fprintf (stderr ,"more images in the prompt than in %s\n" ,sv );return 1 ; } 146const auto & r = recs [k ]; 147for (int j = 0 ;j < r [0 ];++ j )feed [i + j ]= fnx::Engine ::IMAGE_TOK + (int )k * 65536 + j ; 148imgs .push_back (fnx::Engine ::Image {(int )i ,r [0 ],r [1 ],r [2 ],img_rows .data ()+ (size_t )r [3 ]* fnx::N }); 149i += r [0 ]; 150++ k ; 151 } 152e .set_images (imgs ); 153 std::fprintf (stderr ,"logits: %zu image(s)\n" ,imgs .size ()); 154 } 155// the prompt: its last window's last row is step 0. FNX_PREFILL=1: all but its last token through the batched path 156if (prefill ) { 157const auto t0 = std::chrono::steady_clock::now (); 158e .prefill (std::vector < int > (feed .begin (),feed .end ()- 1 )); 159const double s = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 160 std::fprintf (stderr ,"prefill: %zu tokens in %.2f s (%.0f tok/s)\n" ,feed .size ()- 1 ,s , (feed .size ()- 1 ) /s ); 161e .window ({feed .back ()}); 162put_rows (e .last_logits (1 ),vocab ,0 ,1 ); 163 }else 164for (size_t i = 0 ;i < feed .size ();i += fnx::MAXT ) { 165 std::vector < int > w (feed .begin ()+ i ,feed .begin ()+ std::min (feed .size (),i + fnx::MAXT )); 166e .window (w ); 167if (i + w .size ()== feed .size ())put_rows (e .last_logits ((int )w .size ()),vocab , (int )w .size ()- 1 , (int )w .size ()); 168 } 169// the continuation in windows of T: row r of a window starting at step j gives step j + r + 1 170for (int j = 0 ;j + 1 < ns ;j += T ) { 171 std::vector < int > w (cont .begin ()+ j ,cont .begin ()+ std::min (ns - 1 ,j + T )); 172e .window (w ); 173put_rows (e .last_logits ((int )w .size ()),vocab ,0 , (int )w .size ()); 174 } 175if (std::ferror (out )) { 176 std::fclose (out ); 177 std::fprintf (stderr ,"logits: %s: a write failed\n" ,out_path ); 178return 1 ; 179 } 180if (std::fclose (out )!= 0 ) { 181 std::fprintf (stderr ,"logits: %s: close failed (a buffered write did not reach the disk)\n" ,out_path ); 182return 1 ; 183 } 184 std::fprintf (stderr ,"logits: %d prompt tokens, %d steps in windows of %d\n" ,np ,written ,T ); 185return 0 ; 186} 187 188// ---------------------------------------------------------------- the lab's standard checks (fixed inputs, run from fnx/) 189// exact [NAME] ref/long64.bin (62,794 tokens), code1 and edit1 each through the prompt path, then their llama.cpp 190// continuation steps in windows of 5: the logits to LAB/MODEL-NAME[-PROMPT].lgr (default "try"), 191// compared with llama.cpp CUDA's on that model (see below) and, byte for byte and by KL, with 192// LAB/MODEL-base[-PROMPT].lgr; "exact base" writes the baselines themselves 193// read N [N...] the first N tokens of ref/long64.bin through the prompt path on a fresh engine (after warm_graphs, as 194// sfnx starts): the read's time and tok/s 195// LAB is FNX_LAB_DIR or /tmp/fnx-lab-UID (tools/lab.sh's directory). 196struct Lgr { 197uint32_t k = 0 ; 198 std::vector < int32_t > prompt ; 199struct Step { 200int32_t tok ; 201float lse ; 202 std::vector < int32_t > id ; 203 std::vector < float > v ; 204 }; 205 std::vector < Step > steps ; 206}; 207static bool load_lgr (const std::string & path ,Lgr & g ) { 208 std::FILE * f = std::fopen (path .c_str (),"rb" ); 209if (!f )return false; 210char magic [4 ]; 211int32_t np = 0 ,ns = 0 ; 212bool ok = std::fread (magic ,1 ,4 ,f )== 4 && !std::memcmp (magic ,"LGR1" ,4 )&& std::fread (& g .k ,4 ,1 ,f )== 1 && 213 std::fread (& np ,4 ,1 ,f )== 1 ; 214if (ok ) { 215g .prompt .resize ((size_t )np ); 216ok = std::fread (g .prompt .data (),4 ,g .prompt .size (),f )== g .prompt .size ()&& std::fread (& ns ,4 ,1 ,f )== 1 ; 217 } 218for (int i = 0 ;ok && i < ns ;++ i ) { 219Lgr ::Step s ; 220s .id .resize (g .k ); 221s .v .resize (g .k ); 222ok = std::fread (& s .tok ,4 ,1 ,f )== 1 && std::fread (& s .lse ,4 ,1 ,f )== 1 ; 223for (uint32_t j = 0 ;ok && j < g .k ;++ j )ok = std::fread (& s .id [j ],4 ,1 ,f )== 1 && std::fread (& s .v [j ],4 ,1 ,f )== 1 ; 224g .steps .push_back (std::move (s )); 225 } 226 std::fclose (f ); 227if (!ok )throw std::runtime_error (path + ": a short or malformed .lgr file" ); 228return true; 229} 230// ref/lgrcmp.py's measures: top-1 agreement, the agreeing run from the start, KL(ref || other) over the union of both 231// top-Ks (a token outside a side's top-K gets its K-th logit), the top-10 overlap 232struct LgrCmp { 233int agree = 0 ,run = 0 ; 234size_t n = 0 ; 235double kl_mean = 0 ,kl_median = 0 ,kl_p99 = 0 ,kl_max = 0 ,top10 = 0 ; 236double top1_pct ()const {return 100.0 * agree / (double )n ; } 237 std::string str ()const { 238char buf [256 ]; 239 std::snprintf (buf ,sizeof buf ,"top-1 %d/%zu (first %d in a row), KL mean %.2e median %.2e p99 %.2e max %.2e, top-10 overlap %.2f" , 240agree ,n ,run ,kl_mean ,kl_median ,kl_p99 ,kl_max ,top10 ); 241return buf ; 242 } 243}; 244static LgrCmp lgr_compare (const Lgr & r ,const Lgr & o ) { 245if (r .prompt != o .prompt )throw std::runtime_error ("lgr_compare: different prompts" ); 246const size_t n = std::min (r .steps .size (),o .steps .size ()); 247if (n == 0 )throw std::runtime_error ("lgr_compare: no steps" ); 248int agree = 0 ,run = 0 ; 249bool open = true; 250double ov = 0 ; 251 std::vector < double > kls ; 252for (size_t i = 0 ;i < n ;++ i ) { 253const Lgr ::Step & a = r .steps [i ],& b = o .steps [i ]; 254if (a .tok != b .tok )throw std::runtime_error ("lgr_compare: step " + std::to_string (i )+ " took different tokens" ); 255if (a .id [0 ]== b .id [0 ]) { 256++ agree ; 257run += open ; 258 }else { 259open = false; 260 } 261auto logit = [](const Lgr ::Step & s ,int t ) { 262for (size_t j = 0 ;j < s .id .size ();++ j ) 263if (s .id [j ]== t )return s .v [j ]; 264return s .v .back (); 265 }; 266 std::vector < int32_t > u (a .id ); 267u .insert (u .end (),b .id .begin (),b .id .end ()); 268 std::sort (u .begin (),u .end ()); 269u .erase (std::unique (u .begin (),u .end ()),u .end ()); 270double kl = 0 ; 271for (int t :u ) { 272const double p = std::exp ((double )logit (a ,t )- a .lse ),q = std::exp ((double )logit (b ,t )- b .lse ); 273if (p > 0 && q > 0 )kl += p * std::log (p /q ); 274 } 275kls .push_back (std::max (kl ,0.0 )); 276int o10 = 0 ; 277for (int x = 0 ;x < 10 ;++ x ) 278for (int y = 0 ;y < 10 ;++ y )o10 += a .id [x ]== b .id [y ]; 279ov += o10 ; 280 } 281 std::vector < double > sk (kls ); 282 std::sort (sk .begin (),sk .end ()); 283LgrCmp c ; 284c .agree = agree ,c .run = run ,c .n = n ; 285c .kl_mean = std::accumulate (kls .begin (),kls .end (),0.0 ) /n ,c .kl_median = sk [n /2 ]; 286c .kl_p99 = sk [std::min (n - 1 , (size_t ) (0.99 * n ))],c .kl_max = sk .back (),c .top10 = ov /n ; 287return c ; 288} 289static bool same_bytes (const std::string & a ,const std::string & b ) { 290 std::ifstream fa (a , std::ios::binary ),fb (b , std::ios::binary ); 291if (!fa || !fb )return false; 292const std::string sa (std::istreambuf_iterator < char > (fa ), {}),sb (std::istreambuf_iterator < char > (fb ), {}); 293return !sa .empty ()&& sa == sb ; 294} 295static std::string lab_dir () { 296if (const char * d = std::getenv ("FNX_LAB_DIR" ))return d ; 297return "/tmp/fnx-lab-" + std::to_string (getuid ()); 298} 299 300// The exactness bar (README, "Exactness"): llama.cpp's CPU backend against its CUDA one, teacher-forced on the same 301// tokens, for code1, edit1 and the picture; for long64, llama.cpp's own q8_0 K/V cache against its f16 one, since 302// summation order alone moves long64's KL between 1.8e-3 and 4.3e-3. The Q8_0 model is held to the same bar (its 303// references are llama.cpp's CPU backend on Q8_0). A run passes with KL mean <= KL_SLACK x the bar's and top-1 at most 304// TOP1_SLACK points under the bar's: sFNX's fp16 ring sums put Q8_0's code1 at 1.10x, while the one precision loss 305// caught so far (fast-math decays in the recurrent core) put code1 at 1.44x. The picture (ref/img/sphinx, 200 steps): 306// llama.cpp's CPU backend 98.50% / 6.38e-3; sFNX 99.00% / 5.96e-3. 307struct Bar { 308const char * prompt ; 309double top1_pct ,kl_mean ,kl_slack ; 310}; 311constexpr double TOP1_SLACK = 1.5 ; 312#if FNX_27B 313// the 27B's (make FNX_MODEL=27b), on Qwen3.8-27B Q8_0 (docs/verification.md, "The 27B"): the widest of llama.cpp's own 314// spreads, each teacher-forced on its CUDA run's tokens (the file the check compares against, 315// ref/lgr/llama_cuda_<model>_<prompt>.lgr). Its CPU backend against CUDA (llama_cpu_*: code1 8.95e-5, edit1 1.48e-7, 316// the picture 99.50% / 4.69e-4), and its CUDA with the int8 products of quantized activations off, cuBLAS for every 317// product (ref/llama_cublas_only.patch, llama_cublas_*: code1 1.25e-4, edit1 1.23e-7, the picture 99.00% / 8.91e-4, 318// long64 1.04e-4); long64 its q8_0 K/V against its f16 K/V (2.08e-4), as Flash-Next's. Top-1 the CPU backend's (the 319// highest), KL the widest; the slack on top is Flash-Next's, for sFNX's own summation orders 320constexpr Bar BARS []= { 321 {"code1" ,100.00 ,1.25e-4 ,1.25 }, 322 {"edit1" ,100.00 ,1.48e-7 ,1.25 }, 323 {"picture" ,99.50 ,8.91e-4 ,1.25 }, 324 {"long64" ,99.50 ,2.08e-4 ,1.0 }, 325}; 326#else 327constexpr Bar BARS []= { 328 {"code1" ,98.33 ,4.85e-4 ,1.25 }, 329 {"edit1" ,100.00 ,4.12e-6 ,1.25 }, 330 {"picture" ,98.50 ,6.38e-3 ,1.25 }, 331 {"long64" ,97.50 ,4.98e-3 ,1.0 }, 332}; 333#endif 334// empty when c is within prompt's bar, else what is outside it 335static std::string breach (const std::string & prompt ,const LgrCmp & c ) { 336for (const Bar & b :BARS ) { 337if (prompt != b .prompt )continue ; 338 std::string why ; 339char buf [160 ]; 340if (c .kl_mean > b .kl_mean * b .kl_slack ) { 341 std::snprintf (buf ,sizeof buf ,"KL mean %.2e over %.2e (%.2fx the bar's %.2e)" ,c .kl_mean ,b .kl_mean * b .kl_slack ,b .kl_slack ,b .kl_mean ); 342why = buf ; 343 } 344if (c .top1_pct ()< b .top1_pct - TOP1_SLACK ) { 345 std::snprintf (buf ,sizeof buf ,"top-1 %.2f%% under %.2f%% (the bar's %.2f%% less %.1f)" ,c .top1_pct (),b .top1_pct - TOP1_SLACK , 346b .top1_pct ,TOP1_SLACK ); 347why += (why .empty () ?"" :"; " )+ std::string (buf ); 348 } 349return why ; 350 } 351return "no bar for " + prompt ; 352} 353 354// What made a run's logits, for the base's identity record (LAB/MODEL-base.id): the model file, the engine code that 355// ran (the library or binary holding this function, as loaded: a library rebuilt but not reloaded is still the old 356// one), the source tree's revision, and the FNX_ settings. A base is only compared against runs of the same model 357// file; the rest is shown so a difference can be traced to its build. 358static std::string file_line (const std::string & path ) { 359struct stat st ; 360if (stat (path .c_str (),& st )!= 0 )return path + " (cannot stat)" ; 361char buf [96 ]; 362 std::snprintf (buf ,sizeof buf ," %lld bytes, modified %lld" , (long long )st .st_size , (long long )st .st_mtime ); 363return path + buf ; 364} 365static std::string loaded_code () { 366Dl_info di ; 367if (!dladdr ((void * )& file_line ,& di )|| !di .dli_fname )return "unknown (dladdr failed)" ; 368char real [PATH_MAX ]; 369const std::string path = realpath (di .dli_fname ,real ) ?real :di .dli_fname ; 370// the mapping's inode from /proc/self/maps: the file now at that path may be a newer build 371const auto addr = (uintptr_t )di .dli_fbase ; 372 std::ifstream maps ("/proc/self/maps" ); 373for (std::string line ; std::getline (maps ,line );) { 374uintptr_t lo = 0 ,hi = 0 ; 375unsigned long long ino = 0 ; 376char perms [8 ],dev [16 ]; 377long long off = 0 ; 378if (std::sscanf (line .c_str (),"%" SCNxPTR "-%" SCNxPTR " %7s %llx %15s %llu" ,& lo ,& hi ,perms ,& off ,dev ,& ino )!= 6 )continue ; 379if (addr < lo || addr >=hi )continue ; 380struct stat st ; 381const bool same = stat (path .c_str (),& st )== 0 && (unsigned long long )st .st_ino == ino ; 382return same ?file_line (path ) :path + " (inode " + std::to_string (ino )+ ", replaced on disk since it was loaded)" ; 383 } 384return file_line (path ); 385} 386// what the logits depend on besides the model and the code's sums: the card count it was built for, decode's ring and 387// rope scaling (named only when on, so an unscaled build's line is the one its bases recorded) 388static std::string build_line (int ncard ,bool f32 ,double rope_scale = 0.0 ) { 389 std::string l = "build ncard " + std::to_string (ncard )+ " ring " + (f32 ?"fp32" :"fp16-pairs" ); 390if (rope_scale ) { 391char s [64 ]; 392 std::snprintf (s ,sizeof s ," rope yarn x%.9g" ,rope_scale ); 393l += s ; 394if (const char * o = std::getenv ("FNX_YARN_ORIG_CTX" ))l += std::string (" orig " )+ o ; 395 } 396return l ; 397} 398static std::string run_identity (const char * model ) { 399 std::string id ; 400char real [PATH_MAX ]; 401id += "model " + file_line (realpath (model ,real ) ?real :model )+ "\n" ; 402id += "code " + loaded_code ()+ "\n" ; 403 std::string rev ; 404if (std::FILE * p = popen ("git -C '" FNX_DIR "' describe --always --dirty --abbrev=12 2>&1" ,"r" )) { 405char buf [256 ]; 406while (std::fgets (buf ,sizeof buf ,p ))rev += buf ; 407if (pclose (p )!= 0 )rev = "unknown (git: " + rev + ")" ; 408 } 409while (!rev .empty ()&& (rev .back ()== '\n' || rev .back ()== ' ' ))rev .pop_back (); 410id += "tree " FNX_DIR " " + rev + "\n" ; 411id += build_line (fnx::NCARD , fnx::ring_f32 (), fnx::rope_scale ())+ "\n" ; 412 std::vector < std::string > env ; 413for (char ** e = environ ;* e ;++ e ) 414if (!std::strncmp (* e ,"FNX_" ,4 ))env .emplace_back (* e ); 415 std::sort (env .begin (),env .end ()); 416id += "env" ; 417for (const std::string & e :env )id += " " + e ; 418return id + "\n" ; 419} 420// the line of an identity record that starts with key + " " 421static std::string id_line (const std::string & id ,const std::string & key ) { 422 std::istringstream in (id ); 423for (std::string l ; std::getline (in ,l );) 424if (l .compare (0 ,key .size ()+ 1 ,key + " " )== 0 )return l ; 425return "" ; 426} 427static void sync_cards () { 428for (int c = 0 ;c < fnx::NCARD ;++ c ) { 429if (cudaSetDevice (c )!= cudaSuccess || cudaDeviceSynchronize ()!= cudaSuccess ) 430throw std::runtime_error (std::string ("sync_cards: " )+ cudaGetErrorString (cudaGetLastError ())); 431 } 432} 433static int env_ctx (int need ) { 434const char * c = std::getenv ("FNX_MAX_CTX" ); 435return std::max (c ? std::atoi (c ) :0 ,need ); 436} 437static int lab_check (fnx::Model & m ,int argc ,char ** argv ) { 438const std::string mode = argv [2 ]; 439const char * long64 = "ref/long64.bin" ; 440const std::vector < int > toks = ref_tokens (long64 ); 441if (mode == "read" ) { 442if (argc < 4 ) { std::fprintf (stderr ,"read needs N [N...]\n" );return 2 ; } 443for (int i = 3 ;i < argc ;++ i ) { 444const int n = std::atoi (argv [i ]); 445if (n < 1 || n > (int )toks .size ()) { std::fprintf (stderr ,"read: N in 1..%zu\n" ,toks .size ());return 2 ; } 446const auto te = std::chrono::steady_clock::now (); 447 fnx::Engine e (m ,env_ctx (n + 1024 ),1 ); 448sync_cards (); 449const auto tg = std::chrono::steady_clock::now (); 450e .warm_graphs (); 451sync_cards (); 452const auto t0 = std::chrono::steady_clock::now (); 453e .prefill (std::vector < int > (toks .begin (),toks .begin ()+ n )); 454sync_cards (); 455const double s = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 456 std::printf ("read %d tokens: %.0f ms, %.0f tok/s (engine made in %.1f s, its graphs warmed in %.1f s)\n" ,n ,s * 1000 ,n /s , 457 std::chrono::duration < double > (tg - te ).count (), std::chrono::duration < double > (t0 - tg ).count ()); 458 } 459return 0 ; 460 } 461if (mode == "decode" ) { 462// one request alone as prod decodes it (Session: MTP drafts up to K=6 (their count follows acceptance), lookup drafts up to 15, prod's draft layer files), 463// on an engine made like prod's (262,144 positions, 6 lanes): the code edit (ends at 636 tokens) and new code (N 464// tokens, default 1,024), greedy, each once to warm up, then timed; then prose reasoning in the style of thinking 465// (N tokens) sampled as prod samples (serve/sfnx.json), since thinking is decoded so: seeds 1-5 summed. SAMPLES: 466// which of edit1, code1, prose2 to run (comma separated, default all), or code1s: new code sampled as prose2 is 467const int n = argc > 3 ? std::atoi (argv [3 ]) :1024 ,K = argc > 4 ? std::atoi (argv [4 ]) :6 ,LK = argc > 5 ? std::atoi (argv [5 ]) :15 ; 468if (n < 1 ) { std::fprintf (stderr ,"decode [N]: N >= 1\n" );return 2 ; } 469const std::string samples = argc > 6 ?argv [6 ] :"edit1,code1,prose2" ; 470auto wanted = [& ](const std::string & name ) {return ("," + samples + "," ).find ("," + name + "," )!= std::string::npos ; }; 471for (size_t a = 0 ,b ;a <=samples .size ();a = b + 1 ) { 472b = samples .find (',' ,a ); 473if (b == std::string::npos )b = samples .size (); 474const std::string one = samples .substr (a ,b - a ); 475if (one != "edit1" && one != "code1" && one != "prose2" && one != "code1s" ) { 476 std::fprintf (stderr ,"decode SAMPLES: edit1, code1, prose2, code1s (comma separated), not '%s'\n" ,one .c_str ()); 477return 2 ; 478 } 479 } 480const fnx::Mtp mtp (m ,MTP_RT ,FNX_DIR "/data/draft_vocab_en.bin" ); 481 fnx::Engine e (m ,env_ctx (262144 ),6 ); 482e .mtp_attach (mtp ); 483const std::vector < int > eos {248044 ,248046 }; 484 fnx::Sampling greedy ,served ; 485served .temperature = 0.6f ,served .top_p = 0.95f ,served .pen_present = 1.0f ; 486auto run_one = [& ](const std::vector < int >& prompt ,const fnx::Sampling & smp ) { 487e .reset (); 488 fnx::Session s (e ,K ,LK ,eos ); 489 fnx::GenStats st ; 490s .read (prompt ,st ); 491s .generate (n ,smp , [](int ) {},nullptr ,st ); 492return st ; 493 }; 494auto report = [](const std::string & p ,const fnx::GenStats & st ) { 495 std::printf ("decode %s: %d tokens in %.0f ms, %.1f tok/s, %.2f tokens a round, %.2f ms a round (%d rounds, %d with lookup drafts; drafts %ld of %ld)\n" , 496p .c_str (),st .generated ,st .decode_ms ,st .generated * 1000.0 /st .decode_ms , (double )st .generated /st .rounds , 497st .decode_ms /st .rounds ,st .rounds ,st .lookup_rounds ,st .drafts_accepted ,st .drafts_offered ); 498 std::printf (" a round: verify %.2f ms (GPU %.2f, launch %.2f), drafts %.2f ms in %.1f calls (GPU %.2f), commit %.2f, " 499"the session's own %.2f\n" , 500st .verify_ms /st .rounds ,st .verify_gpu_ms /st .rounds ,st .launch_ms /st .rounds ,st .draft_ms /st .rounds , 501 (double )st .draft_calls /st .rounds ,st .draft_gpu_ms /st .rounds ,st .commit_ms /st .rounds , 502 (st .decode_ms - st .verify_ms - st .draft_ms - st .commit_ms ) /st .rounds ); 503 }; 504bool warm = false; 505for (const char * p : {"edit1" ,"code1" }) { 506if (!wanted (p ))continue ; 507const std::vector < int > prompt = ref_tokens ((std::string ("ref/" )+ p + ".bin" ).c_str ()); 508run_one (prompt ,greedy ); 509warm = true; 510report (p ,run_one (prompt ,greedy )); 511 } 512for (const char * p : {"prose2" ,"code1s" }) { 513if (!wanted (p ))continue ; 514const std::string file = std::string (p )== "code1s" ?"code1" :p ; 515const std::vector < int > prompt = ref_tokens (("ref/" + file + ".bin" ).c_str ()); 516if (!warm ) {// the graphs and the first request's costs, out of the timed runs 517 fnx::Sampling w = served ; 518w .seed = 0 ; 519 fnx::Session s (e ,K ,LK ,eos ); 520 fnx::GenStats st ; 521e .reset (); 522s .read (prompt ,st ); 523s .generate (64 ,w , [](int ) {},nullptr ,st ); 524warm = true; 525 } 526 fnx::GenStats sum ; 527for (uint64_t seed = 1 ;seed <=5 ;++ seed ) { 528served .seed = seed ; 529const fnx::GenStats st = run_one (prompt ,served ); 530sum .generated += st .generated ,sum .decode_ms += st .decode_ms ,sum .rounds += st .rounds ,sum .lookup_rounds += st .lookup_rounds ; 531sum .drafts_accepted += st .drafts_accepted ,sum .drafts_offered += st .drafts_offered ; 532sum .verify_ms += st .verify_ms ,sum .verify_gpu_ms += st .verify_gpu_ms ,sum .launch_ms += st .launch_ms ; 533sum .draft_ms += st .draft_ms ,sum .draft_gpu_ms += st .draft_gpu_ms ,sum .commit_ms += st .commit_ms ,sum .draft_calls += st .draft_calls ; 534 } 535report (std::string (p )+ " (served sampling, seeds 1-5)" ,sum ); 536 } 537return 0 ; 538 } 539if (mode == "cache2" ) { 540// the conversation cache where a prompt shares much with what a lane holds (prompts made from long64's tokens, 541// message boundaries where a chat template puts them): 542// A. X and Y share a 9k system prompt (75% of each) and alternate on one lane: X's next turn reuses all of X 543// (Y's read parks X, though it shares more than half) 544// B. a 17k system prompt changed at token 16,000: the prompt reuses 12,288 (the first message's last checkpoint 545// before the change) instead of nothing 546// each cached read against the same prompt read from scratch as cache_test compares them: the first token's top-64 547// (KL(fresh || cached), at most 1.5e-3, the worst measured, and the same top-1), then 16 greedy tokens a row at a 548// time (printed, not judged: they may part at a near-tie); exit 1 when a reuse is not what the cache promises or a 549// first token is off 550constexpr int TURN = 248045 ,SYS = 8678 ,USER = 872 ; 551 std::vector < int > fill ; 552for (int t :toks ) 553if (t != TURN && t != 248044 && t != 248046 )fill .push_back (t ); 554auto span = [& ](size_t a ,size_t n ) { 555if (a + n > fill .size ())throw std::runtime_error ("cache2: long64 too short" ); 556return std::vector < int > (fill .begin ()+ (long )a ,fill .begin ()+ (long ) (a + n )); 557 }; 558auto cat = [](std::vector < int > a ,const std::vector < int >& b ) { 559a .insert (a .end (),b .begin (),b .end ()); 560return a ; 561 }; 562auto msg = [& ](int role ,const std::vector < int >& body ) {return cat ({TURN ,role },body ); }; 563const fnx::Mtp mtp (m ,MTP_RT ,FNX_DIR "/data/draft_vocab_en.bin" ); 564 fnx::Engine e (m ,env_ctx (65536 ),1 ); 565e .mtp_attach (mtp ); 566const std::vector < int > eos {248044 ,248046 }; 567int fails = 0 ; 568struct Res { 569 std::vector < std::pair < float ,int >> top ; 570 std::vector < int > gen ; 571 }; 572// the prompt read, then its last token's window (top-64) and greedy tokens one row a window 573auto first16 = [& ](fnx::Session & s ,const std::vector < int >& p ,int & reused ) { 574 fnx::GenStats st ; 575s .read (p ,st ); 576reused = st .reused ; 577Res r ; 578 std::vector < int > o = e .verify ({p .back ()}); 579r .top = e .top_tokens (1 , {})[0 ]; 580e .commit (1 ); 581r .gen .push_back (o [0 ]); 582while (r .gen .size ()< 16 ) { 583o = e .verify ({r .gen .back ()}); 584e .commit (1 ); 585r .gen .push_back (o [0 ]); 586 } 587return r ; 588 }; 589auto fresh16 = [& ](const std::vector < int >& p ) { 590e .reset (); 591 fnx::Session f (e ,6 ,15 ,eos ,TURN ,0 ,0 ); 592int r = 0 ; 593return first16 (f ,p ,r ); 594 }; 595auto judge = [& ](const char * name ,int reused ,int want ,const Res & got ,const Res & ref ) { 596auto lse = [](const std::vector < std::pair < float ,int >>& t ) { 597double mx = t [0 ].first ,s = 0 ; 598for (const auto & x :t )s += std::exp (x .first - mx ); 599return mx + std::log (s ); 600 }; 601const double la = lse (got .top ),lb = lse (ref .top ); 602double kl = 0 ; 603for (const auto & x :ref .top ) { 604double qa = got .top .back ().first ; 605for (const auto & y :got .top ) 606if (y .second == x .second )qa = y .first ; 607kl += std::exp (x .first - lb )* ((x .first - lb )- (qa - la )); 608 } 609int same = 0 ; 610while (same < 16 && got .gen [(size_t )same ]== ref .gen [(size_t )same ])++ same ; 611const bool top1 = got .top [0 ].second == ref .top [0 ].second ,ok = reused == want && top1 && kl <=1.5e-3 ; 612 std::printf ("cache2 %s: reused %d (want %d), first token KL %.2e, top-1 %s, %d of 16 greedy tokens as from scratch: %s\n" ,name , 613reused ,want ,kl ,top1 ?"the same" :"DIFFERENT" ,same ,ok ?"ok" :"FAIL" ); 614if (!ok )++ fails ; 615 }; 616 {// A 617e .reset (); 618 fnx::Session s (e ,6 ,15 ,eos ,TURN , (size_t )32 <<30 ,0 ); 619const std::vector < int > sys = msg (SYS ,span (0 ,9000 )); 620const std::vector < int > X = cat (sys ,msg (USER ,span (20000 ,3000 ))),Y = cat (sys ,msg (USER ,span (30000 ,3000 ))); 621int r = 0 ; 622first16 (s ,X ,r ); 623const std::vector < int > hx = e .lane_history (0 );// X as the lane holds it: its prompt and the reply kept 624first16 (s ,Y ,r ); 625const std::vector < int > X2 = cat (hx ,msg (USER ,span (40000 ,500 ))); 626int reused = 0 ; 627const Res got = first16 (s ,X2 ,reused ); 628judge ("A (X's next turn after Y on its lane)" ,reused , (int )hx .size (),got ,fresh16 (X2 )); 629 } 630 {// B 631e .reset (); 632 fnx::Session s (e ,6 ,15 ,eos ,TURN , (size_t )32 <<30 ,0 ); 633const std::vector < int > sys1 = msg (SYS ,span (0 ,17000 )); 634 std::vector < int > sys2 = sys1 ; 635sys2 [16000 ]= sys2 [16000 ]== fill [1 ] ?fill [2 ] :fill [1 ]; 636const std::vector < int > P1 = cat (sys1 ,msg (USER ,span (20000 ,2000 ))),P2 = cat (sys2 ,msg (USER ,span (20000 ,2000 ))); 637int r = 0 ; 638first16 (s ,P1 ,r ); 639first16 (s ,msg (USER ,span (30000 ,3000 )),r );// another conversation: P1 parked 640int reused = 0 ; 641const Res got = first16 (s ,P2 ,reused ); 642judge ("B (the system prompt changed at 16,000)" ,reused ,12288 ,got ,fresh16 (P2 )); 643 } 644return fails ?1 :0 ; 645 } 646if (mode == "bdecode" ) { 647// LANES requests decoding together through batched windows with drafts (FNX_BATCH_DRAFTS lookup or 1; the drafts 648// a lane: the plan's, or FNX_BATCH_FIXED), prod's sampling, seeds fixed: lanes take PROMPTS in turn (comma 649// separated ref/ names, default prose2,code1), N tokens each (default 512); each lane's prompt read first, then 650// windows until every lane is done. One warm-up run 651const int nl = argc > 3 ? std::atoi (argv [3 ]) :2 ,n = argc > 4 ? std::atoi (argv [4 ]) :512 ; 652if (nl < 1 || nl > 6 || n < 1 ) { std::fprintf (stderr ,"bdecode [LANES 1..6] [N >= 1] [PROMPTS]\n" );return 2 ; } 653const std::string names = argc > 5 ?argv [5 ] :"prose2,code1" ; 654if (fnx::batch_drafts ()== fnx::BatchDrafts ::off ) { std::fprintf (stderr ,"bdecode: set FNX_BATCH_DRAFTS (lookup or 1)\n" );return 2 ; } 655const fnx::Mtp mtp (m ,MTP_RT ,FNX_DIR "/data/draft_vocab_en.bin" ); 656 fnx::Engine e (m ,env_ctx (262144 ),6 ); 657e .mtp_attach (mtp ); 658const std::vector < int > eos {248044 ,248046 }; 659 std::vector < int > lanes {0 }; 660while ((int )lanes .size ()< nl )lanes .push_back (e .add_lane ()); 661 std::vector < std::vector < int >> prompts ; 662for (size_t a = 0 ,b ;a <=names .size ();a = b + 1 ) { 663b = names .find (',' ,a ); 664if (b == std::string::npos )b = names .size (); 665prompts .push_back (ref_tokens (("ref/" + names .substr (a ,b - a )+ ".bin" ).c_str ())); 666 } 667 fnx::Sampling s ; 668s .temperature = 0.6f ,s .top_p = 0.95f ,s .pen_present = 1.0f ; 669 fnx::BatchDecoder dec (e ,6 ,15 ,eos , fnx::batch_drafts ()); 670const int seed0 = (int ) fnx::env_int ("FNX_BDECODE_SEED" ,1000 );// lane r's sampling seed: seed0 + r 671for (int run = 0 ;run < 2 ;++ run ) { 672 std::vector < fnx::BatchLane > bl ((size_t )nl ); 673for (int r = 0 ;r < nl ;++ r ) { 674e .use_lane (lanes [(size_t )r ]); 675e .reset (); 676 fnx::Session sess (e ,6 ,15 ,eos ,248045 ,0 ,lanes [(size_t )r ]); 677 fnx::GenStats st ; 678const std::vector < int >& p = prompts [(size_t )r %prompts .size ()]; 679sess .read (p ,st ); 680bl [(size_t )r ].start (lanes [(size_t )r ],s , std::mt19937_64 (seed0 + r ),p ); 681 } 682 std::vector < int > got ((size_t )nl ,0 ); 683 std::vector < bool > ended ((size_t )nl , false); 684int windows = 0 ,rows = 0 ,full = 0 ,full_rows = 0 ; 685long lane_windows = 0 ,full_tokens = 0 ;// the windows each lane was in, summed; the tokens of windows with every lane 686double ms = 0 ,verify_ms = 0 ,full_ms = 0 ,full_verify = 0 ,full_draft = 0 ,full_capture = 0 ; 687long full_calls = 0 ,full_captures = 0 ; 688for (;;) { 689 std::vector < fnx::BatchLane *> ls ; 690 std::vector < int > idx ,limit ; 691for (int r = 0 ;r < nl ;++ r ) 692if (!ended [(size_t )r ]&& got [(size_t )r ]< n ) { 693ls .push_back (& bl [(size_t )r ]); 694idx .push_back (r ); 695limit .push_back (n - got [(size_t )r ]); 696 } 697if (ls .empty ())break ; 698 fnx::BatchDecoder ::fit (ls ); 699long emitted = 0 ; 700const auto out = dec .window (ls ,limit , [& ](int i ,int ) {++ got [(size_t )idx [(size_t )i ]],++ emitted ; }); 701ms += dec .last_ms ; 702verify_ms += dec .last_verify_ms ; 703++ windows ; 704rows += dec .last_rows ; 705lane_windows += (long )ls .size (); 706if ((int )ls .size ()== nl ) { 707++ full ,full_rows += dec .last_rows ,full_tokens += emitted ,full_ms += dec .last_ms ; 708full_verify += dec .last_verify_ms ,full_draft += dec .last_draft_ms ,full_calls += dec .last_calls ; 709if (e .last_capture_ms > 0 )++ full_captures ,full_capture += e .last_capture_ms ; 710 } 711for (size_t i = 0 ;i < out .size ();++ i ) 712if (out [i ].eos )ended [(size_t )idx [i ]]= true; 713 } 714if (run == 0 )continue ; 715long tokens = 0 ,offered = 0 ,accepted = 0 ; 716for (int r = 0 ;r < nl ;++ r )tokens += got [(size_t )r ],offered += bl [(size_t )r ].offered ,accepted += bl [(size_t )r ].accepted ; 717 std::printf ("bdecode %d lanes: every lane in: %.1f tok/s, %.2f rows and %.2f ms a window (%d windows); overall %ld tokens, " 718"%.1f tok/s, %d windows, %.2f ms a window (verify %.2f), %.2f tokens a lane a window, drafts %ld of %ld\n" , 719nl ,full ?full_tokens * 1000.0 /full_ms :0.0 ,full ? (double )full_rows /full :0.0 ,full ?full_ms /full :0.0 , 720full ,tokens ,tokens * 1000.0 /ms ,windows ,ms /windows ,verify_ms /windows , (double )tokens /lane_windows , 721accepted ,offered ); 722if (full ) 723 std::printf ("bdecode %d lanes: every lane in, a window: verify %.2f ms, drafting %.2f ms (%.2f draft-layer calls), the " 724"rest %.2f ms; graph captures in %ld of %d windows, %.2f ms each\n" , 725nl ,full_verify /full ,full_draft /full , (double )full_calls /full , (full_ms - full_verify - full_draft ) /full , 726full_captures ,full ,full_captures ?full_capture /full_captures :0.0 ); 727 } 728return 0 ; 729 } 730if (mode == "compare" ) {// two .lgr files (ref/lgrcmp.py's measures), the first as the reference 731if (argc < 5 ) { std::fprintf (stderr ,"compare REF.lgr OTHER.lgr\n" );return 2 ; } 732Lgr a ,b ; 733if (!load_lgr (argv [3 ],a )|| !load_lgr (argv [4 ],b )) { std::fprintf (stderr ,"compare: cannot open both files\n" );return 1 ; } 734 std::printf ("%s vs %s: %s\n" ,argv [3 ],argv [4 ],lgr_compare (a ,b ).str ().c_str ()); 735return 0 ; 736 } 737if (mode == "batch" ) { 738// tools/batch_check.sh's lanes: two long prompts (past 2,048 positions, so the QSA selection runs) and a short one 739const int gen = argc > 3 ? std::atoi (argv [3 ]) :64 ; 740if (gen < 1 ) { std::fprintf (stderr ,"batch [GEN]: GEN >= 1\n" );return 2 ; } 741const fnx::Mtp mtp (m ,MTP_RT ,"data/draft_vocab_en.bin" ); 742 fnx::Engine e (m ,env_ctx (100000 )); 743return batch_check (m ,e ,mtp ,gen , 744 {ref_tokens ("ref/long2.bin" ),ref_tokens ("ref/code1.bin" ),ref_tokens ("ref/long2.bin" )}); 745 } 746// exact: the model's llama.cpp reference (FNX_EXACT_REF for long64, else by the model's name: Q4's from llama.cpp 747// CUDA, Q8_0's from its CPU backend (tools/q8_exact.sh; code1 and edit1 only), any other model's 748// ref/lgr/llama_cuda_<model>_<prompt>.lgr, which has no bar), held to the bar above, and its own base 749 std::string stem = argv [1 ]; 750stem = stem .substr (stem .rfind ('/' )+ 1 ); 751if (const size_t s = stem .find ("-00001-of-" );s != std::string::npos )stem = stem .substr (0 ,s ); 752else if (stem .size ()> 5 && stem .compare (stem .size ()- 5 ,5 ,".gguf" )== 0 )stem .resize (stem .size ()- 5 ); 753// the prompts: long64 (62,794 tokens: long-context drift, where any summation reorder moves KL by ~2e-3), the 754// README's code1 and edit1 (61 and 686 tokens: little room for chaos, so a real error shows plainly) and its 755// picture (ref/img/sphinx: the logo, the encoder's rows from sphinx.sve; llama.cpp's reference made on Q4 756// only). code1 and edit1 also run in windows of 1, 2, 3, 11 and 16 rows, which must give the 5-row windows' logits 757// byte for byte: decode verifies windows of 1..MAXT rows, so a kernel whose sums depend on the row count (or one 758// that takes another path for small windows, as FNX_HC1) would move served output while every 5-row check passed. 759#if FNX_27B // the 27B's references are its own, named by the model (Flash-Next's Q4 and Q8 files are not its) 760const bool q4 = false,q8 = false; 761const std::string pic_stem = "ref/img/sphinx_" + stem ; 762#else 763const bool q4 = stem .find ("UD-Q4_K_XL" )!= std::string::npos ,q8 = stem .find ("Q8_0" )!= std::string::npos ; 764#endif 765const std::string name = argc > 3 ?argv [3 ] :"try" ,dir = lab_dir (); 766const bool base_run = name == "base" ; 767// a base is written only from a run within the bar: its files go to MODEL-base-new*.lgr first and replace the 768// base (with its identity record) only when every prompt passed 769const std::string id_path = dir + "/" + stem + "-base.id" ,out_name = base_run ?"base-new" :name ; 770const std::string me = run_identity (argv [1 ]); 771 std::string base_id ; 772 { 773 std::ifstream f (id_path ); 774base_id .assign (std::istreambuf_iterator < char > (f ), {}); 775 } 776// a base made by another build (card count, ring) is neither compared with nor written over: its logits differ in 777// their last bits by design, and a base written over would be lost to the build that owns it. A record from before 778// build lines is three cards', its ring as its env set it 779if (!base_id .empty ()) { 780 std::string theirs = id_line (base_id ,"build" ); 781if (theirs .empty ())theirs = build_line (3 ,id_line (base_id ,"env" ).find (" FNX_RING_F32=1" )!= std::string::npos ); 782if (theirs != id_line (me ,"build" )) { 783const char * rs = std::getenv ("FNX_ROPE_SCALE" ); 784 std::printf ("exact: the base in %s is another build's (%s; this one: %s): give this build a lab directory of its own, " 785"FNX_LAB_DIR=/tmp/fnx-lab-%u-%dcard%s%s\n" , 786dir .c_str (),theirs .c_str (),id_line (me ,"build" ).c_str (), (unsigned )getuid (), fnx::NCARD ,rs ?"-yarn" :"" , 787rs ?rs :"" ); 788return 1 ; 789 } 790 } 791if (!base_run ) { 792if (base_id .empty ()) 793 std::printf ("exact: no base identity %s (a base from before identity records, or none): make one with `exact base`\n" , 794id_path .c_str ()); 795else if (id_line (base_id ,"model" )!= id_line (me ,"model" )) 796 std::printf ("exact: the base was made from another model file:\n base: %s\n now: %s\n make a new one with `exact base`\n" , 797id_line (base_id ,"model" ).c_str (),id_line (me ,"model" ).c_str ()); 798else { 799 std::printf ("exact: base from %s\n %s\n" ,id_line (base_id ,"tree" ).c_str (),id_line (base_id ,"code" ).c_str ()); 800if (id_line (base_id ,"env" )!= id_line (me ,"env" )) 801 std::printf (" (other settings: base %s; now %s)\n" ,id_line (base_id ,"env" ).c_str (),id_line (me ,"env" ).c_str ()); 802 } 803 } 804const bool base_usable = !base_id .empty ()&& id_line (base_id ,"model" )== id_line (me ,"model" ); 805int rc = 0 ; 806 std::vector < std::pair < std::string , std::string >> made ;// a base run's files: candidate, base 807 std::string verdicts ; 808auto fail = [& ](const std::string & what ) { 809 std::printf (" FAIL: %s\n" ,what .c_str ()); 810rc = 1 ; 811 }; 812for (const char * p : {"long64" ,"code1" ,"edit1" ,"picture" }) { 813const bool pic = std::string (p )== "picture" ,long64 = std::string (p )== "long64" ; 814#if !FNX_27B // the 27B has its own picture reference 815if (pic && !q4 ) { 816 std::printf ("exact %s picture: not run (llama.cpp's picture reference is Q4's only)\n" ,name .c_str ()); 817continue ; 818 } 819#endif 820if (long64 && q8 && !std::getenv ("FNX_EXACT_REF" )) { 821 std::printf ("exact %s long64: not run (no llama.cpp reference on Q8_0 at 62k; FNX_EXACT_REF=FILE.lgr gives one)\n" , 822name .c_str ()); 823continue ; 824 } 825#if FNX_27B 826const std::string prompt = pic ?pic_stem + ".bin" : std::string ("ref/" )+ p + ".bin" , 827#else 828const std::string prompt = pic ?"ref/img/sphinx.bin" : std::string ("ref/" )+ p + ".bin" , 829#endif 830tag = long64 ?"" : std::string ("-" )+ p ; 831// a scaled build is held to llama.cpp run with the same scaling (ref/fnx_logref and ref/img_logref read the same 832// settings), else the comparison measures the rope change itself; the file names the scale, the trained length 833// it scales from when set, and the model unless it is Q4's 834const double scale = fnx::rope_scale (); 835 std::string scaled_env ,yarn_tag ; 836if (scale ) { 837char s [64 ]; 838 std::snprintf (s ,sizeof s ,"%.9g" ,scale ); 839scaled_env = std::string ("FNX_ROPE_SCALE=" )+ s + " " ; 840yarn_tag = std::string ("llama_yarn_" )+ s ; 841if (const char * oc = std::getenv ("FNX_YARN_ORIG_CTX" )) { 842scaled_env += std::string ("FNX_YARN_ORIG_CTX=" )+ oc + " " ; 843yarn_tag += std::string ("_orig" )+ oc ; 844 } 845if (!q4 )yarn_tag += "_" + stem ; 846 } 847 std::string llama_s = long64 && std::getenv ("FNX_EXACT_REF" ) ? std::getenv ("FNX_EXACT_REF" ) 848 :scale ?"ref/lgr/" + yarn_tag + "_" + p + ".lgr" 849#if FNX_27B 850 :pic ?pic_stem + ".lgr" 851#else 852 :pic ?"ref/img/sphinx.lgr" 853#endif 854 :q4 ?"ref/lgr/llama_cuda_" + std::string (p )+ ".lgr" 855 :q8 ?"ref/lgr/llama_cpu_q8w_" + std::string (p )+ ".lgr" 856 :"ref/lgr/llama_cuda_" + stem + "_" + p + ".lgr" ; 857if (std::FILE * f = std::fopen (llama_s .c_str (),"rb" )) std::fclose (f ); 858else { 859if (pic ) 860 std::fprintf (stderr ,"exact: no llama.cpp reference %s for %s; make it with\n %sref/img_logref %s MMPROJ.gguf " 861"ref/img/sphinx.png 'What does this picture show? Answer in two sentences.' 200 %s\n" , 862llama_s .c_str (),stem .c_str (),scaled_env .c_str (),argv [1 ], 863#if FNX_27B 864scale ?llama_s .substr (0 ,llama_s .size ()- 4 ).c_str () :pic_stem .c_str ()); 865#else 866scale ?llama_s .substr (0 ,llama_s .size ()- 4 ).c_str () :"ref/img/sphinx" ); 867#endif 868else 869 std::fprintf (stderr ,"exact: no llama.cpp reference %s for %s; make it with\n %sref/fnx_logref %s %s %d %s\n" , 870llama_s .c_str (),stem .c_str (),scaled_env .c_str (),argv [1 ],prompt .c_str (),long64 ?200 :300 , 871llama_s .c_str ()); 872 std::printf ("exact %s %s: FAIL: no llama.cpp reference %s\n" ,name .c_str (),p ,llama_s .c_str ()); 873rc = 1 ; 874continue ; 875 } 876const int n_prompt = (int )ref_tokens (prompt .c_str ()).size (); 877// the logits of the prompt and the reference's steps in windows of T rows, on a fresh engine 878auto logits = [& ](int T ,const std::string & out ) { 879 fnx::Engine e (m ,env_ctx (n_prompt + 1024 ),1 ); 880#if FNX_27B 881if (pic )setenv ("FNX_IMAGES" , (pic_stem + ".sve" ).c_str (),1 ); 882#else 883if (pic )setenv ("FNX_IMAGES" ,"ref/img/sphinx.sve" ,1 ); 884#endif 885const int r = run_logits (m ,e ,prompt .c_str (),llama_s .c_str (),T ,out .c_str (), true); 886if (pic )unsetenv ("FNX_IMAGES" ); 887return r ; 888 }; 889const std::string out = dir + "/" + stem + "-" + out_name + tag + ".lgr" ,base = dir + "/" + stem + "-base" + tag + ".lgr" ; 890 { 891const auto t0 = std::chrono::steady_clock::now (); 892if (const int r = logits (5 ,out ))return r ; 893 std::printf ("exact %s %s: logits in %.0f s to %s\n" ,name .c_str (),p , 894 std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (),out .c_str ()); 895 } 896Lgr ref ,mine ; 897load_lgr (llama_s ,ref ); 898load_lgr (out ,mine ); 899const LgrCmp vs_llama = lgr_compare (ref ,mine ); 900 std::printf (" vs llama.cpp %s: %s\n" ,q8 ?"CPU" :"CUDA" ,vs_llama .str ().c_str ()); 901if (!std::isfinite (vs_llama .kl_mean ))fail ("KL is not a number: one side's logits are broken" ); 902#if !FNX_27B 903else if (!q4 && !q8 )fail ("no documented bar for " + stem + ": the numbers above are not judged" ); 904#endif 905else if (scale ) { 906// YaRN moves the model's own outputs (docs/verification.md, "Rope scaling"), and llama.cpp's backends part 907// differently under it, so the bar is not held here: only a port that is plainly broken fails, at 10x the 908// bar's KL or 5 points of top-1 under it. The byte-for-byte base comparison below still judges 909 std::printf (" scaled: measured against a scaled llama.cpp, not held to the bar\n" ); 910for (const Bar & b :BARS ) 911if (p == std::string (b .prompt )&& (vs_llama .kl_mean > 10 * b .kl_mean || vs_llama .top1_pct ()< b .top1_pct - 5 )) 912fail ("far outside the bar for a scaled build (10x its KL or 5 points of top-1): a broken port, not YaRN's shift" ); 913 }else if (const std::string why = breach (p ,vs_llama ); !why .empty ())fail ("outside the exactness bar: " + why ); 914verdicts += std::string ("llama.cpp " )+ p + " " + vs_llama .str ()+ "\n" ; 915if (std::string (p )== "code1" || std::string (p )== "edit1" ) 916for (int T : {1 ,2 ,3 ,11 ,16 }) { 917const std::string rows_out = dir + "/" + stem + "-" + out_name + tag + "-rows" + std::to_string (T )+ ".lgr" ; 918if (const int r = logits (T ,rows_out ))return r ; 919if (same_bytes (out ,rows_out )) std::printf (" windows of %d: the 5-row windows' logits byte for byte\n" ,T ); 920else { 921Lgr rows ; 922load_lgr (rows_out ,rows ); 923fail ("windows of " + std::to_string (T )+ " give other logits than windows of 5: " + lgr_compare (mine ,rows ).str ()); 924 } 925 } 926if (base_run ) { 927made .emplace_back (out ,base ); 928continue ; 929 } 930Lgr b ; 931if (!base_usable )fail ("no base to compare with (see above)" ); 932else if (!load_lgr (base ,b ))fail ("no " + base + " (exact base writes it)" ); 933else if (same_bytes (base ,out )) std::printf (" vs base: byte for byte identical\n" ); 934else fail ("vs base: DIFFERENT: " + lgr_compare (b ,mine ).str ()); 935 } 936if (base_run ) { 937if (rc != 0 || made .empty ()) { 938 std::printf ("exact base: NOT written (%s); the base stays as it was, this run's files are %s/%s-base-new*.lgr\n" , 939made .empty () ?"nothing ran" :"a check failed" ,dir .c_str (),stem .c_str ()); 940return 1 ; 941 } 942// the old identity goes first: a base half replaced has no identity, and runs refuse to compare with it 943if (std::remove (id_path .c_str ())!= 0 && errno != ENOENT )throw std::runtime_error ("exact base: cannot remove " + id_path ); 944for (const auto & [cand ,base ] :made ) 945if (std::rename (cand .c_str (),base .c_str ())!= 0 )throw std::runtime_error ("exact base: cannot move " + cand + " to " + base ); 946const std::string tmp = id_path + ".new" ; 947 std::FILE * f = std::fopen (tmp .c_str (),"w" ); 948if (!f )throw std::runtime_error ("exact base: cannot write " + tmp ); 949const std::string rec = me + verdicts ; 950const bool ok = std::fwrite (rec .data (),1 ,rec .size (),f )== rec .size (); 951if (std::fclose (f )!= 0 || !ok || std::rename (tmp .c_str (),id_path .c_str ())!= 0 ) 952throw std::runtime_error ("exact base: cannot write " + id_path ); 953 std::printf ("exact base: written for %zu prompt(s), identity in %s:\n%s" ,made .size (),id_path .c_str (),me .c_str ()); 954 } 955return rc ; 956} 957 958// one command on a loaded model, its arguments as fnx_run takes them (argv[1] the model's path, argv[2] the mode); 959// bin/fnx_lab calls it from libfnx_lab.so for each command, around a model it keeps loaded 960static bool lab_mode (const std:: string & mode ) { 961return mode == "exact" || mode == "read" || mode == "batch" || mode == "compare" || mode == "decode" || mode == "bdecode" || 962mode == "cache2" ; 963} 964// a known mode with at least its first argument (each mode checks the rest); else the usage on stderr 965static bool args_ok ( int argc , char ** argv ) { 966const std:: string mode = argc >= 3 ? argv [ 2 ] : "" ; 967const bool plain = mode == "check" || mode == "gen" || mode == "rows" || mode == "bench" || mode == "bench_step" || mode == "mtp" || 968mode == "spec" || mode == "logits" ; 969if ( lab_mode ( mode ) || ( plain && argc >= 4 )) return true; 970std:: fputs ( "usage: fnx_run MODEL.gguf MODE ARGS...\n" 971" check REF.bin OUT.bin [W] | gen REF.bin N | rows REF.bin T N | bench REF.bin T N | bench_step REF.bin L N C [step]\n" 972" mtp RT_DIR REF.bin N K [VOCAB [LK]] | spec REF.bin GEN.txt K [BAD%] | logits PROMPT.bin CONT.lgr T OUT.lgr\n" 973" exact [NAME] | read N [N...] | decode [N] [K] [LK] [SAMPLES] | bdecode [LANES] [N] [PROMPTS] | cache2 | batch [GEN] | compare REF.lgr OTHER.lgr\n" , 974stderr ); 975return false; 976} 977 978extern "C" int fnx_run_cmd (fnx:: Model * model , int argc , char ** argv ) { 979if (! model || ! args_ok ( argc , argv )) return 2 ; 980const std:: string mode = argv [ 2 ]; 981if ( lab_mode ( mode )) return lab_check ( * model , argc , argv ); 982fnx:: Model & m = * model ; 983 984// FNX_MAX_CTX: the context the engine allocates for (default 4096); FNX_LANES: lanes the K/V pool has room for 985std:: optional < fnx:: Mtp > mtp_mode ; // mode mtp's draft layer, made before the engine 986if ( mode == "mtp" && argc >= 7 ) mtp_mode . emplace ( m , argv [ 3 ], argc > 7 ? argv [ 7 ] : "" ); 987fnx:: Engine e ( m , ( int ) fnx:: env_int ( "FNX_MAX_CTX" , 4096 ), 988( int ) fnx:: env_int ( "FNX_LANES" , 1 )); 989if ( mode == "logits" ) { 990if ( argc < 7 ) { std:: fprintf ( stderr , "logits needs PROMPT.bin CONT.lgr T OUT.lgr\n" ); return 2 ; } 991return run_logits ( m , e , argv [ 3 ], argv [ 4 ], std:: atoi ( argv [ 5 ]), argv [ 6 ], 992fnx:: env_flag ( "FNX_PREFILL" )); 993} 994if ( mode == "mtp" ) { 995if ( argc < 7 ) { std:: fprintf ( stderr , "mtp needs RT_DIR REF.bin N K\n" ); return 2 ; } 996const fnx:: Mtp & mtp = * mtp_mode ; 997e . mtp_attach ( mtp ); 998const std:: vector < int > prompt = ref_tokens ( argv [ 4 ]); 999const int n_gen = std:: atoi ( argv [ 5 ]), K = std:: atoi ( argv [ 6 ]); 1000if ( K < 1 || K + 1 > fnx:: MAXT ) { std:: fprintf ( stderr , "K: 1..%d\n" , fnx:: MAXT - 1 ); return 2 ; } 1001const int LK = argc > 8 ? std:: atoi ( argv [ 8 ]) : 0 , LNG = 3 ; // lookup drafts (0: off), n-gram length 1002if ( LK < 0 || LK + 1 > fnx:: MAXT ) { std:: fprintf ( stderr , "LOOKUP_K: 0..%d\n" , fnx:: MAXT - 1 ); return 2 ; } 1003// the prompt: all but its last token through the prompt path (the draft layer reading each row with the token 1004// after it), then the last token through a window, the draft layer reading its row with the first generated. 1005// FNX_PREFILL=0: the whole prompt in windows, each followed by the draft layer over its rows 1006std:: vector < int > out ; 1007int p = 0 , T = 0 , d = -1 ; 1008const bool batched = fnx:: env_int ( "FNX_PREFILL" , 1 ) != 0 ; 1009const auto t_read = std::chrono::steady_clock:: now (); 1010if ( batched && prompt . size () > 1 ) { 1011e . prefill (std:: vector < int > ( prompt . begin (), prompt . end () - 1 ), prompt . back ()); 1012p = e . pos (); 1013T = 1 ; 1014out = e . window ({ prompt . back ()}); 1015d = e . draft ( 1 , true, 0 , { out . back ()}, p ); 1016} else 1017for ( size_t i = 0 ; i < prompt . size (); i += fnx:: MAXT ) { 1018std:: vector < int > w ( prompt . begin () + i , prompt . begin () + std:: min ( prompt . size (), i + fnx:: MAXT )); 1019p = e . pos (); 1020T = ( int ) w . size (); 1021out = e . window ( w ); 1022std:: vector < int > next ( w . begin () + 1 , w . end ()); 1023next . push_back ( i + T < prompt . size () ? prompt [ i + T ] : out . back ()); 1024d = e . draft ( T , true, 0 , next , p ); 1025} 1026{ 1027const double s = std::chrono:: duration < double > (std::chrono::steady_clock:: now () - t_read ). count (); 1028std:: fprintf ( stderr , "prompt: %zu tokens in %.2f s (%.0f tok/s, %s)\n" , prompt . size (), s , prompt . size () / s , 1029batched ? "prompt path" : "windows" ); 1030} 1031// the chain from the last row: K drafts in all 1032double dwall = 0 , dgpu = 0 ; 1033long dcalls = 0 ; 1034auto chain = [ & ]( int d1 , int src_row , int cell0 ) { 1035std:: vector < int > drafts { d1 }; 1036for ( int j = 1 ; j < K ; ++ j ) { 1037drafts . push_back ( e . draft ( 1 , false, j == 1 ? src_row : 0 , { drafts . back ()}, cell0 + j )); 1038dwall += e . last_draft_ms ; 1039dgpu += e . last_draft_gpu_ms ; 1040++ dcalls ; 1041} 1042return drafts ; 1043}; 1044std:: vector < int > got { out . back ()}; 1045// the LK tokens after the latest earlier place of the last LNG tokens of prompt + got, if its first is d1 1046auto lookup = [ & ]( int d1 ) { 1047std:: vector < int > ctx ( prompt ); 1048ctx . insert ( ctx . end (), got . begin (), got . end ()); 1049std:: vector < int > r ; 1050if ( LK == 0 || ( int ) ctx . size () <= LNG ) return r ; 1051const size_t n0 = ctx . size () - LNG ; 1052for ( size_t st = n0 ; st -- > 0 ;) 1053if (std:: equal ( ctx . begin () + st , ctx . begin () + st + LNG , ctx . begin () + n0 )) { 1054if ( st + LNG < ctx . size () && ctx [ st + LNG ] == d1 ) 1055r . assign ( ctx . begin () + st + LNG , ctx . begin () + std:: min ( ctx . size (), st + LNG + LK )); 1056break; 1057} 1058return r ; 1059}; 1060int lookups = 0 ; 1061std:: vector < double > round_ms ; 1062std:: vector < int > round_tok ; 1063std:: vector < int > drafts = lookup ( d ); 1064if ( drafts . empty ()) drafts = chain ( d , T - 1 , p + T - 1 ); 1065int rounds = 0 ; 1066long accepted = 0 ; 1067std:: vector < long > tried ( K , 0 ), hit ( K , 0 ); // draft j: rounds that reached it, rounds that accepted it 1068double verify_ms = 0 , verify_gpu = 0 , draft_ms = 0 , head_ms = 0 ; 1069std:: vector < int > rows_hist (fnx:: MAXT + 1 , 0 ); // verify windows by their rows 1070const auto t0 = std::chrono::steady_clock:: now (); 1071while (( int ) got . size () <= n_gen ) { 1072std:: vector < int > rows { got . back ()}; 1073rows . insert ( rows . end (), drafts . begin (), drafts . end ()); 1074p = e . pos (); 1075const auto r0 = std::chrono::steady_clock:: now (); 1076const std:: vector < int > o = e . verify ( rows ); 1077int n = 1 ; 1078while ( n < ( int ) rows . size () && rows [ n ] == o [ n - 1 ]) ++ n ; 1079e . commit ( n ); 1080verify_ms += e . last_ms ; 1081verify_gpu += e . last_gpu_ms ; 1082++ rows_hist [ rows . size ()]; 1083++ rounds ; 1084accepted += n - 1 ; 1085if (( int ) rows . size () - 1 == K ) 1086for ( int j = 0 ; j < K && j < n ; ++ j ) { 1087++ tried [ j ]; 1088if ( j < n - 1 ) ++ hit [ j ]; 1089} 1090got . insert ( got . end (), o . begin (), o . begin () + n ); 1091const auto d0 = std::chrono::steady_clock:: now (); 1092const int d1 = e . draft ( n , true, 0 , std:: vector < int > ( o . begin (), o . begin () + n ), p ); 1093head_ms += e . last_draft_ms ; 1094drafts = lookup ( d1 ); 1095if (! drafts . empty ()) ++ lookups ; 1096else drafts = chain ( d1 , n - 1 , p + n - 1 ); 1097const auto d2 = std::chrono::steady_clock:: now (); 1098draft_ms += std::chrono:: duration < double , std:: milli > ( d2 - d0 ). count (); 1099round_ms . push_back (std::chrono:: duration < double , std:: milli > ( d2 - r0 ). count ()); 1100round_tok . push_back ( n ); 1101} 1102const double ms = std::chrono:: duration < double , std:: milli > (std::chrono::steady_clock:: now () - t0 ). count (); 1103std:: printf ( "generated:" ); 1104for ( int t : got ) std:: printf ( " %d" , t ); 1105std:: printf ( "\nmtp K=%d: %d rounds, %zu tokens, %.2f per round (drafts accepted %.1f%%), verify %.2f ms + drafts %.2f ms per round, " 1106"%.1f tok/s\n" , K , rounds , got . size () - 1 , ( got . size () - 1.0 ) / rounds , 100.0 * accepted / (( double ) rounds * K ), 1107verify_ms / rounds , draft_ms / rounds , ( got . size () - 1.0 ) * 1000.0 / ms ); 1108std:: printf ( "draft step (one row): %.3f ms wall, %.3f ms GPU\n" , dwall / ( dcalls ? dcalls : 1 ), dgpu / ( dcalls ? dcalls : 1 )); 1109// a round: the verify window, then the draft layer over its accepted rows (the first draft), then the chain's 1110// further drafts (or a lookup); the rest is the host between them 1111std:: printf ( "per round: verify %.2f ms wall (%.2f GPU), first draft %.2f ms, chain %.2f ms (%.2f steps), host %.2f ms; " 1112"verify windows by rows:" , verify_ms / rounds , verify_gpu / rounds , head_ms / rounds , dwall / rounds , 1113( double ) dcalls / rounds , ( ms - verify_ms - draft_ms ) / rounds ); 1114for ( int t = 1 ; t <= fnx:: MAXT ; ++ t ) 1115if ( rows_hist [( size_t ) t ]) std:: printf ( " %d:%d" , t , rows_hist [( size_t ) t ]); 1116std:: printf ( "\n" ); 1117{ // the best stretch of at least 64 tokens: consecutive rounds, tokens over their wall time 1118double best = 0 ; 1119for ( size_t a = 0 ; a < round_ms . size (); ++ a ) { 1120double ms_ = 0 ; 1121int tk = 0 ; 1122for ( size_t b = a ; b < round_ms . size (); ++ b ) { 1123ms_ += round_ms [ b ]; 1124tk += round_tok [ b ]; 1125if ( tk >= 64 ) { 1126best = std:: max ( best , tk * 1000.0 / ms_ ); 1127break; 1128} 1129} 1130} 1131std:: printf ( "lookup drafts in %d of %d rounds; best 64-token stretch %.1f tok/s\n" , lookups , rounds , best ); 1132} 1133std:: printf ( "per step (given the steps before were accepted):" ); 1134for ( int j = 0 ; j < K ; ++ j ) std:: printf ( " %.2f" , tried [ j ] ? ( double ) hit [ j ] / tried [ j ] : 0.0 ); 1135std:: printf ( "\n" ); 1136if (const std:: vector < unsigned long long > pc = e . probe_counts (); ! pc . empty () && pc [ 3 ] > 0 ) { 1137std:: printf ( "prefetch probe: %llu layer-windows, distinct experts a layer-window: picked %.2f, guessed %.2f, both %.2f " 1138"(%.1f%% of the picked guessed)\n" , 1139pc [ 3 ], ( double ) pc [ 0 ] / pc [ 3 ], ( double ) pc [ 1 ] / pc [ 3 ], ( double ) pc [ 2 ] / pc [ 3 ], 100.0 * pc [ 2 ] / pc [ 0 ]); 1140if ( pc [ 4 ] > 0 ) 1141std:: printf ( "prefetch probe, experts in RAM: picked and not in a slot %.2f a layer-window, %.1f%% of them guessed; " 1142"guessed, not picked, not in a slot (wasted copies) %.2f\n" , 1143( double ) pc [ 4 ] / pc [ 3 ], 100.0 * pc [ 5 ] / pc [ 4 ], ( double ) pc [ 6 ] / pc [ 3 ]); 1144} 1145// FNX_ROUTE_COUNT=1 with FNX_ROUTE_FILE=path: the run's expert tallies (sfnx's format) 1146if (const char * rf = std:: getenv ( "FNX_ROUTE_FILE" )) { 1147const std:: vector < unsigned > v = e . route_counts (); 1148std:: FILE * f = std:: fopen ( rf , "wb" ); 1149if ( v . empty () || ! f || std:: fwrite ( v . data (), 4 , v . size (), f ) != v . size () || std:: fclose ( f ) != 0 ) { 1150std:: fprintf ( stderr , "FNX_ROUTE_FILE %s: no tallies (FNX_ROUTE_COUNT=1?) or not written\n" , rf ); 1151return 1 ; 1152} 1153} 1154// FNX_ROUTE_TRACE=M with FNX_ROUTE_TRACE_FILE=path: decode's picks in order 1155if (const char * tf = std:: getenv ( "FNX_ROUTE_TRACE_FILE" )) { 1156const std:: vector < unsigned > v = e . route_trace (); 1157std:: FILE * f = std:: fopen ( tf , "wb" ); 1158if ( v . empty () || ! f || std:: fwrite ( v . data (), 4 , v . size (), f ) != v . size () || std:: fclose ( f ) != 0 ) { 1159std:: fprintf ( stderr , "FNX_ROUTE_TRACE_FILE %s: no trace (FNX_ROUTE_TRACE=M?) or not written\n" , tf ); 1160return 1 ; 1161} 1162} 1163std:: printf ( "rounds %d\n" , rounds ); 1164return 0 ; 1165} 1166const std:: vector < int > toks = ref_tokens ( argv [ 3 ]); 1167if ( mode == "check" ) { 1168if ( argc < 5 ) { std:: fprintf ( stderr , "check needs REF.bin OUT.bin [W]\n" ); return 2 ; } 1169long long w_in = 5 ; 1170if ( argc > 5 && (!fnx:: parse_whole ( argv [ 5 ], w_in ) || w_in < 1 || w_in > fnx:: MAXT )) 1171throw std:: runtime_error ( "check: window: want a whole number of rows 1.." + std:: to_string (fnx:: MAXT ) + ", got '" + std:: string ( argv [ 5 ]) + "'" ); 1172const int W = ( int ) w_in ; 1173std:: FILE * out = std:: fopen ( argv [ 4 ], "wb" ); 1174if (! out ) { std:: perror ( argv [ 4 ]); return 1 ; } 1175const std:: string out_path = argv [ 4 ]; 1176e . dump = [ & ](const std:: string & name , int layer , int T , int n , const std:: vector < float >& v ) { 1177const std:: string full = layer >= 0 ? name + "-" + std:: to_string ( layer ) : name ; 1178const uint32_t nl = ( uint32_t ) full . size (), nd = 2 ; 1179const int64_t ne [ 2 ] = { n , T }; 1180std:: fwrite ( & nl , 4 , 1 , out ); 1181std:: fwrite ( full . data (), 1 , nl , out ); 1182std:: fwrite ( & nd , 4 , 1 , out ); 1183std:: fwrite ( ne , 8 , 2 , out ); 1184std:: fwrite ( v . data (), 4 , v . size (), out ); 1185if (std:: ferror ( out )) throw std:: runtime_error ( "check: " + out_path + " write failed" ); 1186}; 1187std:: vector < int > next ; 1188for ( size_t i = 0 ; i < toks . size (); i += W ) { 1189std:: vector < int > w ( toks . begin () + i , toks . begin () + std:: min ( toks . size (), i + W )); 1190const std:: vector < int > o = e . window ( w ); 1191next . insert ( next . end (), o . begin (), o . end ()); 1192std:: printf ( "window at %zu: %zu rows in %.1f ms\n" , i , w . size (), e . last_ms ); 1193} 1194if (std:: fclose ( out ) != 0 ) throw std:: runtime_error ( "check: " + out_path + ": close failed (a buffered write did not reach the disk)" ); 1195std:: printf ( "greedy next token per row:" ); 1196for ( int t : next ) std:: printf ( " %d" , t ); 1197std:: printf ( "\n" ); 1198} else if ( mode == "spec" ) { 1199if ( argc < 6 ) { std:: fprintf ( stderr , "spec needs GEN.txt K\n" ); return 2 ; } 1200std:: vector < int > ref ; 1201{ 1202std:: ifstream f ( argv [ 4 ]); 1203std:: string word ; 1204if (!( f >> word ) || word != "generated:" ) { std:: fprintf ( stderr , "%s: not gen's output\n" , argv [ 4 ]); return 2 ; } 1205for ( int t ; f >> t ;) ref . push_back ( t ); 1206} 1207const int K = std:: atoi ( argv [ 5 ]); 1208const double bad = argc > 6 ? std:: atof ( argv [ 6 ]) / 100.0 : 0.0 ; 1209if ( K < 0 || K + 1 > fnx:: MAXT ) { std:: fprintf ( stderr , "K: 0..%d\n" , fnx:: MAXT - 1 ); return 2 ; } 1210std:: vector < int > o ; 1211for ( size_t i = 0 ; i < toks . size (); i += fnx:: MAXT ) { 1212std:: vector < int > w ( toks . begin () + i , toks . begin () + std:: min ( toks . size (), i + fnx:: MAXT )); 1213o = e . window ( w ); 1214} 1215std:: vector < int > got { o . back ()}; 1216std:: mt19937 rng ( 7 ); 1217std:: uniform_real_distribution < double > u ( 0.0 , 1.0 ); 1218int windows = 0 ; 1219double ms = 0 ; 1220while ( got . size () + K + 1 <= ref . size ()) { 1221const size_t i = got . size () - 1 ; // got[i] = ref[i]: this window's row 0 1222std:: vector < int > rows { got . back ()}; 1223for ( int j = 1 ; j <= K ; ++ j ) rows . push_back ( ref [ i + j ]); 1224if ( K > 0 && u ( rng ) < bad ) rows [ 1 + ( int ) ( u ( rng ) * K )] ^= 1 ; 1225const std:: vector < int > out = e . verify ( rows ); 1226int n = 1 ; 1227while ( n < ( int ) rows . size () && rows [ n ] == out [ n - 1 ]) ++ n ; 1228e . commit ( n ); 1229ms += e . last_ms ; 1230++ windows ; 1231for ( int j = 0 ; j < n ; ++ j ) got . push_back ( out [ j ]); 1232} 1233size_t same = 0 ; 1234while ( same < got . size () && same < ref . size () && got [ same ] == ref [ same ]) ++ same ; 1235std:: printf ( "spec K=%d bad=%.0f%%: %d windows, %zu tokens (%.2f per window), %.2f ms per window, %.1f tok/s; " 1236"%zu of %zu tokens match the reference\n" , K , bad * 100 , windows , got . size () - 1 , 1237( got . size () - 1.0 ) / windows , ms / windows , ( got . size () - 1.0 ) * 1000.0 / ms , same , got . size ()); 1238return same == got . size () ? 0 : 1 ; 1239} else if ( mode == "bench_step" ) { 1240// what a window costs by its rows, at a context of C tokens of the prompt (read through the prompt path) on every 1241// lane: verify windows of 1..MAXT rows on one lane, then batched windows (step: one row per lane) on 1..L lanes 1242// (FNX_LANES >= L); medians of N windows each 1243if ( argc < 7 ) { std:: fprintf ( stderr , "bench_step needs L N C [step]\n" ); return 2 ; } 1244const bool step_only = argc > 7 && std:: string ( argv [ 7 ]) == "step" ; // only batched windows of all L lanes 1245const int L = std:: atoi ( argv [ 4 ]), n = std:: atoi ( argv [ 5 ]), nc = std:: atoi ( argv [ 6 ]); 1246std:: vector < int > lanes { 0 }; 1247while (( int ) lanes . size () < L ) lanes . push_back ( e . add_lane ()); 1248e . warm_graphs (); // every lane's rotary table, as sfnx does after adding its lanes 1249std:: vector < int > x ( L ); 1250for ( int r = 0 ; r < L ; ++ r ) { 1251e . use_lane ( lanes [ r ]); 1252std:: vector < int > ctx ( nc ); 1253for ( int i = 0 ; i < nc ; ++ i ) ctx [ i ] = toks [( i + 97 * r ) % toks . size ()]; 1254e . prefill ( ctx ); 1255x [ r ] = toks [( nc + 97 * r ) % toks . size ()]; 1256} 1257if ( n < 2 ) { std:: fprintf ( stderr , "bench_step: N 2 or more (the first window captures the graph and is not timed)\n" ); return 2 ; } 1258e . use_lane ( 0 ); 1259for ( int T = 1 ; T <= ( step_only ? 0 : fnx:: MAXT ); ++ T ) { 1260std:: vector < double > wall , gpu ; 1261for ( int i = 0 ; i < n ; ++ i ) { 1262std:: vector < int > w ; 1263for ( int t = 0 ; t < T ; ++ t ) w . push_back ( toks [( i + t ) % toks . size ()]); 1264e . verify ( w ); 1265if ( i > 0 ) wall . push_back ( e . last_ms ), gpu . push_back ( e . last_gpu_ms ); // the first captures the graph 1266e . commit ( 1 ); 1267} 1268std:: fprintf ( stderr , "verify, 1 lane, %d rows: wall %.3f ms, gpu %.3f ms\n" , T , median ( wall ), median ( gpu )); 1269} 1270for ( int k = step_only ? L : 1 ; k <= L ; ++ k ) { 1271const std:: vector < int > use ( lanes . begin (), lanes . begin () + k ); 1272std:: vector < int > xk ( x . begin (), x . begin () + k ); 1273std:: vector < double > wall , gpu ; 1274for ( int i = 0 ; i < n ; ++ i ) { 1275xk = e . step ( use , xk ); 1276if ( i > 0 ) wall . push_back ( e . last_ms ), gpu . push_back ( e . last_gpu_ms ); 1277} 1278std:: fprintf ( stderr , "step, %d lanes, 1 row each: wall %.3f ms, gpu %.3f ms\n" , k , median ( wall ), median ( gpu )); 1279} 1280} else if ( mode == "bench" ) { 1281if ( argc < 6 ) { std:: fprintf ( stderr , "bench needs T N\n" ); return 2 ; } 1282const int T = std:: atoi ( argv [ 4 ]), n = std:: atoi ( argv [ 5 ]); 1283// FNX_BENCH_CTX=N: the windows at a context of N tokens (the prompt repeated, read through the prompt path) 1284if (std:: getenv ( "FNX_BENCH_CTX" )) { 1285const int nc = ( int ) fnx:: env_int ( "FNX_BENCH_CTX" , 0 ); 1286std:: vector < int > ctx ( nc ); 1287for ( int i = 0 ; i < nc ; ++ i ) ctx [ i ] = toks [ i % toks . size ()]; 1288e . prefill ( ctx ); 1289} 1290std:: vector < double > wall , gpu ; 1291for ( int i = 0 ; i < n ; ++ i ) { 1292std:: vector < int > w ; 1293for ( int t = 0 ; t < T ; ++ t ) w . push_back ( toks [( i + t ) % toks . size ()]); 1294e . verify ( w ); 1295if ( i > 0 ) { // the first window of a T captures its graph 1296wall . push_back ( e . last_ms ); 1297gpu . push_back ( e . last_gpu_ms ); 1298} 1299e . commit ( 1 ); 1300} 1301auto stats = [](std:: vector < double > v , double & med , double & trim ) { 1302med = median ( v ); 1303std:: sort ( v . begin (), v . end ()); 1304const size_t a = v . size () / 10 , b = v . size () - a ; 1305trim = 0 ; 1306for ( size_t i = a ; i < b ; ++ i ) trim += v [ i ]; 1307trim /= ( double ) ( b - a ); 1308}; 1309double wm , wt , gm , gt ; 1310stats ( wall , wm , wt ); 1311stats ( gpu , gm , gt ); 1312std:: printf ( "bench %d windows of %d rows: wall median %.3f trimmed %.3f ms, gpu median %.3f trimmed %.3f ms\n" , n - 1 , T , wm , wt , 1313gm , gt ); 1314} else if ( mode == "rows" ) { 1315if ( argc < 6 ) { std:: fprintf ( stderr , "rows needs T N\n" ); return 2 ; } 1316const int T = std:: atoi ( argv [ 4 ]), n = std:: atoi ( argv [ 5 ]); 1317if ( n < 2 ) { std:: fprintf ( stderr , "rows: N 2 or more (the first window captures the graph and is not timed)\n" ); return 2 ; } 1318std:: vector < double > wall , gpu , launch , card [fnx:: NCARD ]; 1319size_t k = 0 ; 1320for ( int i = 0 ; i < n ; ++ i ) { 1321std:: vector < int > w ; 1322for ( int t = 0 ; t < T ; ++ t ) w . push_back ( toks [ k ++ % toks . size ()]); 1323e . window ( w ); 1324if ( i > 0 ) { // the first window of a T captures its graph 1325wall . push_back ( e . last_ms ); 1326gpu . push_back ( e . last_gpu_ms ); 1327launch . push_back ( e . last_launch_ms ); 1328for ( int c = 0 ; c < fnx:: NCARD ; ++ c ) card [ c ]. push_back ( e . last_card_ms [ c ]); 1329} 1330} 1331std:: printf ( "%d windows of %d rows: median wall %.2f ms, gpu %.2f ms (p90 wall %.2f), graph launches %.3f ms; " 1332"each card's gpu %.2f / %.2f / %.2f ms\n" , 1333n - 1 , T , median ( wall ), median ( gpu ), pct ( wall , 0.9 ), median ( launch ), median ( card [ 0 ]), median ( card [ 1 ]), median ( card [ 2 ])); 1334} else { // gen 1335const int n = std:: atoi ( argv [ 4 ]); 1336if ( n < 2 ) { std:: fprintf ( stderr , "gen: N 2 or more\n" ); return 2 ; } 1337std:: vector < int > o ; 1338for ( size_t i = 0 ; i < toks . size (); i += fnx:: MAXT ) { 1339std:: vector < int > w ( toks . begin () + i , toks . begin () + std:: min ( toks . size (), i + fnx:: MAXT )); 1340o = e . window ( w ); 1341} 1342int cur = o . back (); 1343std:: vector < int > gen { cur }; 1344double ms = 0 ; 1345std:: vector < double > wall , emb , gpu ; 1346for ( int i = 1 ; i < n ; ++ i ) { 1347cur = e . window ({ cur })[ 0 ]; 1348ms += e . last_ms ; 1349wall . push_back ( e . last_ms ); 1350emb . push_back ( e . last_embed_ms ); 1351gpu . push_back ( e . last_gpu_ms ); 1352gen . push_back ( cur ); 1353} 1354std:: printf ( "generated:" ); 1355for ( int t : gen ) std:: printf ( " %d" , t ); 1356std:: printf ( "\n%d single-row windows: %.2f ms each, %.1f tok/s\n" , n - 1 , ms / ( n - 1 ), ( n - 1 ) * 1000.0 / ms ); 1357std:: printf ( " p10/p50/p90 ms: wall %.2f/%.2f/%.2f embed %.2f/%.2f/%.2f gpu %.2f/%.2f/%.2f\n" , pct ( wall , .1 ), 1358pct ( wall , .5 ), pct ( wall , .9 ), pct ( emb , .1 ), pct ( emb , .5 ), pct ( emb , .9 ), pct ( gpu , .1 ), pct ( gpu , .5 ), 1359pct ( gpu , .9 )); 1360} 1361return 0 ; 1362} 1363 1364#ifndef FNX_LAB_LIB 1365int main ( int argc , char ** argv ) { 1366try { 1367if (! args_ok ( argc , argv )) return 2 ; // before the model's minutes of loading 1368fnx:: Model m ( argv [ 1 ]); 1369return fnx_run_cmd ( & m , argc , argv ); 1370} catch (const std:: exception & e ) { 1371std:: fprintf ( stderr , "fnx_run: %s\n" , e . what ()); 1372return 1 ; 1373} 1374} 1375#endif