okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e412ff76e
main
1#include "strata/core/conversation_snapshot.hpp" 2#include "conversation_checked.hpp" 3#include "conversation_copy.hpp" 4#include "conversation_trace.hpp" 5#include <chrono> 6#include <cstdio> 7#include <cstdlib> 8 9#include <algorithm> 10#include <array> 11#include <cstring> 12#include <future> 13#include <limits> 14#include <mutex> 15 16namespace strata::core { 17namespace { 18using conversation_detail::add ; 19using conversation_detail::product ; 20 21std::array < int64_t ,18 > geometry_key (const ModelGeometry & g ) { 22return {g .n_embd ,g .n_layers ,g .qsa_interval ,g .ssm_state_size ,g .ssm_k_heads , 23g .ssm_v_heads ,g .ssm_d_conv ,g .ssm_conv_channels ,g .ssm_value_dim , 24g .n_head ,g .n_head_kv ,g .head_dim ,g .idx_q_heads ,g .idx_key_dim , 25g .hc ,g .hc_lr ,g .n_expert ,g .n_ff }; 26} 27 28bool fail (std::string & error ,const char * message ) { 29error = std::string ("conversation snapshot: " )+ message ; 30return false; 31} 32 33bool sync (std::string & error ) { 34const auto status = cudaDeviceSynchronize (); 35if (status == cudaSuccess )return true; 36error = std::string ("conversation snapshot synchronize: " )+ cudaGetErrorString (status ); 37return false; 38} 39 40bool copy (void * dst ,const void * src ,size_t bytes , std::string & error ,bool queued = false) { 41if (!bytes )return true; 42if (!dst || !src )return fail (error ,"missing running-state buffer" ); 43const auto status = conversation_detail::copy_nonblocking (dst ,src ,bytes ,queued ); 44if (status == cudaSuccess )return true; 45error = std::string ("conversation snapshot running-state copy: " )+ cudaGetErrorString (status ); 46return false; 47} 48 49// The session's carve (#216): `qsa_states` keeps global ordinals and holds the owned ones 50// [qsa_ord0, qsa_ord0 + qsa_alloc); `gdn_state` holds `gdn_alloc` rows. A whole-model session owns every layer. 51size_t owned_qsa (const SessionState & ss ) {return (size_t ) std::max < int64_t > (ss .qsa_alloc ,0 ); } 52const QsaState & owned (const SessionState & ss ,size_t j ) {return ss .qsa_states [(size_t )ss .qsa_ord0 + j ]; } 53 54bool image_keys (const std::vector < ConversationImageKey >& images ,size_t tokens ) { 55int64_t previous = -1 ; 56for (const auto & image :images ) { 57if (image .start <=previous || image .start < 0 || (uint64_t )image .start >=tokens )return false; 58previous = image .start ; 59 } 60return true; 61} 62 63bool checkpoint_targets (const SessionState & ss ,const ModelGeometry & g ,size_t tokens , 64ConversationStateSizes & z , std::string & error ) { 65if (!conversation_session_sizes (g ,ss ,z ,error ))return false; 66if (ss .max_cells < 0 || tokens > (uint64_t )ss .max_cells || (z .gdn && !ss .gdn_state )|| 67 (owned_qsa (ss )&& !ss .qsa_states ))return fail (error ,"invalid session running-state targets" ); 68for (size_t j = 0 ;j < owned_qsa (ss );++ j ) { 69const auto & st = owned (ss ,j ); 70const auto block = strata::kernels::qsa_real_shapes ().idx_block ; 71size_t pooled_bytes = 0 ; 72if (!st .idx_tail || !st .idx_dead || !st .idx_block_pos || !st .idx_pooled || 73st .max_cells < 0 || tokens > (uint64_t )st .max_cells || 74 (tokens && tokens / (uint64_t )block >= (uint64_t ) std::max < int64_t > (0 ,st .idx_pooled_rows ))|| 75 !product (pooled_bytes , {tokens / (uint64_t )block + 1 , (uint64_t )g .idx_key_dim ,sizeof (float )})) 76return fail (error ,"invalid indexer running-state target" ); 77 } 78return true; 79} 80 81bool view_validate (const ConversationView & view ,const SessionState & ss , 82const ModelGeometry & g , std::string & error ) { 83ConversationStateSizes z ; 84if (!checkpoint_targets (ss ,g ,view .ids .size (),z ,error ))return false; 85if (view .ids .empty ()|| !image_keys (view .images ,view .ids .size ())|| 86 std::any_of (view .ids .begin (),view .ids .end (), [](int32_t id ) {return id < 0 ; })) 87return fail (error ,"invalid live token/image metadata" ); 88for (const auto & c :view .checkpoints ) { 89if (!c .stage_parts .empty ()|| c .ids .empty ()|| c .ids .size ()> view .ids .size ()|| 90 !std::equal (c .ids .begin (),c .ids .end (),view .ids .begin ())) 91return fail (error ,"checkpoint is not a live token prefix" ); 92if (!conversation_checkpoint_validate (c ,ss ,g ,error ))return false; 93size_t image = 0 ; 94for (const auto & key :view .images ) { 95if ((uint64_t )key .start >=c .ids .size ())break ; 96if (image >=c .imgs .size ()|| !(c .imgs [image ++ ]== key )) 97return fail (error ,"checkpoint image identity differs" ); 98 } 99if (image != c .imgs .size ())return fail (error ,"checkpoint image prefix differs" ); 100 } 101return true; 102} 103 104bool metadata_bytes (const ConversationCheckpoint & c ,size_t & total ) { 105size_t ids = 0 ,images = 0 ; 106if (!product (ids , {c .ids .size (),sizeof (int32_t )})|| 107 !product (images , {c .imgs .size (),sizeof (ConversationImageKey )}))return false; 108for (size_t n : {ids ,images ,c .gdn .size (),c .ple .size (),c .tails .size (),c .dead .size (),c .block_pos .size ()}) 109if (!add (total ,n ))return false; 110return true; 111} 112}// namespace 113 114bool conversation_state_sizes (const ModelGeometry & g ,ConversationStateSizes & z , std::string & error ) { 115z = {}; 116const auto key = geometry_key (g ); 117for (size_t i = 0 ;i < key .size ();++ i ) 118if (key [i ]< 0 || (i != 1 && key [i ]== 0 ))return fail (error ,"invalid model geometry" ); 119size_t recurrence = 0 ,convolution = 0 ; 120if (!product (recurrence , {(uint64_t )g .ssm_state_size , (uint64_t )g .ssm_v_heads , (uint64_t )g .ssm_state_size })|| 121 !product (convolution , {(uint64_t )g .ssm_conv_channels , (uint64_t ) (g .ssm_d_conv - 1 )})|| 122 !add (recurrence ,convolution )|| 123 !product (z .gdn , {(uint64_t )g .n_gdn_layers (),recurrence ,sizeof (float )})|| 124 !product (z .ple , {strata::kernels::NG_HIST , strata::kernels::NG_HC_DIM ,sizeof (float )})|| 125 !product (z .tail , {(uint64_t ) (strata::kernels::qsa_real_shapes ().idx_block - 1 ), 126 (uint64_t )g .idx_key_dim ,sizeof (float )})|| 127 !product (z .dead , {(uint64_t )g .idx_key_dim ,sizeof (float )})) 128return fail (error ,"running-state byte count overflow" ); 129z .block_pos = sizeof (int32_t ); 130size_t total = 0 ; 131if (!product (total , {(uint64_t )g .n_qsa_layers (),z .tail })|| 132 !product (total , {(uint64_t )g .n_qsa_layers (),z .dead })|| 133 !product (total , {(uint64_t )g .n_qsa_layers (),z .block_pos })) 134return fail (error ,"indexer byte count overflow" ); 135return true; 136} 137 138bool conversation_session_sizes (const ModelGeometry & g ,const SessionState & ss ,ConversationStateSizes & z , 139 std::string & error ) { 140if (!conversation_state_sizes (g ,z ,error ))return false; 141const int64_t n_gdn = g .n_gdn_layers (),n_qsa = g .n_qsa_layers (); 142if (ss .gdn_alloc < 0 || ss .gdn_alloc > n_gdn || ss .qsa_ord0 < 0 || ss .qsa_alloc < 0 || 143ss .qsa_ord0 > n_qsa || ss .qsa_alloc > n_qsa - ss .qsa_ord0 ) 144return fail (error ,"invalid session layer carve" ); 145// z.gdn is n_gdn whole rows; the session holds gdn_alloc of them (all of them for the default full range) 146z .gdn = n_gdn > 0 ?z .gdn / (size_t )n_gdn * (size_t )ss .gdn_alloc :0 ; 147return true; 148} 149 150bool conversation_checkpoint_validate (const ConversationCheckpoint & c ,const SessionState & ss , 151const ModelGeometry & g , std::string & error ) { 152ConversationStateSizes z ; 153if (!checkpoint_targets (ss ,g ,c .ids .size (),z ,error ))return false; 154const size_t layers = owned_qsa (ss ); 155if (c .gdn .size ()!= z .gdn || c .ple .size ()!= (ss .ple_hist ?z .ple :0 )|| 156c .tails .size ()!= layers * z .tail || c .dead .size ()!= layers * z .dead || 157c .block_pos .size ()!= layers * z .block_pos || !image_keys (c .imgs ,c .ids .size ())) 158return fail (error ,"invalid checkpoint running-state payload" ); 159return true; 160} 161 162#if defined(STRATA_GPU_METAL ) 163}// namespace strata::core 164namespace strata::metal_engine { 165// the running state lives in the Metal decode window (metal/src/engine/window.cpp), not in the session's buffers 166bool window_checkpoint_save (strata::core::ConversationCheckpoint & c ,const strata::core::SessionState * ss , std::string & error ); 167bool window_checkpoint_restore (const strata::core::ConversationCheckpoint & c ,const strata::core::SessionState * ss , std::string & error ); 168}// namespace strata::metal_engine 169namespace strata::core { 170#endif 171 172namespace { 173struct CkptAsync { 174 std::mutex mu ; 175 std::future < cudaError_t > pending ; 176const void * dst = nullptr ;// the checkpoint bytes the copy in flight writes 177void * stage = nullptr ; 178void * host = nullptr ;// pinned: the DMA lands here, then a plain memcpy (no driver staging beside the decode) 179cudaStream_t stream = nullptr ; 180size_t cap = 0 ; 181int dev = -1 ; 182}; 183CkptAsync & ckpt_async () {static CkptAsync a ;return a ; } 184// STRATA_CKPT_VRAM_SLOTS=N (with STRATA_CKPT_ASYNC): the last N saved GDN states stay in VRAM (allocated only while 185// more than 1.5 GB stays free); a restore of a checkpoint whose tag a slot holds copies device to device. 186struct VramSlot {void * p = nullptr ;size_t n = 0 ;uint64_t tag = 0 ,used = 0 ;int dev = -1 ; }; 187struct VramSlots { std::vector < VramSlot > s ;uint64_t clock = 0 ,next_tag = 0 ; }; 188VramSlots & vram_slots () {static VramSlots v ;return v ; } 189int vram_slots_n () { 190static const int n = [] {const char * v = std::getenv ("STRATA_CKPT_VRAM_SLOTS" );return v ? std::max (0 , std::min (16 , std::atoi (v ))) :0 ; }(); 191return n ; 192} 193// a slot for `n` bytes on `dev`: a free one, a new one if VRAM allows, else the least recently used (nullptr: none) 194VramSlot * vram_slot_for (size_t n ,int dev ) { 195VramSlots & v = vram_slots (); 196VramSlot * best = nullptr ; 197for (VramSlot & x :v .s ) 198if (x .dev == dev && x .n == n && (best == nullptr || x .used < best -> used ))best = & x ; 199if ((int )v .s .size ()< vram_slots_n ()) { 200size_t fr = 0 ,tot = 0 ; 201if (cudaMemGetInfo (& fr ,& tot )== cudaSuccess && fr > n + ((size_t )3 <<29 )) { 202VramSlot x ; 203if (cudaMalloc (& x .p ,n )== cudaSuccess ) {x .n = n ;x .dev = dev ;v .s .push_back (x );return & v .s .back (); } 204 } 205 (void )cudaGetLastError (); 206 } 207return best ; 208} 209bool ckpt_async_on () { 210#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 )|| defined(STRATA_GPU_METAL ) 211return false; 212#else 213static const bool on = [] {const char * v = std::getenv ("STRATA_CKPT_ASYNC" );return v != nullptr && v [0 ]== '1' ; }(); 214return on ; 215#endif 216} 217// STRATA_CKPT_GATHER=1 (CUDA, opt-in): the small running-state vectors (ple, then each layer's indexer tail, dead row 218// and block position: 1 + 3 x layers pieces) are gathered device to device into one buffer, allocated once, and 219// fetched with ONE copy into a pinned buffer, then copied into the vectors. A small D2H copy issued while the 220// checkpoint DMA (STRATA_CKPT_ASYNC) is in flight waits behind the 4 MiB piece on the copy engine: one such wait 221// instead of 37. The same bytes in the same places. One set of buffers: the mutex serializes the saves a layer 222// split runs on one thread per stage (STRATA_CKPT_THREADS), which otherwise gather through the same buffer. 223struct CkptGather { std::mutex mu ;void * stage = nullptr ;void * host = nullptr ;size_t cap = 0 ;int dev = -1 ; }; 224CkptGather & ckpt_gather () {static CkptGather a ;return a ; } 225bool ckpt_gather_on () { 226#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 )|| defined(STRATA_GPU_METAL ) 227return false; 228#else 229static const bool on = [] {const char * v = std::getenv ("STRATA_CKPT_GATHER" );return v != nullptr && v [0 ]== '1' ; }(); 230return on ; 231#endif 232} 233// 1: the vectors are filled; 0: no buffers (the caller copies them one by one); -1: a copy failed (`error` set) 234int ckpt_gather_small (ConversationCheckpoint & c ,const SessionState & ss ,const ConversationStateSizes & z , 235size_t layers , std::string & error ) { 236const size_t ple = c .ple .size (),tails = c .tails .size (),dead = c .dead .size (),block_pos = c .block_pos .size (); 237const size_t total = ple + tails + dead + block_pos ; 238if (total == 0 )return 1 ; 239CkptGather & a = ckpt_gather (); 240 std::lock_guard < std::mutex > lk (a .mu ); 241int dev = 0 ; 242 (void )cudaGetDevice (& dev ); 243if (a .stage != nullptr && (a .cap < total || a .dev != dev )) { 244const int cur = dev ; 245 (void )cudaSetDevice (a .dev ); (void )cudaFree (a .stage ); (void )cudaFreeHost (a .host ); (void )cudaSetDevice (cur ); 246a .stage = a .host = nullptr ;a .cap = 0 ; 247 } 248if (a .stage == nullptr ) { 249if (cudaMalloc (& a .stage ,total )== cudaSuccess && cudaMallocHost (& a .host ,total )== cudaSuccess ) {a .cap = total ;a .dev = dev ; } 250else {if (a .stage ) (void )cudaFree (a .stage );if (a .host ) (void )cudaFreeHost (a .host );a .stage = a .host = nullptr ; } 251 (void )cudaGetLastError (); 252if (a .stage == nullptr )return 0 ; 253 } 254// the pieces in the vectors' order, queued on the private stream (in order), then the one copy to the host 255uint8_t * s = (uint8_t * )a .stage ; 256if (!copy (s ,ss .ple_hist ,ple ,error , true))return -1 ; 257for (size_t j = 0 ;j < layers ;++ j ) { 258const auto & st = owned (ss ,j ); 259if (!copy (s + ple + j * z .tail ,st .idx_tail ,z .tail ,error , true)|| 260 !copy (s + ple + tails + j * z .dead ,st .idx_dead ,z .dead ,error , true)|| 261 !copy (s + ple + tails + dead + j * z .block_pos ,st .idx_block_pos ,z .block_pos ,error , true))return -1 ; 262 } 263if (!copy (a .host ,a .stage ,total ,error ))return -1 ; 264const uint8_t * h = (const uint8_t * )a .host ; 265if (ple ) std::memcpy (c .ple .data (),h ,ple ); 266if (tails ) std::memcpy (c .tails .data (),h + ple ,tails ); 267if (dead ) std::memcpy (c .dead .data (),h + ple + tails ,dead ); 268if (block_pos ) std::memcpy (c .block_pos .data (),h + ple + tails + dead ,block_pos ); 269return 1 ; 270} 271}// namespace 272 273void conversation_checkpoint_join (const void * only ) { 274CkptAsync & a = ckpt_async (); 275 std::lock_guard < std::mutex > lk (a .mu ); 276if (a .pending .valid ()&& (only == nullptr || only == a .dst )) { 277const cudaError_t e = a .pending .get (); 278if (e != cudaSuccess ) std::fprintf (stderr ,"strata: STRATA_CKPT_ASYNC: a checkpoint copy failed (%s)\n" ,cudaGetErrorString (e )); 279 } 280} 281 282namespace { 283// conversation_checkpoint_save; `staged` (STRATA_CKPT_ASYNC): the GDN bytes land in `c.gdn` on the background thread 284// after this returns (conversation_checkpoint_join waits for them) 285bool checkpoint_save (ConversationCheckpoint & c ,const SessionState & ss ,const ModelGeometry & g , std::string & error , 286bool & staged ) { 287staged = false; 288const auto j0 = std::chrono::steady_clock::now (); 289conversation_checkpoint_join (nullptr );// (the staging buffer is reused) 290if (std::getenv ("STRATA_PARK_TRACE" )) std::fprintf (stderr ,"strata parktrace: save join %.2f ms\n" , 291 std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- j0 ).count ()); 292#if defined(STRATA_GPU_METAL ) 293 (void )g ; 294return strata::metal_engine::window_checkpoint_save (c ,& ss ,error ); 295#endif 296ConversationStateSizes z ; 297if (!checkpoint_targets (ss ,g ,c .ids .size (),z ,error ))return false; 298const size_t layers = owned_qsa (ss ); 299static const bool atr = std::getenv ("STRATA_PARK_TRACE" )!= nullptr ; 300const bool ready = c .gdn .size ()== z .gdn ;// (a pooled checkpoint's pages are in; a fresh vector faults them all) 301const auto r0 = std::chrono::steady_clock::now (); 302const long rf0 = atr ? conversation_trace::thread_minflt () :0 ; 303c .gdn .resize (z .gdn );c .ple .resize (ss .ple_hist ?z .ple :0 ); 304c .tails .resize (layers * z .tail );c .dead .resize (layers * z .dead );c .block_pos .resize (layers * z .block_pos ); 305if (atr ) std::fprintf (stderr ,"strata parktrace: save vectors %s, resize %.2f ms, %ld faults, gdn %zu MB at %p (%s)\n" ,ready ?"ready" :"fresh" , 306 std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- r0 ).count (), 307 conversation_trace::thread_minflt ()- rf0 ,c .gdn .size () >>20 , (const void * )c .gdn .data (), conversation_trace::where (c .gdn .data ())); 308if (ckpt_async_on ()&& c .gdn .size () >= ((size_t )1 <<20 )) { 309CkptAsync & a = ckpt_async (); 310int dev = 0 ; 311 (void )cudaGetDevice (& dev ); 312if (a .stage != nullptr && (a .cap < c .gdn .size ()|| a .dev != dev )) { 313const int cur = dev ; 314 (void )cudaSetDevice (a .dev ); (void )cudaFree (a .stage ); (void )cudaFreeHost (a .host ); 315 (void )cudaStreamDestroy (a .stream ); (void )cudaSetDevice (cur ); 316a .stage = a .host = nullptr ;a .stream = nullptr ;a .cap = 0 ; 317 } 318if (a .stage == nullptr ) { 319if (cudaMalloc (& a .stage ,c .gdn .size ())== cudaSuccess && cudaMallocHost (& a .host ,c .gdn .size ())== cudaSuccess && 320cudaStreamCreateWithFlags (& a .stream ,cudaStreamNonBlocking )== cudaSuccess ) {a .cap = c .gdn .size ();a .dev = dev ; } 321else {if (a .stage ) (void )cudaFree (a .stage );if (a .host ) (void )cudaFreeHost (a .host );a .stage = a .host = nullptr ; } 322 } 323 (void )cudaGetLastError (); 324const auto q0 = std::chrono::steady_clock::now (); 325VramSlot * slot = vram_slots_n ()> 0 ?vram_slot_for (c .gdn .size (),dev ) :nullptr ; 326if (slot != nullptr )slot -> tag = 0 ;// (being rewritten) 327void * dsrc = slot != nullptr ?slot -> p :a .stage ; 328c .dev_tag = 0 ; 329if (dsrc != nullptr && copy (dsrc ,ss .gdn_state ,c .gdn .size (),error )) {// device to device: fast 330const auto q1 = std::chrono::steady_clock::now (); 331if (slot != nullptr ) { 332VramSlots & v = vram_slots (); 333slot -> tag = c .dev_tag = ++ v .next_tag ; 334slot -> used = ++ v .clock ; 335 } 336uint8_t * dst = c .gdn .data (); 337const size_t n = c .gdn .size (); 338void * host = a .host ; 339const uint8_t * stage = (const uint8_t * )dsrc ; 340cudaStream_t st = a .stream ; 341if (atr ) std::fprintf (stderr ,"strata parktrace: async ckpt d2d %.2f ms\n" , 342 std::chrono::duration < double , std::milli > (q1 - q0 ).count ()); 343 std::lock_guard < std::mutex > lk (a .mu ); 344// the DMA in 4 MiB pieces, one in flight: a D2H copy queues behind the one before it on the copy engine, and 345// the decode's own small reads would otherwise wait for the whole 100+ MB at the link's ~1.6 GB/s 346a .dst = dst ; 347a .pending = std::async (std::launch::async , [dst ,host ,stage ,n ,st ,dev ] { 348 conversation_detail::background_thread_placement (); 349 (void )cudaSetDevice (dev ); 350cudaEvent_t done = nullptr ; 351cudaError_t e = cudaEventCreateWithFlags (& done ,cudaEventDisableTiming |cudaEventBlockingSync ); 352constexpr size_t PIECE = (size_t )4 <<20 ; 353for (size_t o = 0 ;e == cudaSuccess && o < n ;o += PIECE ) { 354const size_t k = std::min (PIECE ,n - o ); 355e = cudaMemcpyAsync ((uint8_t * )host + o ,stage + o ,k ,cudaMemcpyDeviceToHost ,st ); 356if (e == cudaSuccess )e = cudaEventRecord (done ,st ); 357if (e == cudaSuccess )e = cudaEventSynchronize (done ); 358if (e == cudaSuccess ) std::memcpy (dst + o , (const uint8_t * )host + o ,k ); 359 } 360if (done ) (void )cudaEventDestroy (done ); 361return e ; 362 }); 363staged = true; 364 } 365 } 366if (!staged && !copy (c .gdn .data (),ss .gdn_state ,c .gdn .size (),error ))return false; 367const auto s0 = std::chrono::steady_clock::now (); 368const bool ok = [& ] { 369// STRATA_CKPT_GATHER=1: the small vectors through one device gather and one copy (else one copy each) 370if (ckpt_gather_on ()) { 371const int r = ckpt_gather_small (c ,ss ,z ,layers ,error ); 372if (r != 0 )return r > 0 ; 373 } 374if (!copy (c .ple .data (),ss .ple_hist ,c .ple .size (),error ))return false; 375for (size_t j = 0 ;j < layers ;++ j ) { 376const auto & st = owned (ss ,j ); 377if (!copy (c .tails .data ()+ j * z .tail ,st .idx_tail ,z .tail ,error )|| 378 !copy (c .dead .data ()+ j * z .dead ,st .idx_dead ,z .dead ,error )|| 379 !copy (c .block_pos .data ()+ j * z .block_pos ,st .idx_block_pos ,z .block_pos ,error ))return false; 380 } 381return true; 382 }(); 383if (atr ) std::fprintf (stderr ,"strata parktrace: save small copies %.2f ms\n" , 384 std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- s0 ).count ()); 385return ok ; 386} 387}// namespace 388 389bool conversation_checkpoint_save (ConversationCheckpoint & c ,const SessionState & ss , 390const ModelGeometry & g , std::string & error ) { 391bool staged = false; 392return checkpoint_save (c ,ss ,g ,error ,staged ); 393} 394 395bool conversation_checkpoint_restore (const ConversationCheckpoint & c ,SessionState & ss , 396const ModelGeometry & g , std::string & error ) { 397const VramSlot * hit = nullptr ; 398if (c .dev_tag != 0 ) { 399int dev = 0 ; 400 (void )cudaGetDevice (& dev ); 401for (VramSlot & x :vram_slots ().s ) 402if (x .tag == c .dev_tag && x .dev == dev && x .n == c .gdn .size ()) {x .used = ++ vram_slots ().clock ;hit = & x ; } 403 } 404if (hit == nullptr )conversation_checkpoint_join (c .gdn .data ()); 405#if defined(STRATA_GPU_METAL ) 406 (void )g ; 407if (!strata::metal_engine::window_checkpoint_restore (c ,& ss ,error ))return false; 408ss .ple_prev [0 ]= c .ids .size () >=2 ?c .ids [c .ids .size ()- 2 ] :-1 ; 409ss .ple_prev [1 ]= c .ids .size () >=1 ?c .ids [c .ids .size ()- 1 ] :-1 ; 410return true; 411#endif 412if (!conversation_checkpoint_validate (c ,ss ,g ,error ))return false; 413ConversationStateSizes z ; 414if (!conversation_session_sizes (g ,ss ,z ,error ))return false; 415if (!sync (error ))return false;// the copies below no longer ride the legacy stream's implicit ordering 416if (!copy (ss .gdn_state ,hit != nullptr ?hit -> p : (const void * )c .gdn .data (),c .gdn .size (),error )|| 417 !copy (ss .ple_hist ,c .ple .data (),c .ple .size (),error ))return false; 418for (size_t j = 0 ;j < owned_qsa (ss );++ j ) { 419const auto & st = owned (ss ,j ); 420if (!copy (st .idx_tail ,c .tails .data ()+ j * z .tail ,z .tail ,error )|| 421 !copy (st .idx_dead ,c .dead .data ()+ j * z .dead ,z .dead ,error )|| 422 !copy (st .idx_block_pos ,c .block_pos .data ()+ j * z .block_pos ,z .block_pos ,error ))return false; 423if (!c .ids .empty ()) { 424const size_t row = c .ids .size () / strata::kernels::qsa_real_shapes ().idx_block ; 425if (!copy (st .idx_pooled + row * g .idx_key_dim ,c .dead .data ()+ j * z .dead ,z .dead ,error ))return false; 426 } 427 } 428const size_t tokens = c .ids .size (); 429ss .ple_prev [0 ]= tokens >=2 ?c .ids [tokens - 2 ] :-1 ; 430ss .ple_prev [1 ]= tokens >=1 ?c .ids [tokens - 1 ] :-1 ; 431return sync (error ); 432} 433 434bool conversation_checkpoint_copy (const SessionState & from ,SessionState & to ,const std::vector < int32_t >& ids , 435const ModelGeometry & g , std::string & error ,bool queued ) { 436// conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) without the host image, for two 437// sessions carved alike on the same device (a stage's own session and its batch slots): the same bytes into 438// the same places, through copy() like the restore (the private non-blocking stream, complete on return unless 439// `queued`: then the caller synchronizes the device). 440ConversationStateSizes zf ,zt ; 441if (!checkpoint_targets (from ,g ,ids .size (),zf ,error )|| !checkpoint_targets (to ,g ,ids .size (),zt ,error )) 442return false; 443if (zf .gdn != zt .gdn || zf .tail != zt .tail || zf .dead != zt .dead || zf .block_pos != zt .block_pos || 444owned_qsa (from )!= owned_qsa (to )|| (from .ple_hist != nullptr )!= (to .ple_hist != nullptr )) 445return fail (error ,"direct copy between differently carved sessions" ); 446auto acopy = [& ](void * dst ,const void * src ,size_t bytes ) {return copy (dst ,src ,bytes ,error ,queued ); }; 447if (!acopy (to .gdn_state ,from .gdn_state ,zf .gdn )|| 448 !acopy (to .ple_hist ,from .ple_hist ,from .ple_hist ?zf .ple :0 ))return false; 449for (size_t j = 0 ;j < owned_qsa (from );++ j ) { 450const auto & a = owned (from ,j ); 451const auto & b = owned (to ,j ); 452if (!acopy (b .idx_tail ,a .idx_tail ,zf .tail )|| !acopy (b .idx_dead ,a .idx_dead ,zf .dead )|| 453 !acopy (b .idx_block_pos ,a .idx_block_pos ,zf .block_pos ))return false; 454if (!ids .empty ()) {// restore writes the saved `dead` row into the pooled row the next token fills 455const size_t row = ids .size () / strata::kernels::qsa_real_shapes ().idx_block ; 456if (!acopy (b .idx_pooled + row * g .idx_key_dim ,a .idx_dead ,zf .dead ))return false; 457 } 458 } 459const size_t tokens = ids .size (); 460to .ple_prev [0 ]= tokens >=2 ?ids [tokens - 2 ] :-1 ; 461to .ple_prev [1 ]= tokens >=1 ?ids [tokens - 1 ] :-1 ; 462return true; 463} 464 465bool conversation_snapshot_bytes (const ConversationView & view ,const SessionState & ss , 466const ModelGeometry & g ,const QsaState * draft ,size_t & bytes , std::string & error ) { 467bytes = 0 ; 468if (!view_validate (view ,ss ,g ,error ))return false; 469ConversationStateSizes z ; 470if (!conversation_session_sizes (g ,ss ,z ,error ))return false; 471size_t ids = 0 ,images = 0 ,checkpoints = 0 ,layers = 0 ,tails = 0 ,dead = 0 ,positions = 0 ; 472const auto qsa = (uint64_t )owned_qsa (ss ); 473if (!product (ids , {view .ids .size (),sizeof (int32_t )})|| 474 !product (images , {view .images .size (),sizeof (ConversationImageKey )})|| 475 !product (checkpoints , {view .checkpoints .size (),sizeof (ConversationCheckpoint )})|| 476 !product (layers , {qsa + (draft ?1 :0 ),sizeof (ConversationKv )})|| 477 !product (tails , {qsa ,z .tail })|| !product (dead , {qsa ,z .dead })|| 478 !product (positions , {qsa ,z .block_pos }))return fail (error ,"snapshot metadata byte count overflow" ); 479for (size_t n : {ids ,images ,checkpoints ,layers ,tails ,dead ,positions ,z .gdn ,ss .ple_hist ?z .ple :0 }) 480if (!add (bytes ,n ))return fail (error ,"snapshot byte count overflow" ); 481for (const auto & c :view .checkpoints ) 482if (!metadata_bytes (c ,bytes ))return fail (error ,"checkpoint byte count overflow" ); 483const int64_t upto = (int64_t )view .ids .size ();// view_validate bounds this by signed max_cells 484for (uint64_t i = 0 ;i < qsa + (draft ?1 :0 );++ i ) { 485const auto & st = i == qsa ?* draft :owned (ss , (size_t )i ); 486const size_t n = conversation_kv_bytes (st ,g ,upto ,i != qsa ); 487if (!n || !add (bytes ,n ))return fail (error ,"invalid or overflowing K/V byte estimate" ); 488 } 489return true; 490} 491 492bool conversation_snapshot_capture_bytes (const ConversationKvReuse & reuse ,const ConversationView & view , 493const SessionState & ss ,const ModelGeometry & g , 494const QsaState * draft ,size_t & bytes , std::string & error ) { 495if (!conversation_snapshot_bytes (view ,ss ,g ,draft ,bytes ,error ))return false; 496if (reuse .kv .empty ())return true; 497const size_t layers = owned_qsa (ss )+ (draft ?1 :0 ); 498if (reuse .kv .size ()!= layers || reuse .unchanged_tokens < 0 || 499reuse .unchanged_tokens > reuse .captured_tokens || reuse .unchanged_tokens > int64_t (view .ids .size ())) 500return fail (error ,"invalid retained K/V prefix" ); 501for (size_t i = 0 ;i < layers ;++ i ) { 502const bool index = i < owned_qsa (ss ); 503const auto & st = index ?owned (ss ,i ) :* draft ; 504if (!conversation_kv_validate (reuse .kv [i ],st ,g ,reuse .captured_tokens ,index ,error ))return false; 505const size_t fresh = conversation_kv_bytes (st ,g ,int64_t (view .ids .size ()),index ); 506size_t retained = 0 ; 507if (!conversation_kv_capture_bytes (reuse .kv [i ],st ,g ,int64_t (view .ids .size ()),index ,retained ,error ))return false; 508bytes -= fresh ; 509if (!add (bytes ,retained ))return fail (error ,"retained K/V allocation overflow" ); 510 } 511size_t directory = 0 ; 512if (!product (directory , {reuse .kv .capacity ()- layers ,sizeof (ConversationKv )})|| !add (bytes ,directory )) 513return fail (error ,"retained K/V directory overflow" ); 514return true; 515} 516 517// (conversation_snapshot.cpp) STRATA_PARK_TRACE: conversation_kv_save's time since the park's begin, by part (ms) 518void conversation_kv_save_trace (double & attrs_ms ,double & resize_ms ,double & copy_ms ); 519long conversation_kv_save_trace_faults ();// (E1) minor faults of the K/V buffer resizes of this park's saves 520 521bool conversation_snapshot_save (SavedConversation & image ,const ConversationView & view , 522const SessionState & ss ,const ModelGeometry & g , 523const QsaState * draft , std::string & error , 524ConversationKvReuse reuse ,size_t * reused_bytes , 525 std::vector < ConversationCheckpoint >* storage , 526 std::vector < ConversationCheckpoint >* moved ) { 527static const bool ptr = std::getenv ("STRATA_PARK_TRACE" )!= nullptr ; 528auto now = [] {return std::chrono::steady_clock::now (); }; 529auto ms = [](std::chrono::steady_clock::time_point a , std::chrono::steady_clock::time_point b ) { 530return std::chrono::duration < double , std::milli > (b - a ).count (); }; 531const auto pj = now (); 532conversation_checkpoint_join (nullptr );// the last turn checkpoint's DMA (STRATA_CKPT_ASYNC) 533conversation_park_join ();// the previous park's K/V DMA 534const auto p0 = now (); 535size_t estimate = 0 ; 536if (!conversation_snapshot_capture_bytes (reuse ,view ,ss ,g ,draft ,estimate ,error )|| !sync (error ))return false; 537// Build into a new object so a failure cannot publish a partial snapshot. 538SavedConversation captured ; 539captured .geometry = geometry_key (g ); 540captured .layer_lo = ss .layer_lo ;captured .layer_hi = ss .layer_hi ; 541if (storage != nullptr && !storage -> empty ()) {// the running state into a dropped checkpoint's vectors 542captured .live = std::move (storage -> back ()); 543storage -> pop_back (); 544captured .live .stage_parts .clear (); 545 } 546captured .live .ids = view .ids ;captured .live .imgs = view .images ; 547const auto p1 = now (); 548const long cf0 = ptr ? conversation_trace::thread_minflt () :0 ; 549captured .cvec = view .cvec ;captured .checkpoints = conversation_detail::copy_checkpoints_beating (view .checkpoints ,storage ); 550const long ck_faults = ptr ? conversation_trace::thread_minflt ()- cf0 :0 ; 551if (ptr )// (E1: where each copied checkpoint's running state went: faults of the whole copy, address, heap or mapping) 552for (const auto & c :captured .checkpoints ) 553 std::fprintf (stderr ,"strata parktrace: ckpt copy gdn %zu MB at %p (%s)\n" ,c .gdn .size () >>20 , 554 (const void * )c .gdn .data (), conversation_trace::where (c .gdn .data ())); 555if (moved != nullptr ) 556for (auto & c :* moved ) { 557conversation_checkpoint_join (c .gdn .data ()); 558captured .checkpoints .push_back (std::move (c )); 559 } 560const auto p2 = now (); 561const int64_t unchanged = reuse .kv .empty () ?0 :reuse .unchanged_tokens ; 562captured .kv = std::move (reuse .kv ); 563const size_t layers = owned_qsa (ss ); 564captured .kv .resize (layers + (draft ?1 :0 )); 565// STRATA_PARK_VRAM_MIB: the retained layers' tokens go now (joined above, so no wait): held past the launch below, 566// their replacement would join the copy just launched 567for (auto & k :captured .kv )k .pending .reset (); 568bool live_staged = false; 569const bool live_saved = checkpoint_save (captured .live ,ss ,g ,error ,live_staged ); 570// STRATA_CKPT_ASYNC: the running state lands in live.gdn after the save returns; the image waits for that copy 571// before the vector is freed (an eviction within the copy's ~70 ms), as `pending` does for the K/V. The join is 572// selective: a no-op once the copy has landed or another checkpoint's is in flight. 573if (live_staged ) 574captured .live_pending = std::shared_ptr < void > (new char , [dst = (const void * )captured .live .gdn .data ()](void * p ) { 575conversation_checkpoint_join (dst ); 576delete (char * )p ; 577 }); 578if (!live_saved )return false; 579const auto p3 = now (); 580const int64_t upto = (int64_t )view .ids .size (); 581// STRATA_PARK_ASYNC: the K/V bytes these saves copy (the stage they need; an over-estimate by the kept prefix) 582size_t kv_need = 0 ; 583for (size_t j = 0 ;j < layers ;++ j )kv_need += conversation_kv_bytes (owned (ss ,j ),g ,upto , true); 584if (draft )kv_need += conversation_kv_bytes (* draft ,g ,upto , false); 585const bool staged = conversation_park_async_begin (kv_need ); 586const auto p4 = now (); 587struct Abandon {bool on ; ~Abandon () {if (on )conversation_park_async_abandon (); } }abandon {staged }; 588double kv_max = 0 ,kv_sum = 0 ;// (STRATA_PARK_TRACE: the per-layer save time) 589const long kf0 = ptr ? conversation_trace::thread_minflt () :0 ; 590for (size_t j = 0 ;j < layers ;++ j ) { 591const auto k0 = now (); 592if (!conversation_kv_save (captured .kv [j ],owned (ss ,j ),g ,upto , true,error , 593unchanged ,reused_bytes ))return false; 594const double kt = ms (k0 ,now ()); 595kv_sum += kt ;kv_max = std::max (kv_max ,kt ); 596 } 597const long kv_faults_total = ptr ? conversation_trace::thread_minflt ()- kf0 :0 ; 598if (ptr ) { 599size_t kvb = 0 ; 600for (const auto & k :captured .kv )kvb += k .bytes (); 601double attrs_ms = 0 ,resize_ms = 0 ,copy_ms = 0 ; 602conversation_kv_save_trace (attrs_ms ,resize_ms ,copy_ms );// (the main layers' saves above) 603 std::fprintf (stderr ,"strata parktrace: joins %.1f ms, sync %.1f ms, %zu checkpoints copied %.1f ms, live state %.1f ms, " 604"begin %.1f ms, K/V %zu MB %.1f ms (layer max %.2f, sum %.2f; attrs %.2f, resize %.2f, copy %.2f)\n" , 605ms (pj ,p0 ),ms (p0 ,p1 ),captured .checkpoints .size (),ms (p1 ,p2 ),ms (p2 ,p3 ),ms (p3 ,p4 ),kvb >>20 , 606ms (p4 ,now ()),kv_max ,kv_sum ,attrs_ms ,resize_ms ,copy_ms ); 607static const bool thp_said = [] { 608 std::fprintf (stderr ,"strata parktrace: THP enabled %s; defrag %s; page size %ld; sbrk end %p\n" , 609 conversation_trace::sys_line ("/sys/kernel/mm/transparent_hugepage/enabled" ).c_str (), 610 conversation_trace::sys_line ("/sys/kernel/mm/transparent_hugepage/defrag" ).c_str (), 611 conversation_trace::page_size (), conversation_trace::brk_end ()); 612return true; 613 }(); 614 (void )thp_said ; 615// E1: page faults per phase (a 4 KiB first touch = 1, a 2 MiB huge page = 1). (Not AnonHugePages: reading /proc/self/smaps_rollup 616// walks the 47 GB expert mapping and costs ~0.5 s a read, which the first E1 job (e1, 11-11) put inside the park's own times.) 617 std::fprintf (stderr ,"strata parktrace: faults: checkpoint copies %ld, K/V resize %ld (copy phase included in the layer loop: %ld)\n" , 618ck_faults ,conversation_kv_save_trace_faults (),kv_faults_total ); 619if (!captured .kv .empty ()) { 620const auto & k0 = captured .kv .front (); 621 std::fprintf (stderr ,"strata parktrace: K/V layer 0 buffers (bytes): k %zu v %zu k_scale %zu v_scale %zu pooled %zu; %zu layers; " 622"segment %zu MiB\n" ,k0 .k .size (),k0 .v .size (),k0 .k_scale .size (),k0 .v_scale .size (),k0 .pooled .size (), 623captured .kv .size (),ConversationBuffer ::segment_bytes >>20 ); 624 } 625 } 626// The draft's final cell may not have been computed when the output cap was 627// reached. Refresh that page even when the main prefix continued unchanged. 628if (draft && !conversation_kv_save (captured .kv .back (),* draft ,g ,upto , false,error , 629 std::max < int64_t > (0 ,unchanged - 1 ),reused_bytes ))return false; 630abandon .on = false; 631if (staged && !conversation_park_async_launch (error ))return false; 632if (staged ) { 633// STRATA_PARK_VRAM_MIB: the image's slot goes with the image, after the copy that reads it; each K/V layer 634// carries a token of its own too (the layers outlive the image when they are retained for the next park, and 635// the copy fills their buffers). Without a slot: the image's join as before, no layer tokens. 636const uint64_t slot = conversation_park_slot_tag (); 637auto token = [slot ] { 638return std::shared_ptr < void > (new char , [slot ](void * p ) { 639conversation_park_join (); 640conversation_park_slot_release (slot ); 641delete (char * )p ; 642 }); 643 }; 644captured .pending = token (); 645if (slot != 0 ) 646for (auto & k :captured .kv )k .pending = token (); 647 } 648image = std::move (captured ); 649return true; 650} 651 652bool conversation_snapshot_sources (SavedConversation & meta , std::vector < SessionKvSource >& sources , 653const ConversationView & view ,const SessionState & ss ,const ModelGeometry & g , 654const QsaState & draft , std::string & error ) { 655if (!view_validate (view ,ss ,g ,error )|| !sync (error ))return false; 656SavedConversation captured ; 657captured .geometry = geometry_key (g ); 658captured .layer_lo = ss .layer_lo ;captured .layer_hi = ss .layer_hi ; 659captured .live .ids = view .ids ;captured .live .imgs = view .images ; 660captured .cvec = view .cvec ;captured .checkpoints = conversation_detail::copy_checkpoints_beating (view .checkpoints ); 661if (!conversation_checkpoint_save (captured .live ,ss ,g ,error ))return false; 662// STRATA_CKPT_ASYNC: the caller writes `meta` to the session file at once, so the running state's copy lands first 663conversation_checkpoint_join (captured .live .gdn .data ()); 664const int64_t upto = (int64_t )view .ids .size (); 665const size_t layers = owned_qsa (ss ); 666 std::vector < SessionKvSource > out (layers + 1 ); 667for (size_t j = 0 ;j < layers ;++ j ) 668if (!conversation_kv_source (out [j ],owned (ss ,j ),g ,upto , true,error ))return false; 669if (!conversation_kv_source (out .back (),draft ,g ,upto , false,error ))return false; 670meta = std::move (captured ); 671sources = std::move (out ); 672return true; 673} 674 675bool conversation_session_read_limits (SessionReadLimits & limits ,const SessionState & ss ,const ModelGeometry & g , 676const QsaState & draft ,uint64_t max_tokens ,uint64_t max_checkpoints , 677 std::string & error ) { 678ConversationStateSizes z ; 679if (!conversation_session_sizes (g ,ss ,z ,error ))return false; 680if (ss .max_cells < 0 )return fail (error ,"invalid session cells" ); 681const uint64_t tokens = std::min < uint64_t > (max_tokens , (uint64_t )ss .max_cells ); 682const size_t layers = owned_qsa (ss ); 683if ((owned_qsa (ss )&& !ss .qsa_states ))return fail (error ,"invalid session running-state targets" ); 684size_t tails = 0 ,dead = 0 ,block_pos = 0 ; 685if (!product (tails , {layers ,z .tail })|| !product (dead , {layers ,z .dead })|| 686 !product (block_pos , {layers ,z .block_pos }))return fail (error ,"indexer byte count overflow" ); 687SessionReadLimits l = limits ;// keeps the caller's admit / progress / max_file_bytes 688l .max_tokens = tokens ; 689l .max_checkpoints = max_checkpoints ; 690l .max_kv_layers = layers + 1 ; 691l .geometry = geometry_key (g ); 692l .layer_range = std::make_pair (ss .layer_lo ,ss .layer_hi ); 693l .max_state_bytes = {z .gdn ,ss .ple_hist ?z .ple :0 ,tails ,dead ,block_pos }; 694l .max_kv_bytes .assign (layers + 1 , {}); 695for (size_t j = 0 ;j < layers ;++ j ) { 696const auto & st = owned (ss ,j ); 697const int64_t upto = (int64_t ) std::min < uint64_t > (tokens , (uint64_t ) std::max < int64_t > (st .max_cells ,0 )); 698if (!conversation_kv_part_sizes (st ,g ,upto , true,l .max_kv_bytes [j ],error ))return false; 699 } 700const int64_t dupto = (int64_t ) std::min < uint64_t > (tokens , (uint64_t ) std::max < int64_t > (draft .max_cells ,0 )); 701if (!conversation_kv_part_sizes (draft ,g ,dupto , false,l .max_kv_bytes .back (),error ))return false; 702limits = std::move (l ); 703return true; 704} 705 706bool conversation_snapshot_validate (const SavedConversation & image ,const SessionState & ss , 707const ModelGeometry & g ,const QsaState * draft , std::string & error ) { 708if (!image .live .stage_parts .empty ()) 709return fail (error ,"a running checkpoint's stage parts belong in the stage images, not in live.stage_parts" ); 710if (image .geometry != geometry_key (g ))return fail (error ,"incompatible runtime geometry" ); 711// an image holds exactly one carve's running state and K/V: same layer range or nothing 712if (image .layer_lo != ss .layer_lo || image .layer_hi != ss .layer_hi ) 713return fail (error ,"snapshot from another session layer range" ); 714const ConversationView view {image .live .ids ,image .live .imgs ,image .checkpoints ,image .cvec }; 715if (!view_validate (view ,ss ,g ,error )|| !conversation_checkpoint_validate (image .live ,ss ,g ,error ))return false; 716const size_t layers = owned_qsa (ss ); 717if (image .kv .size ()!= layers + (draft ?1 :0 ))return fail (error ,"invalid K/V layer count" ); 718const int64_t upto = (int64_t )image .live .ids .size (); 719for (size_t j = 0 ;j < layers ;++ j ) 720if (!conversation_kv_validate (image .kv [j ],owned (ss ,j ),g ,upto , true,error ))return false; 721return !draft || conversation_kv_validate (image .kv .back (),* draft ,g ,upto , false,error ); 722} 723 724bool conversation_copy_stream_ready (int device ) {return conversation_detail::copy_stream_ready (device ); } 725 726ConversationRestore conversation_snapshot_restore (const SavedConversation & image ,SessionState & ss , 727const ModelGeometry & g ,const QsaState * draft , std::string & error ) { 728conversation_checkpoint_join (image .live .gdn .data ()); 729for (const auto & c :image .checkpoints )conversation_checkpoint_join (c .gdn .data ()); 730conversation_park_join_for (image );// (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot) 731if (!conversation_snapshot_validate (image ,ss ,g ,draft ,error ))return ConversationRestore ::invalid ; 732if (!sync (error ))return ConversationRestore ::transfer_failed ; 733const int64_t upto = (int64_t )image .live .ids .size (); 734for (size_t j = 0 ;j < owned_qsa (ss );++ j ) 735if (!conversation_kv_restore (image .kv [j ],owned (ss ,j ),g ,upto , true,error )) 736return ConversationRestore ::transfer_failed ; 737if ((draft && !conversation_kv_restore (image .kv .back (),* draft ,g ,upto , false,error ))|| 738 !conversation_checkpoint_restore (image .live ,ss ,g ,error ))return ConversationRestore ::transfer_failed ; 739return ConversationRestore ::restored ; 740} 741 742// the draft layer's K/V included (the stage that owns the draft head, or no layer split) 743bool conversation_snapshot_bytes (const ConversationView & view ,const SessionState & ss ,const ModelGeometry & g , 744const QsaState & draft ,size_t & bytes , std::string & error ) { 745return conversation_snapshot_bytes (view ,ss ,g ,& draft ,bytes ,error ); 746} 747bool conversation_snapshot_capture_bytes (const ConversationKvReuse & reuse ,const ConversationView & view , 748const SessionState & ss ,const ModelGeometry & g ,const QsaState & draft , 749size_t & bytes , std::string & error ) { 750return conversation_snapshot_capture_bytes (reuse ,view ,ss ,g ,& draft ,bytes ,error ); 751} 752bool conversation_snapshot_save (SavedConversation & image ,const ConversationView & view ,const SessionState & ss , 753const ModelGeometry & g ,const QsaState & draft , std::string & error , 754ConversationKvReuse reuse ,size_t * reused_bytes ) { 755return conversation_snapshot_save (image ,view ,ss ,g ,& draft ,error , std::move (reuse ),reused_bytes ); 756} 757bool conversation_snapshot_validate (const SavedConversation & image ,const SessionState & ss ,const ModelGeometry & g , 758const QsaState & draft , std::string & error ) { 759// the whole-session form: a layer split's image (stage images) is restored stage by stage, never through here 760if (!image .stage_images .empty ())return fail (error ,"a layer split's image restored as a single session" ); 761return conversation_snapshot_validate (image ,ss ,g ,& draft ,error ); 762} 763ConversationRestore conversation_snapshot_restore (const SavedConversation & image ,SessionState & ss , 764const ModelGeometry & g ,const QsaState & draft , std::string & error ) { 765conversation_checkpoint_join (image .live .gdn .data ()); 766for (const auto & c :image .checkpoints )conversation_checkpoint_join (c .gdn .data ()); 767conversation_park_join_for (image );// (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot) 768return conversation_snapshot_restore (image ,ss ,g ,& draft ,error ); 769} 770ConversationRestore conversation_snapshot_restore_prefix (const SavedConversation & image ,int64_t upto , 771SessionState & ss ,const ModelGeometry & g , 772const QsaState & draft , std::string & error ) { 773conversation_checkpoint_join (image .live .gdn .data ()); 774for (const auto & c :image .checkpoints )conversation_checkpoint_join (c .gdn .data ()); 775conversation_park_join_for (image );// (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot) 776return conversation_snapshot_restore_prefix (image ,upto ,ss ,g ,& draft ,error ); 777} 778ConversationRestore conversation_snapshot_restore_prefix (const SavedConversation & image ,int64_t upto , 779SessionState & ss ,const ModelGeometry & g , 780const QsaState * draft , std::string & error ) { 781conversation_checkpoint_join (image .live .gdn .data ()); 782for (const auto & c :image .checkpoints )conversation_checkpoint_join (c .gdn .data ()); 783conversation_park_join_for (image );// (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot) 784// a layer split's image (stage images) is restored stage by stage, never in part 785if (!image .stage_images .empty ()) { 786fail (error ,"a layer split's image restored as a single session" ); 787return ConversationRestore ::invalid ; 788 } 789if (!conversation_snapshot_validate (image ,ss ,g ,draft ,error ))return ConversationRestore ::invalid ; 790const int64_t captured = (int64_t )image .live .ids .size (); 791if (upto < 1 || upto > captured ) { 792fail (error ,"the borrowed prefix is not inside the parked conversation" ); 793return ConversationRestore ::invalid ; 794 } 795if (!sync (error ))return ConversationRestore ::transfer_failed ; 796for (size_t j = 0 ;j < owned_qsa (ss );++ j ) 797if (!conversation_kv_restore_prefix (image .kv [j ],owned (ss ,j ),g ,captured ,upto , true,error )) 798return ConversationRestore ::transfer_failed ; 799if (draft && !conversation_kv_restore_prefix (image .kv .back (),* draft ,g ,captured ,upto , false,error )) 800return ConversationRestore ::transfer_failed ; 801return ConversationRestore ::restored ; 802} 803 804bool conversation_session_dump (const SessionState & ss ,const ModelGeometry & g ,const std::vector < int32_t >& ids , 805const std::string & path , std::string & error ) { 806const std::vector < ConversationImageKey > images ; 807const std::vector < ConversationCheckpoint > checkpoints ; 808SavedConversation image ; 809if (!conversation_snapshot_save (image ,ConversationView {ids ,images ,checkpoints , true},ss ,g ,nullptr ,error )) 810return false; 811conversation_checkpoint_join (image .live .gdn .data ()); 812conversation_park_join_for (image ); 813 std::FILE * f = std::fopen (path .c_str (),"wb" ); 814if (f == nullptr )return fail (error ,"the session dump could not be opened" ); 815bool ok = true; 816auto put = [& ](const void * p ,size_t n ) {ok = ok && (n == 0 || std::fwrite (p ,1 ,n ,f )== n ); }; 817const int64_t head [3 ]= {ss .layer_lo ,ss .layer_hi , (int64_t )ids .size ()}; 818put (head ,sizeof head ); 819for (const auto * v : {& image .live .gdn ,& image .live .ple ,& image .live .tails ,& image .live .dead ,& image .live .block_pos }) 820put (v -> data (),v -> size ()); 821for (const ConversationKv & kv :image .kv ) 822for (const ConversationBuffer * b : {& kv .k ,& kv .v ,& kv .k_scale ,& kv .v_scale ,& kv .pooled }) 823b -> visit (0 ,b -> size (), [& ](const uint8_t * p ,size_t n ,size_t ) {put (p ,n );return ok ; }); 824const int32_t ple [3 ]= {ss .ple_prev [0 ],ss .ple_prev [1 ],ss .ple_token }; 825put (ple ,sizeof ple ); 826ok = std::fclose (f )== 0 && ok ; 827return ok || fail (error ,"the session dump could not be written" ); 828} 829 830}// namespace strata::core