okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a46c667cc
main
1#include "strata/core/conversation_snapshot.hpp" 2#include "strata/kernels/kv_q4.hpp" 3#include "conversation_checked.hpp" 4#include "conversation_copy.hpp" 5#include "conversation_trace.hpp" 6#include <cuda_runtime.h> 7 8#include <array> 9#include <chrono> 10#include <cstdio> 11#include <cstdlib> 12#include <cstring> 13#include <future> 14#include <limits> 15#include <memory> 16#include <mutex> 17 18namespace strata::core { 19namespace { 20struct Layout { 21int format ; 22int64_t cells ,pooled_rows ,page_size ; 23size_t data ,scales ,pooled ,value_data ,value_scales ; 24}; 25 26bool valid_extent (const QsaState & st ,int64_t upto , std::string & error ) { 27const int64_t page = strata::kernels::qsa_real_shapes ().page_size ; 28if (upto < 0 || upto > st .max_cells || upto > std::numeric_limits < int64_t > ::max ()- (page - 1 )) { 29error = "conversation snapshot: invalid K/V extent" ; 30return false; 31 } 32return true; 33} 34 35bool layout (const QsaState & st ,const ModelGeometry & g ,int64_t upto ,bool index ,Layout & l , std::string & error ) { 36if (!valid_extent (st ,upto ,error ))return false; 37if (st .kv_hybrid && (st .kv_mode == 2 || st .kv_q4 || st .kv_int8 )) {// a streamed one reads its host copy 38error = "conversation snapshot: hybrid K8V4 cannot be a ring and needs distinct format flags" ; 39return false; 40 } 41const auto s = strata::kernels::qsa_real_shapes (); 42const bool int8_keys = st .kv_int8 || st .kv_hybrid ; 43if (g .n_head_kv <=0 || g .head_dim <=0 || g .head_dim > INT32_MAX || g .idx_key_dim <=0 || 44 (st .kv_q4 && g .head_dim %32 )|| (int8_keys && !st .kv_q4 && g .head_dim %64 )) { 45error = "conversation snapshot: invalid K/V geometry" ; 46return false; 47 } 48const int64_t cells = ((upto + s .page_size - 1 ) /s .page_size )* s .page_size ; 49const size_t per = st .kv_q4 ? (size_t ) strata::kernels::kv_q4_bytes_per_head ((int )g .head_dim ) 50 : (size_t )g .head_dim * (int8_keys ?1 :2 ); 51// Include the moving spare row, not only completed blocks. The checkpoint 52// restore reconstructs that row when rewinding to an earlier prefix. 53const int64_t pooled = index && upto > 0 ?upto /s .idx_block + 1 :0 ; 54// Format 3 identifies snapshot K8V4 only; never pass it to the block movers. Rotated INT8 K/V (#293, 55// STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a 56// snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse. 57// (Q4_0 is always rotated: nothing to tell apart; without the rotation the format is the one it always was.) 58const int rotated = st .kv_rot && !st .kv_q4 && !st .kv_hybrid ?16 :0 ; 59l = {(st .kv_hybrid ?3 :qsa_kv_format (st ))+ rotated ,cells ,pooled ,s .page_size ,0 ,0 ,0 ,0 ,0 }; 60using conversation_detail::product ; 61if (!product (l .data , {(uint64_t )cells , (uint64_t )g .n_head_kv ,per })|| 62 !product (l .scales , {(uint64_t )cells , (uint64_t )g .n_head_kv , 63int8_keys && !st .kv_q4 ? (uint64_t ) (g .head_dim /64 )* 2 :0 })|| 64 !product (l .pooled , {(uint64_t )pooled , (uint64_t )g .idx_key_dim ,sizeof (float )})) { 65error = "conversation snapshot: K/V byte count overflow" ; 66return false; 67 } 68l .value_data = l .data ; 69l .value_scales = l .scales ; 70if (st .kv_hybrid ) { 71if (!product (l .value_data , {(uint64_t )cells , (uint64_t )g .n_head_kv , 72 (uint64_t ) strata::kernels::kv_q4_bytes_per_head ((int )g .head_dim )})) { 73error = "conversation snapshot: hybrid V byte count overflow" ; 74return false; 75 } 76l .value_scales = 0 ; 77 } 78return true; 79} 80 81std::array < void * ,5 > pools (const QsaState & st ,bool resident = false) { 82const bool host = st .kv_mode != 0 && !resident ; 83if (st .kv_hybrid ) 84return {host ?st .host .k_q :st .k_q ,host ?st .host .v_q4 :st .v_q4 ,host ?st .host .k_scale :st .k_scale , 85nullptr ,st .idx_pooled }; 86if (st .kv_q4 ) 87return {host ?st .host .k_q4 :st .k_q4 ,host ?st .host .v_q4 :st .v_q4 ,nullptr ,nullptr ,st .idx_pooled }; 88if (st .kv_int8 ) 89return {host ?st .host .k_q :st .k_q ,host ?st .host .v_q :st .v_q , 90host ?st .host .k_scale :st .k_scale ,host ?st .host .v_scale :st .v_scale ,st .idx_pooled }; 91return {host ?st .host .k_pool :st .k_pool ,host ?st .host .v_pool :st .v_pool ,nullptr ,nullptr ,st .idx_pooled }; 92} 93 94bool valid (const QsaState & st ,const Layout & l ,int64_t upto , std::string & error ) { 95if (upto < 0 || upto > st .max_cells || st .n_pages < 0 || l .cells /l .page_size > st .n_pages || 96st .kv_mode < 0 || st .kv_mode > 2 || st .n_slots <=0 || 97 (st .kv_mode == 0 && st .n_slots < st .n_pages )|| 98l .pooled_rows > st .idx_pooled_rows || (st .kv_mode != 0 && !st .host .present ())) { 99error = "conversation snapshot: invalid K/V extent or missing authoritative host pool" ; 100return false; 101 } 102if (st .kv_mode == 1 ) { 103const auto & m = st .map ; 104if (m .n_blocks != st .n_pages || m .n_slots != st .n_slots || !m .page_table || !m .slot_block || 105 !m .slot_stamp || !m .slot_ref || !m .ctl || !m .miss_block || !m .miss_slot ) { 106error = "conversation snapshot: invalid streaming map" ; 107return false; 108 } 109 } 110if (st .kv_mode == 2 && (!st .page_table || 111 (st .kv_q4 ? !st .k_q4 || !st .v_q4 :st .kv_int8 ? !st .k_q || !st .v_q || !st .k_scale || !st .v_scale 112 : !st .k_pool || !st .v_pool ))) { 113error = "conversation snapshot: invalid draft ring" ; 114return false; 115 } 116return true; 117} 118 119// STRATA_PARK_VRAM_MIB=N (with STRATA_PARK_ASYNC): a park also keeps the whole K/V of its image in VRAM, in a slot 120// of its own, while the slots' total stays within N MiB; a restore of that image copies from the slot device to 121// device (~1 ms) instead of from the host buffers over PCIe, and needs no wait for the background copy. A slot is 122// released with the image or its K/V layers (their tokens), or all at once under VRAM pressure 123// (conversation_park_vram_release_all). Host thread only; the background copy only reads a slot's bytes, and every 124// reuse or free of one comes after a join (conversation_park_async_begin, release_all). 125struct VramKvSlot { 126void * p = nullptr ; 127size_t cap = 0 ,used = 0 ; 128uint64_t tag = 0 ;// 0: free (kept for reuse by size) 129int dev = -1 ; 130struct Part {uint64_t tag ;size_t part ,offset ,bytes ; };// one layer's part (k, v, k_scale, v_scale, pooled) 131 std::vector < Part > parts ; 132}; 133struct VramKv { 134 std::vector < std::unique_ptr < VramKvSlot >> slots ; 135uint64_t next_tag = 1 ;// slot and layer tags, never reused 136}; 137VramKv & vram_kv () {static VramKv v ;return v ; } 138size_t park_vram_budget () { 139static const size_t b = [] { 140const char * v = std::getenv ("STRATA_PARK_VRAM_MIB" ); 141const long long mib = v != nullptr ? std::atoll (v ) :0 ; 142return mib > 0 ? (size_t )mib <<20 : (size_t )0 ; 143 }(); 144return b ; 145} 146bool park_trace () {static const bool on = std::getenv ("STRATA_PARK_TRACE" )!= nullptr ;return on ; } 147void vram_kv_free (VramKvSlot & s ) { 148int cur = s .dev ; 149 (void )cudaGetDevice (& cur ); 150if (cur != s .dev ) (void )cudaSetDevice (s .dev ); 151 (void )cudaFree (s .p ); 152if (cur != s .dev ) (void )cudaSetDevice (cur ); 153 (void )cudaGetLastError (); 154s .p = nullptr ;s .cap = 0 ; 155} 156void vram_kv_release (VramKvSlot & s ) {s .tag = 0 ;s .used = 0 ;s .parts .clear (); }// free, kept for reuse 157// A slot of `need` bytes on `dev`: the best-fitting free one, else (the free ones freed first) a new one, rounded up 158// to 64 MiB so a growing conversation's next parks reuse it, while the slots' total stays within the budget and 159// 1.5 GB of VRAM stays free beside it. nullptr, with `why`, otherwise. 160VramKvSlot * vram_kv_take (size_t need ,int dev ,const char *& why ) { 161VramKv & v = vram_kv (); 162const size_t budget = park_vram_budget (); 163if (budget == 0 ) {why = "off" ;return nullptr ; } 164VramKvSlot * best = nullptr ; 165for (auto & s :v .slots ) 166if (s -> tag == 0 && s -> dev == dev && s -> cap >=need && (best == nullptr || s -> cap < best -> cap ))best = s .get (); 167if (best == nullptr ) { 168size_t held = 0 ; 169for (size_t i = 0 ;i < v .slots .size ();) { 170if (v .slots [i ]-> tag != 0 ) {held += v .slots [i ]-> cap ;++ i ;continue ; } 171vram_kv_free (* v .slots [i ]); 172v .slots .erase (v .slots .begin ()+ (std::ptrdiff_t )i ); 173 } 174const size_t want = (need + ((size_t )64 <<20 )- 1 )& ~(((size_t )64 <<20 )- 1 ); 175if (held > budget || want > budget - held ) {why = "budget" ;return nullptr ; } 176size_t fr = 0 ,tot = 0 ; 177if (cudaMemGetInfo (& fr ,& tot )!= cudaSuccess || fr < want + ((size_t )3 <<29 )) { 178 (void )cudaGetLastError (); 179why = "vram" ; 180return nullptr ; 181 } 182void * p = nullptr ; 183if (cudaMalloc (& p ,want )!= cudaSuccess ) { (void )cudaGetLastError ();why = "cudaMalloc" ;return nullptr ; } 184auto s = std::make_unique < VramKvSlot > (); 185s -> p = p ;s -> cap = want ;s -> dev = dev ; 186best = s .get (); 187v .slots .push_back (std::move (s )); 188 } 189best -> tag = v .next_tag ++ ; 190best -> used = 0 ; 191best -> parts .clear (); 192return best ; 193} 194// The live slot on the current device holding parts under `tag` (nullptr: none, or tag 0) 195const VramKvSlot * vram_kv_find (uint64_t tag ) { 196if (tag == 0 )return nullptr ; 197int dev = 0 ; 198if (cudaGetDevice (& dev )!= cudaSuccess ) { (void )cudaGetLastError ();return nullptr ; } 199for (const auto & s :vram_kv ().slots ) { 200if (s -> tag == 0 || s -> dev != dev )continue ; 201for (const auto & p :s -> parts ) 202if (p .tag == tag )return s .get (); 203 } 204return nullptr ; 205} 206// Whether the slot holds, under `tag`, at least sizes[i] bytes of every part i that has any; `at` gets the offsets 207bool vram_kv_locate (const VramKvSlot & s ,uint64_t tag ,const std::array < size_t ,5 >& sizes , std::array < size_t ,5 >& at ) { 208 std::array < bool ,5 > have {}; 209for (const auto & p :s .parts ) 210if (p .tag == tag && p .part < at .size ()&& p .bytes >=sizes [p .part ]) {have [p .part ]= true;at [p .part ]= p .offset ; } 211for (size_t i = 0 ;i < sizes .size ();++ i ) 212if (sizes [i ]> 0 && !have [i ])return false; 213return true; 214} 215 216struct ParkAsync { 217 std::mutex mu ; 218 std::future < cudaError_t > pending ; 219struct Item {uint8_t * dst ;size_t n ,at ; }; 220 std::vector < Item > items ; 221uint8_t * stage = nullptr ; 222size_t cap = 0 ,used = 0 ; 223void * host [2 ]= {nullptr ,nullptr };// pinned, 4 MiB each 224cudaStream_t stream = nullptr ; 225int dev = -1 ; 226bool active = false; 227VramKvSlot * slot = nullptr ;// STRATA_PARK_VRAM_MIB: the begun park's slot (the stage is not used then) 228uint64_t slot_tag = 0 ;// its tag, kept past launch for the image's and its layers' tokens 229}; 230ParkAsync & park_async () {static ParkAsync a ;return a ; } 231constexpr size_t kParkPiece = (size_t )4 <<20 ; 232bool park_async_on () { 233#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 )|| defined(STRATA_GPU_METAL ) 234return false; 235#else 236static const bool on = [] {const char * v = std::getenv ("STRATA_PARK_ASYNC" );return v != nullptr && v [0 ]== '1' ; }(); 237return on ; 238#endif 239} 240bool on_device (const void * p ) { 241#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 )|| defined(STRATA_GPU_METAL ) 242 (void )p ;// (no pointer-attribute query in the shims: the slot takes no part, as when the query fails) 243return false; 244#else 245cudaPointerAttributes at {}; 246if (cudaPointerGetAttributes (& at ,p )!= cudaSuccess ) {cudaGetLastError ();return false; } 247return at .type == cudaMemoryTypeDevice ; 248#endif 249} 250// STRATA_PARK_TRACE: where conversation_kv_save's time goes since the park's begin (ms): the pointer-attribute 251// queries, the host buffer resizes and the copies (into the stage, or the synchronous ones). Read by the park trace. 252struct KvSaveTrace {double attrs = 0 ,resize = 0 ,copy = 0 ;long resize_faults = 0 ; }; 253KvSaveTrace & kv_save_trace () {static KvSaveTrace t ;return t ; } 254bool park_trace_on () { 255static const bool on = std::getenv ("STRATA_PARK_TRACE" )!= nullptr ; 256return on ; 257} 258 259bool transfer (void * dst ,const void * src ,size_t n , std::string & error ) { 260if (!n )return true; 261if (!src || !dst ) {error = "conversation snapshot: missing state buffer" ;return false; } 262// Default handles both device allocations and device-mapped host pool aliases. 263const cudaError_t e = conversation_detail::copy_nonblocking (dst ,src ,n ); 264if (e == cudaSuccess )return true; 265error = std::string ("conversation snapshot copy: " )+ cudaGetErrorString (e ); 266return false; 267} 268}// namespace 269 270bool conversation_kv_capture_bytes (const ConversationKv & image ,const QsaState & st ,const ModelGeometry & g , 271int64_t upto ,bool index ,size_t & bytes , std::string & error ) { 272Layout l {}; 273if (!layout (st ,g ,upto ,index ,l ,error )|| !valid (st ,l ,upto ,error ))return false; 274const std::array < size_t ,5 > sizes = {l .data ,l .value_data ,l .scales ,l .value_scales ,l .pooled }; 275const std::array < const ConversationBuffer * ,5 > buffers = {& image .k ,& image .v ,& image .k_scale ,& image .v_scale ,& image .pooled }; 276bytes = 0 ; 277for (size_t i = 0 ;i < buffers .size ();++ i ) { 278const size_t n = buffers [i ]-> allocation_peak (sizes [i ]); 279if (n == SIZE_MAX || !conversation_detail::add (bytes ,n )) { 280error = "conversation snapshot: segmented K/V allocation overflow" ; 281return false; 282 } 283 } 284return true; 285} 286 287size_t conversation_kv_bytes (const QsaState & st ,const ModelGeometry & g ,int64_t upto ,bool index ) { 288size_t bytes = 0 ; 289 std::string error ; 290return conversation_kv_capture_bytes ({},st ,g ,upto ,index ,bytes ,error ) ?bytes :0 ; 291} 292 293bool conversation_kv_save (ConversationKv & image ,const QsaState & st ,const ModelGeometry & g , 294int64_t upto ,bool index , std::string & error , 295int64_t unchanged_tokens ,size_t * reused_bytes ) { 296Layout l {}; 297if (!layout (st ,g ,upto ,index ,l ,error ))return false; 298if (!valid (st ,l ,upto ,error ))return false; 299if (unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image .cells ) { 300error = "conversation snapshot: invalid unchanged prefix" ; 301return false; 302 } 303const int64_t whole_cells = (unchanged_tokens /l .page_size )* l .page_size ; 304image .format = l .format ; 305image .cells = l .cells ; 306image .heads = g .n_head_kv ; 307image .head_dim = g .head_dim ; 308image .page_size = l .page_size ; 309image .pooled_rows = l .pooled_rows ; 310image .idx_dim = g .idx_key_dim ; 311const auto src = pools (st ); 312const std::array < size_t ,5 > sizes = {l .data ,l .value_data ,l .scales ,l .value_scales ,l .pooled }; 313const std::array < ConversationBuffer * ,5 > dst = {& image .k ,& image .v ,& image .k_scale ,& image .v_scale ,& image .pooled }; 314// STRATA_PARK_VRAM_MIB: this layer's parts go into the park's slot under a fresh tag (0: no slot this park) 315image .dev_tag = park_async ().slot != nullptr ?vram_kv ().next_tag ++ :0 ; 316for (size_t i = 0 ;i < dst .size ();++ i ) { 317// Recopy the partial page and the indexer's moving spare row. Completed 318// pages/rows strictly before the first rewritten token remain identical. 319const size_t keep = i == 4 ? (index ?size_t (unchanged_tokens / strata::kernels::qsa_real_shapes ().idx_block )* g .idx_key_dim * 4 :0 ) 320 :l .cells ? (sizes [i ] /size_t (l .cells ))* size_t (whole_cells ) :0 ; 321if (keep > dst [i ]-> size ()) {error = "conversation snapshot: missing reusable prefix" ;return false; } 322 {// STRATA_PARK_VRAM_MIB: with a slot, the whole part goes device to device into it (a restore of this image 323// reads it from there) and the host buffer gets only the bytes past the kept prefix, read from the slot on 324// the background thread; a part the slot cannot take is copied synchronously - never through the stage, 325// whose offsets launch would read from the slot 326ParkAsync & a = park_async (); 327if (a .slot != nullptr ) { 328VramKvSlot & s = * a .slot ; 329const bool fits = src [i ]!= nullptr && sizes [i ]> 0 && s .used + sizes [i ] <=s .cap && 330 (st .kv_mode == 0 || on_device (src [i ]));// (kv_mode 0: the pools are device memory) 331if (fits ) { 332const size_t at0 = s .used ; 333const cudaError_t e = conversation_detail::copy_nonblocking (static_cast < uint8_t *> (s .p )+ at0 ,src [i ],sizes [i ], true); 334if (e != cudaSuccess ) {error = std::string ("conversation snapshot slot copy: " )+ cudaGetErrorString (e );return false; } 335s .parts .push_back ({image .dev_tag ,i ,at0 ,sizes [i ]}); 336s .used += sizes [i ]; 337dst [i ]-> resize_for_overwrite (sizes [i ]); 338if (!dst [i ]-> visit (keep ,sizes [i ]- keep , [& ](uint8_t * p ,size_t n ,size_t at ) { 339a .items .push_back ({p ,n ,at0 + at }); 340return true; 341 }))return false; 342 }else { 343dst [i ]-> resize (sizes [i ]); 344if (!dst [i ]-> visit (keep ,sizes [i ]- keep , [& ](uint8_t * p ,size_t n ,size_t at ) { 345return transfer (p ,src [i ] ?static_cast < const uint8_t *> (src [i ])+ at :nullptr ,n ,error ); 346 }))return false; 347 } 348if (reused_bytes )* reused_bytes += keep ; 349continue ; 350 } 351 } 352// STRATA_PARK_ASYNC: device bytes go to the VRAM stage now and into the buffer on the background thread 353ParkAsync & a = park_async (); 354const bool trace = park_trace_on (); 355auto tick = [trace ] {return trace ? std::chrono::steady_clock::now () : std::chrono::steady_clock::time_point {}; }; 356const auto t0 = tick (); 357// (kv_mode 0: the pools are device memory by construction, so no pointer-attribute query) 358const bool staged = a .active && src [i ]!= nullptr && sizes [i ]> keep && a .used + (sizes [i ]- keep ) <=a .cap && 359 (st .kv_mode == 0 || on_device (src [i ])); 360const auto t1 = tick (); 361const long rf0 = trace ? conversation_trace::thread_minflt () :0 ; 362if (staged )dst [i ]-> resize_for_overwrite (sizes [i ]); 363else dst [i ]-> resize (sizes [i ]); 364const auto t2 = tick (); 365if (trace )kv_save_trace ().resize_faults += conversation_trace::thread_minflt ()- rf0 ; 366const bool copied = dst [i ]-> visit (keep ,sizes [i ]- keep , [& ](uint8_t * p ,size_t n ,size_t at ) { 367const uint8_t * s = src [i ] ?static_cast < const uint8_t *> (src [i ])+ at :nullptr ; 368if (!staged )return transfer (p ,s ,n ,error ); 369const cudaError_t e = conversation_detail::copy_nonblocking (a .stage + a .used ,s ,n , true); 370if (e != cudaSuccess ) {error = std::string ("conversation snapshot stage copy: " )+ cudaGetErrorString (e );return false; } 371a .items .push_back ({p ,n ,a .used }); 372a .used += n ; 373return true; 374 }); 375if (trace ) { 376auto ms = [](std::chrono::steady_clock::time_point x , std::chrono::steady_clock::time_point y ) { 377return std::chrono::duration < double , std::milli > (y - x ).count (); }; 378KvSaveTrace & t = kv_save_trace (); 379t .attrs += ms (t0 ,t1 );t .resize += ms (t1 ,t2 );t .copy += ms (t2 ,tick ()); 380 } 381if (!copied )return false; 382if (reused_bytes )* reused_bytes += keep ; 383 } 384return true; 385} 386 387bool conversation_kv_validate (const ConversationKv & image ,const QsaState & st ,const ModelGeometry & g , 388int64_t upto ,bool index , std::string & error ) { 389Layout l {}; 390if (!layout (st ,g ,upto ,index ,l ,error ))return false; 391if (!valid (st ,l ,upto ,error ))return false; 392const std::array < size_t ,5 > sizes = {l .data ,l .value_data ,l .scales ,l .value_scales ,l .pooled }; 393const std::array < const ConversationBuffer * ,5 > src = {& image .k ,& image .v ,& image .k_scale ,& image .v_scale ,& image .pooled }; 394if (image .format != l .format || image .cells != l .cells || image .heads != g .n_head_kv || 395image .head_dim != g .head_dim || image .page_size != l .page_size || image .pooled_rows != l .pooled_rows || 396image .idx_dim != g .idx_key_dim ) { 397error = "conversation snapshot: incompatible K/V geometry" ; 398return false; 399 } 400for (size_t i = 0 ;i < src .size ();++ i ) 401if (src [i ]-> size ()!= sizes [i ]) {error = "conversation snapshot: invalid K/V payload size" ;return false; } 402const auto dst = pools (st ); 403for (size_t i = 0 ;i < src .size ();++ i ) 404if (sizes [i ]&& !dst [i ]) {error = "conversation snapshot: missing target state buffer" ;return false; } 405return true; 406} 407 408namespace { 409// After the authoritative pools were rewritten: the VRAM slots of a streamed state still hold the outgoing 410// conversation, so resolve must refill them before any attention reads (shared by restore and direct copy). 411bool refresh_residency (const QsaState & st ,const ModelGeometry & g ,int64_t upto , std::string & error ) { 412if (st .kv_mode == 1 ) strata::kernels::kv_stream_reset (st .map ,nullptr ); 413if (st .kv_mode == 2 && upto > 0 ) { 414auto shapes = strata::kernels::qsa_real_shapes (); 415shapes .n_head_kv = g .n_head_kv ;shapes .head_dim = g .head_dim ; 416const int64_t end = (upto + shapes .page_size - 1 ) /shapes .page_size ; 417 strata::kernels::kv_ring_restore (qsa_attn_pools (st ),st .host ,qsa_kv_format (st ), 418 std::max < int64_t > (0 ,end - st .n_slots ),end ,st .n_slots ,shapes ,nullptr ); 419 } 420const auto status = cudaGetLastError (); 421if (status == cudaSuccess )return true; 422error = std::string ("conversation snapshot residency restore: " )+ cudaGetErrorString (status ); 423return false; 424} 425}// namespace 426 427bool conversation_kv_copy (const QsaState & from ,const QsaState & to ,const ModelGeometry & g , 428int64_t upto ,bool index , std::string & error ,bool queued ) { 429Layout lf {},lt {}; 430if (!layout (from ,g ,upto ,index ,lf ,error )|| !valid (from ,lf ,upto ,error )|| 431 !layout (to ,g ,upto ,index ,lt ,error )|| !valid (to ,lt ,upto ,error ))return false; 432if (lf .format != lt .format || lf .cells != lt .cells || lf .page_size != lt .page_size || 433lf .pooled_rows != lt .pooled_rows || lf .data != lt .data || lf .value_data != lt .value_data || 434lf .scales != lt .scales || lf .value_scales != lt .value_scales || lf .pooled != lt .pooled ) { 435error = "conversation snapshot: direct K/V copy between different layouts" ; 436return false; 437 } 438// The same bytes conversation_kv_save + conversation_kv_restore move, without the host image: each part 439// straight from the source's authoritative pool into the target's (device or mapped host memory), through the 440// private non-blocking stream the other snapshot copies use (complete on return, before the residency refresh). 441// `queued`: the copies are only queued, and a streamed state's refresh waits for them on the device (an event). 442const auto src = pools (from ); 443const auto dst = pools (to ); 444const std::array < size_t ,5 > sizes = {lf .data ,lf .value_data ,lf .scales ,lf .value_scales ,lf .pooled }; 445for (size_t i = 0 ;i < sizes .size ();++ i ) { 446if (!sizes [i ])continue ; 447if (!src [i ]|| !dst [i ]) {error = "conversation snapshot: missing state buffer" ;return false; } 448const cudaError_t e = conversation_detail::copy_nonblocking (dst [i ],src [i ],sizes [i ],queued ); 449if (e != cudaSuccess ) {error = std::string ("conversation snapshot direct copy: " )+ cudaGetErrorString (e );return false; } 450 } 451if (queued && to .kv_mode != 0 ) { 452const cudaError_t e = conversation_detail::order_after_queued (); 453if (e != cudaSuccess ) {error = std::string ("conversation snapshot direct copy: " )+ cudaGetErrorString (e );return false; } 454 } 455return refresh_residency (to ,g ,upto ,error ); 456} 457 458bool conversation_kv_restore (const ConversationKv & image ,const QsaState & st ,const ModelGeometry & g , 459int64_t upto ,bool index , std::string & error ) { 460// STRATA_PARK_VRAM_MIB: from the image's VRAM slot when it holds every part (no host buffer is read: no join) 461const VramKvSlot * slot = vram_kv_find (image .dev_tag ); 462if (slot == nullptr )conversation_park_join (); 463if (!conversation_kv_validate (image ,st ,g ,upto ,index ,error ))return false; 464const std::array < const ConversationBuffer * ,5 > src = {& image .k ,& image .v ,& image .k_scale ,& image .v_scale ,& image .pooled }; 465const auto dst = pools (st ); 466 std::array < size_t ,5 > sizes {},off {}; 467for (size_t i = 0 ;i < src .size ();++ i )sizes [i ]= src [i ]-> size (); 468if (slot != nullptr && !vram_kv_locate (* slot ,image .dev_tag ,sizes ,off )) {slot = nullptr ;conversation_park_join (); } 469if (slot != nullptr ) { 470for (size_t i = 0 ;i < src .size ();++ i ) 471if (!transfer (dst [i ],static_cast < const uint8_t *> (slot -> p )+ off [i ],sizes [i ],error ))return false; 472return refresh_residency (st ,g ,upto ,error ); 473 } 474for (size_t i = 0 ;i < src .size ();++ i ) 475if (!src [i ]-> visit (0 ,src [i ]-> size (), [& ](const uint8_t * p ,size_t n ,size_t at ) { 476return transfer (static_cast < uint8_t *> (dst [i ])+ at ,p ,n ,error ); 477 }))return false; 478return refresh_residency (st ,g ,upto ,error ); 479} 480 481bool conversation_kv_restore_prefix (const ConversationKv & image ,const QsaState & st ,const ModelGeometry & g , 482int64_t captured ,int64_t upto ,bool index , std::string & error ) { 483const VramKvSlot * slot = vram_kv_find (image .dev_tag );// (STRATA_PARK_VRAM_MIB, as in conversation_kv_restore) 484if (slot == nullptr )conversation_park_join (); 485if (upto < 0 || upto > captured ) { 486error = "conversation snapshot: prefix beyond the captured K/V" ; 487return false; 488 } 489if (!conversation_kv_validate (image ,st ,g ,captured ,index ,error ))return false; 490Layout l {};// the prefix's extent; validation above checked the image against the captured one 491if (!layout (st ,g ,upto ,index ,l ,error )|| !valid (st ,l ,upto ,error ))return false; 492const std::array < size_t ,5 > sizes = {l .data ,l .value_data ,l .scales ,l .value_scales ,l .pooled }; 493const std::array < const ConversationBuffer * ,5 > src = {& image .k ,& image .v ,& image .k_scale ,& image .v_scale ,& image .pooled }; 494for (size_t i = 0 ;i < src .size ();++ i ) 495if (sizes [i ]> src [i ]-> size ()) {error = "conversation snapshot: prefix beyond the K/V payload" ;return false; } 496const auto dst = pools (st ); 497// STRATA_PARK_VRAM_MIB: the prefix is the leading bytes of each part in the slot too 498 std::array < size_t ,5 > off {}; 499if (slot != nullptr && !vram_kv_locate (* slot ,image .dev_tag ,sizes ,off )) {slot = nullptr ;conversation_park_join (); } 500if (slot != nullptr ) { 501for (size_t i = 0 ;i < src .size ();++ i ) 502if (!transfer (dst [i ],static_cast < const uint8_t *> (slot -> p )+ off [i ],sizes [i ],error ))return false; 503return refresh_residency (st ,g ,upto ,error ); 504 } 505for (size_t i = 0 ;i < src .size ();++ i ) 506if (!src [i ]-> visit (0 ,sizes [i ], [& ](const uint8_t * p ,size_t n ,size_t at ) { 507return transfer (static_cast < uint8_t *> (dst [i ])+ at ,p ,n ,error ); 508 }))return false; 509return refresh_residency (st ,g ,upto ,error ); 510} 511 512bool conversation_kv_part_sizes (const QsaState & st ,const ModelGeometry & g ,int64_t upto ,bool index , 513 std::array < uint64_t ,5 >& sizes , std::string & error ) { 514Layout l {}; 515if (!layout (st ,g ,upto ,index ,l ,error ))return false; 516sizes = {l .data ,l .value_data ,l .scales ,l .value_scales ,l .pooled }; 517return true; 518} 519 520bool conversation_kv_source (SessionKvSource & out ,const QsaState & st ,const ModelGeometry & g , 521int64_t upto ,bool index , std::string & error ) { 522Layout l {}; 523if (!layout (st ,g ,upto ,index ,l ,error )|| !valid (st ,l ,upto ,error ))return false; 524SessionKvSource s ; 525s .format = l .format ;s .cells = l .cells ;s .heads = g .n_head_kv ;s .head_dim = g .head_dim ; 526s .page_size = l .page_size ;s .pooled_rows = l .pooled_rows ;s .idx_dim = g .idx_key_dim ; 527s .sizes = {l .data ,l .value_data ,l .scales ,l .value_scales ,l .pooled }; 528const auto src = pools (st ); 529const auto sizes = s .sizes ; 530auto why = std::make_shared < std::string > (); 531s .read = [src ,sizes ,why ](size_t part ,size_t offset ,void * dst ,size_t n ) { 532if (part >=5 || offset > sizes [part ]|| n > sizes [part ]- offset ) {* why = "K/V read out of range" ;return false; } 533return transfer (dst ,src [part ] ?static_cast < const uint8_t *> (src [part ])+ offset :nullptr ,n ,* why ); 534 }; 535s .error = [why ] {return * why ; }; 536out = std::move (s ); 537return true; 538} 539 540bool conversation_kv_verify (const ConversationKv & image ,const QsaState & st ,const ModelGeometry & g , 541int64_t upto ,bool index ,uint64_t & fingerprint , std::string & error ) { 542conversation_park_join (); 543if (!conversation_kv_validate (image ,st ,g ,upto ,index ,error ))return false; 544 std::array < uint8_t ,65536 > buffer ; 545uint64_t hash = 1469598103934665603ull ; 546auto compare = [& ](const void * device ,const uint8_t * expected ,size_t bytes ,bool include_hash ) { 547for (size_t offset = 0 ;offset < bytes ;) { 548const size_t n = std::min (buffer .size (),bytes - offset ); 549if (!transfer (buffer .data (),static_cast < const uint8_t *> (device )+ offset ,n ,error ))return false; 550if (std::memcmp (buffer .data (),expected + offset ,n )!= 0 ) { 551error = "conversation snapshot: restored K/V bytes differ" ; 552return false; 553 } 554if (include_hash )for (size_t i = 0 ;i < n ;++ i ) {hash ^=buffer [i ];hash *=1099511628211ull ; } 555offset += n ; 556 } 557return true; 558 }; 559const std::array < const ConversationBuffer * ,5 > saved = {& image .k ,& image .v ,& image .k_scale ,& image .v_scale ,& image .pooled }; 560const auto authoritative = pools (st ); 561for (size_t i = 0 ;i < saved .size ();++ i ) 562if (!saved [i ]-> visit (0 ,saved [i ]-> size (), [& ](const uint8_t * p ,size_t n ,size_t at ) { 563return compare (static_cast < const uint8_t *> (authoritative [i ])+ at ,p ,n , true); 564 }))return false; 565if (st .kv_mode == 2 && image .cells > 0 ) { 566const auto resident = pools (st , true); 567const int64_t end = image .cells /image .page_size ; 568const int64_t begin = std::max < int64_t > (0 ,end - st .n_slots ); 569for (size_t i = 0 ;i < 4 ;++ i ) { 570if (saved [i ]-> empty ())continue ; 571const size_t page_bytes = saved [i ]-> size () /size_t (end ); 572for (int64_t page = begin ;page < end ;++ page ) 573if (!saved [i ]-> visit (size_t (page )* page_bytes ,page_bytes , 574 [& ](const uint8_t * p ,size_t n ,size_t at ) { 575const size_t offset = size_t (page %st .n_slots )* page_bytes + at - size_t (page )* page_bytes ; 576return compare (static_cast < const uint8_t *> (resident [i ])+ offset ,p ,n , false); 577 }))return false; 578 } 579 } 580fingerprint = hash ; 581return true; 582} 583 584void conversation_park_join () { 585ParkAsync & a = park_async (); 586 std::lock_guard < std::mutex > lk (a .mu ); 587if (a .pending .valid ()) { 588const cudaError_t e = a .pending .get (); 589if (e != cudaSuccess ) std::fprintf (stderr ,"strata: STRATA_PARK_ASYNC: a parked K/V copy failed (%s)\n" ,cudaGetErrorString (e )); 590 } 591} 592 593void conversation_kv_save_trace (double & attrs_ms ,double & resize_ms ,double & copy_ms ) { 594const KvSaveTrace & t = kv_save_trace (); 595attrs_ms = t .attrs ;resize_ms = t .resize ;copy_ms = t .copy ; 596} 597 598long conversation_kv_save_trace_faults () {return kv_save_trace ().resize_faults ; } 599 600bool conversation_park_async_begin (size_t need ) { 601if (park_trace_on ())kv_save_trace ()= {};// (the sums cover this park's saves) 602conversation_park_join ();// (the stage is reused) 603ParkAsync & a = park_async (); 604a .active = false; 605a .items .clear (); 606a .used = 0 ; 607a .slot = nullptr ; 608a .slot_tag = 0 ; 609if (!park_async_on ()|| need == 0 )return false; 610int dev = 0 ; 611if (cudaGetDevice (& dev )!= cudaSuccess ) { (void )cudaGetLastError ();return false; } 612// STRATA_PARK_VRAM_MIB: a slot of the whole K/V instead of the stage, while the budget allows - taken before the 613// stage would be re-allocated, so a growing conversation's park pays no cudaFree (a device sync) when it gets one 614const char * why = "" ; 615a .slot = vram_kv_take (need ,dev ,why ); 616a .slot_tag = a .slot != nullptr ?a .slot -> tag :0 ; 617if (park_trace ()&& park_vram_budget ()!= 0 ) { 618if (a .slot != nullptr ) 619 std::fprintf (stderr ,"strata parktrace: kv slot %zu MB tag %llu\n" ,need >>20 , (unsigned long long )a .slot_tag ); 620else 621 std::fprintf (stderr ,"strata parktrace: kv slot: none (%s)\n" ,why ); 622 } 623if (a .stage != nullptr && ((a .slot == nullptr && a .cap < need )|| a .dev != dev )) { 624const int cur = dev ; 625 (void )cudaSetDevice (a .dev ); (void )cudaFree (a .stage ); (void )cudaSetDevice (cur ); 626a .stage = nullptr ;a .cap = 0 ; 627 } 628if (a .stream != nullptr && a .dev != dev ) { 629const int cur = dev ; 630 (void )cudaSetDevice (a .dev ); (void )cudaStreamDestroy (a .stream ); 631 (void )cudaFreeHost (a .host [0 ]); (void )cudaFreeHost (a .host [1 ]); (void )cudaSetDevice (cur ); 632a .stream = nullptr ;a .host [0 ]= a .host [1 ]= nullptr ; 633 } 634a .dev = dev ; 635if (a .stream == nullptr && 636 (cudaStreamCreateWithFlags (& a .stream ,cudaStreamNonBlocking )!= cudaSuccess || 637cudaMallocHost (& a .host [0 ],kParkPiece )!= cudaSuccess || cudaMallocHost (& a .host [1 ],kParkPiece )!= cudaSuccess )) { 638if (a .host [0 ]) (void )cudaFreeHost (a .host [0 ]); 639if (a .host [1 ]) (void )cudaFreeHost (a .host [1 ]); 640if (a .stream ) (void )cudaStreamDestroy (a .stream ); 641a .stream = nullptr ;a .host [0 ]= a .host [1 ]= nullptr ; 642 (void )cudaGetLastError (); 643if (a .slot != nullptr ) {vram_kv_release (* a .slot );a .slot = nullptr ;a .slot_tag = 0 ; }// (STRATA_PARK_VRAM_MIB) 644return false; 645 } 646if (a .slot != nullptr ) {// STRATA_PARK_VRAM_MIB: the slot stands in for the stage this park 647a .active = true; 648return true; 649 } 650if (a .stage == nullptr ) { 651// rounded up to 64 MiB: the next parks of a growing conversation reuse it instead of re-allocating (a cudaFree 652// synchronizes the device, and the checkpoint DMA is in flight at this point) 653const size_t want = (need + ((size_t )64 <<20 )- 1 )& ~(((size_t )64 <<20 )- 1 ); 654size_t fr = 0 ,tot = 0 ; 655if (cudaMemGetInfo (& fr ,& tot )!= cudaSuccess || fr < want + ((size_t )3 <<29 )|| 656cudaMalloc ((void ** )& a .stage ,want )!= cudaSuccess ) { 657a .stage = nullptr ; 658 (void )cudaGetLastError (); 659return false; 660 } 661a .cap = want ; 662 } 663a .active = true; 664return true; 665} 666 667void conversation_park_async_abandon () { 668ParkAsync & a = park_async (); 669if (!a .active )return ; 670a .active = false; 671a .items .clear (); 672cudaStream_t s = nullptr ; 673if (conversation_detail::private_stream (s )== cudaSuccess ) (void )cudaStreamSynchronize (s );// nothing reads the stage after 674 (void )cudaGetLastError (); 675if (a .slot != nullptr ) {vram_kv_release (* a .slot );a .slot = nullptr ;a .slot_tag = 0 ; }// (STRATA_PARK_VRAM_MIB) 676} 677 678bool conversation_park_async_launch (std::string & error ) { 679ParkAsync & a = park_async (); 680if (!a .active )return true; 681a .active = false; 682cudaStream_t s = nullptr ; 683cudaError_t e = conversation_detail::private_stream (s ); 684if (e == cudaSuccess )e = cudaStreamSynchronize (s );// the device-to-device copies into the stage 685if (e != cudaSuccess ) { 686a .items .clear (); 687if (a .slot != nullptr ) {vram_kv_release (* a .slot );a .slot = nullptr ;a .slot_tag = 0 ; }// (STRATA_PARK_VRAM_MIB) 688error = std::string ("conversation snapshot stage: " )+ cudaGetErrorString (e ); 689return false; 690 } 691// STRATA_PARK_VRAM_MIB: the host copies read the slot; it stays until the image and its K/V layers go (their tokens) 692const uint8_t * stage = a .slot != nullptr ?static_cast < const uint8_t *> (a .slot -> p ) :a .stage ; 693a .slot = nullptr ; 694if (a .items .empty ())return true; 695 std::vector < ParkAsync ::Item > items ; 696items .swap (a .items ); 697void * host [2 ]= {a .host [0 ],a .host [1 ]}; 698cudaStream_t st = a .stream ; 699const int dev = a .dev ; 700 std::lock_guard < std::mutex > lk (a .mu ); 701// two pinned pieces in turn: the next piece's DMA runs while this one is copied into its segment 702a .pending = std::async (std::launch::async , [items = std::move (items ),stage ,host ,st ,dev ] { 703 conversation_detail::background_thread_placement (); 704 (void )cudaSetDevice (dev ); 705cudaEvent_t done [2 ]= {nullptr ,nullptr }; 706cudaError_t e = cudaEventCreateWithFlags (& done [0 ],cudaEventDisableTiming |cudaEventBlockingSync ); 707if (e == cudaSuccess )e = cudaEventCreateWithFlags (& done [1 ],cudaEventDisableTiming |cudaEventBlockingSync ); 708struct Piece {uint8_t * dst ;size_t n ; }; 709Piece held [2 ]= {{nullptr ,0 }, {nullptr ,0 }}; 710int b = 0 ; 711auto land = [& ](int k ) { 712if (held [k ].dst == nullptr || e != cudaSuccess )return ; 713e = cudaEventSynchronize (done [k ]); 714if (e == cudaSuccess ) std::memcpy (held [k ].dst ,host [k ],held [k ].n ); 715held [k ]= {nullptr ,0 }; 716 }; 717for (const auto & it :items ) 718for (size_t o = 0 ;e == cudaSuccess && o < it .n ;o += kParkPiece ) { 719const size_t n = std::min (kParkPiece ,it .n - o ); 720land (b ); 721if (e == cudaSuccess )e = cudaMemcpyAsync (host [b ],stage + it .at + o ,n ,cudaMemcpyDeviceToHost ,st ); 722if (e == cudaSuccess )e = cudaEventRecord (done [b ],st ); 723if (e == cudaSuccess )held [b ]= {it .dst + o ,n }; 724b ^=1 ; 725 } 726land (b ); 727land (b ^1 ); 728for (cudaEvent_t d :done )if (d ) (void )cudaEventDestroy (d ); 729return e ; 730 }); 731return true; 732} 733 734uint64_t conversation_park_slot_tag () {return park_async ().slot_tag ; } 735 736void conversation_park_slot_release (uint64_t tag ) { 737if (tag == 0 )return ; 738for (auto & s :vram_kv ().slots ) 739if (s -> tag == tag ) {vram_kv_release (* s );return ; } 740} 741 742size_t conversation_park_vram_release_all () { 743if (park_vram_budget ()== 0 )return 0 ;// off: nothing was taken, and the stage stays as it was 744conversation_park_join ();// the background copy may be reading a slot or the stage 745ParkAsync & a = park_async (); 746VramKv & v = vram_kv (); 747size_t freed = 0 ; 748for (size_t i = 0 ;i < v .slots .size ();) { 749if (a .active && v .slots [i ].get ()== a .slot ) {++ i ;continue ; }// a park in progress keeps its own 750freed += v .slots [i ]-> cap ; 751vram_kv_free (* v .slots [i ]); 752v .slots .erase (v .slots .begin ()+ (std::ptrdiff_t )i ); 753 } 754if (a .stage != nullptr && !a .active ) { 755int cur = a .dev ; 756 (void )cudaGetDevice (& cur ); 757if (cur != a .dev ) (void )cudaSetDevice (a .dev ); 758 (void )cudaFree (a .stage ); 759if (cur != a .dev ) (void )cudaSetDevice (cur ); 760 (void )cudaGetLastError (); 761freed += a .cap ; 762a .stage = nullptr ;a .cap = 0 ; 763 } 764return freed ; 765} 766 767void conversation_park_join_for (const SavedConversation & image ) { 768size_t hits = 0 ; 769for (const auto & k :image .kv )hits += vram_kv_find (k .dev_tag )!= nullptr ?1 :0 ; 770if (park_trace ()&& park_vram_budget ()!= 0 ) 771 std::fprintf (stderr ,"strata parktrace: kv restore: %zu of %zu layers from the slot\n" ,hits ,image .kv .size ()); 772if (hits < image .kv .size ())conversation_park_join (); 773} 774 775}// namespace strata::core