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