okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

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