okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
1#include "strata/core/conversation_snapshot.hpp" 2#include "strata/core/conversation_file.hpp" 3#include "strata/kernels/kv_q4.hpp" 4#include <cuda_runtime.h> 5 6#include <array> 7#include <chrono> 8#include <cstdio> 9#include <filesystem> 10#include <fstream> 11#include <iterator> 12#include <string> 13#include <cstdlib> 14#include <limits> 15#include <utility> 16#include <vector> 17 18using namespace strata::core ; 19using namespace strata::kernels ; 20 21namespace { 22// STRATA_CKPT_ASYNC=1 (the ctest entries conversation_snapshot_test_ckpt_async / _vram_slots): the checkpoint's GDN bytes land in 23// the background; the test reads them at once, so it joins after each save (the engine's readers join before they read) 24template < class ...A > bool ckpt_save (A && ...a ) { 25const bool ok = conversation_checkpoint_save (std::forward < A > (a )...); 26conversation_checkpoint_join (nullptr ); 27return ok ; 28} 29template < class ...A > bool snap_save (A && ...a ) { 30const bool ok = conversation_snapshot_save (std::forward < A > (a )...); 31conversation_checkpoint_join (nullptr ); 32return ok ; 33} 34}// namespace 35 36namespace { 37int checks = 0 ; 38void check (bool ok ,const char * label ) { 39++ checks ; 40if (!ok ) { std::fprintf (stderr ,"FAIL: %s\n" ,label ); std::exit (1 ); } 41} 42void cuda_check (cudaError_t e ) { 43if (e != cudaSuccess ) { std::fprintf (stderr ,"CUDA: %s\n" ,cudaGetErrorString (e )); std::exit (1 ); } 44} 45struct Fixture { 46ModelGeometry g ; 47QsaState state ; 48 std::vector < void *> device ,host ; 49 std::array < void * ,5 > sources {}; 50 std::array < size_t ,5 > sizes {}; 51 52template < class T > void alloc (T *& p ,size_t n ,bool pinned = false) { 53if (!n )return ; 54void * raw = nullptr ; 55if (pinned ) { 56cuda_check (cudaHostAlloc (& raw ,n ,cudaHostAllocMapped )); 57host .push_back (raw ); 58void * mapped = nullptr ; 59cuda_check (cudaHostGetDevicePointer (& mapped ,raw ,0 )); 60p = static_cast < T *> (mapped ); 61 }else { 62cuda_check (cudaMalloc (& raw ,n ));device .push_back (raw );p = static_cast < T *> (raw ); 63 } 64 } 65Fixture (int fmt ,int mode ) { 66auto & st = state ; 67st .kv_mode = mode ;st .kv_int8 = fmt == kKvInt8 ;st .kv_q4 = fmt == kKvQ4 ;st .kv_hybrid = fmt == 3 ; 68st .n_pages = 24 ;st .n_slots = mode ?4 :st .n_pages ; 69st .max_cells = st .n_pages * 4 ;st .idx_pooled_rows = mode == 2 ?2 :st .max_cells /4 + 2 ; 70const size_t per = fmt == kKvQ4 ?kv_q4_bytes_per_head ((int )g .head_dim ) :g .head_dim * ((st .kv_int8 || st .kv_hybrid ) ?1 :2 ); 71const size_t rows = st .max_cells * g .n_head_kv ,slot_rows = st .n_slots * 4 * g .n_head_kv ; 72sizes = {rows * per ,rows * per ,fmt == kKvInt8 ?rows * (g .head_dim /64 )* 2 :0 , 73fmt == kKvInt8 ?rows * (g .head_dim /64 )* 2 :0 , (size_t )st .idx_pooled_rows * g .idx_key_dim * 4 }; 74if (fmt == 3 ) { 75sizes = {rows * per ,rows * kv_q4_bytes_per_head ((int )g .head_dim ),rows * (g .head_dim /64 )* 2 ,0 , 76 (size_t )st .idx_pooled_rows * g .idx_key_dim * 4 }; 77alloc (st .k_q ,sizes [0 ]);alloc (st .v_q4 ,sizes [1 ]);alloc (st .k_scale ,sizes [2 ]); 78sources [0 ]= st .k_q ;sources [1 ]= st .v_q4 ;sources [2 ]= st .k_scale ; 79 }else if (fmt == kKvQ4 ) { 80alloc (st .k_q4 ,slot_rows * per );alloc (st .v_q4 ,slot_rows * per ); 81if (mode ) {alloc (st .host .k_q4 ,sizes [0 ],true);alloc (st .host .v_q4 ,sizes [1 ],true);} 82sources [0 ]= mode ?st .host .k_q4 :st .k_q4 ;sources [1 ]= mode ?st .host .v_q4 :st .v_q4 ; 83 }else if (fmt == kKvInt8 ) { 84alloc (st .k_q ,slot_rows * per );alloc (st .v_q ,slot_rows * per ); 85alloc (st .k_scale ,slot_rows * (g .head_dim /64 )* 2 );alloc (st .v_scale ,slot_rows * (g .head_dim /64 )* 2 ); 86if (mode ) { 87alloc (st .host .k_q ,sizes [0 ],true);alloc (st .host .v_q ,sizes [1 ],true); 88alloc (st .host .k_scale ,sizes [2 ],true);alloc (st .host .v_scale ,sizes [3 ],true); 89 } 90sources [0 ]= mode ?st .host .k_q :st .k_q ;sources [1 ]= mode ?st .host .v_q :st .v_q ; 91sources [2 ]= mode ?st .host .k_scale :st .k_scale ;sources [3 ]= mode ?st .host .v_scale :st .v_scale ; 92 }else { 93alloc (st .k_pool ,slot_rows * per );alloc (st .v_pool ,slot_rows * per ); 94if (mode ) {alloc (st .host .k_pool ,sizes [0 ],true);alloc (st .host .v_pool ,sizes [1 ],true);} 95sources [0 ]= mode ?st .host .k_pool :st .k_pool ;sources [1 ]= mode ?st .host .v_pool :st .v_pool ; 96 } 97alloc (st .idx_pooled ,sizes [4 ]);sources [4 ]= st .idx_pooled ; 98alloc (st .page_table ,st .n_pages * 4 ); 99if (mode == 1 ) { 100auto & m = st .map ; 101m .page_table = st .page_table ;m .n_blocks = st .n_pages ;m .n_slots = st .n_slots ; 102alloc (m .slot_block ,st .n_slots * 4 );alloc (m .slot_stamp ,st .n_slots * 4 );alloc (m .slot_ref ,st .n_slots * 4 ); 103alloc (m .miss_block ,st .n_slots * 4 );alloc (m .miss_slot ,st .n_slots * 4 );alloc (m .ctl ,kKvCtlInts * 4 ); 104 }else if (mode == 2 ) { 105kv_ring_table (st .page_table ,st .n_pages ,st .n_slots ,nullptr ); 106 } 107 } 108void fill (uint8_t salt ) { 109for (size_t i = 0 ;i < sources .size ();++ i ) { 110 std::vector < uint8_t > data (sizes [i ]); 111for (size_t j = 0 ;j < data .size ();++ j )data [j ]= (uint8_t )(salt + i * 31 + j * 7 + j /257 ); 112if (!data .empty ())cuda_check (cudaMemcpy (sources [i ],data .data (),data .size (),cudaMemcpyDefault )); 113 } 114 } 115void fill_after (uint8_t salt ,int64_t first_dirty ) { 116for (size_t i = 0 ;i < sources .size ();++ i ) { 117const size_t offset = i == 4 ?size_t (first_dirty /4 )* g .idx_key_dim * 4 118 : (sizes [i ]/size_t (state .max_cells ))* size_t ((first_dirty /4 )* 4 ); 119if (sizes [i ]> offset ) 120cuda_check (cudaMemset (static_cast < uint8_t *> (sources [i ])+ offset ,salt ,sizes [i ]- offset )); 121 } 122 } 123 ~Fixture () {for (void * p :device )cudaFree (p );for (void * p :host )cudaFreeHost (p ); } 124}; 125bool equal (const ConversationKv & a ,const ConversationKv & b ) { 126return a .k == b .k && a .v == b .v && a .k_scale == b .k_scale && a .v_scale == b .v_scale && a .pooled == b .pooled ; 127} 128 129void full_session (int fmt ,int mode ,int experts ) { 130Fixture main (fmt ,mode ),draft (fmt == 3 ?kKvInt8 :fmt ,2 ); 131auto & g = main .g ; 132g .n_layers = 4 ;g .n_expert = experts ; 133g .ssm_state_size = 2 ;g .ssm_v_heads = 2 ;g .ssm_conv_channels = 8 ; 134if (std::getenv ("STRATA_TEST_BIG_GDN" )) {g .ssm_state_size = 64 ;g .ssm_v_heads = 64 ; }// a GDN state over 1 MiB: the async checkpoint path 135SessionState ss ; 136ss .max_cells = 96 ;ss .qsa_states =& main .state ; 137ss .layer_hi = g .n_layers ;ss .gdn_alloc = g .n_gdn_layers ();ss .qsa_alloc = g .n_qsa_layers ();// the whole-model carve 138 std::string err ; 139ConversationStateSizes sizes ; 140check (conversation_state_sizes (g ,sizes ,err ),"whole-session geometry sizes" ); 141main .alloc (ss .gdn_state ,sizes .gdn );main .alloc (ss .ple_hist ,sizes .ple ); 142main .alloc (main .state .idx_tail ,sizes .tail );main .alloc (main .state .idx_dead ,sizes .dead ); 143main .alloc (main .state .idx_block_pos ,sizes .block_pos ); 144 std::vector < int32_t > ids (65 ); 145for (size_t i = 0 ;i < ids .size ();++ i )ids [i ]= (int32_t )i + 1 ; 146 std::vector < ConversationImageKey > images ; 147 std::vector < ConversationCheckpoint > checkpoints ; 148auto fill = [& ](uint8_t salt ) { 149main .fill (salt );draft .fill (salt ); 150for (const auto & [p ,n ] : std::vector < std::pair < void * ,size_t >> { 151 {ss .gdn_state ,sizes .gdn },{ss .ple_hist ,sizes .ple },{main .state .idx_tail ,sizes .tail }, 152 {main .state .idx_dead ,sizes .dead },{main .state .idx_block_pos ,sizes .block_pos }}) 153cuda_check (cudaMemset (p ,salt ,n )); 154// A real indexer maintains its spare pooled row as a copy of idx_dead. 155cuda_check (cudaMemcpy (main .state .idx_pooled + (ids .size ()/4 )* g .idx_key_dim , 156main .state .idx_dead ,sizes .dead ,cudaMemcpyDeviceToDevice )); 157cuda_check (cudaDeviceSynchronize ()); 158 }; 159fill (13 ); 160ConversationCheckpoint checkpoint ; 161checkpoint .ids .assign (ids .begin (),ids .begin ()+ 3 ); 162check (ckpt_save (checkpoint ,ss ,g ,err ),"save complete running checkpoint" ); 163checkpoint .used = 17 ; 164checkpoints .push_back (std::move (checkpoint )); 165const ConversationView view {ids ,images ,checkpoints ,true}; 166SavedConversation a ,b ,restored ; 167check (snap_save (a ,view ,ss ,g ,draft .state ,err ),"capture complete A" ); 168check (a .checkpoints [0 ].used == 17 ,"upstream checkpoint LRU stamp survives capture" ); 169fill (177 ); 170check (snap_save (b ,view ,ss ,g ,draft .state ,err ),"capture complete B" ); 171 { 172// disk save path: metadata + streamed K/V give the same file as the captured image 173SavedConversation meta ; 174 std::vector < SessionKvSource > sources ; 175check (conversation_snapshot_sources (meta ,sources ,view ,ss ,g ,draft .state ,err ),"disk-save sources" ); 176check (meta .kv .empty ()&& sources .size ()== b .kv .size (),"one source per K/V layer, none captured" ); 177const SessionFileIdentity id {1 ,2 }; 178namespace fs= std::filesystem; 179const fs::path dir = fs::temp_directory_path ()/("strata-snap-test-" + std::to_string (experts )+ "-" + 180 std::to_string (std::chrono::steady_clock::now ().time_since_epoch ().count ())); 181 fs::create_directories (dir ); 182const std::string p1 = (dir /"streamed.bin" ).string (),p2 = (dir /"captured.bin" ).string (); 183auto slurp = [](const std::string & p ){ std::ifstream f (p ,std::ios::binary ); 184return std::vector < char > ((std::istreambuf_iterator < char > (f )),std::istreambuf_iterator < char > ()); }; 185size_t n1 = 0 ,n2 = 0 ; 186check (session_file_write (p1 ,meta ,sources ,id ,n1 ,err ),"streamed session write" ); 187check (session_file_write (p2 ,b ,id ,n2 ,err ),"captured session write" ); 188SavedConversation x ,y ; 189check (session_file_read (p1 ,id ,x ,n1 ,err )&& session_file_read (p2 ,id ,y ,n2 ,err )&& n1 == n2 ,"both files read" ); 190check (x .live .gdn == y .live .gdn && x .live .dead == y .live .dead && x .live .ids == y .live .ids && 191x .checkpoints .size ()== y .checkpoints .size ()&& equal (x .kv [0 ],y .kv [0 ])&& equal (x .kv .back (),y .kv .back ()), 192"streamed file equals captured file" ); 193check (slurp (p1 )== slurp (p2 ),"streamed file is byte-identical to the captured file" ); 194 std::error_code ec ; 195 fs::remove_all (dir ,ec ); 196auto empty_ids = std::vector < int32_t > {}; 197const ConversationView none {empty_ids ,images ,checkpoints ,true}; 198check (!conversation_snapshot_sources (meta ,sources ,none ,ss ,g ,draft .state ,err ),"empty session refused" ); 199 } 200check (a .live .dead != b .live .dead ,"different opening-state spare keys in regression fixture" ); 201auto bad = a ;bad .kv .back ().k .pop_back (); 202check (conversation_snapshot_restore (bad ,ss ,g ,draft .state ,err )== ConversationRestore ::invalid , 203"reject invalid late draft before any main-layer write" ); 204check (snap_save (restored ,view ,ss ,g ,draft .state ,err ),"capture B after refused restore" ); 205check (restored .live .gdn == b .live .gdn && restored .live .dead == b .live .dead && 206equal (restored .kv [0 ],b .kv [0 ])&& equal (restored .kv [1 ],b .kv [1 ]),"refusal preserves all tested state" ); 207check (conversation_snapshot_restore (a ,ss ,g ,draft .state ,err )== ConversationRestore ::restored ,"restore complete A" ); 208check (snap_save (restored ,view ,ss ,g ,draft .state ,err ),"capture restored A" ); 209check (restored .live .gdn == a .live .gdn && restored .live .ple == a .live .ple && restored .live .tails == a .live .tails && 210restored .live .dead == a .live .dead && restored .live .block_pos == a .live .block_pos && 211equal (restored .kv [0 ],a .kv [0 ])&& equal (restored .kv [1 ],a .kv [1 ]),"whole-session A/B/A exactness including spare key" ); 212check (ss .ple_prev [0 ]== 64 && ss .ple_prev [1 ]== 65 ,"PLE token window reconstructed" ); 213 { 214// #2409: a restore writes into the session's own buffers. After the copy stream exists (the restores above made 215// it) a restore of either image allocates nothing on the card: free memory does not move (2 MiB allocation 216// granules; 4 MiB of slack for a desktop card's other programs). 217check (conversation_copy_stream_ready (0 ),"this thread has its copy stream after the first restore" ); 218cudaDeviceSynchronize (); 219size_t before = 0 ,after = 0 ,total = 0 ; 220check (cudaMemGetInfo (& before ,& total )== cudaSuccess ,"free memory before the repeated restores" ); 221for (int i = 0 ;i < 6 ;++ i ) 222check (conversation_snapshot_restore (i %2 ?b :a ,ss ,g ,draft .state ,err )== ConversationRestore ::restored ,"repeated restore" ); 223cudaDeviceSynchronize (); 224check (cudaMemGetInfo (& after ,& total )== cudaSuccess ,"free memory after the repeated restores" ); 225check ((long long )after + (4ll <<20 )>=(long long )before ,"six more restores allocate nothing on the card" ); 226check (conversation_snapshot_restore (a ,ss ,g ,draft .state ,err )== ConversationRestore ::restored ,"A is back" ); 227 } 228 { 229// a borrowed prefix (ConversationCache::borrows): the K/V of A's first tokens and A's checkpoint there, A 230// untouched - the same bytes as restoring A whole and rewinding to that checkpoint 231const int64_t at = (int64_t )a .checkpoints [0 ].ids .size (); 232check (conversation_snapshot_restore (a ,ss ,g ,draft .state ,err )== ConversationRestore ::restored ,"restore A whole" ); 233check (conversation_checkpoint_restore (a .checkpoints [0 ],ss ,g ,err ),"rewind it to its checkpoint" ); 234ConversationKv want_main ,want_draft ,got_main ,got_draft ; 235ConversationCheckpoint want_state ,got_state ; 236want_state .ids = got_state .ids = a .checkpoints [0 ].ids ; 237check (conversation_kv_save (want_main ,main .state ,g ,at ,true,err )&& 238conversation_kv_save (want_draft ,draft .state ,g ,at ,false,err )&& 239ckpt_save (want_state ,ss ,g ,err ),"capture the rewound prefix" ); 240fill (201 );// another conversation in the session 241const SavedConversation untouched = a ; 242check (conversation_snapshot_restore_prefix (a ,(int64_t )a .live .ids .size ()+ 1 ,ss ,g ,draft .state ,err )== 243ConversationRestore ::invalid && 244conversation_snapshot_restore_prefix (a ,0 ,ss ,g ,draft .state ,err )== ConversationRestore ::invalid , 245"a prefix outside the image is refused" ); 246check (conversation_snapshot_restore_prefix (a ,at ,ss ,g ,draft .state ,err )== ConversationRestore ::restored , 247"restore A's prefix only" ); 248check (conversation_checkpoint_restore (a .checkpoints [0 ],ss ,g ,err ),"mount the checkpoint over it" ); 249check (conversation_kv_save (got_main ,main .state ,g ,at ,true,err )&& 250conversation_kv_save (got_draft ,draft .state ,g ,at ,false,err )&& 251ckpt_save (got_state ,ss ,g ,err ),"capture the borrowed prefix" ); 252check (equal (got_main ,want_main )&& equal (got_draft ,want_draft ), 253"borrowed K/V equals the whole restore's prefix" ); 254check (got_state .gdn == want_state .gdn && got_state .ple == want_state .ple && got_state .tails == want_state .tails && 255got_state .dead == want_state .dead && got_state .block_pos == want_state .block_pos ,"the same running state" ); 256check (untouched .live .ids == a .live .ids && equal (untouched .kv [0 ],a .kv [0 ])&& equal (untouched .kv [1 ],a .kv [1 ]), 257"the parked image is unchanged" ); 258 } 259for (int64_t dirty : {65 ,3 ,0 }) { 260check (conversation_snapshot_restore (a ,ss ,g ,draft .state ,err )== ConversationRestore ::restored ,"restore growth fixture base" ); 261ConversationKvReuse reuse {a .kv ,65 ,dirty }; 262const uint8_t * original = nullptr ; 263reuse .kv [0 ].k .visit (0 ,1 ,[& ](const uint8_t * p ,size_t ,size_t ){original = p ;return true;}); 264main .fill_after (91 ,dirty );draft .fill_after (91 ,std::max < int64_t > (0 ,dirty - 1 )); 265cuda_check (cudaMemset (ss .gdn_state ,91 ,sizes .gdn )); 266ids .resize (70 ); 267for (size_t i = 65 ;i < ids .size ();++ i )ids [i ]= int32_t (i + 1 ); 268cuda_check (cudaMemcpy (main .state .idx_pooled + (ids .size ()/4 )* g .idx_key_dim , 269main .state .idx_dead ,sizes .dead ,cudaMemcpyDeviceToDevice )); 270SavedConversation fresh ,incremental ; 271check (snap_save (fresh ,view ,ss ,g ,draft .state ,err ),"full capture reference after growth or rewind" ); 272size_t peak = 0 ,reused = 0 ; 273check (conversation_snapshot_capture_bytes (reuse ,view ,ss ,g ,draft .state ,peak ,err ),"admit incremental capture peak" ); 274check (snap_save (incremental ,view ,ss ,g ,draft .state ,err ,std::move (reuse ),& reused ),"capture with retained pages" ); 275check (incremental .bytes () <=peak ,"incremental allocation stays within admitted bound" ); 276check (incremental .live .gdn == fresh .live .gdn && incremental .live .ple == fresh .live .ple && 277incremental .live .dead == fresh .live .dead && equal (incremental .kv [0 ],fresh .kv [0 ])&& 278equal (incremental .kv [1 ],fresh .kv [1 ]),"incremental capture equals full capture after growth or rewind" ); 279check ((dirty >=4 )== (reused > 0 ),"only complete unchanged pages or rows are retained" ); 280incremental .kv [0 ].k .visit (0 ,1 ,[& ](const uint8_t * p ,size_t ,size_t ){ 281check (p == original ,"growth never reallocates the retained payload" );return true; 282 }); 283check (conversation_snapshot_restore (incremental ,ss ,g ,draft .state ,err )== ConversationRestore ::restored ,"restore segmented incremental snapshot" ); 284uint64_t fingerprint = 0 ; 285check (conversation_kv_verify (incremental .kv .back (),draft .state ,g ,70 ,false,fingerprint ,err ),"incremental draft authoritative and ring read-back" ); 286ids .resize (65 ); 287 } 288 { 289// a layer split's later stage: the same image WITHOUT the draft layer's K/V (draft == nullptr) 290check (conversation_snapshot_restore (a ,ss ,g ,draft .state ,err )== ConversationRestore ::restored ,"restore A before stage images" ); 291size_t with_draft = 0 ,without = 0 ; 292check (conversation_snapshot_bytes (view ,ss ,g ,draft .state ,with_draft ,err )&& 293conversation_snapshot_bytes (view ,ss ,g ,nullptr ,without ,err )&& without < with_draft , 294"a stage image's estimate leaves the draft out" ); 295SavedConversation stage ,stage_b ,stage_back ; 296check (snap_save (stage ,view ,ss ,g ,nullptr ,err ),"capture a stage image" ); 297check (stage .kv .size ()== a .kv .size ()- 1 && equal (stage .kv [0 ],a .kv [0 ])&& stage .live .gdn == a .live .gdn , 298"a stage image holds the session's own layers, no draft" ); 299check (stage .bytes ()< a .bytes (),"a stage image is smaller by the draft ring" ); 300check (conversation_snapshot_validate (stage ,ss ,g ,nullptr ,err ),"validate a stage image without a draft" ); 301check (!conversation_snapshot_validate (stage ,ss ,g ,draft .state ,err ),"a stage image is refused where a draft is expected" ); 302check (!conversation_snapshot_validate (a ,ss ,g ,nullptr ,err ),"an image with a draft is refused where none is expected" ); 303fill (201 ); 304check (snap_save (stage_b ,view ,ss ,g ,nullptr ,err ),"capture another stage state" ); 305check (conversation_snapshot_restore (a ,ss ,g ,nullptr ,err )== ConversationRestore ::invalid , 306"restoring a draft image as a stage image is refused before any write" ); 307check (snap_save (stage_back ,view ,ss ,g ,nullptr ,err )&& stage_back .live .gdn == stage_b .live .gdn && 308equal (stage_back .kv [0 ],stage_b .kv [0 ]),"the refusal left the stage untouched" ); 309check (conversation_snapshot_restore (stage ,ss ,g ,nullptr ,err )== ConversationRestore ::restored ,"restore a stage image" ); 310check (snap_save (stage_back ,view ,ss ,g ,nullptr ,err )&& stage_back .live .gdn == stage .live .gdn && 311stage_back .live .dead == stage .live .dead && equal (stage_back .kv [0 ],stage .kv [0 ]),"stage A/B/A exactness" ); 312// its retained K/V: the next park copies only what changed, and equals a full capture 313ConversationKvReuse reuse {stage .kv ,65 ,65 ,{}}; 314SavedConversation fresh ,incremental ; 315size_t peak = 0 ,reused = 0 ; 316check (snap_save (fresh ,view ,ss ,g ,nullptr ,err ),"full stage capture reference" ); 317check (conversation_snapshot_capture_bytes (reuse ,view ,ss ,g ,nullptr ,peak ,err ),"admit an incremental stage capture" ); 318check (snap_save (incremental ,view ,ss ,g ,nullptr ,err ,std::move (reuse ),& reused ),"incremental stage capture" ); 319check (reused > 0 && incremental .bytes ()<=peak && equal (incremental .kv [0 ],fresh .kv [0 ])&& 320incremental .live .gdn == fresh .live .gdn ,"an incremental stage capture reuses pages and equals a full one" ); 321SavedConversation split_image = stage ; 322split_image .stage_images .push_back (stage ); 323check (!conversation_snapshot_validate (split_image ,ss ,g ,draft .state ,err ), 324"a layer split's image is refused by the whole-session form" ); 325ConversationKvReuse wrong {a .kv ,65 ,65 ,{}}; 326check (!conversation_snapshot_capture_bytes (wrong ,view ,ss ,g ,nullptr ,peak ,err ),"a draft image's K/V is not a stage's reuse" ); 327 } 328check (conversation_snapshot_restore (a ,ss ,g ,draft .state ,err )== ConversationRestore ::restored ,"restore A after stage images" ); 329check (conversation_checkpoint_restore (a .checkpoints [0 ],ss ,g ,err ),"restore early running checkpoint" ); 330 std::vector < uint8_t > spare (sizes .dead ); 331cuda_check (cudaMemcpy (spare .data (),main .state .idx_pooled ,sizes .dead ,cudaMemcpyDeviceToHost )); 332check (spare == a .checkpoints [0 ].dead ,"checkpoint rebuilds spare row over a later completed block" ); 333check (ss .ple_prev [0 ]== 2 && ss .ple_prev [1 ]== 3 ,"checkpoint PLE token window" ); 334} 335} 336 337int main () { 338int devices = 0 ; 339if (cudaGetDeviceCount (& devices )!= cudaSuccess || !devices )return 77 ; 340for (int fmt : std::array < int ,4 > {kKvF16 ,kKvInt8 ,kKvQ4 ,3 })for (int mode : {0 ,1 ,2 }) { 341if (fmt == 3 && mode != 0 )continue ; 342Fixture f (fmt ,mode ); 343if (fmt == 3 ) { 344 std::string err ; 345ConversationKv invalid ; 346for (int unsupported : {1 ,2 }) { 347f .state .kv_mode = unsupported ; 348check (conversation_kv_bytes (f .state ,f .g ,9 ,true)== 0 ,"hybrid streaming/ring rejected without block-mover abort" ); 349check (!conversation_kv_save (invalid ,f .state ,f .g ,9 ,true,err ),"hybrid streaming/ring capture fails closed" ); 350 } 351f .state .kv_mode = 0 ; 352 } 353 { 354 std::string err ; 355ConversationKv invalid ; 356for (const int64_t bad : {-1LL ,97LL , (long long ) std::numeric_limits < int64_t > ::max ()}) { 357check (!conversation_kv_save (invalid ,f .state ,f .g ,bad ,mode != 2 ,err ),"reject invalid save extent before allocation" ); 358check (!conversation_kv_restore (invalid ,f .state ,f .g ,bad ,mode != 2 ,err ),"reject invalid restore extent before copying" ); 359check (conversation_kv_bytes (f .state ,f .g ,bad ,mode != 2 )== 0 ,"invalid extent cannot overflow byte estimate" ); 360 } 361 } 362for (int64_t upto : {0 ,1 ,3 ,4 ,5 ,63 ,64 ,65 ,96 }) { 363const bool index = mode != 2 ; 364 std::string err ; 365f .fill (13 ); 366ConversationKv a ,b ,restored ; 367cuda_check (cudaDeviceSynchronize ()); 368check (conversation_kv_save (a ,f .state ,f .g ,upto ,index ,err ),"save A" ); 369check (a .bytes ()== conversation_kv_bytes (f .state ,f .g ,upto ,index ),"size estimate equals snapshot payload" ); 370f .fill (177 ); 371check (conversation_kv_save (b ,f .state ,f .g ,upto ,index ,err ),"save B" ); 372check (upto == 0 || !equal (a ,b ),"fixture changes state" ); 373check (conversation_kv_restore (a ,f .state ,f .g ,upto ,index ,err ),"restore A over B" ); 374cuda_check (cudaDeviceSynchronize ()); 375check (conversation_kv_save (restored ,f .state ,f .g ,upto ,index ,err ),"read back restored A" ); 376check (equal (a ,restored ),"A/B/A byte-exact K/V and indexer state" ); 377uint64_t fingerprint = 0 ; 378check (conversation_kv_verify (a ,f .state ,f .g ,upto ,index ,fingerprint ,err ),"verify restored authoritative and resident bytes without rewriting them" ); 379 { 380// disk save streams the same bytes as a captured image, without the host copy 381SessionKvSource src ; 382check (conversation_kv_source (src ,f .state ,f .g ,upto ,index ,err ),"K/V source for a disk save" ); 383check (src .format == a .format && src .cells == a .cells && src .heads == a .heads && src .head_dim == a .head_dim && 384src .page_size == a .page_size && src .pooled_rows == a .pooled_rows && src .idx_dim == a .idx_dim , 385"K/V source metadata equals the captured image" ); 386const std::array < const ConversationBuffer * ,5 > parts = {& a .k ,& a .v ,& a .k_scale ,& a .v_scale ,& a .pooled }; 387for (size_t i = 0 ;i < 5 ;++ i ) { 388check (src .sizes [i ]== parts [i ]-> size (),"K/V source part size" ); 389 std::vector < uint8_t > got (src .sizes [i ]),want (src .sizes [i ]); 390const size_t half = src .sizes [i ]/2 ;// two reads: offsets are honoured 391check (src .read (i ,0 ,got .data (),half )&& src .read (i ,half ,got .data ()+ half ,src .sizes [i ]- half ), 392"K/V source reads" ); 393check (parts [i ]-> read (want .data (),0 ,want .size ())&& got == want ,"K/V source bytes equal the image" ); 394 } 395SessionKvSource none ; 396check (!conversation_kv_source (none ,f .state ,f .g ,-1 ,index ,err ),"K/V source rejects an invalid extent" ); 397 } 398if (mode == 1 ) { 399 std::vector < int32_t > table ((size_t )f .state .n_pages ); 400cuda_check (cudaMemcpy (table .data (),f .state .page_table ,table .size ()* 4 ,cudaMemcpyDeviceToHost )); 401check (std::all_of (table .begin (),table .end (),[](int32_t x ){return x == -1 ;}),"stale VRAM pages invalidated" ); 402 } 403if (mode == 2 && upto > 0 ) { 404const auto s = qsa_real_shapes (); 405const int64_t b1 = (upto + s .page_size - 1 )/s .page_size ,b0 = std::max < int64_t > (0 ,b1 - f .state .n_slots ); 406const size_t block = kv_block_bytes (s ,fmt )/2 ; 407// Codes and scales are separate in INT8; check code bytes here. 408const size_t code_block = fmt == kKvInt8 ?s .page_size * s .n_head_kv * s .head_dim :block ; 409const void * slots = fmt == kKvQ4 ?(void * )f .state .k_q4 :fmt == kKvInt8 ?(void * )f .state .k_q :(void * )f .state .k_pool ; 410 std::vector < uint8_t > got (code_block ); 411for (int64_t page = b0 ;page < b1 ;++ page ) { 412cuda_check (cudaMemcpy (got .data (),(const uint8_t * )slots + (page %f .state .n_slots )* code_block ,code_block ,cudaMemcpyDeviceToHost )); 413 std::vector < uint8_t > expected (code_block ); 414check (a .k .read (expected .data (),page * code_block ,code_block ),"read segmented expected draft page" ); 415check (got == expected ,"draft ring contains restored pages" ); 416 } 417 } 418auto bad = a ;bad .head_dim ++ ; 419check (!conversation_kv_restore (bad ,f .state ,f .g ,upto ,index ,err ),"reject incompatible geometry" ); 420if (fmt == kKvInt8 ) { 421// #293: INT8 K/V saved through the Hadamard rotation (STRATA_KV_ROT=1) never restores into a state 422// without it, nor the reverse 423f .state .kv_rot = true; 424ConversationKv rotated ; 425check (conversation_kv_save (rotated ,f .state ,f .g ,upto ,index ,err ),"save rotated INT8" ); 426check (!conversation_kv_restore (a ,f .state ,f .g ,upto ,index ,err ),"unrotated image into a rotated state rejected" ); 427f .state .kv_rot = false; 428check (!conversation_kv_restore (rotated ,f .state ,f .g ,upto ,index ,err ),"rotated image into an unrotated state rejected" ); 429check (conversation_kv_restore (a ,f .state ,f .g ,upto ,index ,err ),"unrotated image still restores" ); 430 } 431if (!a .k .empty ()) { 432bad = a ;bad .k .pop_back (); 433check (!conversation_kv_restore (bad ,f .state ,f .g ,upto ,index ,err ),"reject malformed payload" ); 434 } 435 } 436 } 437for (int fmt : {kKvF16 ,kKvInt8 ,kKvQ4 })for (int mode : {0 ,1 })for (int experts : {256 ,512 }) 438full_session (fmt ,mode ,experts ); 439for (int experts : {256 ,512 })full_session (3 ,0 ,experts ); 440 std::printf ("conversation_snapshot_test: %d checks passed\n" ,checks ); 441}