okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c850b979b
main
1// sFNX engine process for its front end (front/, Strata's line protocol): the engine half on stdin/stdout (token ids 2// only; the server tokenizes, applies the chat template, matches stop strings and parses tools). 3// 4// sfnx --serve --native MODEL.gguf --mtp RT_DIR --draft-vocab VOCAB.bin [--max-context N] [--spec K] [--lookup K] 5// [--conversation-cache-mib M] [--batch SLOTS] 6// 7// One request alone: GEN <max_new> [key=value ...] <ids>, answered with PP <done> <total> per prompt chunk, RESUME 8// <reused>, T <id> per token (speculative: the draft layer's chain and n-gram lookups, verified a window at a time), 9// DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> <finish> <drafts_accepted> <drafts_offered> <reused>, or ERR 10// (prompt_tokens: the prompt's tokens the lane holds, reused ones included; on a cancelled read as far as it got). 11// STOP any time ends it. BYIELD <slot> during its prompt read ends the read at the next chunk, the part read left in 12// that (free) slot for a BGEN there to go on from: YIELDED <slot> <read>, then DONE ... cancel. With --batch (INFO 13// batch_slots): BGEN <slot> <max_new> ... reads a prompt into a slot (each slot a lane) between the decoding slots' 14// windows, answers its first token as T + DONE, then BADM <slot> 1 if it goes on; decoding slots share windows (a row 15// each and their drafts: src/batch.hpp; one row each with FNX_BATCH_DRAFTS=0) and stream BT <slot> <id> ... BDONE <slot> 16// <produced> <finish> <ms> <drafts_accepted> <drafts_offered> <rounds> (the batched windows after its first token; 17// drafts 0 with FNX_BATCH_DRAFTS=0). BSTOP <slot> ends a decoding slot, or its prompt read at the next chunk (DONE ... 18// cancel, then BADM <slot> 0), and so does a STOP for the request decoding in a slot; BYIELD <slot> ends its prompt 19// read at the next chunk (YIELDED <slot> <read>). STOP, BSTOP and BYIELD act on the requests whose lines came before 20// them (sfnx_input.hpp). 21#include <algorithm> 22#include <atomic> 23#include <chrono> 24#include <cmath> 25#include <condition_variable> 26#include <cstdint> 27#include <cstdio> 28#include <cstdlib> 29#include <cstring> 30#include <deque> 31#include <functional> 32#include <iostream> 33#include <memory> 34#include <mutex> 35#include <optional> 36#include <random> 37#include <set> 38#include <sstream> 39#include <stdexcept> 40#include <string> 41#include <thread> 42#include <vector> 43 44#include "../src/batch.hpp" 45#include "../src/engine.hpp" 46#include "../src/env.hpp" 47#include "../src/session.hpp" 48#include "sfnx_input.hpp" 49 50namespace { 51 52using sfnx::Input ; 53using sfnx::MAX_SLOTS ; 54using sfnx::Running ; 55const std::vector < int > EOS {248044 ,248046 }; 56 57std::mutex out_mu ; 58void say (const std::string & line ) { 59 std::lock_guard < std::mutex > lk (out_mu ); 60 std::fwrite (line .data (),1 ,line .size (),stdout ); 61 std::fputc ('\n' ,stdout ); 62 std::fflush (stdout ); 63} 64 65struct Args { 66 std::string gguf ,mtp_dir ,draft_vocab ; 67 std::string draft = "mtp" ,draft_model ;// --draft mtp|dflash2 (FNX_DRAFT), --draft-model PACK: DFlash2's runtime pack (tools/dflash2_pack.py) 68int max_ctx = 262144 ,K = 6 ,lookup = 15 ,batch = 1 ; 69long cache_mib = 0 ;// checkpoints and parked conversations in host memory (0: none) 70bool vision = false;// GENI / BGENI: prompts with images (embeddings from sfnx-vision) 71}; 72 73Args parse_args (int argc ,char ** argv ) { 74Args a ; 75bool serve = false; 76for (int i = 1 ;i < argc ;++ i ) { 77const std::string k = argv [i ]; 78auto val = [& ]()-> std::string { 79if (i + 1 >=argc )throw std::runtime_error (k + " needs a value" ); 80return argv [++ i ]; 81 }; 82if (k == "--serve" )serve = true; 83else if (k == "--native" )a .gguf = val (); 84else if (k == "--mtp" )a .mtp_dir = val (); 85else if (k == "--draft-vocab" )a .draft_vocab = val (); 86else if (k == "--draft" )a .draft = val (); 87else if (k == "--draft-model" )a .draft_model = val (); 88else if (k == "--max-context" )a .max_ctx = std::stoi (val ()); 89else if (k == "--spec" )a .K = std::stoi (val ()); 90else if (k == "--lookup" )a .lookup = std::stoi (val ()); 91else if (k == "--conversation-cache-mib" )a .cache_mib = std::stol (val ()); 92else if (k == "--batch" )a .batch = std::stoi (val ()); 93else if (k == "--layer-split" )val ();// Strata's layer split; sFNX splits every layer across the cards 94else if (k == "--rope-scale" ) {// YaRN for a longer context: the engine reads it as FNX_ROPE_SCALE 95const std::string s = val (); 96if (const char * e = std::getenv ("FNX_ROPE_SCALE" );e && s != e ) 97throw std::runtime_error ("--rope-scale " + s + " and FNX_ROPE_SCALE=" + e + " disagree" ); 98 ::setenv ("FNX_ROPE_SCALE" ,s .c_str (),1 ); 99 } 100else if (k == "--vision" )a .vision = true; 101else throw std::runtime_error ("unknown argument " + k ); 102 } 103if (!serve )throw std::runtime_error ("sfnx runs as --serve" ); 104if (const char * e = std::getenv ("FNX_DRAFT" );e && e [0 ])a .draft = e ; 105if (a .draft != "mtp" && a .draft != "dflash2" )throw std::runtime_error ("--draft takes mtp or dflash2" ); 106if (a .draft == "dflash2" ) { 107if (a .gguf .empty ()|| a .draft_model .empty ()|| (a .draft_vocab .empty ()&& a .mtp_dir .empty ())) 108throw std::runtime_error ("--draft dflash2 needs --native, --draft-model PACK and --draft-vocab FILE (or --mtp DIR for DIR/draft_vocab.bin)" ); 109if (a .draft_vocab .empty ())a .draft_vocab = a .mtp_dir + "/draft_vocab.bin" ; 110 }else if (a .gguf .empty ()|| a .mtp_dir .empty ())throw std::runtime_error ("--native and --mtp are required" ); 111if (a .batch < 1 || a .batch > MAX_SLOTS )throw std::runtime_error ("--batch must be 1.." + std::to_string (MAX_SLOTS )); 112 fnx::rope_scale ();// a bad scale stops here, not after the minute of loading (the context's limit needs the model) 113return a ; 114} 115 116// GEN <max_new> [key=value ...] <ids csv>, BGEN <slot> <max_new> ...; with images GENI / BGENI, the embeddings file 117// (sfnx-vision records) before the ids 118struct GenReq { 119long seq = 0 ;// its number among the request lines (Input) 120int slot = -1 ; 121int max_new = 0 ; 122 fnx::Sampling s ; 123 fnx::ReadHints hints ; 124 std::vector < int > ids ; 125 std::vector < float > img_rows ;// every image's rows, in prompt order (hints.images point into it) 126GenReq ()= default ; 127GenReq (GenReq && )= default ;// a vector's move keeps its buffer, so hints.images stay valid 128GenReq & operator= (GenReq && )= default ; 129GenReq (const GenReq & )= delete ;// a copy's hints.images would point into the original's img_rows 130GenReq & operator= (const GenReq & )= delete ; 131}; 132 133uint64_t mix64 (uint64_t x ) {// splitmix64's finalizer 134x ^=x >>30 ; 135x *=0xbf58476d1ce4e5b9ull ; 136x ^=x >>27 ; 137x *=0x94d049bb133111ebull ; 138return x ^ (x >>31 ); 139} 140 141uint64_t fnv1a (const void * p ,size_t n ,uint64_t h = 0xcbf29ce484222325ull ) { 142const unsigned char * b = (const unsigned char * )p ; 143for (size_t i = 0 ;i < n ;++ i )h = (h ^b [i ])* 0x100000001b3ull ; 144return h ; 145} 146 147// the images of a GENI prompt: the file's records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt 148// order, each on its run of n image-pad tokens. Each picture's cells get ids of their own from its key (the server's 149// hash of the picture, else its rows') and grid, so the conversation cache matches a picture by what it is 150void attach_images (GenReq & r ,const std::string & path ,const std::vector < uint64_t >& keys ,int pad ) { 151struct Rec { 152int n ,nx ,ny ; 153size_t off ; 154 }; 155 std::vector < Rec > recs ; 156 std::FILE * f = std::fopen (path .c_str (),"rb" ); 157if (!f )throw std::runtime_error ("GENI: cannot open " + path ); 158for (;;) { 159int32_t h [5 ]; 160const size_t got = std::fread (h ,4 ,5 ,f ); 161if (got == 0 )break ; 162if (got != 5 || h [0 ]!= 0x31455653 || h [1 ]< 1 || h [2 ]< 1 || h [3 ]< 1 || (int64_t )h [2 ]* h [3 ]!= h [1 ]|| h [4 ]!= fnx::N ) { 163 std::fclose (f ); 164throw std::runtime_error ("GENI: bad embeddings file (expected sfnx-vision records of width " + std::to_string (fnx::N )+ ")" ); 165 } 166const size_t off = r .img_rows .size (),cnt = (size_t )h [1 ]* fnx::N ; 167r .img_rows .resize (off + cnt ); 168if (std::fread (r .img_rows .data ()+ off ,4 ,cnt ,f )!= cnt ) { 169 std::fclose (f ); 170throw std::runtime_error ("GENI: short embeddings file" ); 171 } 172recs .push_back ({h [1 ],h [2 ],h [3 ],off }); 173 } 174 std::fclose (f ); 175if (!keys .empty ()&& keys .size ()!= recs .size ())throw std::runtime_error ("GENI: img_keys and the file's images differ in number" ); 176size_t k = 0 ; 177for (size_t i = 0 ;i < r .ids .size ();) { 178if (r .ids [i ]!= pad ) { 179++ i ; 180continue ; 181 } 182if (k >=recs .size ())throw std::runtime_error ("GENI: the prompt has more images than the embeddings file" ); 183const Rec & im = recs [k ]; 184const int64_t grid [3 ]= {im .n ,im .nx ,im .ny }; 185uint64_t key = fnv1a (grid ,sizeof grid ); 186key = keys .empty () ?fnv1a (r .img_rows .data ()+ im .off , (size_t )im .n * fnx::N * 4 ,key ) :fnv1a (& keys [k ],8 ,key ); 187for (int j = 0 ;j < im .n ;++ j ) { 188if (i + j >=r .ids .size ()|| r .ids [i + j ]!= pad ) 189throw std::runtime_error ("GENI: image " + std::to_string (k + 1 )+ " has " + std::to_string (im .n )+ " rows but fewer image-pad tokens" ); 190r .ids [i + j ]= fnx::Engine ::IMAGE_TOK | (int ) (mix64 (key + (uint64_t )j )& (fnx::Engine ::IMAGE_TOK - 1 )); 191 } 192r .hints .images .push_back (fnx::Engine ::Image {(int )i ,im .n ,im .nx ,im .ny ,nullptr }); 193i += im .n ; 194++ k ; 195 } 196if (k != recs .size ())throw std::runtime_error ("GENI: the embeddings file has more images than the prompt" ); 197if (r .ids .back () >= fnx::Engine ::IMAGE_TOK )throw std::runtime_error ("GENI: the prompt cannot end in an image" ); 198for (size_t j = 0 ;j < recs .size ();++ j )r .hints .images [j ].rows = r .img_rows .data ()+ recs [j ].off ; 199} 200 201// a request line's fields, each parsed whole (the field named in the error): an int, a float, a 64-bit hex key 202int field_int (const std::string & cmd ,const std::string & key ,const std::string & v ) { 203long long x = 0 ; 204if (!fnx::parse_whole (v .c_str (),x )|| x < INT32_MIN || x > INT32_MAX ) 205throw std::runtime_error (cmd + ": " + key + "=" + v + " is not a whole number" ); 206return (int )x ; 207} 208 209float field_float (const std::string & cmd ,const std::string & key ,const std::string & v ) { 210double x = 0 ; 211if (!fnx::parse_number (v .c_str (),x )|| !std::isfinite ((float )x ))throw std::runtime_error (cmd + ": " + key + "=" + v + " is not a number" ); 212return (float )x ; 213} 214 215uint64_t field_hex64 (const std::string & cmd ,const std::string & key ,const std::string & v ) { 216if (v .empty ()|| v .size ()> 16 || v .find_first_not_of ("0123456789abcdefABCDEF" )!= std::string::npos ) 217throw std::runtime_error (cmd + ": " + key + " holds '" + v + "', not 1 to 16 hex digits" ); 218return std::stoull (v ,nullptr ,16 ); 219} 220 221// a comma-separated list's items, empty ones included ("1,,2" has three; "" has one, empty) 222std::vector < std::string > split_commas (const std::string & s ) { 223 std::vector < std::string > out (1 ); 224for (char ch :s ) { 225if (ch == ',' )out .emplace_back (); 226else out .back ()+= ch ; 227 } 228return out ; 229} 230 231GenReq parse_gen (const std::string & line ,int vocab ,int pad ,bool batch ,bool images ) { 232 std::istringstream is (line ); 233 std::string cmd ,word ; 234GenReq r ; 235is >>cmd ; 236if (batch ) { 237if (!(is >>word ))throw std::runtime_error (cmd + ": no slot" ); 238r .slot = field_int (cmd ,"slot" ,word ); 239 } 240if (!(is >>word ))throw std::runtime_error (cmd + ": no max_new" ); 241r .max_new = field_int (cmd ,"max_new" ,word ); 242if (r .max_new < 1 )throw std::runtime_error (cmd + ": max_new must be a number >= 1" ); 243 std::string ids ,emb_path ; 244 std::vector < uint64_t > img_keys ; 245while (is >>word ) { 246const size_t eq = word .find ('=' ); 247if (eq == std::string::npos ) { 248if (images && emb_path .empty ()) { 249emb_path = word ; 250continue ; 251 } 252ids = word ; 253break ; 254 } 255const std::string k = word .substr (0 ,eq ),v = word .substr (eq + 1 ); 256if (k == "img_keys" ) { 257for (const std::string & h :split_commas (v ))img_keys .push_back (field_hex64 (cmd ,k ,h )); 258continue ; 259 } 260if (k == "temperature" )r .s .temperature = field_float (cmd ,k ,v ); 261else if (k == "top_p" )r .s .top_p = field_float (cmd ,k ,v ); 262else if (k == "top_k" )r .s .top_k = field_int (cmd ,k ,v ); 263else if (k == "min_p" )r .s .min_p = field_float (cmd ,k ,v ); 264else if (k == "penalty_repeat" )r .s .pen_repeat = field_float (cmd ,k ,v ); 265else if (k == "penalty_freq" )r .s .pen_freq = field_float (cmd ,k ,v ); 266else if (k == "penalty_present" )r .s .pen_present = field_float (cmd ,k ,v ); 267else if (k == "penalty_last_n" )r .s .pen_last_n = field_int (cmd ,k ,v ); 268else if (k == "seed" ) {// 0 to 2^64-1; no seed= draws one from std::random_device 269if (v .empty ()|| v .size ()> 20 || v .find_first_not_of ("0123456789" )!= std::string::npos || 270 (v .size ()== 20 && v > "18446744073709551615" )) 271throw std::runtime_error (cmd + ": seed=" + v + " is not a whole number from 0 to 2^64-1" ); 272r .s .seed = std::stoull (v ); 273 } 274else if (k == "logit_bias" )throw std::runtime_error (cmd + ": logit_bias is not supported" ); 275else if (k == "keep" )r .hints .keep = field_int (cmd ,k ,v ); 276else if (k == "ckpt" ) { 277if (v != "0" && v != "1" )throw std::runtime_error (cmd + ": ckpt=" + v + " is not 0 or 1" ); 278r .hints .cache = v == "1" ; 279 } 280else if (k == "pin" ) {// a client's strata_prefix: sFNX's cache has no pinned checkpoints 281static bool said = false; 282if (!said ) std::fprintf (stderr ,"sfnx: pin= (a client's strata_prefix) is not supported: such requests go on without it\n" ); 283said = true; 284 } 285// Strata's per-request engine tuning (strata_tune) and its control vector: nothing in sFNX to set 286else if (k == "pcie_frac" || k == "spec_min_p" || k == "pipe" || k == "aux_cpus" || k == "cvec" ) { 287static std::set < std::string > said ; 288if (said .insert (k ).second ) 289 std::fprintf (stderr ,"sfnx: %s= (Strata's per-request engine tuning or control vector) has nothing to set in sfnx: " 290"such requests go on without it\n" ,k .c_str ()); 291 } 292else throw std::runtime_error (cmd + ": unknown key " + k ); 293 } 294if (is >>word )throw std::runtime_error (cmd + ": text after the token ids" ); 295if (ids .empty ())throw std::runtime_error (cmd + ": no token ids" ); 296try { 297 fnx::check_sampling (r .s ); 298 }catch (const std::runtime_error & ex ) { 299throw std::runtime_error (cmd + ": " + ex .what ()); 300 } 301for (const std::string & t :split_commas (ids )) { 302long long v = 0 ; 303if (!fnx::parse_whole (t .c_str (),v ))throw std::runtime_error (cmd + ": token id '" + t + "' is not a whole number" ); 304if (v < 0 || v >=vocab )throw std::runtime_error (cmd + ": token id " + t + " outside the vocabulary" ); 305r .ids .push_back ((int )v ); 306 } 307if (images )attach_images (r ,emb_path ,img_keys ,pad ); 308// SFNX_TEST_PROMPT=FILE.bin with SFNX_TEST_PROMPT_CONFIRM=1 (measurements only; check_test_prompt at start): a text 309// request's ids replaced by the file's, so a request through the front end reads exactly the tokens fnx_run reads 310if (const char * tp = std::getenv ("SFNX_TEST_PROMPT" );tp && !images ) { 311 std::FILE * f = std::fopen (tp ,"rb" ); 312if (!f )throw std::runtime_error (std::string ("SFNX_TEST_PROMPT: cannot open " )+ tp ); 313uint32_t nl = 0 ,nd = 0 ; 314int64_t ne = 0 ; 315const bool head = std::fread (& nl ,4 ,1 ,f )== 1 && std::fseek (f ,nl ,SEEK_CUR )== 0 && std::fread (& nd ,4 ,1 ,f )== 1 && 316 std::fread (& ne ,8 ,1 ,f )== 1 ; 317if (!head || ne < 1 || ne > 0x7fffffffLL ) { 318 std::fclose (f ); 319throw std::runtime_error (std::string ("SFNX_TEST_PROMPT: " )+ tp + " has no valid tokens header" ); 320 } 321 std::vector < float > v ((size_t )ne ); 322const bool full = std::fread (v .data (),4 ,v .size (),f )== v .size (); 323 std::fclose (f ); 324if (!full )throw std::runtime_error ("SFNX_TEST_PROMPT: short file" ); 325r .ids .clear (); 326for (float x :v ) { 327if (!(x >=0.f && x < (float )vocab )|| x != (float ) (int )x ) 328throw std::runtime_error (std::string ("SFNX_TEST_PROMPT: " )+ tp + " holds a value that is not a token id" ); 329r .ids .push_back ((int )x ); 330 } 331 std::fprintf (stderr ,"sfnx: SFNX_TEST_PROMPT: the request reads %s (%zu tokens) instead\n" ,tp ,r .ids .size ()); 332 } 333return r ; 334} 335 336struct Interrupted {// a prompt read ended at a chunk boundary (BYIELD, STOP) 337int read ; 338}; 339 340bool is_eos (int t ) { 341for (int e :EOS ) 342if (t == e )return true; 343return false; 344} 345 346std::vector < int > tail (const std::vector < int >& v ,int n ) { 347return std::vector < int > (v .size ()> (size_t )n ?v .end ()- n :v .begin (),v .end ()); 348} 349 350// a slot: a lane with its conversation, and when decoding in the batch its request's state 351struct Slot { 352int lane = -1 ; 353 std::unique_ptr < fnx::Session > sess ; 354bool decoding = false; 355long seq = 0 ;// the request it reads or decodes for (Input's number: BSTOP and BYIELD for it) 356int max_new = 0 ,produced = 0 ,x = -1 ; 357int rounds = 0 ;// batched windows it was in (after its first token's) 358 fnx::Sampling s ; 359 std::mt19937_64 rng ; 360 std::vector < int > recent ;// the tokens before the next pick (the penalty window's) 361 std::chrono::steady_clock::time_point t0 ; 362long used = 0 ;// last admission or finish, for choosing which idle lane to park 363 std::chrono::steady_clock::time_point idle_since ;// its last reply's end (an arena's idle lanes park after IDLE_PARK) 364// a decoding slot whose conversation was taken off its lane because the pool ran out (every decoding lane needed 365// a page): its request state stays, and so does its lane (never dealt to another slot meanwhile); it resumes from 366// `held` (its conversation, x not among it; kept here, not in the conversation cache, so nothing evicts it) once 367// there is room for it again 368bool paused = false; 369 std::shared_ptr < fnx::Engine ::SeqState > held ; 370int sat_out = 0 ;// windows in a row it was left out of for want of a free page 371 fnx::BatchLane bl ;// with FNX_BATCH_DRAFTS: its next row, drafts and sampler (x and recent are not used) 372bool free ()const {return !decoding && !paused ; } 373}; 374 375constexpr int pages_for (int n_pos ) {return n_pos / fnx::KVP_POS + 1 ; } 376// pages of growth each decoding lane gets before a paused slot resumes (16: ~3k tokens) 377constexpr int RESUME_ROOM = 16 ; 378// an admission waits until the prompt and this much of its reply (or all of max_new, if less) fit the pool 379constexpr int ADMIT_REPLY = 2048 ; 380// FNX_ARENA: while experts are lent to the K/V pool, a lane idle this long has its conversation parked to host memory 381// (an agent between tool calls comes back within seconds; an ended conversation never does), so the pages free and 382// the slots go back to the experts; the upkeep runs at most this often 383constexpr std::chrono::seconds IDLE_PARK {120 },UPKEEP {5 }; 384 385struct Server { 386Args a ; 387 fnx::Model & m ; 388 fnx::Engine & e ; 389Input & in ; 390 std::shared_ptr < fnx::ConvCache > cache ; 391 std::vector < Slot > slots ; 392long clock = 0 ; 393int reading = -1 ;// the slot whose prompt is being read (its lane is never parked for room) 394 std::unique_ptr < fnx::BatchDecoder > dec ;// FNX_BATCH_DRAFTS: the batched windows carry drafts 395 396// slot i's request is ended by BSTOP <i>, or by a STOP that came while it was the latest request line (STOP acts on 397// the latest request, which here decodes in a slot) 398bool slot_stopped (int i )const { 399const long n = slots [(size_t )i ].seq ; 400return in .bstopped (i ,n )|| in .stop_upto .load ()== n ; 401 } 402 403// free pool pages until `need` are free: the idle lanes' conversations to host memory, least recently used first 404// (never slot `keep`'s); false when the idle lanes do not hold enough 405bool make_room (int need ,int keep ) { 406while (e .free_pages ()< need ) { 407int k = -1 ; 408for (int i = 0 ;i < (int )slots .size ();++ i ) { 409const Slot & s = slots [(size_t )i ]; 410if (i == keep || i == reading || s .decoding || s .paused || s .lane < 0 || e .lane_pages (s .lane )== 0 )continue ; 411if (k < 0 || s .used < slots [(size_t )k ].used )k = i ; 412 } 413if (k < 0 )return false; 414const int was = e .lane (); 415 std::fprintf (stderr ,"sfnx: K/V pool short (%d pages free, %d wanted): slot %d's conversation parked\n" ,e .free_pages (),need ,k ); 416slots [(size_t )k ].sess -> park (); 417e .use_lane (was ); 418 } 419return true; 420 } 421 422// FNX_ARENA, while experts are lent: idle lanes past IDLE_PARK parked, then the slots the freed pages allow given 423// back (Engine::arena_reclaim: not within its hold after a lend) 424 std::chrono::steady_clock::time_point last_upkeep ; 425void upkeep () { 426const auto now = std::chrono::steady_clock::now (); 427if (now - last_upkeep < UPKEEP )return ; 428last_upkeep = now ; 429bool lent = false; 430for (int v :e .arena_lent ())lent = lent || v > 0 ; 431if (!lent )return ; 432const int was = e .lane (); 433for (int i = 0 ;i < (int )slots .size ();++ i ) { 434Slot & s = slots [(size_t )i ]; 435if (!s .free ()|| i == reading || s .lane < 0 || e .lane_pages (s .lane )== 0 || now - s .idle_since < IDLE_PARK )continue ; 436 std::fprintf (stderr ,"sfnx: slot %d idle %.0f s while experts are lent: its conversation parked\n" ,i , 437 std::chrono::duration < double > (now - s .idle_since ).count ()); 438s .sess -> park (); 439 } 440e .use_lane (was ); 441e .arena_reclaim (); 442 } 443 444Server (const Args & args , fnx::Model & model , fnx::Engine & eng ,Input & input ) :a (args ),m (model ),e (eng ),in (input ) { 445cache = std::make_shared < fnx::ConvCache > (); 446cache -> budget = (size_t )a .cache_mib <<20 ; 447slots .resize ((size_t )a .batch ); 448slots [0 ].lane = 0 ; 449slots [0 ].sess = std::make_unique < fnx::Session > (e ,a .K ,a .lookup ,EOS ,248045 ,cache ,0 ); 450// every lane and every window graph now: what they take, taken before the first request 451for (int i = 1 ;i < a .batch ;++ i )lane_for (i ); 452if (a .batch > 1 && fnx::batch_drafts ()!= fnx::BatchDrafts ::off ) 453dec = std::make_unique < fnx::BatchDecoder > (e ,a .K ,a .lookup ,EOS , fnx::batch_drafts ()); 454e .warm_graphs (); 455 } 456 457// the slot's lane and session, made on first use (lane 0 is slot 0's from the start, but lanes move between 458// slots, so any slot may be the one without; a new lane takes pool pages) 459 fnx::Session & lane_for (int slot ) { 460Slot & sl = slots [(size_t )slot ]; 461if (sl .lane < 0 ) { 462sl .lane = e .add_lane (); 463sl .sess = std::make_unique < fnx::Session > (e ,a .K ,a .lookup ,EOS ,248045 ,cache ,sl .lane ); 464 } 465return * sl .sess ; 466 } 467 468bool any_decoding ()const { 469for (const Slot & s :slots ) 470if (s .decoding || s .paused )return true; 471return false; 472 } 473 474// the K/V pool is out of pages for every decoding lane and no idle lane can give any: the most recently admitted 475// decoding slot's conversation goes to host memory (its pages back to the pool) and the slot waits, request intact 476void pause_one (const std::vector < int >& rows ) { 477int k = rows [0 ]; 478for (int i :rows ) 479if (slots [(size_t )i ].t0 > slots [(size_t )k ].t0 )k = i ; 480Slot & sl = slots [(size_t )k ]; 481const int was = e .lane (); 482const auto t_p = std::chrono::steady_clock::now (); 483sl .held = sl .sess -> unload (); 484e .use_lane (was ); 485sl .decoding = false; 486sl .sat_out = 0 ; 487sl .paused = true; 488 std::fprintf (stderr ,"sfnx: K/V pool full: slot %d paused, its %zu tokens held in host memory in %.0f ms (%d pages free)\n" ,k , 489sl .held -> tokens .size (), std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t_p ).count (), 490e .free_pages ()); 491 } 492 493// paused slots back, oldest admission first, while there is room for one (idle lanes are parked for it): its 494// conversation reloaded from the held state (a copy, not a read), then it decodes on from its next token 495void resume_paused () { 496if (reading >=0 )return ;// not while a prompt read holds the engine (its progress runs the decoding windows) 497for (;;) { 498int k = -1 ; 499for (int i = 0 ;i < (int )slots .size ();++ i ) 500if (slots [(size_t )i ].paused && (k < 0 || slots [(size_t )i ].t0 < slots [(size_t )k ].t0 ))k = i ; 501if (k < 0 )return ; 502Slot & sl = slots [(size_t )k ]; 503// with room for every decoding lane, it included, to grow RESUME_ROOM pages, so it is not paused again at once 504// (alone, its own pages are enough: a conversation always fits the pool) 505int others = 0 ; 506for (const Slot & o :slots )others += o .decoding ; 507const int need = pages_for ((int )sl .held -> tokens .size ()+ fnx::MAXT )+ (others ?RESUME_ROOM * (others + 1 ) :0 )- 508e .lane_pages (sl .lane ); 509if (!make_room (need ,k ))return ; 510const int was = e .lane (); 511const auto t_r = std::chrono::steady_clock::now (); 512sl .sess -> reload (* sl .held ); 513e .use_lane (was ); 514sl .paused = false; 515sl .decoding = true; 516const size_t n = sl .held -> tokens .size (); 517sl .held .reset (); 518 std::fprintf (stderr ,"sfnx: slot %d resumed: its %zu tokens reloaded in %.0f ms\n" ,k ,n , 519 std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t_r ).count ()); 520 } 521 } 522 523// FNX_ROUTE_COUNT=1 with FNX_ROUTE_FILE=path: the engine's expert tallies to path after every reply (u32 524// [decode | prompt][NL][NEXP]) 525// FNX_ROUTE_TRACE=M with FNX_ROUTE_TRACE_FILE=path: decode's picks since the last reply appended to path 526// (check_route_env makes sure of the paths at start). A file that cannot be written ends that measurement, said on 527// stderr, and the engine serves on 528size_t traced = 0 ; 529bool trace_failed = false,count_failed = false; 530// v to path (fopen mode `mode`); false with errno set when any step fails 531static bool write_u32s (const char * path ,const char * mode ,const std::vector < unsigned >& v ) { 532 std::FILE * f = std::fopen (path ,mode ); 533if (!f )return false; 534const bool wrote = std::fwrite (v .data (),sizeof (unsigned ),v .size (),f )== v .size (); 535const int werr = errno ; 536if (std::fclose (f )!= 0 )return false; 537errno = werr ; 538return wrote ; 539 } 540void save_routes () { 541if (!trace_failed ) 542if (const std::vector < unsigned > t = e .route_trace (traced ); !t .empty ()) { 543const char * tpath = std::getenv ("FNX_ROUTE_TRACE_FILE" ); 544if (write_u32s (tpath ,traced ?"ab" :"wb" ,t )) { 545traced += t .size (); 546 }else { 547 std::fprintf (stderr ,"sfnx: FNX_ROUTE_TRACE_FILE: cannot write %s (%s): route tracing stopped after %zu picks\n" ,tpath , 548 std::strerror (errno ),traced ); 549trace_failed = true; 550 } 551 } 552if (count_failed )return ; 553const std::vector < unsigned > v = e .route_counts (); 554if (v .empty ())return ; 555const char * path = std::getenv ("FNX_ROUTE_FILE" ); 556const std::string tmp = std::string (path )+ ".tmp" ; 557if (!write_u32s (tmp .c_str (),"wb" ,v )|| std::rename (tmp .c_str (),path )!= 0 ) { 558 std::fprintf (stderr ,"sfnx: FNX_ROUTE_FILE: cannot write %s (%s): route counting stopped\n" ,path , std::strerror (errno )); 559count_failed = true; 560 } 561 } 562 563void finish_slot (int i , fnx::Finish f ) { 564Slot & sl = slots [(size_t )i ]; 565const double ms = std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- sl .t0 ).count (); 566char buf [128 ]; 567 std::snprintf (buf ,sizeof buf ,"BDONE %d %d %s %.1f %ld %ld %d" ,i ,sl .produced , fnx::finish_name (f ),ms ,dec ?sl .bl .accepted :0L , 568dec ?sl .bl .offered :0L ,sl .rounds ); 569say (buf ); 570sl .decoding = false; 571sl .sat_out = 0 ; 572sl .used = ++ clock ; 573sl .idle_since = std::chrono::steady_clock::now (); 574int busy = 0 ; 575for (const Slot & o :slots )busy += o .decoding ; 576 std::fprintf (stderr ,"sfnx: slot %d done: %d tokens in %.0f ms (%s), %d slots decoding%s\n" ,i ,sl .produced ,ms , fnx::finish_name (f ),busy , 577dec ? (", drafts " + std::to_string (sl .bl .accepted )+ " of " + std::to_string (sl .bl .offered )).c_str () :"" ); 578save_routes (); 579 } 580 581// one window for every decoding slot: a row each 582void decode_step () { 583for (int i = 0 ;i < (int )slots .size ();++ i ) 584if (slots [(size_t )i ].paused && slot_stopped (i )) { 585slots [(size_t )i ].paused = false; 586slots [(size_t )i ].held .reset (); 587finish_slot (i , fnx::Finish ::cancel ); 588 } 589resume_paused (); 590 std::vector < int > rows ; 591for (int i = 0 ;i < (int )slots .size ();++ i ) { 592if (!slots [(size_t )i ].decoding )continue ; 593if (slot_stopped (i )) { 594finish_slot (i , fnx::Finish ::cancel ); 595continue ; 596 } 597rows .push_back (i ); 598 } 599// with drafts, a lane's rows: within the window's MAXT, then their pages if idle lanes can give them, else its 600// drafts cut to the pages it holds (at least its first row, which the loop below sees to as without drafts) 601if (dec && !rows .empty ()) { 602 std::vector < fnx::BatchLane *> ls ; 603for (int i :rows )ls .push_back (& slots [(size_t )i ].bl ); 604 fnx::BatchDecoder ::fit (ls ); 605int want = 0 ; 606for (int i :rows ) { 607const int lane = slots [(size_t )i ].lane ; 608want += std::max (0 ,pages_for (e .lane_pos (lane )+ slots [(size_t )i ].bl .rows ())- e .lane_pages (lane )); 609 } 610if (want > 0 && !make_room (want ,-1 )) 611for (int i :rows ) { 612const int lane = slots [(size_t )i ].lane ; 613slots [(size_t )i ].bl .cut (std::max (1 ,e .lane_pages (lane )* fnx::KVP_POS - 1 - e .lane_pos (lane ))); 614 } 615 } 616auto rows_of = [& ](int i ) {return dec ?slots [(size_t )i ].bl .rows () :1 ; }; 617// a lane that crosses into a new page needs one free: idle lanes are parked for it, else it sits this window out; 618// when that leaves no lane to run, a decoding slot is paused (its conversation parked) for the others' pages 619for (;;) { 620if (rows .empty ())return ; 621int grow = 0 ; 622for (int i :rows )grow += e .lane_pages (slots [(size_t )i ].lane )< pages_for (e .lane_pos (slots [(size_t )i ].lane )+ rows_of (i )); 623if (grow == 0 || make_room (grow ,-1 ))break ; 624 std::vector < int > fit ; 625int left = e .free_pages (); 626for (int i :rows ) { 627const int lane = slots [(size_t )i ].lane ; 628const bool needs = e .lane_pages (lane )< pages_for (e .lane_pos (lane )+ rows_of (i )); 629if (!needs || left > 0 ) { 630fit .push_back (i ); 631left -= needs ; 632 } 633 } 634if (!fit .empty ()) { 635for (int i :rows ) 636if (std::find (fit .begin (),fit .end (),i )== fit .end ()&& slots [(size_t )i ].sat_out ++ == 0 ) 637 std::fprintf (stderr ,"sfnx: K/V pool short (%d pages free): slot %d waits for a page while %zu slot(s) decode\n" , 638e .free_pages (),i ,fit .size ()); 639rows = fit ; 640break ; 641 } 642if (rows .size ()== 1 ) 643throw std::runtime_error ("the K/V pool is full with one lane decoding: its conversation outgrew the pool" ); 644pause_one (rows ); 645 std::vector < int > still ; 646for (int i :rows ) 647if (slots [(size_t )i ].decoding )still .push_back (i ); 648rows = still ; 649 } 650for (int i :rows ) 651if (slots [(size_t )i ].sat_out > 0 ) { 652 std::fprintf (stderr ,"sfnx: slot %d decodes again after waiting %d window(s) for a page\n" ,i ,slots [(size_t )i ].sat_out ); 653slots [(size_t )i ].sat_out = 0 ; 654 } 655if (dec ) { 656 std::vector < fnx::BatchLane *> ls ; 657 std::vector < int > limit ; 658for (int i :rows ) { 659ls .push_back (& slots [(size_t )i ].bl ); 660limit .push_back (slots [(size_t )i ].max_new - slots [(size_t )i ].produced ); 661 } 662for (int i :rows )++ slots [(size_t )i ].rounds ; 663// FNX_BATCH_STATS=1: where a window cycle goes on the host, per 100 windows: the batch decoder's window (verify, draft layer and chain, the rest of it) and what runs 664// between two windows (this loop: upkeep, request polling, page rooms, finishing slots) 665static const bool wstats = fnx::env_flag ("FNX_BATCH_STATS" ); 666static std::chrono::steady_clock::time_point t_prev_end {}; 667static double acc_out = 0 ,acc_win = 0 ,acc_ver = 0 ,acc_dr = 0 ,acc_say = 0 ; 668static int nwin = 0 ; 669const auto tw0 = std::chrono::steady_clock::now (); 670if (wstats && t_prev_end .time_since_epoch ().count ()!= 0 ) { 671const double gap = std::chrono::duration < double , std::milli > (tw0 - t_prev_end ).count (); 672if (gap < 400.0 )acc_out += gap ; 673 } 674const auto got = dec -> window (ls ,limit , [& ](int r ,int tok ) { 675say ("BT " + std::to_string (rows [(size_t )r ])+ " " + std::to_string (tok )); 676++ slots [(size_t )rows [(size_t )r ]].produced ; 677 }); 678if (wstats ) { 679t_prev_end = std::chrono::steady_clock::now (); 680acc_win += std::chrono::duration < double , std::milli > (t_prev_end - tw0 ).count (); 681acc_ver += dec -> last_verify_ms ; 682acc_dr += dec -> last_draft_ms ; 683if (++ nwin == 100 ) { 684 std::fprintf (stderr ,"fnx: window cycle (100 windows, means in ms): between windows %.1f, window() %.1f = verify_rows %.1f + draft_next %.1f + the rest %.1f\n" ,acc_out /nwin , 685acc_win /nwin ,acc_ver /nwin ,acc_dr /nwin , (acc_win - acc_ver - acc_dr ) /nwin ); 686acc_out = acc_win = acc_ver = acc_dr = acc_say = 0 ; 687nwin = 0 ; 688 } 689 } 690for (size_t r = 0 ;r < rows .size ();++ r ) { 691const int i = rows [r ]; 692if (got [r ].eos )finish_slot (i , fnx::Finish ::stop ); 693else if (slots [(size_t )i ].produced >=slots [(size_t )i ].max_new )finish_slot (i ,slot_stopped (i ) ? fnx::Finish ::cancel : fnx::Finish ::length ); 694 } 695return ; 696 } 697 std::vector < int > lanes ,xs ; 698bool sample = false; 699for (int i :rows ) { 700lanes .push_back (slots [(size_t )i ].lane ); 701xs .push_back (slots [(size_t )i ].x ); 702sample = sample || slots [(size_t )i ].s .temperature > 0.f ; 703 } 704const std::vector < int > o = e .step (lanes ,xs ); 705for (int i :rows )++ slots [(size_t )i ].rounds ; 706 std::vector < std::vector < std::pair < float ,int >>> cand ; 707if (sample ) { 708 fnx::Engine ::Penalties pen ; 709bool any_pen = false; 710for (int i :rows )any_pen = any_pen || fnx::penalizes (slots [(size_t )i ].s ); 711if (any_pen ) 712for (int i :rows ) { 713const Slot & sl = slots [(size_t )i ]; 714pen .rows .push_back (fnx::penalizes (sl .s ) ? fnx::penalty_row (sl .recent ,sl .s ) : fnx::Engine ::Penalties ::Row {}); 715 } 716cand = e .top_tokens ((int )rows .size (),pen ); 717 } 718for (size_t r = 0 ;r < rows .size ();++ r ) { 719const int i = rows [r ]; 720Slot & sl = slots [(size_t )i ]; 721const int tok = sl .s .temperature > 0.f ? fnx::sample_token (cand [r ],sl .s ,sl .rng ) :o [r ]; 722say ("BT " + std::to_string (i )+ " " + std::to_string (tok )); 723++ sl .produced ; 724sl .x = tok ; 725sl .recent .push_back (tok ); 726if ((int )sl .recent .size ()> 2 * fnx::Engine ::PEN_CAP )sl .recent = tail (sl .recent , fnx::Engine ::PEN_CAP ); 727if (is_eos (tok ))finish_slot (i , fnx::Finish ::stop ); 728else if (sl .produced >=sl .max_new )finish_slot (i ,in .bstopped (i ,sl .seq ) ? fnx::Finish ::cancel : fnx::Finish ::length ); 729 } 730 } 731 732// a prompt read's progress for request seq: PP, the end of the read on STOP, on BYIELD or BSTOP for this slot (a 733// batch read; slot -1, a solo read, ends on a BYIELD it can give way to), the decoding slots' windows. A decoding 734// window that finds no room is no failure of the read's request: it ends the engine, as it does outside a read 735 std::function < void (int ,int )> progress (int slot ,long seq ) { 736return [this ,slot ,seq ](int done ,int total ) { 737say ("PP " + std::to_string (done )+ " " + std::to_string (total )); 738if (in .stop_now )throw Interrupted {done }; 739if (slot >=0 ?in .yielded (slot ,seq )|| in .bstopped (slot ,seq ) :solo_yield_to (seq ) >=0 )throw Interrupted {done }; 740if (!any_decoding ())return ; 741try { 742decode_step (); 743 }catch (const fnx::Refused & ex ) { 744throw std::runtime_error (std::string ("a decoding window during a prompt read: " )+ ex .what ()); 745 } 746 }; 747 } 748 749// the idle slot whose lane holds the longest prefix of the prompt (prefer on a tie; -1: no idle slot) 750int best_slot (const std::vector < int >& ids ,int prefer ) { 751int best = -1 ; 752size_t best_n = 0 ; 753const int was = e .lane (); 754for (int i = 0 ;i < (int )slots .size ();++ i ) { 755if (!slots [(size_t )i ].free ())continue ; 756size_t k = 0 ; 757if (slots [(size_t )i ].lane >=0 ) { 758e .use_lane (slots [(size_t )i ].lane ); 759const std::vector < int >& h = e .history (); 760while (k < h .size ()&& k < ids .size ()&& h [k ]== ids [k ])++ k ; 761 } 762if (best < 0 || k > best_n || (k == best_n && i == prefer )) { 763best_n = k ; 764best = i ; 765 } 766 } 767e .use_lane (was ); 768return best ; 769 } 770 771void done_line (const fnx::GenStats & st , fnx::Finish f ) { 772char buf [256 ]; 773 std::snprintf (buf ,sizeof buf ,"DONE %d %d %.1f %.1f %s %ld %ld %d" ,st .generated ,st .prompt_tokens ,st .prompt_ms ,st .decode_ms , 774 fnx::finish_name (f ),st .drafts_accepted ,st .drafts_offered ,st .reused ); 775say (buf ); 776 } 777 778// a prompt read the engine had no room for (fnx::Refused): ERR for the request, and no DONE (the front end reads 779// an ERR as the request's end). The message never starts "BGEN:", which the front end takes for a refused slot with 780// nothing read and sends again; this lane holds what was read, and the next request on it reuses that or parks it 781void read_refused (int slot ,const fnx::Refused & ex ,const char * cmd ) { 782Slot & sl = slots [(size_t )slot ]; 783sl .idle_since = std::chrono::steady_clock::now (); 784 std::fprintf (stderr ,"sfnx: slot %d: the prompt read failed (%s); its lane holds %d tokens, %d pages free\n" ,slot ,ex .what (), 785e .lane_pos (sl .lane ),e .free_pages ()); 786say (std::string ("ERR prompt read (" )+ cmd + " slot " + std::to_string (slot )+ "): " + ex .what ()); 787 } 788 789// a BYIELD for solo request seq names the slot its part read is to wait in (the front end holds that slot for it 790// and sends BGEN there after the shorter request): that slot, when it can take the lane (said once if not), else -1 791bool yield_said = false; 792int solo_yield_to (long seq ) { 793const int to = in .solo_yield (seq ); 794if (to < 0 )return -1 ; 795if (to < (int )slots .size ()&& slots [(size_t )to ].free ())return to ; 796if (!yield_said ) 797 std::fprintf (stderr ,"sfnx: BYIELD %d during a solo read: no free slot %d to leave the part read in; the read goes on\n" ,to ,to ); 798yield_said = true; 799return -1 ; 800 } 801 802void solo (const GenReq & r ) { 803const Running running (in ,r .seq ); 804yield_said = false; 805int slot = best_slot (r .ids ,0 ); 806if (slot < 0 ) {// the front end sends GEN only when no slot decodes 807say ("ERR GEN: every slot is decoding" ); 808return ; 809 } 810 fnx::Session & s = lane_for (slot ); 811slots [(size_t )slot ].used = ++ clock ; 812// the prompt and the start of its reply, as an admission takes (idle lanes parked for them now); later pages as 813// the reply grows, idle lanes parked for them then (on_pool_short below), so a request that sets no max_tokens 814// (max_new: the rest of the context) does not empty every idle lane before its first token 815const int need = pages_for ((int )r .ids .size ()+ std::min (r .max_new ,ADMIT_REPLY )+ fnx::MAXT )- e .lane_pages (slots [(size_t )slot ].lane ); 816if (!make_room (need ,slot )) { 817say ("ERR GEN: the K/V pool is full: the request needs " + std::to_string (need )+ " more pages, " + 818 std::to_string (e .free_pages ())+ " are free" ); 819return ; 820 } 821 fnx::GenStats st ; 822try { 823reading = slot ; 824e .set_pass_rows (any_decoding () ?8192 :0 );// other requests decode: they run between passes, so a pass stays at most 8192 rows (what 2 chunks of 4096 were) 825s .read (r .ids ,st ,progress (-1 ,r .seq ),r .hints ); 826reading = -1 ; 827 }catch (const Interrupted & it ) { 828reading = -1 ; 829st .prompt_tokens = it .read ;// as far as the read got (st.reused of them reused), not the whole prompt 830// given way (not stopped): the lane with the part read goes to the slot the BYIELD named, which the front 831// end's BGEN for the rest of this prompt will name 832if (const int to = in .stop_now ?-1 :solo_yield_to (r .seq );to >=0 ) { 833if (to != slot ) { 834 std::swap (slots [(size_t )slot ].lane ,slots [(size_t )to ].lane ); 835 std::swap (slots [(size_t )slot ].sess ,slots [(size_t )to ].sess ); 836slot = to ; 837 } 838slots [(size_t )slot ].idle_since = std::chrono::steady_clock::now (); 839 std::fprintf (stderr ,"sfnx: solo read gave way after %d of %zu tokens; slot %d holds them\n" ,it .read ,r .ids .size (),slot ); 840say ("YIELDED " + std::to_string (slot )+ " " + std::to_string (it .read )); 841 } 842done_line (st , fnx::Finish ::cancel ); 843return ; 844 }catch (const fnx::Refused & ex ) {// no room for the read: this request fails, the lane keeps what was read 845reading = -1 ; 846read_refused (slot ,ex ,"GEN" ); 847return ; 848 } 849say ("RESUME " + std::to_string (st .reused )); 850// the reply's pages beyond what was made room for: idle lanes parked as it needs them (nothing else decodes) 851struct PoolShort { 852 fnx::Engine & e ; 853 ~PoolShort () {e .on_pool_short = nullptr ; } 854 }pool_short {e }; 855e .on_pool_short = [this ,slot ](int ,int pages ) {make_room (e .free_pages ()+ pages ,slot ); }; 856const fnx::Finish f = s .generate (r .max_new ,r .s , [& ](int t ) {say ("T " + std::to_string (t )); },& in .stop_now ,st ); 857done_line (st ,f ); 858 std::fprintf (stderr ,"sfnx: slot %d: prompt %d tokens = %d reused + %d read in %.0f ms, %d generated in %.0f ms (%.1f tok/s), " 859"drafts %ld of %ld, %d rounds (%d with lookup drafts, %.2f ms a round)\n" , 860slot ,st .prompt_tokens ,st .reused ,st .prompt_tokens - st .reused ,st .prompt_ms ,st .generated ,st .decode_ms , 861st .generated * 1000.0 / std::max (1.0 ,st .decode_ms ),st .drafts_accepted ,st .drafts_offered ,st .rounds ,st .lookup_rounds , 862st .decode_ms / std::max (1 ,st .rounds )); 863slots [(size_t )slot ].idle_since = std::chrono::steady_clock::now (); 864save_routes (); 865 } 866 867void admit (const GenReq & r ) { 868if (r .slot < 0 || r .slot >= (int )slots .size ()|| !slots [(size_t )r .slot ].free ()) { 869say ("ERR BGEN: no such free slot " + std::to_string (r .slot )+ " (--batch " + std::to_string (slots .size ())+ ")" ); 870return ; 871 } 872const Running running (in ,r .seq ); 873const int i = r .slot ; 874// the slot takes the idle lane that holds most of the prompt (the front end picks slots by what it believes they 875// hold; the lanes are sFNX's to deal) 876const int k = best_slot (r .ids ,i ); 877if (k >=0 && k != i && slots [(size_t )k ].lane >=0 ) { 878 std::swap (slots [(size_t )i ].lane ,slots [(size_t )k ].lane ); 879 std::swap (slots [(size_t )i ].sess ,slots [(size_t )k ].sess ); 880 } 881 fnx::Session & s = lane_for (i ); 882Slot & sl = slots [(size_t )i ]; 883sl .used = ++ clock ; 884sl .seq = r .seq ; 885// the prompt's pages and the first ADMIT_REPLY tokens of its reply (the lane's own count: it may restart), and 886// room for the decoding slots to grow while it reads; short of that, the decoding slots go on until enough of 887// them end 888for (;;) { 889int growing = 0 ; 890for (const Slot & o :slots )growing += o .decoding ; 891const int need = pages_for ((int )r .ids .size ()+ std::min (r .max_new ,ADMIT_REPLY )+ fnx::MAXT )+ 2 * growing - 892e .lane_pages (sl .lane ); 893if (make_room (need ,i ))break ; 894if (!any_decoding ()) { 895say ("ERR BGEN: the K/V pool is full: the prompt needs " + std::to_string (need )+ " more pages, " + 896 std::to_string (e .free_pages ())+ " are free" ); 897return ; 898 } 899if (in .yielded (i ,r .seq )|| in .bstopped (i ,r .seq )|| in .stop_now ) { 900if (in .yielded (i ,r .seq ))say ("YIELDED " + std::to_string (i )+ " 0" ); 901 fnx::GenStats st ;// nothing read: prompt_tokens 0 902done_line (st , fnx::Finish ::cancel ); 903say ("BADM " + std::to_string (i )+ " 0" ); 904return ; 905 } 906decode_step (); 907 } 908 fnx::GenStats st ; 909try { 910reading = i ; 911e .set_pass_rows (any_decoding () ?8192 :0 ); 912s .read (r .ids ,st ,progress (i ,r .seq ),r .hints ); 913reading = -1 ; 914 }catch (const Interrupted & it ) { 915reading = -1 ; 916if (in .yielded (i ,r .seq ))say ("YIELDED " + std::to_string (i )+ " " + std::to_string (it .read )); 917st .prompt_tokens = it .read ; 918done_line (st , fnx::Finish ::cancel ); 919say ("BADM " + std::to_string (i )+ " 0" ); 920return ; 921 }catch (const fnx::Refused & ex ) { 922reading = -1 ; 923read_refused (i ,ex ,"BGEN" ); 924return ; 925 } 926if (in .bstopped (i ,r .seq )) {// BSTOP after the last chunk (or a prompt with nothing to read): cancelled before its first token 927done_line (st , fnx::Finish ::cancel ); 928say ("BADM " + std::to_string (i )+ " 0" ); 929sl .idle_since = std::chrono::steady_clock::now (); 930return ; 931 } 932// the first token: the prompt's last through a window of this lane alone 933const auto t1 = std::chrono::steady_clock::now (); 934const std::vector < int > o = e .step ({sl .lane }, {r .ids .back ()}); 935sl .s = r .s ; 936sl .rng .seed (r .s .seed ?* r .s .seed : std::random_device {}()); 937sl .recent = tail (r .ids , std::max (1 ,r .s .pen_last_n )); 938int tok = o [0 ]; 939if (r .s .temperature > 0.f ) { 940 fnx::Engine ::Penalties pen ; 941if (fnx::penalizes (r .s ))pen .rows .push_back (fnx::penalty_row (sl .recent ,r .s )); 942tok = fnx::sample_token (e .top_tokens (1 ,pen )[0 ],r .s ,sl .rng ); 943 } 944say ("T " + std::to_string (tok )); 945st .generated = 1 ; 946st .decode_ms = std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t1 ).count (); 947const bool more = !is_eos (tok )&& r .max_new > 1 ; 948done_line (st ,is_eos (tok ) ? fnx::Finish ::stop : fnx::Finish ::length ); 949say ("BADM " + std::to_string (i )+ (more ?" 1" :" 0" )); 950if (!more ) { 951sl .idle_since = std::chrono::steady_clock::now (); 952return ; 953 } 954sl .decoding = true; 955sl .max_new = r .max_new ; 956sl .produced = 1 ; 957sl .rounds = 0 ; 958sl .x = tok ; 959sl .recent .push_back (tok ); 960if (dec ) { 961 std::vector < int > ctx (r .ids ); 962ctx .push_back (tok ); 963sl .bl .start (sl .lane ,r .s ,sl .rng , std::move (ctx )); 964 } 965sl .t0 = t1 ; 966int busy = 0 ; 967for (const Slot & o :slots )busy += o .decoding ; 968 std::fprintf (stderr ,"sfnx: slot %d (lane %d) admitted: prompt %d = %d reused + %d read in %.0f ms; %d slots decoding\n" ,i ,sl .lane , 969st .prompt_tokens ,st .reused ,st .prompt_tokens - st .reused ,st .prompt_ms ,busy ); 970 } 971 972void run () { 973 std::string line ; 974long seq = 0 ; 975for (;;) { 976// requests first; the decoding slots' window when none is waiting 977upkeep (); 978if (!in .next (line ,seq , !any_decoding (), std::chrono::duration_cast < std::chrono::milliseconds > (UPKEEP ))) { 979if (in .closed ())return ; 980decode_step (); 981continue ; 982 } 983if (line .empty ())continue ; 984const std::string cmd = line .substr (0 ,line .find (' ' )); 985if (cmd == "QUIT" )return ; 986if (cmd != "GEN" && cmd != "BGEN" && cmd != "GENI" && cmd != "BGENI" ) { 987say ("ERR " + cmd + ": not supported by sfnx" ); 988continue ; 989 } 990const bool batch = cmd [0 ]== 'B' ,images = cmd .back ()== 'I' ; 991if (batch && a .batch < 2 ) { 992say ("ERR " + cmd + ": sfnx runs without --batch" ); 993continue ; 994 } 995if (images && !a .vision ) { 996say ("ERR this engine was started without --vision" ); 997continue ; 998 } 999GenReq r ; 1000try { 1001r = parse_gen (line ,m .vocab , (int )m .ple_image ,batch ,images ); 1002if ((long )r .ids .size ()+ r .max_new + 8 > a .max_ctx )throw std::runtime_error (cmd + ": prompt + max_new exceed the context" ); 1003r .seq = seq ; 1004 }catch (const std::exception & ex ) { 1005say (std::string ("ERR " )+ ex .what ()); 1006continue ; 1007 } 1008if (batch )admit (r ); 1009else solo (r ); 1010// FNX_ADMIT_INTERLEAVE=1 (default off): a request read takes the engine for 0.2-0.5 s even for a few tokens; the slots already decoding run one window between two 1011// admissions instead of waiting for all of them (8 users that start together: the first ones decode while the last are read) 1012if (batch && interleave_ && any_decoding ())decode_step (); 1013 } 1014 } 1015const bool interleave_ = fnx::env_int ("FNX_ADMIT_INTERLEAVE" ,0 )!= 0 ;// off: measured no gain on 4 x R9700 (RESULTS-HIP.md section 8) 1016}; 1017 1018// FNX_ROUTE_COUNT and FNX_ROUTE_TRACE (measurements) each need their file's path: checked before the model loads, not 1019// at the first reply 1020void check_route_env () { 1021if (fnx::env_flag ("FNX_ROUTE_COUNT" )&& !std::getenv ("FNX_ROUTE_FILE" ))throw std::runtime_error ("FNX_ROUTE_COUNT needs FNX_ROUTE_FILE" ); 1022if (fnx::env_int ("FNX_ROUTE_TRACE" ,0 )> 0 && !std::getenv ("FNX_ROUTE_TRACE_FILE" )) 1023throw std::runtime_error ("FNX_ROUTE_TRACE needs FNX_ROUTE_TRACE_FILE" ); 1024} 1025 1026// SFNX_TEST_PROMPT replaces every text request's tokens: it starts only beside SFNX_TEST_PROMPT_CONFIRM=1, so the one 1027// variable leaking into a service's environment cannot turn every answer into the test prompt's 1028void check_test_prompt () { 1029const char * tp = std::getenv ("SFNX_TEST_PROMPT" ); 1030if (!tp )return ; 1031const char * ok = std::getenv ("SFNX_TEST_PROMPT_CONFIRM" ); 1032if (!ok || std::string (ok )!= "1" ) 1033throw std::runtime_error (std::string ("SFNX_TEST_PROMPT=" )+ tp + " replaces every text request's tokens (measurements only): set " 1034"SFNX_TEST_PROMPT_CONFIRM=1 beside it, or unset it" ); 1035 std::fprintf (stderr ,"sfnx: SFNX_TEST_PROMPT: every text request reads %s instead of its own tokens\n" ,tp ); 1036} 1037 1038float half_bits_to_float (uint16_t h ) { 1039const uint32_t sign = (uint32_t ) (h & 0x8000u ) <<16 ; 1040uint32_t e = (h >>10 )& 0x1f ,mant = h & 0x3ffu ,bits ; 1041if (e == 0 ) { 1042if (mant == 0 )bits = sign ; 1043else {// subnormal 1044e = 127 - 15 + 1 ; 1045while (!(mant & 0x400u ))mant <<=1 ,-- e ; 1046bits = sign | (e <<23 ) | ((mant & 0x3ffu ) <<13 ); 1047 } 1048 }else if (e == 31 )bits = sign |0x7f800000u | (mant <<13 ); 1049else bits = sign | ((e + 127 - 15 ) <<23 ) | (mant <<13 ); 1050float f ; 1051 std::memcpy (& f ,& bits ,4 ); 1052return f ; 1053} 1054 1055// DFlash2 (src/df2_bridge.hpp): the pack, the draft vocabulary's rows of output.weight and the embedding of a token (the model's Q8_0 rows, dequantized as 1056// Engine::embed_token does) handed to the bridge, which puts them on the first card 1057void load_dflash2 (fnx::df2::Bridge & br ,const fnx::Model & m ,const Args & a ) { 1058 std::vector < int32_t > vocab ; 1059 { 1060 std::FILE * f = std::fopen (a .draft_vocab .c_str (),"rb" ); 1061if (!f )throw std::runtime_error ("dflash2: cannot open the draft vocabulary " + a .draft_vocab ); 1062int32_t id ; 1063while (std::fread (& id ,4 ,1 ,f )== 1 )vocab .push_back (id ); 1064 std::fclose (f ); 1065if (vocab .empty ())throw std::runtime_error ("dflash2: " + a .draft_vocab + " is empty" ); 1066for (int32_t t :vocab ) 1067if (t < 0 || t >=m .vocab )throw std::runtime_error ("dflash2: " + a .draft_vocab + " holds a token outside the vocabulary" ); 1068 } 1069const fnx::Tensor * out = m .g .find ("output.weight" ); 1070if (!out || out -> type != fnx::T_Q8_0 )throw std::runtime_error ("dflash2: output.weight is not Q8_0" ); 1071const size_t rb = out -> row_bytes (); 1072 std::vector < uint8_t > rows (vocab .size ()* rb ); 1073for (size_t i = 0 ;i < vocab .size ();++ i ) std::memcpy (rows .data ()+ i * rb ,out -> data + (size_t )vocab [i ]* rb ,rb ); 1074const fnx::Tensor * te = m .tok_embd ; 1075auto embed = [te ,& m ](int tok ,float * o ) { 1076if (tok < 0 || tok >=m .vocab )throw std::runtime_error ("dflash2: embedding of token " + std::to_string (tok )); 1077const uint8_t * row = te -> data + (size_t )tok * te -> row_bytes (); 1078for (int b = 0 ;b < fnx::N /32 ;++ b ) { 1079uint16_t dh ; 1080 std::memcpy (& dh ,row + b * 34 ,2 ); 1081const float d = half_bits_to_float (dh ); 1082for (int j = 0 ;j < 32 ;++ j )o [b * 32 + j ]= d * (float ) (int8_t )row [b * 34 + 2 + j ]; 1083 } 1084 }; 1085 std::string err ; 1086if (!br .load (a .draft_model ,m .cards [0 ].dev ,a .batch ,vocab ,rows .data (),rb ,8 ,embed ,err ))throw std::runtime_error (err ); 1087 std::fprintf (stderr ,"sfnx: DFlash2 on card 0: %zu draft tokens, %d drafter(s), %.0f MiB of VRAM\n" ,vocab .size (),br .lanes (), (double )br .vram_bytes () /1048576.0 ); 1088} 1089 1090// the engine state after a failure part way is unknown: say why and _exit at once (the front end starts it again). No 1091// destructors: freeing the conversation cache's pinned memory takes minutes, and the stdin reader thread keeps the 1092// process up, while the front end waits for the ERR line or EOF 1093[[noreturn ]]void fail (const std::exception & ex ) { 1094say (std::string ("ERR " )+ ex .what ()); 1095 std::fprintf (stderr ,"sfnx: failed: %s\n" ,ex .what ()); 1096 std::fflush (stdout ); 1097 std::fflush (stderr ); 1098 std::_Exit (1 ); 1099} 1100 1101}// namespace 1102 1103int main (int argc ,char ** argv ) { 1104Args a ; 1105try { 1106a = parse_args (argc ,argv ); 1107check_route_env (); 1108check_test_prompt (); 1109 }catch (const std::exception & e ) { 1110 std::fprintf (stderr ,"sfnx: %s\n" ,e .what ()); 1111return 2 ; 1112 } 1113const auto t_load = std::chrono::steady_clock::now (); 1114// made in place and failed like the rest, so a card or link refused at load ends with its reason too 1115 std::optional < fnx::Model > m ; 1116 std::optional < fnx::Mtp > mtp ; 1117 std::optional < fnx::df2::Bridge > df2 ; 1118 std::optional < fnx::Engine > e ; 1119try { 1120m .emplace (a .gguf .c_str ()); 1121if (a .draft == "dflash2" ) { 1122df2 .emplace (); 1123load_dflash2 (* df2 ,* m ,a );// before the Engine: it sizes its K/V pool from what is left on the cards 1124 }else { 1125mtp .emplace (* m ,a .mtp_dir ,a .draft_vocab ); 1126 } 1127e .emplace (* m ,a .max_ctx ,a .batch ); 1128if (mtp )e -> mtp_attach (* mtp ); 1129else e -> df2_attach (* df2 ); 1130 }catch (const std::exception & ex ) { 1131fail (ex ); 1132 } 1133Input in ; 1134try { 1135Server srv (a ,* m ,* e ,in ); 1136 std::string vfree ;// each card's, "a / b / c" 1137for (const long v :e -> free_vram_mib ())vfree += (vfree .empty () ?"" :" / " )+ std::to_string (v ); 1138 std::fprintf (stderr , 1139"sfnx: loaded in %.1f s, context %d, MTP K=%d, lookup %d, %d slot(s); %d cards, sums between them %s; K/V pool " 1140"(%s) %d positions free; VRAM free %s MiB\n" , 1141 std::chrono::duration < double > (std::chrono::steady_clock::now ()- t_load ).count (),a .max_ctx ,a .K ,a .lookup ,a .batch , 1142 fnx::NCARD , fnx::ring_f32 () ?"fp32" :"fp16" , 1143#if FNX_27B 1144"f16" ,e -> free_pages ()* fnx::S27_PP ,vfree .c_str ()); 1145#else 1146 fnx::kv_q8 () ?"int8" :"f16" ,e -> free_pages ()* fnx::KVP_POS ,vfree .c_str ()); 1147#endif 1148if (fnx::NCARD > 3 ) 1149 std::fprintf (stderr ,"sfnx: %d cards builds and passes the CPU checks but has not been validated on hardware " 1150"(docs/verification.md, \"Other card counts\")\n" , fnx::NCARD ); 1151say ("INFO engine=sfnx version=0.2 spec=" + std::to_string (a .K )+ " conversation_cache_mib=" + std::to_string (a .cache_mib )+ 1152 (a .batch > 1 ?" batch_slots=" + std::to_string (a .batch )+ " slot_cache=1" :"" )); 1153say ("READY " + std::to_string (a .max_ctx )+ " stop" ); 1154 std::thread reader ([& ] {in .run (); }); 1155reader .detach (); 1156try { 1157srv .run (); 1158 }catch (const std::exception & ex ) { 1159fail (ex ); 1160 } 1161 }catch (const std::exception & ex ) { 1162fail (ex ); 1163 } 1164 std::fflush (stdout ); 1165 std::_Exit (0 ); 1166}