okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-intel (2b4d43bac)5438023a6

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