okami.mom/strata

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

Niko1221Merge f-park-pool ef371eba8 into f-p4-inta46c667cc

main
39.4 KiB775 linesraw
1#include "strata/core/conversation_snapshot.hpp"
2#include "strata/kernels/kv_q4.hpp"
3#include "conversation_checked.hpp"
4#include "conversation_copy.hpp"
5#include "conversation_trace.hpp"
6#include <cuda_runtime.h>
7
8#include <array>
9#include <chrono>
10#include <cstdio>
11#include <cstdlib>
12#include <cstring>
13#include <future>
14#include <limits>
15#include <memory>
16#include <mutex>
17
18namespace strata::core {
19namespace {
20struct Layout {
21    int format;
22    int64_t cells, pooled_rows, page_size;
23    size_t data, scales, pooled, value_data, value_scales;
24};
25
26bool valid_extent(const QsaState& st, int64_t upto, std::string& error) {
27    const int64_t page = strata::kernels::qsa_real_shapes().page_size;
28    if (upto < 0 || upto > st.max_cells || upto > std::numeric_limits<int64_t>::max() - (page - 1)) {
29        error = "conversation snapshot: invalid K/V extent";
30        return false;
31    }
32    return true;
33}
34
35bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) {
36    if (!valid_extent(st, upto, error)) return false;
37    if (st.kv_hybrid && (st.kv_mode == 2 || st.kv_q4 || st.kv_int8)) {   // a streamed one reads its host copy
38        error = "conversation snapshot: hybrid K8V4 cannot be a ring and needs distinct format flags";
39        return false;
40    }
41    const auto s = strata::kernels::qsa_real_shapes();
42    const bool int8_keys = st.kv_int8 || st.kv_hybrid;
43    if (g.n_head_kv <= 0 || g.head_dim <= 0 || g.head_dim > INT32_MAX || g.idx_key_dim <= 0 ||
44        (st.kv_q4 && g.head_dim % 32) || (int8_keys && !st.kv_q4 && g.head_dim % 64)) {
45        error = "conversation snapshot: invalid K/V geometry";
46        return false;
47    }
48    const int64_t cells = ((upto + s.page_size - 1) / s.page_size) * s.page_size;
49    const size_t per = st.kv_q4 ? (size_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)
50                              : (size_t) g.head_dim * (int8_keys ? 1 : 2);
51    // Include the moving spare row, not only completed blocks. The checkpoint
52    // restore reconstructs that row when rewinding to an earlier prefix.
53    const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0;
54    // Format 3 identifies snapshot K8V4 only; never pass it to the block movers.  Rotated INT8 K/V (#293,
55    // STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a
56    // snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse.
57    // (Q4_0 is always rotated: nothing to tell apart; without the rotation the format is the one it always was.)
58    const int rotated = st.kv_rot && !st.kv_q4 && !st.kv_hybrid ? 16 : 0;
59    l = {(st.kv_hybrid ? 3 : qsa_kv_format(st)) + rotated, cells, pooled, s.page_size, 0, 0, 0, 0, 0};
60    using conversation_detail::product;
61    if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) ||
62        !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv,
63                           int8_keys && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) ||
64        !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)})) {
65        error = "conversation snapshot: K/V byte count overflow";
66        return false;
67    }
68    l.value_data = l.data;
69    l.value_scales = l.scales;
70    if (st.kv_hybrid) {
71        if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv,
72                                   (uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) {
73            error = "conversation snapshot: hybrid V byte count overflow";
74            return false;
75        }
76        l.value_scales = 0;
77    }
78    return true;
79}
80
81std::array<void*, 5> pools(const QsaState& st, bool resident = false) {
82    const bool host = st.kv_mode != 0 && !resident;
83    if (st.kv_hybrid)
84        return {host ? st.host.k_q : st.k_q, host ? st.host.v_q4 : st.v_q4, host ? st.host.k_scale : st.k_scale,
85                nullptr, st.idx_pooled};
86    if (st.kv_q4)
87        return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled};
88    if (st.kv_int8)
89        return {host ? st.host.k_q : st.k_q, host ? st.host.v_q : st.v_q,
90                host ? st.host.k_scale : st.k_scale, host ? st.host.v_scale : st.v_scale, st.idx_pooled};
91    return {host ? st.host.k_pool : st.k_pool, host ? st.host.v_pool : st.v_pool, nullptr, nullptr, st.idx_pooled};
92}
93
94bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error) {
95    if (upto < 0 || upto > st.max_cells || st.n_pages < 0 || l.cells / l.page_size > st.n_pages ||
96        st.kv_mode < 0 || st.kv_mode > 2 || st.n_slots <= 0 ||
97        (st.kv_mode == 0 && st.n_slots < st.n_pages) ||
98        l.pooled_rows > st.idx_pooled_rows || (st.kv_mode != 0 && !st.host.present())) {
99        error = "conversation snapshot: invalid K/V extent or missing authoritative host pool";
100        return false;
101    }
102    if (st.kv_mode == 1) {
103        const auto& m = st.map;
104        if (m.n_blocks != st.n_pages || m.n_slots != st.n_slots || !m.page_table || !m.slot_block ||
105            !m.slot_stamp || !m.slot_ref || !m.ctl || !m.miss_block || !m.miss_slot) {
106            error = "conversation snapshot: invalid streaming map";
107            return false;
108        }
109    }
110    if (st.kv_mode == 2 && (!st.page_table ||
111        (st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale
112                                                    : !st.k_pool || !st.v_pool))) {
113        error = "conversation snapshot: invalid draft ring";
114        return false;
115    }
116    return true;
117}
118
119// STRATA_PARK_VRAM_MIB=N (with STRATA_PARK_ASYNC): a park also keeps the whole K/V of its image in VRAM, in a slot
120// of its own, while the slots' total stays within N MiB; a restore of that image copies from the slot device to
121// device (~1 ms) instead of from the host buffers over PCIe, and needs no wait for the background copy.  A slot is
122// released with the image or its K/V layers (their tokens), or all at once under VRAM pressure
123// (conversation_park_vram_release_all).  Host thread only; the background copy only reads a slot's bytes, and every
124// reuse or free of one comes after a join (conversation_park_async_begin, release_all).
125struct VramKvSlot {
126    void* p = nullptr;
127    size_t cap = 0, used = 0;
128    uint64_t tag = 0;   // 0: free (kept for reuse by size)
129    int dev = -1;
130    struct Part { uint64_t tag; size_t part, offset, bytes; };   // one layer's part (k, v, k_scale, v_scale, pooled)
131    std::vector<Part> parts;
132};
133struct VramKv {
134    std::vector<std::unique_ptr<VramKvSlot>> slots;
135    uint64_t next_tag = 1;   // slot and layer tags, never reused
136};
137VramKv& vram_kv() { static VramKv v; return v; }
138size_t park_vram_budget() {
139    static const size_t b = [] {
140        const char* v = std::getenv("STRATA_PARK_VRAM_MIB");
141        const long long mib = v != nullptr ? std::atoll(v) : 0;
142        return mib > 0 ? (size_t) mib << 20 : (size_t) 0;
143    }();
144    return b;
145}
146bool park_trace() { static const bool on = std::getenv("STRATA_PARK_TRACE") != nullptr; return on; }
147void vram_kv_free(VramKvSlot& s) {
148    int cur = s.dev;
149    (void) cudaGetDevice(&cur);
150    if (cur != s.dev) (void) cudaSetDevice(s.dev);
151    (void) cudaFree(s.p);
152    if (cur != s.dev) (void) cudaSetDevice(cur);
153    (void) cudaGetLastError();
154    s.p = nullptr; s.cap = 0;
155}
156void vram_kv_release(VramKvSlot& s) { s.tag = 0; s.used = 0; s.parts.clear(); }   // free, kept for reuse
157// A slot of `need` bytes on `dev`: the best-fitting free one, else (the free ones freed first) a new one, rounded up
158// to 64 MiB so a growing conversation's next parks reuse it, while the slots' total stays within the budget and
159// 1.5 GB of VRAM stays free beside it.  nullptr, with `why`, otherwise.
160VramKvSlot* vram_kv_take(size_t need, int dev, const char*& why) {
161    VramKv& v = vram_kv();
162    const size_t budget = park_vram_budget();
163    if (budget == 0) { why = "off"; return nullptr; }
164    VramKvSlot* best = nullptr;
165    for (auto& s : v.slots)
166        if (s->tag == 0 && s->dev == dev && s->cap >= need && (best == nullptr || s->cap < best->cap)) best = s.get();
167    if (best == nullptr) {
168        size_t held = 0;
169        for (size_t i = 0; i < v.slots.size();) {
170            if (v.slots[i]->tag != 0) { held += v.slots[i]->cap; ++i; continue; }
171            vram_kv_free(*v.slots[i]);
172            v.slots.erase(v.slots.begin() + (std::ptrdiff_t) i);
173        }
174        const size_t want = (need + ((size_t) 64 << 20) - 1) & ~(((size_t) 64 << 20) - 1);
175        if (held > budget || want > budget - held) { why = "budget"; return nullptr; }
176        size_t fr = 0, tot = 0;
177        if (cudaMemGetInfo(&fr, &tot) != cudaSuccess || fr < want + ((size_t) 3 << 29)) {
178            (void) cudaGetLastError();
179            why = "vram";
180            return nullptr;
181        }
182        void* p = nullptr;
183        if (cudaMalloc(&p, want) != cudaSuccess) { (void) cudaGetLastError(); why = "cudaMalloc"; return nullptr; }
184        auto s = std::make_unique<VramKvSlot>();
185        s->p = p; s->cap = want; s->dev = dev;
186        best = s.get();
187        v.slots.push_back(std::move(s));
188    }
189    best->tag = v.next_tag++;
190    best->used = 0;
191    best->parts.clear();
192    return best;
193}
194// The live slot on the current device holding parts under `tag` (nullptr: none, or tag 0)
195const VramKvSlot* vram_kv_find(uint64_t tag) {
196    if (tag == 0) return nullptr;
197    int dev = 0;
198    if (cudaGetDevice(&dev) != cudaSuccess) { (void) cudaGetLastError(); return nullptr; }
199    for (const auto& s : vram_kv().slots) {
200        if (s->tag == 0 || s->dev != dev) continue;
201        for (const auto& p : s->parts)
202            if (p.tag == tag) return s.get();
203    }
204    return nullptr;
205}
206// Whether the slot holds, under `tag`, at least sizes[i] bytes of every part i that has any; `at` gets the offsets
207bool vram_kv_locate(const VramKvSlot& s, uint64_t tag, const std::array<size_t,5>& sizes, std::array<size_t,5>& at) {
208    std::array<bool,5> have{};
209    for (const auto& p : s.parts)
210        if (p.tag == tag && p.part < at.size() && p.bytes >= sizes[p.part]) { have[p.part] = true; at[p.part] = p.offset; }
211    for (size_t i = 0; i < sizes.size(); ++i)
212        if (sizes[i] > 0 && !have[i]) return false;
213    return true;
214}
215
216struct ParkAsync {
217    std::mutex mu;
218    std::future<cudaError_t> pending;
219    struct Item { uint8_t* dst; size_t n, at; };
220    std::vector<Item> items;
221    uint8_t* stage = nullptr;
222    size_t cap = 0, used = 0;
223    void* host[2] = {nullptr, nullptr};   // pinned, 4 MiB each
224    cudaStream_t stream = nullptr;
225    int dev = -1;
226    bool active = false;
227    VramKvSlot* slot = nullptr;   // STRATA_PARK_VRAM_MIB: the begun park's slot (the stage is not used then)
228    uint64_t slot_tag = 0;        // its tag, kept past launch for the image's and its layers' tokens
229};
230ParkAsync& park_async() { static ParkAsync a; return a; }
231constexpr size_t kParkPiece = (size_t) 4 << 20;
232bool park_async_on() {
233#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL)
234    return false;
235#else
236    static const bool on = [] { const char* v = std::getenv("STRATA_PARK_ASYNC"); return v != nullptr && v[0] == '1'; }();
237    return on;
238#endif
239}
240bool on_device(const void* p) {
241#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL)
242    (void) p;   // (no pointer-attribute query in the shims: the slot takes no part, as when the query fails)
243    return false;
244#else
245    cudaPointerAttributes at{};
246    if (cudaPointerGetAttributes(&at, p) != cudaSuccess) { cudaGetLastError(); return false; }
247    return at.type == cudaMemoryTypeDevice;
248#endif
249}
250// STRATA_PARK_TRACE: where conversation_kv_save's time goes since the park's begin (ms): the pointer-attribute
251// queries, the host buffer resizes and the copies (into the stage, or the synchronous ones).  Read by the park trace.
252struct KvSaveTrace { double attrs = 0, resize = 0, copy = 0; long resize_faults = 0; };
253KvSaveTrace& kv_save_trace() { static KvSaveTrace t; return t; }
254bool park_trace_on() {
255    static const bool on = std::getenv("STRATA_PARK_TRACE") != nullptr;
256    return on;
257}
258
259bool transfer(void* dst, const void* src, size_t n, std::string& error) {
260    if (!n) return true;
261    if (!src || !dst) { error = "conversation snapshot: missing state buffer"; return false; }
262    // Default handles both device allocations and device-mapped host pool aliases.
263    const cudaError_t e = conversation_detail::copy_nonblocking(dst, src, n);
264    if (e == cudaSuccess) return true;
265    error = std::string("conversation snapshot copy: ") + cudaGetErrorString(e);
266    return false;
267}
268} // namespace
269
270bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
271                                   int64_t upto, bool index, size_t& bytes, std::string& error) {
272    Layout l{};
273    if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false;
274    const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
275    const std::array<const ConversationBuffer*,5> buffers = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
276    bytes = 0;
277    for (size_t i = 0; i < buffers.size(); ++i) {
278        const size_t n = buffers[i]->allocation_peak(sizes[i]);
279        if (n == SIZE_MAX || !conversation_detail::add(bytes, n)) {
280            error = "conversation snapshot: segmented K/V allocation overflow";
281            return false;
282        }
283    }
284    return true;
285}
286
287size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) {
288    size_t bytes = 0;
289    std::string error;
290    return conversation_kv_capture_bytes({}, st, g, upto, index, bytes, error) ? bytes : 0;
291}
292
293bool conversation_kv_save(ConversationKv& image, const QsaState& st, const ModelGeometry& g,
294                          int64_t upto, bool index, std::string& error,
295                          int64_t unchanged_tokens, size_t* reused_bytes) {
296    Layout l{};
297    if (!layout(st, g, upto, index, l, error)) return false;
298    if (!valid(st, l, upto, error)) return false;
299    if (unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image.cells) {
300        error = "conversation snapshot: invalid unchanged prefix";
301        return false;
302    }
303    const int64_t whole_cells = (unchanged_tokens / l.page_size) * l.page_size;
304    image.format = l.format;
305    image.cells = l.cells;
306    image.heads = g.n_head_kv;
307    image.head_dim = g.head_dim;
308    image.page_size = l.page_size;
309    image.pooled_rows = l.pooled_rows;
310    image.idx_dim = g.idx_key_dim;
311    const auto src = pools(st);
312    const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
313    const std::array<ConversationBuffer*,5> dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
314    // STRATA_PARK_VRAM_MIB: this layer's parts go into the park's slot under a fresh tag (0: no slot this park)
315    image.dev_tag = park_async().slot != nullptr ? vram_kv().next_tag++ : 0;
316    for (size_t i = 0; i < dst.size(); ++i) {
317        // Recopy the partial page and the indexer's moving spare row. Completed
318        // pages/rows strictly before the first rewritten token remain identical.
319        const size_t keep = i == 4 ? (index ? size_t(unchanged_tokens / strata::kernels::qsa_real_shapes().idx_block) * g.idx_key_dim * 4 : 0)
320                                  : l.cells ? (sizes[i] / size_t(l.cells)) * size_t(whole_cells) : 0;
321        if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; }
322        {   // STRATA_PARK_VRAM_MIB: with a slot, the whole part goes device to device into it (a restore of this image
323            // reads it from there) and the host buffer gets only the bytes past the kept prefix, read from the slot on
324            // the background thread; a part the slot cannot take is copied synchronously - never through the stage,
325            // whose offsets launch would read from the slot
326            ParkAsync& a = park_async();
327            if (a.slot != nullptr) {
328                VramKvSlot& s = *a.slot;
329                const bool fits = src[i] != nullptr && sizes[i] > 0 && s.used + sizes[i] <= s.cap &&
330                                  (st.kv_mode == 0 || on_device(src[i]));   // (kv_mode 0: the pools are device memory)
331                if (fits) {
332                    const size_t at0 = s.used;
333                    const cudaError_t e = conversation_detail::copy_nonblocking(static_cast<uint8_t*>(s.p) + at0, src[i], sizes[i], true);
334                    if (e != cudaSuccess) { error = std::string("conversation snapshot slot copy: ") + cudaGetErrorString(e); return false; }
335                    s.parts.push_back({image.dev_tag, i, at0, sizes[i]});
336                    s.used += sizes[i];
337                    dst[i]->resize_for_overwrite(sizes[i]);
338                    if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) {
339                            a.items.push_back({p, n, at0 + at});
340                            return true;
341                        })) return false;
342                } else {
343                    dst[i]->resize(sizes[i]);
344                    if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) {
345                            return transfer(p, src[i] ? static_cast<const uint8_t*>(src[i]) + at : nullptr, n, error);
346                        })) return false;
347                }
348                if (reused_bytes) *reused_bytes += keep;
349                continue;
350            }
351        }
352        // STRATA_PARK_ASYNC: device bytes go to the VRAM stage now and into the buffer on the background thread
353        ParkAsync& a = park_async();
354        const bool trace = park_trace_on();
355        auto tick = [trace] { return trace ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; };
356        const auto t0 = tick();
357        // (kv_mode 0: the pools are device memory by construction, so no pointer-attribute query)
358        const bool staged = a.active && src[i] != nullptr && sizes[i] > keep && a.used + (sizes[i] - keep) <= a.cap &&
359                            (st.kv_mode == 0 || on_device(src[i]));
360        const auto t1 = tick();
361        const long rf0 = trace ? conversation_trace::thread_minflt() : 0;
362        if (staged) dst[i]->resize_for_overwrite(sizes[i]);
363        else dst[i]->resize(sizes[i]);
364        const auto t2 = tick();
365        if (trace) kv_save_trace().resize_faults += conversation_trace::thread_minflt() - rf0;
366        const bool copied = dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) {
367                const uint8_t* s = src[i] ? static_cast<const uint8_t*>(src[i]) + at : nullptr;
368                if (!staged) return transfer(p, s, n, error);
369                const cudaError_t e = conversation_detail::copy_nonblocking(a.stage + a.used, s, n, true);
370                if (e != cudaSuccess) { error = std::string("conversation snapshot stage copy: ") + cudaGetErrorString(e); return false; }
371                a.items.push_back({p, n, a.used});
372                a.used += n;
373                return true;
374            });
375        if (trace) {
376            auto ms = [](std::chrono::steady_clock::time_point x, std::chrono::steady_clock::time_point y) {
377                return std::chrono::duration<double, std::milli>(y - x).count(); };
378            KvSaveTrace& t = kv_save_trace();
379            t.attrs += ms(t0, t1); t.resize += ms(t1, t2); t.copy += ms(t2, tick());
380        }
381        if (!copied) return false;
382        if (reused_bytes) *reused_bytes += keep;
383    }
384    return true;
385}
386
387bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
388                              int64_t upto, bool index, std::string& error) {
389    Layout l{};
390    if (!layout(st, g, upto, index, l, error)) return false;
391    if (!valid(st, l, upto, error)) return false;
392    const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
393    const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
394    if (image.format != l.format || image.cells != l.cells || image.heads != g.n_head_kv ||
395        image.head_dim != g.head_dim || image.page_size != l.page_size || image.pooled_rows != l.pooled_rows ||
396        image.idx_dim != g.idx_key_dim) {
397        error = "conversation snapshot: incompatible K/V geometry";
398        return false;
399    }
400    for (size_t i = 0; i < src.size(); ++i)
401        if (src[i]->size() != sizes[i]) { error = "conversation snapshot: invalid K/V payload size"; return false; }
402    const auto dst = pools(st);
403    for (size_t i = 0; i < src.size(); ++i)
404        if (sizes[i] && !dst[i]) { error = "conversation snapshot: missing target state buffer"; return false; }
405    return true;
406}
407
408namespace {
409// After the authoritative pools were rewritten: the VRAM slots of a streamed state still hold the outgoing
410// conversation, so resolve must refill them before any attention reads (shared by restore and direct copy).
411bool refresh_residency(const QsaState& st, const ModelGeometry& g, int64_t upto, std::string& error) {
412    if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr);
413    if (st.kv_mode == 2 && upto > 0) {
414        auto shapes = strata::kernels::qsa_real_shapes();
415        shapes.n_head_kv = g.n_head_kv; shapes.head_dim = g.head_dim;
416        const int64_t end = (upto + shapes.page_size - 1) / shapes.page_size;
417        strata::kernels::kv_ring_restore(qsa_attn_pools(st), st.host, qsa_kv_format(st),
418                                        std::max<int64_t>(0, end - st.n_slots), end, st.n_slots, shapes, nullptr);
419    }
420    const auto status = cudaGetLastError();
421    if (status == cudaSuccess) return true;
422    error = std::string("conversation snapshot residency restore: ") + cudaGetErrorString(status);
423    return false;
424}
425} // namespace
426
427bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelGeometry& g,
428                          int64_t upto, bool index, std::string& error, bool queued) {
429    Layout lf{}, lt{};
430    if (!layout(from, g, upto, index, lf, error) || !valid(from, lf, upto, error) ||
431        !layout(to, g, upto, index, lt, error) || !valid(to, lt, upto, error)) return false;
432    if (lf.format != lt.format || lf.cells != lt.cells || lf.page_size != lt.page_size ||
433        lf.pooled_rows != lt.pooled_rows || lf.data != lt.data || lf.value_data != lt.value_data ||
434        lf.scales != lt.scales || lf.value_scales != lt.value_scales || lf.pooled != lt.pooled) {
435        error = "conversation snapshot: direct K/V copy between different layouts";
436        return false;
437    }
438    // The same bytes conversation_kv_save + conversation_kv_restore move, without the host image: each part
439    // straight from the source's authoritative pool into the target's (device or mapped host memory), through the
440    // private non-blocking stream the other snapshot copies use (complete on return, before the residency refresh).
441    // `queued`: the copies are only queued, and a streamed state's refresh waits for them on the device (an event).
442    const auto src = pools(from);
443    const auto dst = pools(to);
444    const std::array<size_t,5> sizes = {lf.data, lf.value_data, lf.scales, lf.value_scales, lf.pooled};
445    for (size_t i = 0; i < sizes.size(); ++i) {
446        if (!sizes[i]) continue;
447        if (!src[i] || !dst[i]) { error = "conversation snapshot: missing state buffer"; return false; }
448        const cudaError_t e = conversation_detail::copy_nonblocking(dst[i], src[i], sizes[i], queued);
449        if (e != cudaSuccess) { error = std::string("conversation snapshot direct copy: ") + cudaGetErrorString(e); return false; }
450    }
451    if (queued && to.kv_mode != 0) {
452        const cudaError_t e = conversation_detail::order_after_queued();
453        if (e != cudaSuccess) { error = std::string("conversation snapshot direct copy: ") + cudaGetErrorString(e); return false; }
454    }
455    return refresh_residency(to, g, upto, error);
456}
457
458bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
459                             int64_t upto, bool index, std::string& error) {
460    // STRATA_PARK_VRAM_MIB: from the image's VRAM slot when it holds every part (no host buffer is read: no join)
461    const VramKvSlot* slot = vram_kv_find(image.dev_tag);
462    if (slot == nullptr) conversation_park_join();
463    if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;
464    const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
465    const auto dst = pools(st);
466    std::array<size_t,5> sizes{}, off{};
467    for (size_t i = 0; i < src.size(); ++i) sizes[i] = src[i]->size();
468    if (slot != nullptr && !vram_kv_locate(*slot, image.dev_tag, sizes, off)) { slot = nullptr; conversation_park_join(); }
469    if (slot != nullptr) {
470        for (size_t i = 0; i < src.size(); ++i)
471            if (!transfer(dst[i], static_cast<const uint8_t*>(slot->p) + off[i], sizes[i], error)) return false;
472        return refresh_residency(st, g, upto, error);
473    }
474    for (size_t i = 0; i < src.size(); ++i)
475        if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) {
476                return transfer(static_cast<uint8_t*>(dst[i]) + at, p, n, error);
477            })) return false;
478    return refresh_residency(st, g, upto, error);
479}
480
481bool conversation_kv_restore_prefix(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
482                                    int64_t captured, int64_t upto, bool index, std::string& error) {
483    const VramKvSlot* slot = vram_kv_find(image.dev_tag);   // (STRATA_PARK_VRAM_MIB, as in conversation_kv_restore)
484    if (slot == nullptr) conversation_park_join();
485    if (upto < 0 || upto > captured) {
486        error = "conversation snapshot: prefix beyond the captured K/V";
487        return false;
488    }
489    if (!conversation_kv_validate(image, st, g, captured, index, error)) return false;
490    Layout l{};   // the prefix's extent; validation above checked the image against the captured one
491    if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false;
492    const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
493    const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
494    for (size_t i = 0; i < src.size(); ++i)
495        if (sizes[i] > src[i]->size()) { error = "conversation snapshot: prefix beyond the K/V payload"; return false; }
496    const auto dst = pools(st);
497    // STRATA_PARK_VRAM_MIB: the prefix is the leading bytes of each part in the slot too
498    std::array<size_t,5> off{};
499    if (slot != nullptr && !vram_kv_locate(*slot, image.dev_tag, sizes, off)) { slot = nullptr; conversation_park_join(); }
500    if (slot != nullptr) {
501        for (size_t i = 0; i < src.size(); ++i)
502            if (!transfer(dst[i], static_cast<const uint8_t*>(slot->p) + off[i], sizes[i], error)) return false;
503        return refresh_residency(st, g, upto, error);
504    }
505    for (size_t i = 0; i < src.size(); ++i)
506        if (!src[i]->visit(0, sizes[i], [&](const uint8_t* p, size_t n, size_t at) {
507                return transfer(static_cast<uint8_t*>(dst[i]) + at, p, n, error);
508            })) return false;
509    return refresh_residency(st, g, upto, error);
510}
511
512bool conversation_kv_part_sizes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index,
513                                std::array<uint64_t, 5>& sizes, std::string& error) {
514    Layout l{};
515    if (!layout(st, g, upto, index, l, error)) return false;
516    sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
517    return true;
518}
519
520bool conversation_kv_source(SessionKvSource& out, const QsaState& st, const ModelGeometry& g,
521                            int64_t upto, bool index, std::string& error) {
522    Layout l{};
523    if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false;
524    SessionKvSource s;
525    s.format = l.format; s.cells = l.cells; s.heads = g.n_head_kv; s.head_dim = g.head_dim;
526    s.page_size = l.page_size; s.pooled_rows = l.pooled_rows; s.idx_dim = g.idx_key_dim;
527    s.sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
528    const auto src = pools(st);
529    const auto sizes = s.sizes;
530    auto why = std::make_shared<std::string>();
531    s.read = [src, sizes, why](size_t part, size_t offset, void* dst, size_t n) {
532        if (part >= 5 || offset > sizes[part] || n > sizes[part] - offset) { *why = "K/V read out of range"; return false; }
533        return transfer(dst, src[part] ? static_cast<const uint8_t*>(src[part]) + offset : nullptr, n, *why);
534    };
535    s.error = [why] { return *why; };
536    out = std::move(s);
537    return true;
538}
539
540bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
541                            int64_t upto, bool index, uint64_t& fingerprint, std::string& error) {
542    conversation_park_join();
543    if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;
544    std::array<uint8_t, 65536> buffer;
545    uint64_t hash = 1469598103934665603ull;
546    auto compare = [&](const void* device, const uint8_t* expected, size_t bytes, bool include_hash) {
547        for (size_t offset = 0; offset < bytes;) {
548            const size_t n = std::min(buffer.size(), bytes - offset);
549            if (!transfer(buffer.data(), static_cast<const uint8_t*>(device) + offset, n, error)) return false;
550            if (std::memcmp(buffer.data(), expected + offset, n) != 0) {
551                error = "conversation snapshot: restored K/V bytes differ";
552                return false;
553            }
554            if (include_hash) for (size_t i = 0; i < n; ++i) { hash ^= buffer[i]; hash *= 1099511628211ull; }
555            offset += n;
556        }
557        return true;
558    };
559    const std::array<const ConversationBuffer*, 5> saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
560    const auto authoritative = pools(st);
561    for (size_t i = 0; i < saved.size(); ++i)
562        if (!saved[i]->visit(0, saved[i]->size(), [&](const uint8_t* p, size_t n, size_t at) {
563                return compare(static_cast<const uint8_t*>(authoritative[i]) + at, p, n, true);
564            })) return false;
565    if (st.kv_mode == 2 && image.cells > 0) {
566        const auto resident = pools(st, true);
567        const int64_t end = image.cells / image.page_size;
568        const int64_t begin = std::max<int64_t>(0, end - st.n_slots);
569        for (size_t i = 0; i < 4; ++i) {
570            if (saved[i]->empty()) continue;
571            const size_t page_bytes = saved[i]->size() / size_t(end);
572            for (int64_t page = begin; page < end; ++page)
573                if (!saved[i]->visit(size_t(page) * page_bytes, page_bytes,
574                        [&](const uint8_t* p, size_t n, size_t at) {
575                            const size_t offset = size_t(page % st.n_slots) * page_bytes + at - size_t(page) * page_bytes;
576                            return compare(static_cast<const uint8_t*>(resident[i]) + offset, p, n, false);
577                        })) return false;
578        }
579    }
580    fingerprint = hash;
581    return true;
582}
583
584void conversation_park_join() {
585    ParkAsync& a = park_async();
586    std::lock_guard<std::mutex> lk(a.mu);
587    if (a.pending.valid()) {
588        const cudaError_t e = a.pending.get();
589        if (e != cudaSuccess) std::fprintf(stderr, "strata: STRATA_PARK_ASYNC: a parked K/V copy failed (%s)\n", cudaGetErrorString(e));
590    }
591}
592
593void conversation_kv_save_trace(double& attrs_ms, double& resize_ms, double& copy_ms) {
594    const KvSaveTrace& t = kv_save_trace();
595    attrs_ms = t.attrs; resize_ms = t.resize; copy_ms = t.copy;
596}
597
598long conversation_kv_save_trace_faults() { return kv_save_trace().resize_faults; }
599
600bool conversation_park_async_begin(size_t need) {
601    if (park_trace_on()) kv_save_trace() = {};   // (the sums cover this park's saves)
602    conversation_park_join();   // (the stage is reused)
603    ParkAsync& a = park_async();
604    a.active = false;
605    a.items.clear();
606    a.used = 0;
607    a.slot = nullptr;
608    a.slot_tag = 0;
609    if (!park_async_on() || need == 0) return false;
610    int dev = 0;
611    if (cudaGetDevice(&dev) != cudaSuccess) { (void) cudaGetLastError(); return false; }
612    // STRATA_PARK_VRAM_MIB: a slot of the whole K/V instead of the stage, while the budget allows - taken before the
613    // stage would be re-allocated, so a growing conversation's park pays no cudaFree (a device sync) when it gets one
614    const char* why = "";
615    a.slot = vram_kv_take(need, dev, why);
616    a.slot_tag = a.slot != nullptr ? a.slot->tag : 0;
617    if (park_trace() && park_vram_budget() != 0) {
618        if (a.slot != nullptr)
619            std::fprintf(stderr, "strata parktrace: kv slot %zu MB tag %llu\n", need >> 20, (unsigned long long) a.slot_tag);
620        else
621            std::fprintf(stderr, "strata parktrace: kv slot: none (%s)\n", why);
622    }
623    if (a.stage != nullptr && ((a.slot == nullptr && a.cap < need) || a.dev != dev)) {
624        const int cur = dev;
625        (void) cudaSetDevice(a.dev); (void) cudaFree(a.stage); (void) cudaSetDevice(cur);
626        a.stage = nullptr; a.cap = 0;
627    }
628    if (a.stream != nullptr && a.dev != dev) {
629        const int cur = dev;
630        (void) cudaSetDevice(a.dev); (void) cudaStreamDestroy(a.stream);
631        (void) cudaFreeHost(a.host[0]); (void) cudaFreeHost(a.host[1]); (void) cudaSetDevice(cur);
632        a.stream = nullptr; a.host[0] = a.host[1] = nullptr;
633    }
634    a.dev = dev;
635    if (a.stream == nullptr &&
636        (cudaStreamCreateWithFlags(&a.stream, cudaStreamNonBlocking) != cudaSuccess ||
637         cudaMallocHost(&a.host[0], kParkPiece) != cudaSuccess || cudaMallocHost(&a.host[1], kParkPiece) != cudaSuccess)) {
638        if (a.host[0]) (void) cudaFreeHost(a.host[0]);
639        if (a.host[1]) (void) cudaFreeHost(a.host[1]);
640        if (a.stream) (void) cudaStreamDestroy(a.stream);
641        a.stream = nullptr; a.host[0] = a.host[1] = nullptr;
642        (void) cudaGetLastError();
643        if (a.slot != nullptr) { vram_kv_release(*a.slot); a.slot = nullptr; a.slot_tag = 0; }   // (STRATA_PARK_VRAM_MIB)
644        return false;
645    }
646    if (a.slot != nullptr) {   // STRATA_PARK_VRAM_MIB: the slot stands in for the stage this park
647        a.active = true;
648        return true;
649    }
650    if (a.stage == nullptr) {
651        // rounded up to 64 MiB: the next parks of a growing conversation reuse it instead of re-allocating (a cudaFree
652        // synchronizes the device, and the checkpoint DMA is in flight at this point)
653        const size_t want = (need + ((size_t) 64 << 20) - 1) & ~(((size_t) 64 << 20) - 1);
654        size_t fr = 0, tot = 0;
655        if (cudaMemGetInfo(&fr, &tot) != cudaSuccess || fr < want + ((size_t) 3 << 29) ||
656            cudaMalloc((void**) &a.stage, want) != cudaSuccess) {
657            a.stage = nullptr;
658            (void) cudaGetLastError();
659            return false;
660        }
661        a.cap = want;
662    }
663    a.active = true;
664    return true;
665}
666
667void conversation_park_async_abandon() {
668    ParkAsync& a = park_async();
669    if (!a.active) return;
670    a.active = false;
671    a.items.clear();
672    cudaStream_t s = nullptr;
673    if (conversation_detail::private_stream(s) == cudaSuccess) (void) cudaStreamSynchronize(s);   // nothing reads the stage after
674    (void) cudaGetLastError();
675    if (a.slot != nullptr) { vram_kv_release(*a.slot); a.slot = nullptr; a.slot_tag = 0; }   // (STRATA_PARK_VRAM_MIB)
676}
677
678bool conversation_park_async_launch(std::string& error) {
679    ParkAsync& a = park_async();
680    if (!a.active) return true;
681    a.active = false;
682    cudaStream_t s = nullptr;
683    cudaError_t e = conversation_detail::private_stream(s);
684    if (e == cudaSuccess) e = cudaStreamSynchronize(s);   // the device-to-device copies into the stage
685    if (e != cudaSuccess) {
686        a.items.clear();
687        if (a.slot != nullptr) { vram_kv_release(*a.slot); a.slot = nullptr; a.slot_tag = 0; }   // (STRATA_PARK_VRAM_MIB)
688        error = std::string("conversation snapshot stage: ") + cudaGetErrorString(e);
689        return false;
690    }
691    // STRATA_PARK_VRAM_MIB: the host copies read the slot; it stays until the image and its K/V layers go (their tokens)
692    const uint8_t* stage = a.slot != nullptr ? static_cast<const uint8_t*>(a.slot->p) : a.stage;
693    a.slot = nullptr;
694    if (a.items.empty()) return true;
695    std::vector<ParkAsync::Item> items;
696    items.swap(a.items);
697    void* host[2] = {a.host[0], a.host[1]};
698    cudaStream_t st = a.stream;
699    const int dev = a.dev;
700    std::lock_guard<std::mutex> lk(a.mu);
701    // two pinned pieces in turn: the next piece's DMA runs while this one is copied into its segment
702    a.pending = std::async(std::launch::async, [items = std::move(items), stage, host, st, dev] {
703        conversation_detail::background_thread_placement();
704        (void) cudaSetDevice(dev);
705        cudaEvent_t done[2] = {nullptr, nullptr};
706        cudaError_t e = cudaEventCreateWithFlags(&done[0], cudaEventDisableTiming | cudaEventBlockingSync);
707        if (e == cudaSuccess) e = cudaEventCreateWithFlags(&done[1], cudaEventDisableTiming | cudaEventBlockingSync);
708        struct Piece { uint8_t* dst; size_t n; };
709        Piece held[2] = {{nullptr, 0}, {nullptr, 0}};
710        int b = 0;
711        auto land = [&](int k) {
712            if (held[k].dst == nullptr || e != cudaSuccess) return;
713            e = cudaEventSynchronize(done[k]);
714            if (e == cudaSuccess) std::memcpy(held[k].dst, host[k], held[k].n);
715            held[k] = {nullptr, 0};
716        };
717        for (const auto& it : items)
718            for (size_t o = 0; e == cudaSuccess && o < it.n; o += kParkPiece) {
719                const size_t n = std::min(kParkPiece, it.n - o);
720                land(b);
721                if (e == cudaSuccess) e = cudaMemcpyAsync(host[b], stage + it.at + o, n, cudaMemcpyDeviceToHost, st);
722                if (e == cudaSuccess) e = cudaEventRecord(done[b], st);
723                if (e == cudaSuccess) held[b] = {it.dst + o, n};
724                b ^= 1;
725            }
726        land(b);
727        land(b ^ 1);
728        for (cudaEvent_t d : done) if (d) (void) cudaEventDestroy(d);
729        return e;
730    });
731    return true;
732}
733
734uint64_t conversation_park_slot_tag() { return park_async().slot_tag; }
735
736void conversation_park_slot_release(uint64_t tag) {
737    if (tag == 0) return;
738    for (auto& s : vram_kv().slots)
739        if (s->tag == tag) { vram_kv_release(*s); return; }
740}
741
742size_t conversation_park_vram_release_all() {
743    if (park_vram_budget() == 0) return 0;   // off: nothing was taken, and the stage stays as it was
744    conversation_park_join();   // the background copy may be reading a slot or the stage
745    ParkAsync& a = park_async();
746    VramKv& v = vram_kv();
747    size_t freed = 0;
748    for (size_t i = 0; i < v.slots.size();) {
749        if (a.active && v.slots[i].get() == a.slot) { ++i; continue; }   // a park in progress keeps its own
750        freed += v.slots[i]->cap;
751        vram_kv_free(*v.slots[i]);
752        v.slots.erase(v.slots.begin() + (std::ptrdiff_t) i);
753    }
754    if (a.stage != nullptr && !a.active) {
755        int cur = a.dev;
756        (void) cudaGetDevice(&cur);
757        if (cur != a.dev) (void) cudaSetDevice(a.dev);
758        (void) cudaFree(a.stage);
759        if (cur != a.dev) (void) cudaSetDevice(cur);
760        (void) cudaGetLastError();
761        freed += a.cap;
762        a.stage = nullptr; a.cap = 0;
763    }
764    return freed;
765}
766
767void conversation_park_join_for(const SavedConversation& image) {
768    size_t hits = 0;
769    for (const auto& k : image.kv) hits += vram_kv_find(k.dev_tag) != nullptr ? 1 : 0;
770    if (park_trace() && park_vram_budget() != 0)
771        std::fprintf(stderr, "strata parktrace: kv restore: %zu of %zu layers from the slot\n", hits, image.kv.size());
772    if (hits < image.kv.size()) conversation_park_join();
773}
774
775} // namespace strata::core