okami.mom/strata

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

Niko1221conversation_transfer_test: wrap the calls of the non-blocking copy helper7a4bc813b

main
15.2 KiB249 linesraw
1// Host-only validation fixtures. CUDA is linked but must never be initialized:
2// invalid restores must return before the first CUDA call or destination write.
3#include "strata/core/conversation_snapshot.hpp"
4#include "strata/kernels/kv_q4.hpp"
5
6#include <cstdint>
7#include <cstdio>
8#include <cstdlib>
9#include <functional>
10#include <limits>
11#include <cstring>
12
13#if defined(CONVERSATION_TEST_TRANSFERS)
14// GNU/ELF link wrapping exercises the actual restore control flow without
15// initializing CUDA or deliberately poisoning a real device context. This is
16// host-backend fault injection, not a claim of hardware-failure recovery.
17namespace {
18int copy_calls = 0, sync_calls = 0, fail_copy = 0, fail_sync = 0;
19size_t copied_bytes = 0;
20}
21extern "C" cudaError_t __wrap_cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind) {
22    if (++copy_calls == fail_copy) return cudaErrorInvalidValue;
23    copied_bytes += n;
24    std::memcpy(dst, src, n);
25    return cudaSuccess;
26}
27// the snapshot/checkpoint copies go through a private non-blocking stream (conversation_copy.hpp)
28extern "C" cudaError_t __wrap_cudaGetDevice(int* dev) { *dev = 0; return cudaSuccess; }
29extern "C" cudaError_t __wrap_cudaStreamCreateWithFlags(cudaStream_t* s, unsigned int) {
30    *s = reinterpret_cast<cudaStream_t>(static_cast<uintptr_t>(1)); return cudaSuccess;
31}
32extern "C" cudaError_t __wrap_cudaMemcpyAsync(void* dst, const void* src, size_t n, cudaMemcpyKind, cudaStream_t) {
33    return __wrap_cudaMemcpy(dst, src, n, cudaMemcpyDefault);
34}
35extern "C" cudaError_t __wrap_cudaStreamSynchronize(cudaStream_t) { return cudaSuccess; }
36extern "C" cudaError_t __wrap_cudaDeviceSynchronize() {
37    return ++sync_calls == fail_sync ? cudaErrorUnknown : cudaSuccess;
38}
39extern "C" cudaError_t __wrap_cudaGetLastError() { return cudaSuccess; }
40#endif
41
42using namespace strata::core;
43namespace {
44int checks = 0;
45void check(bool ok, const char* label) {
46    ++checks;
47    if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }
48}
49struct Pools {
50    QsaState st;
51    std::array<std::vector<uint8_t>, 8> data;
52    Pools(const ModelGeometry& g, int format) {
53        st.max_cells = 96; st.n_pages = st.n_slots = 24; st.idx_pooled_rows = 26;
54        st.kv_int8 = format == 1; st.kv_q4 = format == 2;
55        const size_t per = format == 2 ? strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)
56                                      : g.head_dim * (format == 1 ? 1 : 2);
57        data[0].resize(96 * g.n_head_kv * per, 0xa5); data[1] = data[0];
58        data[2].resize(format == 1 ? 96 * g.n_head_kv * (g.head_dim / 64) * 2 : 0, 0xa5); data[3] = data[2];
59        data[4].resize(26 * g.idx_key_dim * 4, 0xa5);
60        data[5].resize(3 * g.idx_key_dim * 4, 0xa5);
61        data[6].resize(g.idx_key_dim * 4, 0xa5); data[7].resize(4, 0xa5);
62        if (format == 2) { st.k_q4 = data[0].data(); st.v_q4 = data[1].data(); }
63        else if (format == 1) {
64            st.k_q = (int8_t*) data[0].data(); st.v_q = (int8_t*) data[1].data();
65            st.k_scale = (uint16_t*) data[2].data(); st.v_scale = (uint16_t*) data[3].data();
66        } else { st.k_pool = (uint16_t*) data[0].data(); st.v_pool = (uint16_t*) data[1].data(); }
67        st.idx_pooled = (float*) data[4].data(); st.idx_tail = (float*) data[5].data();
68        st.idx_dead = (float*) data[6].data(); st.idx_block_pos = (int32_t*) data[7].data();
69    }
70    ConversationKv image(const ModelGeometry& g, bool index) const {
71        ConversationKv k;
72        k.format = qsa_kv_format(st); k.cells = 12; k.page_size = 4;
73        k.heads = g.n_head_kv; k.head_dim = g.head_dim; k.idx_dim = g.idx_key_dim;
74        k.pooled_rows = index ? 3 : 0;
75        k.k.resize(data[0].size() / 8, 13); k.v = k.k;
76        k.k_scale.resize(data[2].size() / 8, 13); k.v_scale = k.k_scale;
77        k.pooled.resize(k.pooled_rows * g.idx_key_dim * 4, 13);
78        return k;
79    }
80};
81
82void fixture(int format, int experts, bool zero_qsa, bool ple) {
83    ModelGeometry g;
84    g.n_layers = zero_qsa ? 3 : 8; g.n_expert = experts;
85    g.ssm_state_size = 2; g.ssm_v_heads = 2; g.ssm_conv_channels = 8;
86    g.n_head_kv = 1; g.head_dim = 64; g.idx_key_dim = 8;
87    std::string error;
88    ConversationStateSizes z;
89    check(conversation_state_sizes(g, z, error), "checked canonical/pruned/zero-QSA sizing");
90    Pools first(g, format), last(g, format), draft(g, format);
91    std::array<QsaState, 2> layers{first.st, last.st};
92    std::vector<uint8_t> gdn(z.gdn, 0xa5), history(ple ? z.ple : 0, 0xa5);
93    SessionState ss;
94    ss.max_cells = 96; ss.gdn_state = (float*) gdn.data();
95    // the whole-model carve, as session_init leaves a one-GPU session
96    ss.layer_hi = g.n_layers; ss.gdn_alloc = g.n_gdn_layers(); ss.qsa_alloc = g.n_qsa_layers();
97    ss.ple_hist = ple ? (float*) history.data() : nullptr;
98    ss.qsa_states = zero_qsa ? nullptr : layers.data();
99    SavedConversation image;
100    image.geometry = {g.n_embd,g.n_layers,g.qsa_interval,g.ssm_state_size,g.ssm_k_heads,g.ssm_v_heads,
101                      g.ssm_d_conv,g.ssm_conv_channels,g.ssm_value_dim,g.n_head,g.n_head_kv,g.head_dim,
102                      g.idx_q_heads,g.idx_key_dim,g.hc,g.hc_lr,g.n_expert,g.n_ff};
103    image.layer_hi = g.n_layers;
104    auto checkpoint = [&](size_t tokens) {
105        ConversationCheckpoint c;
106        c.ids.resize(tokens);
107        for (size_t i = 0; i < tokens; ++i) c.ids[i] = (int32_t) i + 1;
108        c.imgs = {{1, 44}};
109        c.gdn.resize(z.gdn, 13); c.ple.resize(ple ? z.ple : 0, 13);
110        c.tails.resize(g.n_qsa_layers() * z.tail, 13); c.dead.resize(g.n_qsa_layers() * z.dead, 13);
111        c.block_pos.resize(g.n_qsa_layers() * z.block_pos, 13);
112        return c;
113    };
114    image.live = checkpoint(9); image.checkpoints.push_back(checkpoint(5));
115    image.kv.reserve((size_t) g.n_qsa_layers() + 1);
116    if (!zero_qsa) { image.kv.push_back(first.image(g, true)); image.kv.push_back(last.image(g, true)); }
117    image.kv.push_back(draft.image(g, false));
118    check(conversation_snapshot_validate(image, ss, g, draft.st, error), "complete image validates without CUDA");
119    size_t estimate = 0;
120    check(conversation_snapshot_bytes({image.live.ids,image.live.imgs,image.checkpoints,true},ss,g,draft.st,estimate,error),
121          "capture estimate works without CUDA");
122    check(estimate == image.bytes(), "estimate covers checkpoint/indexer/spare payloads");
123    auto unchanged = [&] {
124        auto pristine = [](const auto& bytes) { return std::all_of(bytes.begin(),bytes.end(),[](uint8_t b){return b==0xa5;}); };
125        if (!pristine(gdn) || !pristine(history) || ss.ple_prev[0] != -1 || ss.ple_prev[1] != -1) return false;
126        for (const auto* p : {&first,&last,&draft}) for (const auto& bytes : p->data) if (!pristine(bytes)) return false;
127        return true;
128    };
129    auto reject = [&](const std::function<void(SavedConversation&)>& mutate, const char* label) {
130        auto bad = image; mutate(bad);
131        check(conversation_snapshot_restore(bad,ss,g,draft.st,error) == ConversationRestore::invalid,label);
132        check(unchanged(), "invalid restore did not touch any layer or running-state buffer");
133    };
134    reject([](auto& s){s.kv.back().k.pop_back();}, "late draft corruption rejected before first layer write");
135    reject([](auto& s){s.geometry[16] = 128;}, "different expert geometry rejected");
136    reject([](auto& s){s.live.stage_parts.emplace_back();}, "layer-split live state rejected before writes");
137    reject([](auto& s){s.checkpoints[0].stage_parts.emplace_back();}, "layer-split checkpoint rejected before writes");
138    reject([](auto& s){s.kv.pop_back();}, "missing KV layer rejected");
139    reject([](auto& s){s.live.gdn.pop_back();}, "bad live recurrence rejected");
140    reject([](auto& s){s.checkpoints.back().gdn.pop_back();}, "bad retained checkpoint rejected");
141    reject([](auto& s){s.checkpoints.back().ids[0] = 99;}, "foreign checkpoint prefix rejected");
142    reject([](auto& s){s.checkpoints.back().imgs[0].hash++;}, "foreign checkpoint image rejected");
143    reject([](auto& s){s.live.imgs[0].start = -1;}, "negative image position rejected");
144    reject([](auto& s){s.live.ids[0] = -1;}, "negative live token rejected");
145    reject([](auto& s){s.live.ple.push_back(0);}, "PLE size/enabled mismatch rejected");
146    reject([](auto& s){s.live.tails.push_back(0);}, "tail size/zero-QSA mismatch rejected");
147    if (!zero_qsa) {
148        reject([](auto& s){s.kv[1].pooled.pop_back();}, "late indexer spare row corruption rejected");
149        reject([](auto& s){s.live.dead.pop_back();}, "missing indexer spare key rejected");
150        reject([](auto& s){s.live.block_pos.pop_back();}, "missing indexer metadata rejected");
151        ss.qsa_states = nullptr;
152        check(!conversation_snapshot_validate(image,ss,g,draft.st,error), "missing QSA targets rejected");
153        ss.qsa_states = layers.data();
154        reject([](auto& s){s.layer_lo = 4;}, "snapshot from another layer range rejected");
155        // #216's carve: a split stage owning layers [4, 8) holds GDN rows 3..5 and QSA ordinal 1 only
156        SessionState stage = ss;
157        stage.layer_lo = 4; stage.gdn_alloc = 3; stage.qsa_ord0 = 1; stage.qsa_alloc = 1;
158        ConversationStateSizes zs;
159        check(conversation_session_sizes(g,stage,zs,error) && zs.gdn == z.gdn / 6 * 3 && zs.tail == z.tail,
160              "carved session sizes cover the owned rows only");
161        check(!conversation_checkpoint_validate(image.live,stage,g,error), "whole-model checkpoint rejected by a carve");
162        ConversationCheckpoint part = image.live;
163        part.gdn.resize(zs.gdn); part.tails.resize(zs.tail); part.dead.resize(zs.dead);
164        part.block_pos.resize(zs.block_pos);
165        check(conversation_checkpoint_validate(part,stage,g,error), "carve-sized checkpoint validates");
166        check(!conversation_snapshot_validate(image,stage,g,draft.st,error), "whole-model snapshot rejected by a carve");
167        stage.qsa_alloc = 2;
168        check(!conversation_session_sizes(g,stage,zs,error), "carve past the last QSA ordinal rejected");
169        stage.qsa_alloc = 1; stage.gdn_alloc = 7;
170        check(!conversation_session_sizes(g,stage,zs,error), "carve past the GDN rows rejected");
171    }
172    auto bad_geometry = g; bad_geometry.ssm_state_size = std::numeric_limits<int64_t>::max();
173    check(!conversation_state_sizes(bad_geometry,z,error), "running-state arithmetic overflow rejected");
174    bad_geometry = g; bad_geometry.qsa_interval = 0;
175    check(!conversation_state_sizes(bad_geometry,z,error), "zero layer interval rejected before division");
176    bad_geometry = g; bad_geometry.n_head_kv = std::numeric_limits<int64_t>::max();
177    check(conversation_kv_bytes(draft.st,bad_geometry,9,false)==0, "KV byte overflow rejected");
178#if defined(CONVERSATION_TEST_TRANSFERS)
179    auto reset = [&] {
180        for (auto* p : {&first,&last,&draft}) for (auto& bytes : p->data) std::fill(bytes.begin(),bytes.end(),0xa5);
181        std::fill(gdn.begin(),gdn.end(),0xa5); std::fill(history.begin(),history.end(),0xa5);
182        ss.ple_prev[0] = ss.ple_prev[1] = -1;
183        copy_calls = sync_calls = fail_copy = fail_sync = 0;
184    };
185    reset(); fail_sync = 1;
186    check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed,
187          "pre-transfer CUDA synchronization failure is fatal");
188    check(copy_calls==0 && unchanged(), "pre-sync failure did not mutate state");
189    reset(); fail_copy = 1;
190    check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed,
191          "first CUDA transfer failure is fatal");
192    check(unchanged(), "first-copy failure did not mutate state");
193    reset(); fail_copy = 2;
194    check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed,
195          "partial CUDA transfer failure is fatal, not an invalid-image fallback");
196    check(!unchanged(), "fault fixture genuinely produced partial state");
197    reset(); fail_sync = 2;
198    check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed,
199          "post-transfer CUDA synchronization failure is fatal");
200    check(copy_calls>0 && !unchanged(), "post-sync failure occurred after state writes");
201    reset();
202    check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::restored,
203          "injected host transfer backend completes a valid restore");
204    check(gdn==image.live.gdn && history==image.live.ple && ss.ple_prev[0]==8 && ss.ple_prev[1]==9,
205          "successful restore publishes correct running state and PLE window");
206    uint64_t fingerprint = 0;
207    check(conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back verifies complete draft payload");
208    draft.data[0][0] ^= 1;
209    check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back detects corrupted draft byte");
210    draft.data[0][0] ^= 1;
211    fail_copy = copy_calls + 1;
212    check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back transfer failure is not a successful fingerprint");
213    reset(); copied_bytes = 0;
214    const ConversationView view{image.live.ids,image.live.imgs,image.checkpoints,true};
215    SavedConversation full,incremental;
216    check(conversation_snapshot_save(full,view,ss,g,draft.st,error), "full capture through host transfer backend");
217    const size_t full_copies = copied_bytes;
218    ConversationKvReuse reuse{full.kv,9,9};
219    size_t peak = 0, reused = 0;
220    check(conversation_snapshot_capture_bytes(reuse,view,ss,g,draft.st,peak,error), "incremental capture admission without transfers");
221    copied_bytes = 0;
222    const bool saved_incrementally = conversation_snapshot_save(incremental,view,ss,g,draft.st,error,std::move(reuse),&reused);
223    if (!saved_incrementally) std::fprintf(stderr,"capture error: %s\n",error.c_str());
224    check(saved_incrementally, "incremental capture through host backend");
225    check(reused > 0 && copied_bytes + reused == full_copies, "reused byte count measures transfers actually omitted");
226    check(incremental.bytes() <= peak && incremental.live.gdn == full.live.gdn, "running state refreshed within admitted allocation");
227    for (size_t i=0;i<full.kv.size();++i)
228        check(incremental.kv[i].k==full.kv[i].k && incremental.kv[i].v==full.kv[i].v &&
229              incremental.kv[i].k_scale==full.kv[i].k_scale && incremental.kv[i].v_scale==full.kv[i].v_scale &&
230              incremental.kv[i].pooled==full.kv[i].pooled, "incremental and full capture agree across every payload");
231    reuse = {full.kv,9,9};
232    reuse.kv.back().k.pop_back();
233    copy_calls = sync_calls = 0;
234    check(!conversation_snapshot_capture_bytes(reuse,view,ss,g,draft.st,peak,error), "malformed retained draft rejected before admission");
235    check(!copy_calls && !sync_calls, "invalid retained storage performs no CUDA calls");
236    reuse = {full.kv,9,9};
237    fail_copy = copy_calls + 1;
238    SavedConversation unpublished;
239    check(!conversation_snapshot_save(unpublished,view,ss,g,draft.st,error,std::move(reuse)), "incremental capture copy failure is reported");
240    check(unpublished.kv.empty() && unpublished.live.ids.empty(), "failed incremental capture cannot publish a partial image");
241#endif
242}
243}
244
245int main() {
246    for (int format : {0,1,2}) for (int experts : {256,512})
247        for (bool zero_qsa : {false,true}) for (bool ple : {false,true}) fixture(format,experts,zero_qsa,ple);
248    std::printf("conversation_validation_test: %d host-only checks passed\n", checks);
249}