okami.mom/strata

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

waveringanadump stage 0 session state after each prompt (STRATA_SESSION_DUMP, opt-in) for hand-back checkse412ff76e

main
47.9 KiB830 linesraw
1#include "strata/core/conversation_snapshot.hpp"
2#include "conversation_checked.hpp"
3#include "conversation_copy.hpp"
4#include "conversation_trace.hpp"
5#include <chrono>
6#include <cstdio>
7#include <cstdlib>
8
9#include <algorithm>
10#include <array>
11#include <cstring>
12#include <future>
13#include <limits>
14#include <mutex>
15
16namespace strata::core {
17namespace {
18using conversation_detail::add;
19using conversation_detail::product;
20
21std::array<int64_t, 18> geometry_key(const ModelGeometry& g) {
22    return {g.n_embd, g.n_layers, g.qsa_interval, g.ssm_state_size, g.ssm_k_heads,
23            g.ssm_v_heads, g.ssm_d_conv, g.ssm_conv_channels, g.ssm_value_dim,
24            g.n_head, g.n_head_kv, g.head_dim, g.idx_q_heads, g.idx_key_dim,
25            g.hc, g.hc_lr, g.n_expert, g.n_ff};
26}
27
28bool fail(std::string& error, const char* message) {
29    error = std::string("conversation snapshot: ") + message;
30    return false;
31}
32
33bool sync(std::string& error) {
34    const auto status = cudaDeviceSynchronize();
35    if (status == cudaSuccess) return true;
36    error = std::string("conversation snapshot synchronize: ") + cudaGetErrorString(status);
37    return false;
38}
39
40bool copy(void* dst, const void* src, size_t bytes, std::string& error, bool queued = false) {
41    if (!bytes) return true;
42    if (!dst || !src) return fail(error, "missing running-state buffer");
43    const auto status = conversation_detail::copy_nonblocking(dst, src, bytes, queued);
44    if (status == cudaSuccess) return true;
45    error = std::string("conversation snapshot running-state copy: ") + cudaGetErrorString(status);
46    return false;
47}
48
49// The session's carve (#216): `qsa_states` keeps global ordinals and holds the owned ones
50// [qsa_ord0, qsa_ord0 + qsa_alloc); `gdn_state` holds `gdn_alloc` rows. A whole-model session owns every layer.
51size_t owned_qsa(const SessionState& ss) { return (size_t) std::max<int64_t>(ss.qsa_alloc, 0); }
52const QsaState& owned(const SessionState& ss, size_t j) { return ss.qsa_states[(size_t) ss.qsa_ord0 + j]; }
53
54bool image_keys(const std::vector<ConversationImageKey>& images, size_t tokens) {
55    int64_t previous = -1;
56    for (const auto& image : images) {
57        if (image.start <= previous || image.start < 0 || (uint64_t) image.start >= tokens) return false;
58        previous = image.start;
59    }
60    return true;
61}
62
63bool checkpoint_targets(const SessionState& ss, const ModelGeometry& g, size_t tokens,
64                        ConversationStateSizes& z, std::string& error) {
65    if (!conversation_session_sizes(g, ss, z, error)) return false;
66    if (ss.max_cells < 0 || tokens > (uint64_t) ss.max_cells || (z.gdn && !ss.gdn_state) ||
67        (owned_qsa(ss) && !ss.qsa_states)) return fail(error, "invalid session running-state targets");
68    for (size_t j = 0; j < owned_qsa(ss); ++j) {
69        const auto& st = owned(ss, j);
70        const auto block = strata::kernels::qsa_real_shapes().idx_block;
71        size_t pooled_bytes = 0;
72        if (!st.idx_tail || !st.idx_dead || !st.idx_block_pos || !st.idx_pooled ||
73            st.max_cells < 0 || tokens > (uint64_t) st.max_cells ||
74            (tokens && tokens / (uint64_t) block >= (uint64_t) std::max<int64_t>(0, st.idx_pooled_rows)) ||
75            !product(pooled_bytes, {tokens / (uint64_t) block + 1, (uint64_t) g.idx_key_dim, sizeof(float)}))
76            return fail(error, "invalid indexer running-state target");
77    }
78    return true;
79}
80
81bool view_validate(const ConversationView& view, const SessionState& ss,
82                   const ModelGeometry& g, std::string& error) {
83    ConversationStateSizes z;
84    if (!checkpoint_targets(ss, g, view.ids.size(), z, error)) return false;
85    if (view.ids.empty() || !image_keys(view.images, view.ids.size()) ||
86        std::any_of(view.ids.begin(), view.ids.end(), [](int32_t id) { return id < 0; }))
87        return fail(error, "invalid live token/image metadata");
88    for (const auto& c : view.checkpoints) {
89        if (!c.stage_parts.empty() || c.ids.empty() || c.ids.size() > view.ids.size() ||
90            !std::equal(c.ids.begin(), c.ids.end(), view.ids.begin()))
91            return fail(error, "checkpoint is not a live token prefix");
92        if (!conversation_checkpoint_validate(c, ss, g, error)) return false;
93        size_t image = 0;
94        for (const auto& key : view.images) {
95            if ((uint64_t) key.start >= c.ids.size()) break;
96            if (image >= c.imgs.size() || !(c.imgs[image++] == key))
97                return fail(error, "checkpoint image identity differs");
98        }
99        if (image != c.imgs.size()) return fail(error, "checkpoint image prefix differs");
100    }
101    return true;
102}
103
104bool metadata_bytes(const ConversationCheckpoint& c, size_t& total) {
105    size_t ids = 0, images = 0;
106    if (!product(ids, {c.ids.size(), sizeof(int32_t)}) ||
107        !product(images, {c.imgs.size(), sizeof(ConversationImageKey)})) return false;
108    for (size_t n : {ids, images, c.gdn.size(), c.ple.size(), c.tails.size(), c.dead.size(), c.block_pos.size()})
109        if (!add(total, n)) return false;
110    return true;
111}
112} // namespace
113
114bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& z, std::string& error) {
115    z = {};
116    const auto key = geometry_key(g);
117    for (size_t i = 0; i < key.size(); ++i)
118        if (key[i] < 0 || (i != 1 && key[i] == 0)) return fail(error, "invalid model geometry");
119    size_t recurrence = 0, convolution = 0;
120    if (!product(recurrence, {(uint64_t) g.ssm_state_size, (uint64_t) g.ssm_v_heads, (uint64_t) g.ssm_state_size}) ||
121        !product(convolution, {(uint64_t) g.ssm_conv_channels, (uint64_t) (g.ssm_d_conv - 1)}) ||
122        !add(recurrence, convolution) ||
123        !product(z.gdn, {(uint64_t) g.n_gdn_layers(), recurrence, sizeof(float)}) ||
124        !product(z.ple, {strata::kernels::NG_HIST, strata::kernels::NG_HC_DIM, sizeof(float)}) ||
125        !product(z.tail, {(uint64_t) (strata::kernels::qsa_real_shapes().idx_block - 1),
126                          (uint64_t) g.idx_key_dim, sizeof(float)}) ||
127        !product(z.dead, {(uint64_t) g.idx_key_dim, sizeof(float)}))
128        return fail(error, "running-state byte count overflow");
129    z.block_pos = sizeof(int32_t);
130    size_t total = 0;
131    if (!product(total, {(uint64_t) g.n_qsa_layers(), z.tail}) ||
132        !product(total, {(uint64_t) g.n_qsa_layers(), z.dead}) ||
133        !product(total, {(uint64_t) g.n_qsa_layers(), z.block_pos}))
134        return fail(error, "indexer byte count overflow");
135    return true;
136}
137
138bool conversation_session_sizes(const ModelGeometry& g, const SessionState& ss, ConversationStateSizes& z,
139                                std::string& error) {
140    if (!conversation_state_sizes(g, z, error)) return false;
141    const int64_t n_gdn = g.n_gdn_layers(), n_qsa = g.n_qsa_layers();
142    if (ss.gdn_alloc < 0 || ss.gdn_alloc > n_gdn || ss.qsa_ord0 < 0 || ss.qsa_alloc < 0 ||
143        ss.qsa_ord0 > n_qsa || ss.qsa_alloc > n_qsa - ss.qsa_ord0)
144        return fail(error, "invalid session layer carve");
145    // z.gdn is n_gdn whole rows; the session holds gdn_alloc of them (all of them for the default full range)
146    z.gdn = n_gdn > 0 ? z.gdn / (size_t) n_gdn * (size_t) ss.gdn_alloc : 0;
147    return true;
148}
149
150bool conversation_checkpoint_validate(const ConversationCheckpoint& c, const SessionState& ss,
151                                      const ModelGeometry& g, std::string& error) {
152    ConversationStateSizes z;
153    if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false;
154    const size_t layers = owned_qsa(ss);
155    if (c.gdn.size() != z.gdn || c.ple.size() != (ss.ple_hist ? z.ple : 0) ||
156        c.tails.size() != layers * z.tail || c.dead.size() != layers * z.dead ||
157        c.block_pos.size() != layers * z.block_pos || !image_keys(c.imgs, c.ids.size()))
158        return fail(error, "invalid checkpoint running-state payload");
159    return true;
160}
161
162#if defined(STRATA_GPU_METAL)
163}  // namespace strata::core
164namespace strata::metal_engine {
165// the running state lives in the Metal decode window (metal/src/engine/window.cpp), not in the session's buffers
166bool window_checkpoint_save(strata::core::ConversationCheckpoint& c, const strata::core::SessionState* ss, std::string& error);
167bool window_checkpoint_restore(const strata::core::ConversationCheckpoint& c, const strata::core::SessionState* ss, std::string& error);
168}  // namespace strata::metal_engine
169namespace strata::core {
170#endif
171
172namespace {
173struct CkptAsync {
174    std::mutex mu;
175    std::future<cudaError_t> pending;
176    const void* dst = nullptr;   // the checkpoint bytes the copy in flight writes
177    void* stage = nullptr;
178    void* host = nullptr;   // pinned: the DMA lands here, then a plain memcpy (no driver staging beside the decode)
179    cudaStream_t stream = nullptr;
180    size_t cap = 0;
181    int dev = -1;
182};
183CkptAsync& ckpt_async() { static CkptAsync a; return a; }
184// STRATA_CKPT_VRAM_SLOTS=N (with STRATA_CKPT_ASYNC): the last N saved GDN states stay in VRAM (allocated only while
185// more than 1.5 GB stays free); a restore of a checkpoint whose tag a slot holds copies device to device.
186struct VramSlot { void* p = nullptr; size_t n = 0; uint64_t tag = 0, used = 0; int dev = -1; };
187struct VramSlots { std::vector<VramSlot> s; uint64_t clock = 0, next_tag = 0; };
188VramSlots& vram_slots() { static VramSlots v; return v; }
189int vram_slots_n() {
190    static const int n = [] { const char* v = std::getenv("STRATA_CKPT_VRAM_SLOTS"); return v ? std::max(0, std::min(16, std::atoi(v))) : 0; }();
191    return n;
192}
193// a slot for `n` bytes on `dev`: a free one, a new one if VRAM allows, else the least recently used (nullptr: none)
194VramSlot* vram_slot_for(size_t n, int dev) {
195    VramSlots& v = vram_slots();
196    VramSlot* best = nullptr;
197    for (VramSlot& x : v.s)
198        if (x.dev == dev && x.n == n && (best == nullptr || x.used < best->used)) best = &x;
199    if ((int) v.s.size() < vram_slots_n()) {
200        size_t fr = 0, tot = 0;
201        if (cudaMemGetInfo(&fr, &tot) == cudaSuccess && fr > n + ((size_t) 3 << 29)) {
202            VramSlot x;
203            if (cudaMalloc(&x.p, n) == cudaSuccess) { x.n = n; x.dev = dev; v.s.push_back(x); return &v.s.back(); }
204        }
205        (void) cudaGetLastError();
206    }
207    return best;
208}
209bool ckpt_async_on() {
210#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL)
211    return false;
212#else
213    static const bool on = [] { const char* v = std::getenv("STRATA_CKPT_ASYNC"); return v != nullptr && v[0] == '1'; }();
214    return on;
215#endif
216}
217// STRATA_CKPT_GATHER=1 (CUDA, opt-in): the small running-state vectors (ple, then each layer's indexer tail, dead row
218// and block position: 1 + 3 x layers pieces) are gathered device to device into one buffer, allocated once, and
219// fetched with ONE copy into a pinned buffer, then copied into the vectors.  A small D2H copy issued while the
220// checkpoint DMA (STRATA_CKPT_ASYNC) is in flight waits behind the 4 MiB piece on the copy engine: one such wait
221// instead of 37.  The same bytes in the same places.  One set of buffers: the mutex serializes the saves a layer
222// split runs on one thread per stage (STRATA_CKPT_THREADS), which otherwise gather through the same buffer.
223struct CkptGather { std::mutex mu; void* stage = nullptr; void* host = nullptr; size_t cap = 0; int dev = -1; };
224CkptGather& ckpt_gather() { static CkptGather a; return a; }
225bool ckpt_gather_on() {
226#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL)
227    return false;
228#else
229    static const bool on = [] { const char* v = std::getenv("STRATA_CKPT_GATHER"); return v != nullptr && v[0] == '1'; }();
230    return on;
231#endif
232}
233// 1: the vectors are filled; 0: no buffers (the caller copies them one by one); -1: a copy failed (`error` set)
234int ckpt_gather_small(ConversationCheckpoint& c, const SessionState& ss, const ConversationStateSizes& z,
235                      size_t layers, std::string& error) {
236    const size_t ple = c.ple.size(), tails = c.tails.size(), dead = c.dead.size(), block_pos = c.block_pos.size();
237    const size_t total = ple + tails + dead + block_pos;
238    if (total == 0) return 1;
239    CkptGather& a = ckpt_gather();
240    std::lock_guard<std::mutex> lk(a.mu);
241    int dev = 0;
242    (void) cudaGetDevice(&dev);
243    if (a.stage != nullptr && (a.cap < total || a.dev != dev)) {
244        const int cur = dev;
245        (void) cudaSetDevice(a.dev); (void) cudaFree(a.stage); (void) cudaFreeHost(a.host); (void) cudaSetDevice(cur);
246        a.stage = a.host = nullptr; a.cap = 0;
247    }
248    if (a.stage == nullptr) {
249        if (cudaMalloc(&a.stage, total) == cudaSuccess && cudaMallocHost(&a.host, total) == cudaSuccess) { a.cap = total; a.dev = dev; }
250        else { if (a.stage) (void) cudaFree(a.stage); if (a.host) (void) cudaFreeHost(a.host); a.stage = a.host = nullptr; }
251        (void) cudaGetLastError();
252        if (a.stage == nullptr) return 0;
253    }
254    // the pieces in the vectors' order, queued on the private stream (in order), then the one copy to the host
255    uint8_t* s = (uint8_t*) a.stage;
256    if (!copy(s, ss.ple_hist, ple, error, true)) return -1;
257    for (size_t j = 0; j < layers; ++j) {
258        const auto& st = owned(ss, j);
259        if (!copy(s + ple + j * z.tail, st.idx_tail, z.tail, error, true) ||
260            !copy(s + ple + tails + j * z.dead, st.idx_dead, z.dead, error, true) ||
261            !copy(s + ple + tails + dead + j * z.block_pos, st.idx_block_pos, z.block_pos, error, true)) return -1;
262    }
263    if (!copy(a.host, a.stage, total, error)) return -1;
264    const uint8_t* h = (const uint8_t*) a.host;
265    if (ple) std::memcpy(c.ple.data(), h, ple);
266    if (tails) std::memcpy(c.tails.data(), h + ple, tails);
267    if (dead) std::memcpy(c.dead.data(), h + ple + tails, dead);
268    if (block_pos) std::memcpy(c.block_pos.data(), h + ple + tails + dead, block_pos);
269    return 1;
270}
271}  // namespace
272
273void conversation_checkpoint_join(const void* only) {
274    CkptAsync& a = ckpt_async();
275    std::lock_guard<std::mutex> lk(a.mu);
276    if (a.pending.valid() && (only == nullptr || only == a.dst)) {
277        const cudaError_t e = a.pending.get();
278        if (e != cudaSuccess) std::fprintf(stderr, "strata: STRATA_CKPT_ASYNC: a checkpoint copy failed (%s)\n", cudaGetErrorString(e));
279    }
280}
281
282namespace {
283// conversation_checkpoint_save; `staged` (STRATA_CKPT_ASYNC): the GDN bytes land in `c.gdn` on the background thread
284// after this returns (conversation_checkpoint_join waits for them)
285bool checkpoint_save(ConversationCheckpoint& c, const SessionState& ss, const ModelGeometry& g, std::string& error,
286                     bool& staged) {
287    staged = false;
288    const auto j0 = std::chrono::steady_clock::now();
289    conversation_checkpoint_join(nullptr);   // (the staging buffer is reused)
290    if (std::getenv("STRATA_PARK_TRACE")) std::fprintf(stderr, "strata parktrace: save join %.2f ms\n",
291        std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - j0).count());
292#if defined(STRATA_GPU_METAL)
293    (void) g;
294    return strata::metal_engine::window_checkpoint_save(c, &ss, error);
295#endif
296    ConversationStateSizes z;
297    if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false;
298    const size_t layers = owned_qsa(ss);
299    static const bool atr = std::getenv("STRATA_PARK_TRACE") != nullptr;
300    const bool ready = c.gdn.size() == z.gdn;   // (a pooled checkpoint's pages are in; a fresh vector faults them all)
301    const auto r0 = std::chrono::steady_clock::now();
302    const long rf0 = atr ? conversation_trace::thread_minflt() : 0;
303    c.gdn.resize(z.gdn); c.ple.resize(ss.ple_hist ? z.ple : 0);
304    c.tails.resize(layers * z.tail); c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos);
305    if (atr) std::fprintf(stderr, "strata parktrace: save vectors %s, resize %.2f ms, %ld faults, gdn %zu MB at %p (%s)\n", ready ? "ready" : "fresh",
306        std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - r0).count(),
307        conversation_trace::thread_minflt() - rf0, c.gdn.size() >> 20, (const void*) c.gdn.data(), conversation_trace::where(c.gdn.data()));
308    if (ckpt_async_on() && c.gdn.size() >= ((size_t) 1 << 20)) {
309        CkptAsync& a = ckpt_async();
310        int dev = 0;
311        (void) cudaGetDevice(&dev);
312        if (a.stage != nullptr && (a.cap < c.gdn.size() || a.dev != dev)) {
313            const int cur = dev;
314            (void) cudaSetDevice(a.dev); (void) cudaFree(a.stage); (void) cudaFreeHost(a.host);
315            (void) cudaStreamDestroy(a.stream); (void) cudaSetDevice(cur);
316            a.stage = a.host = nullptr; a.stream = nullptr; a.cap = 0;
317        }
318        if (a.stage == nullptr) {
319            if (cudaMalloc(&a.stage, c.gdn.size()) == cudaSuccess && cudaMallocHost(&a.host, c.gdn.size()) == cudaSuccess &&
320                cudaStreamCreateWithFlags(&a.stream, cudaStreamNonBlocking) == cudaSuccess) { a.cap = c.gdn.size(); a.dev = dev; }
321            else { if (a.stage) (void) cudaFree(a.stage); if (a.host) (void) cudaFreeHost(a.host); a.stage = a.host = nullptr; }
322        }
323        (void) cudaGetLastError();
324        const auto q0 = std::chrono::steady_clock::now();
325        VramSlot* slot = vram_slots_n() > 0 ? vram_slot_for(c.gdn.size(), dev) : nullptr;
326        if (slot != nullptr) slot->tag = 0;   // (being rewritten)
327        void* dsrc = slot != nullptr ? slot->p : a.stage;
328        c.dev_tag = 0;
329        if (dsrc != nullptr && copy(dsrc, ss.gdn_state, c.gdn.size(), error)) {   // device to device: fast
330            const auto q1 = std::chrono::steady_clock::now();
331            if (slot != nullptr) {
332                VramSlots& v = vram_slots();
333                slot->tag = c.dev_tag = ++v.next_tag;
334                slot->used = ++v.clock;
335            }
336            uint8_t* dst = c.gdn.data();
337            const size_t n = c.gdn.size();
338            void* host = a.host;
339            const uint8_t* stage = (const uint8_t*) dsrc;
340            cudaStream_t st = a.stream;
341            if (atr) std::fprintf(stderr, "strata parktrace: async ckpt d2d %.2f ms\n",
342                std::chrono::duration<double, std::milli>(q1 - q0).count());
343            std::lock_guard<std::mutex> lk(a.mu);
344            // the DMA in 4 MiB pieces, one in flight: a D2H copy queues behind the one before it on the copy engine, and
345            // the decode's own small reads would otherwise wait for the whole 100+ MB at the link's ~1.6 GB/s
346            a.dst = dst;
347            a.pending = std::async(std::launch::async, [dst, host, stage, n, st, dev] {
348                conversation_detail::background_thread_placement();
349                (void) cudaSetDevice(dev);
350                cudaEvent_t done = nullptr;
351                cudaError_t e = cudaEventCreateWithFlags(&done, cudaEventDisableTiming | cudaEventBlockingSync);
352                constexpr size_t PIECE = (size_t) 4 << 20;
353                for (size_t o = 0; e == cudaSuccess && o < n; o += PIECE) {
354                    const size_t k = std::min(PIECE, n - o);
355                    e = cudaMemcpyAsync((uint8_t*) host + o, stage + o, k, cudaMemcpyDeviceToHost, st);
356                    if (e == cudaSuccess) e = cudaEventRecord(done, st);
357                    if (e == cudaSuccess) e = cudaEventSynchronize(done);
358                    if (e == cudaSuccess) std::memcpy(dst + o, (const uint8_t*) host + o, k);
359                }
360                if (done) (void) cudaEventDestroy(done);
361                return e;
362            });
363            staged = true;
364        }
365    }
366    if (!staged && !copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error)) return false;
367    const auto s0 = std::chrono::steady_clock::now();
368    const bool ok = [&] {
369        // STRATA_CKPT_GATHER=1: the small vectors through one device gather and one copy (else one copy each)
370        if (ckpt_gather_on()) {
371            const int r = ckpt_gather_small(c, ss, z, layers, error);
372            if (r != 0) return r > 0;
373        }
374        if (!copy(c.ple.data(), ss.ple_hist, c.ple.size(), error)) return false;
375        for (size_t j = 0; j < layers; ++j) {
376            const auto& st = owned(ss, j);
377            if (!copy(c.tails.data() + j * z.tail, st.idx_tail, z.tail, error) ||
378                !copy(c.dead.data() + j * z.dead, st.idx_dead, z.dead, error) ||
379                !copy(c.block_pos.data() + j * z.block_pos, st.idx_block_pos, z.block_pos, error)) return false;
380        }
381        return true;
382    }();
383    if (atr) std::fprintf(stderr, "strata parktrace: save small copies %.2f ms\n",
384        std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - s0).count());
385    return ok;
386}
387}  // namespace
388
389bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss,
390                                  const ModelGeometry& g, std::string& error) {
391    bool staged = false;
392    return checkpoint_save(c, ss, g, error, staged);
393}
394
395bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionState& ss,
396                                     const ModelGeometry& g, std::string& error) {
397    const VramSlot* hit = nullptr;
398    if (c.dev_tag != 0) {
399        int dev = 0;
400        (void) cudaGetDevice(&dev);
401        for (VramSlot& x : vram_slots().s)
402            if (x.tag == c.dev_tag && x.dev == dev && x.n == c.gdn.size()) { x.used = ++vram_slots().clock; hit = &x; }
403    }
404    if (hit == nullptr) conversation_checkpoint_join(c.gdn.data());
405#if defined(STRATA_GPU_METAL)
406    (void) g;
407    if (!strata::metal_engine::window_checkpoint_restore(c, &ss, error)) return false;
408    ss.ple_prev[0] = c.ids.size() >= 2 ? c.ids[c.ids.size() - 2] : -1;
409    ss.ple_prev[1] = c.ids.size() >= 1 ? c.ids[c.ids.size() - 1] : -1;
410    return true;
411#endif
412    if (!conversation_checkpoint_validate(c, ss, g, error)) return false;
413    ConversationStateSizes z;
414    if (!conversation_session_sizes(g, ss, z, error)) return false;
415    if (!sync(error)) return false;   // the copies below no longer ride the legacy stream's implicit ordering
416    if (!copy(ss.gdn_state, hit != nullptr ? hit->p : (const void*) c.gdn.data(), c.gdn.size(), error) ||
417        !copy(ss.ple_hist, c.ple.data(), c.ple.size(), error)) return false;
418    for (size_t j = 0; j < owned_qsa(ss); ++j) {
419        const auto& st = owned(ss, j);
420        if (!copy(st.idx_tail, c.tails.data() + j * z.tail, z.tail, error) ||
421            !copy(st.idx_dead, c.dead.data() + j * z.dead, z.dead, error) ||
422            !copy(st.idx_block_pos, c.block_pos.data() + j * z.block_pos, z.block_pos, error)) return false;
423        if (!c.ids.empty()) {
424            const size_t row = c.ids.size() / strata::kernels::qsa_real_shapes().idx_block;
425            if (!copy(st.idx_pooled + row * g.idx_key_dim, c.dead.data() + j * z.dead, z.dead, error)) return false;
426        }
427    }
428    const size_t tokens = c.ids.size();
429    ss.ple_prev[0] = tokens >= 2 ? c.ids[tokens - 2] : -1;
430    ss.ple_prev[1] = tokens >= 1 ? c.ids[tokens - 1] : -1;
431    return sync(error);
432}
433
434bool conversation_checkpoint_copy(const SessionState& from, SessionState& to, const std::vector<int32_t>& ids,
435                                  const ModelGeometry& g, std::string& error, bool queued) {
436    // conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) without the host image, for two
437    // sessions carved alike on the same device (a stage's own session and its batch slots): the same bytes into
438    // the same places, through copy() like the restore (the private non-blocking stream, complete on return unless
439    // `queued`: then the caller synchronizes the device).
440    ConversationStateSizes zf, zt;
441    if (!checkpoint_targets(from, g, ids.size(), zf, error) || !checkpoint_targets(to, g, ids.size(), zt, error))
442        return false;
443    if (zf.gdn != zt.gdn || zf.tail != zt.tail || zf.dead != zt.dead || zf.block_pos != zt.block_pos ||
444        owned_qsa(from) != owned_qsa(to) || (from.ple_hist != nullptr) != (to.ple_hist != nullptr))
445        return fail(error, "direct copy between differently carved sessions");
446    auto acopy = [&](void* dst, const void* src, size_t bytes) { return copy(dst, src, bytes, error, queued); };
447    if (!acopy(to.gdn_state, from.gdn_state, zf.gdn) ||
448        !acopy(to.ple_hist, from.ple_hist, from.ple_hist ? zf.ple : 0)) return false;
449    for (size_t j = 0; j < owned_qsa(from); ++j) {
450        const auto& a = owned(from, j);
451        const auto& b = owned(to, j);
452        if (!acopy(b.idx_tail, a.idx_tail, zf.tail) || !acopy(b.idx_dead, a.idx_dead, zf.dead) ||
453            !acopy(b.idx_block_pos, a.idx_block_pos, zf.block_pos)) return false;
454        if (!ids.empty()) {   // restore writes the saved `dead` row into the pooled row the next token fills
455            const size_t row = ids.size() / strata::kernels::qsa_real_shapes().idx_block;
456            if (!acopy(b.idx_pooled + row * g.idx_key_dim, a.idx_dead, zf.dead)) return false;
457        }
458    }
459    const size_t tokens = ids.size();
460    to.ple_prev[0] = tokens >= 2 ? ids[tokens - 2] : -1;
461    to.ple_prev[1] = tokens >= 1 ? ids[tokens - 1] : -1;
462    return true;
463}
464
465bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss,
466                                 const ModelGeometry& g, const QsaState* draft, size_t& bytes, std::string& error) {
467    bytes = 0;
468    if (!view_validate(view, ss, g, error)) return false;
469    ConversationStateSizes z;
470    if (!conversation_session_sizes(g, ss, z, error)) return false;
471    size_t ids = 0, images = 0, checkpoints = 0, layers = 0, tails = 0, dead = 0, positions = 0;
472    const auto qsa = (uint64_t) owned_qsa(ss);
473    if (!product(ids, {view.ids.size(), sizeof(int32_t)}) ||
474        !product(images, {view.images.size(), sizeof(ConversationImageKey)}) ||
475        !product(checkpoints, {view.checkpoints.size(), sizeof(ConversationCheckpoint)}) ||
476        !product(layers, {qsa + (draft ? 1 : 0), sizeof(ConversationKv)}) ||
477        !product(tails, {qsa, z.tail}) || !product(dead, {qsa, z.dead}) ||
478        !product(positions, {qsa, z.block_pos})) return fail(error, "snapshot metadata byte count overflow");
479    for (size_t n : {ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ss.ple_hist ? z.ple : 0})
480        if (!add(bytes, n)) return fail(error, "snapshot byte count overflow");
481    for (const auto& c : view.checkpoints)
482        if (!metadata_bytes(c, bytes)) return fail(error, "checkpoint byte count overflow");
483    const int64_t upto = (int64_t) view.ids.size(); // view_validate bounds this by signed max_cells
484    for (uint64_t i = 0; i < qsa + (draft ? 1 : 0); ++i) {
485        const auto& st = i == qsa ? *draft : owned(ss, (size_t) i);
486        const size_t n = conversation_kv_bytes(st, g, upto, i != qsa);
487        if (!n || !add(bytes, n)) return fail(error, "invalid or overflowing K/V byte estimate");
488    }
489    return true;
490}
491
492bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,
493                                         const SessionState& ss, const ModelGeometry& g,
494                                         const QsaState* draft, size_t& bytes, std::string& error) {
495    if (!conversation_snapshot_bytes(view, ss, g, draft, bytes, error)) return false;
496    if (reuse.kv.empty()) return true;
497    const size_t layers = owned_qsa(ss) + (draft ? 1 : 0);
498    if (reuse.kv.size() != layers || reuse.unchanged_tokens < 0 ||
499        reuse.unchanged_tokens > reuse.captured_tokens || reuse.unchanged_tokens > int64_t(view.ids.size()))
500        return fail(error, "invalid retained K/V prefix");
501    for (size_t i = 0; i < layers; ++i) {
502        const bool index = i < owned_qsa(ss);
503        const auto& st = index ? owned(ss, i) : *draft;
504        if (!conversation_kv_validate(reuse.kv[i], st, g, reuse.captured_tokens, index, error)) return false;
505        const size_t fresh = conversation_kv_bytes(st, g, int64_t(view.ids.size()), index);
506        size_t retained = 0;
507        if (!conversation_kv_capture_bytes(reuse.kv[i], st, g, int64_t(view.ids.size()), index, retained, error)) return false;
508        bytes -= fresh;
509        if (!add(bytes, retained)) return fail(error, "retained K/V allocation overflow");
510    }
511    size_t directory = 0;
512    if (!product(directory, {reuse.kv.capacity() - layers, sizeof(ConversationKv)}) || !add(bytes, directory))
513        return fail(error, "retained K/V directory overflow");
514    return true;
515}
516
517// (conversation_snapshot.cpp) STRATA_PARK_TRACE: conversation_kv_save's time since the park's begin, by part (ms)
518void conversation_kv_save_trace(double& attrs_ms, double& resize_ms, double& copy_ms);
519long conversation_kv_save_trace_faults();   // (E1) minor faults of the K/V buffer resizes of this park's saves
520
521bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view,
522                                const SessionState& ss, const ModelGeometry& g,
523                                const QsaState* draft, std::string& error,
524                                ConversationKvReuse reuse, size_t* reused_bytes,
525                                std::vector<ConversationCheckpoint>* storage,
526                                std::vector<ConversationCheckpoint>* moved) {
527    static const bool ptr = std::getenv("STRATA_PARK_TRACE") != nullptr;
528    auto now = [] { return std::chrono::steady_clock::now(); };
529    auto ms = [](std::chrono::steady_clock::time_point a, std::chrono::steady_clock::time_point b) {
530        return std::chrono::duration<double, std::milli>(b - a).count(); };
531    const auto pj = now();
532    conversation_checkpoint_join(nullptr);   // the last turn checkpoint's DMA (STRATA_CKPT_ASYNC)
533    conversation_park_join();                // the previous park's K/V DMA
534    const auto p0 = now();
535    size_t estimate = 0;
536    if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false;
537    // Build into a new object so a failure cannot publish a partial snapshot.
538    SavedConversation captured;
539    captured.geometry = geometry_key(g);
540    captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi;
541    if (storage != nullptr && !storage->empty()) {   // the running state into a dropped checkpoint's vectors
542        captured.live = std::move(storage->back());
543        storage->pop_back();
544        captured.live.stage_parts.clear();
545    }
546    captured.live.ids = view.ids; captured.live.imgs = view.images;
547    const auto p1 = now();
548    const long cf0 = ptr ? conversation_trace::thread_minflt() : 0;
549    captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints, storage);
550    const long ck_faults = ptr ? conversation_trace::thread_minflt() - cf0 : 0;
551    if (ptr)   // (E1: where each copied checkpoint's running state went: faults of the whole copy, address, heap or mapping)
552        for (const auto& c : captured.checkpoints)
553            std::fprintf(stderr, "strata parktrace: ckpt copy gdn %zu MB at %p (%s)\n", c.gdn.size() >> 20,
554                         (const void*) c.gdn.data(), conversation_trace::where(c.gdn.data()));
555    if (moved != nullptr)
556        for (auto& c : *moved) {
557            conversation_checkpoint_join(c.gdn.data());
558            captured.checkpoints.push_back(std::move(c));
559        }
560    const auto p2 = now();
561    const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens;
562    captured.kv = std::move(reuse.kv);
563    const size_t layers = owned_qsa(ss);
564    captured.kv.resize(layers + (draft ? 1 : 0));
565    // STRATA_PARK_VRAM_MIB: the retained layers' tokens go now (joined above, so no wait): held past the launch below,
566    // their replacement would join the copy just launched
567    for (auto& k : captured.kv) k.pending.reset();
568    bool live_staged = false;
569    const bool live_saved = checkpoint_save(captured.live, ss, g, error, live_staged);
570    // STRATA_CKPT_ASYNC: the running state lands in live.gdn after the save returns; the image waits for that copy
571    // before the vector is freed (an eviction within the copy's ~70 ms), as `pending` does for the K/V.  The join is
572    // selective: a no-op once the copy has landed or another checkpoint's is in flight.
573    if (live_staged)
574        captured.live_pending = std::shared_ptr<void>(new char, [dst = (const void*) captured.live.gdn.data()](void* p) {
575            conversation_checkpoint_join(dst);
576            delete (char*) p;
577        });
578    if (!live_saved) return false;
579    const auto p3 = now();
580    const int64_t upto = (int64_t) view.ids.size();
581    // STRATA_PARK_ASYNC: the K/V bytes these saves copy (the stage they need; an over-estimate by the kept prefix)
582    size_t kv_need = 0;
583    for (size_t j = 0; j < layers; ++j) kv_need += conversation_kv_bytes(owned(ss, j), g, upto, true);
584    if (draft) kv_need += conversation_kv_bytes(*draft, g, upto, false);
585    const bool staged = conversation_park_async_begin(kv_need);
586    const auto p4 = now();
587    struct Abandon { bool on; ~Abandon() { if (on) conversation_park_async_abandon(); } } abandon{staged};
588    double kv_max = 0, kv_sum = 0;   // (STRATA_PARK_TRACE: the per-layer save time)
589    const long kf0 = ptr ? conversation_trace::thread_minflt() : 0;
590    for (size_t j = 0; j < layers; ++j) {
591        const auto k0 = now();
592        if (!conversation_kv_save(captured.kv[j], owned(ss, j), g, upto, true, error,
593                                  unchanged, reused_bytes)) return false;
594        const double kt = ms(k0, now());
595        kv_sum += kt; kv_max = std::max(kv_max, kt);
596    }
597    const long kv_faults_total = ptr ? conversation_trace::thread_minflt() - kf0 : 0;
598    if (ptr) {
599        size_t kvb = 0;
600        for (const auto& k : captured.kv) kvb += k.bytes();
601        double attrs_ms = 0, resize_ms = 0, copy_ms = 0;
602        conversation_kv_save_trace(attrs_ms, resize_ms, copy_ms);   // (the main layers' saves above)
603        std::fprintf(stderr, "strata parktrace: joins %.1f ms, sync %.1f ms, %zu checkpoints copied %.1f ms, live state %.1f ms, "
604                             "begin %.1f ms, K/V %zu MB %.1f ms (layer max %.2f, sum %.2f; attrs %.2f, resize %.2f, copy %.2f)\n",
605                     ms(pj, p0), ms(p0, p1), captured.checkpoints.size(), ms(p1, p2), ms(p2, p3), ms(p3, p4), kvb >> 20,
606                     ms(p4, now()), kv_max, kv_sum, attrs_ms, resize_ms, copy_ms);
607        static const bool thp_said = [] {
608            std::fprintf(stderr, "strata parktrace: THP enabled %s; defrag %s; page size %ld; sbrk end %p\n",
609                         conversation_trace::sys_line("/sys/kernel/mm/transparent_hugepage/enabled").c_str(),
610                         conversation_trace::sys_line("/sys/kernel/mm/transparent_hugepage/defrag").c_str(),
611                         conversation_trace::page_size(), conversation_trace::brk_end());
612            return true;
613        }();
614        (void) thp_said;
615        // E1: page faults per phase (a 4 KiB first touch = 1, a 2 MiB huge page = 1).  (Not AnonHugePages: reading /proc/self/smaps_rollup
616        // walks the 47 GB expert mapping and costs ~0.5 s a read, which the first E1 job (e1, 11-11) put inside the park's own times.)
617        std::fprintf(stderr, "strata parktrace: faults: checkpoint copies %ld, K/V resize %ld (copy phase included in the layer loop: %ld)\n",
618                     ck_faults, conversation_kv_save_trace_faults(), kv_faults_total);
619        if (!captured.kv.empty()) {
620            const auto& k0 = captured.kv.front();
621            std::fprintf(stderr, "strata parktrace: K/V layer 0 buffers (bytes): k %zu v %zu k_scale %zu v_scale %zu pooled %zu; %zu layers; "
622                                 "segment %zu MiB\n", k0.k.size(), k0.v.size(), k0.k_scale.size(), k0.v_scale.size(), k0.pooled.size(),
623                         captured.kv.size(), ConversationBuffer::segment_bytes >> 20);
624        }
625    }
626    // The draft's final cell may not have been computed when the output cap was
627    // reached. Refresh that page even when the main prefix continued unchanged.
628    if (draft && !conversation_kv_save(captured.kv.back(), *draft, g, upto, false, error,
629                                       std::max<int64_t>(0, unchanged - 1), reused_bytes)) return false;
630    abandon.on = false;
631    if (staged && !conversation_park_async_launch(error)) return false;
632    if (staged) {
633        // STRATA_PARK_VRAM_MIB: the image's slot goes with the image, after the copy that reads it; each K/V layer
634        // carries a token of its own too (the layers outlive the image when they are retained for the next park, and
635        // the copy fills their buffers).  Without a slot: the image's join as before, no layer tokens.
636        const uint64_t slot = conversation_park_slot_tag();
637        auto token = [slot] {
638            return std::shared_ptr<void>(new char, [slot](void* p) {
639                conversation_park_join();
640                conversation_park_slot_release(slot);
641                delete (char*) p;
642            });
643        };
644        captured.pending = token();
645        if (slot != 0)
646            for (auto& k : captured.kv) k.pending = token();
647    }
648    image = std::move(captured);
649    return true;
650}
651
652bool conversation_snapshot_sources(SavedConversation& meta, std::vector<SessionKvSource>& sources,
653                                   const ConversationView& view, const SessionState& ss, const ModelGeometry& g,
654                                   const QsaState& draft, std::string& error) {
655    if (!view_validate(view, ss, g, error) || !sync(error)) return false;
656    SavedConversation captured;
657    captured.geometry = geometry_key(g);
658    captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi;
659    captured.live.ids = view.ids; captured.live.imgs = view.images;
660    captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints);
661    if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false;
662    // STRATA_CKPT_ASYNC: the caller writes `meta` to the session file at once, so the running state's copy lands first
663    conversation_checkpoint_join(captured.live.gdn.data());
664    const int64_t upto = (int64_t) view.ids.size();
665    const size_t layers = owned_qsa(ss);
666    std::vector<SessionKvSource> out(layers + 1);
667    for (size_t j = 0; j < layers; ++j)
668        if (!conversation_kv_source(out[j], owned(ss, j), g, upto, true, error)) return false;
669    if (!conversation_kv_source(out.back(), draft, g, upto, false, error)) return false;
670    meta = std::move(captured);
671    sources = std::move(out);
672    return true;
673}
674
675bool conversation_session_read_limits(SessionReadLimits& limits, const SessionState& ss, const ModelGeometry& g,
676                                      const QsaState& draft, uint64_t max_tokens, uint64_t max_checkpoints,
677                                      std::string& error) {
678    ConversationStateSizes z;
679    if (!conversation_session_sizes(g, ss, z, error)) return false;
680    if (ss.max_cells < 0) return fail(error, "invalid session cells");
681    const uint64_t tokens = std::min<uint64_t>(max_tokens, (uint64_t) ss.max_cells);
682    const size_t layers = owned_qsa(ss);
683    if ((owned_qsa(ss) && !ss.qsa_states)) return fail(error, "invalid session running-state targets");
684    size_t tails = 0, dead = 0, block_pos = 0;
685    if (!product(tails, {layers, z.tail}) || !product(dead, {layers, z.dead}) ||
686        !product(block_pos, {layers, z.block_pos})) return fail(error, "indexer byte count overflow");
687    SessionReadLimits l = limits;   // keeps the caller's admit / progress / max_file_bytes
688    l.max_tokens = tokens;
689    l.max_checkpoints = max_checkpoints;
690    l.max_kv_layers = layers + 1;
691    l.geometry = geometry_key(g);
692    l.layer_range = std::make_pair(ss.layer_lo, ss.layer_hi);
693    l.max_state_bytes = {z.gdn, ss.ple_hist ? z.ple : 0, tails, dead, block_pos};
694    l.max_kv_bytes.assign(layers + 1, {});
695    for (size_t j = 0; j < layers; ++j) {
696        const auto& st = owned(ss, j);
697        const int64_t upto = (int64_t) std::min<uint64_t>(tokens, (uint64_t) std::max<int64_t>(st.max_cells, 0));
698        if (!conversation_kv_part_sizes(st, g, upto, true, l.max_kv_bytes[j], error)) return false;
699    }
700    const int64_t dupto = (int64_t) std::min<uint64_t>(tokens, (uint64_t) std::max<int64_t>(draft.max_cells, 0));
701    if (!conversation_kv_part_sizes(draft, g, dupto, false, l.max_kv_bytes.back(), error)) return false;
702    limits = std::move(l);
703    return true;
704}
705
706bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss,
707                                    const ModelGeometry& g, const QsaState* draft, std::string& error) {
708    if (!image.live.stage_parts.empty())
709        return fail(error, "a running checkpoint's stage parts belong in the stage images, not in live.stage_parts");
710    if (image.geometry != geometry_key(g)) return fail(error, "incompatible runtime geometry");
711    // an image holds exactly one carve's running state and K/V: same layer range or nothing
712    if (image.layer_lo != ss.layer_lo || image.layer_hi != ss.layer_hi)
713        return fail(error, "snapshot from another session layer range");
714    const ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec};
715    if (!view_validate(view, ss, g, error) || !conversation_checkpoint_validate(image.live, ss, g, error)) return false;
716    const size_t layers = owned_qsa(ss);
717    if (image.kv.size() != layers + (draft ? 1 : 0)) return fail(error, "invalid K/V layer count");
718    const int64_t upto = (int64_t) image.live.ids.size();
719    for (size_t j = 0; j < layers; ++j)
720        if (!conversation_kv_validate(image.kv[j], owned(ss, j), g, upto, true, error)) return false;
721    return !draft || conversation_kv_validate(image.kv.back(), *draft, g, upto, false, error);
722}
723
724bool conversation_copy_stream_ready(int device) { return conversation_detail::copy_stream_ready(device); }
725
726ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss,
727                                                   const ModelGeometry& g, const QsaState* draft, std::string& error) {
728    conversation_checkpoint_join(image.live.gdn.data());
729    for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data());
730    conversation_park_join_for(image);   // (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot)
731    if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid;
732    if (!sync(error)) return ConversationRestore::transfer_failed;
733    const int64_t upto = (int64_t) image.live.ids.size();
734    for (size_t j = 0; j < owned_qsa(ss); ++j)
735        if (!conversation_kv_restore(image.kv[j], owned(ss, j), g, upto, true, error))
736            return ConversationRestore::transfer_failed;
737    if ((draft && !conversation_kv_restore(image.kv.back(), *draft, g, upto, false, error)) ||
738        !conversation_checkpoint_restore(image.live, ss, g, error)) return ConversationRestore::transfer_failed;
739    return ConversationRestore::restored;
740}
741
742// the draft layer's K/V included (the stage that owns the draft head, or no layer split)
743bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss, const ModelGeometry& g,
744                                 const QsaState& draft, size_t& bytes, std::string& error) {
745    return conversation_snapshot_bytes(view, ss, g, &draft, bytes, error);
746}
747bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,
748                                         const SessionState& ss, const ModelGeometry& g, const QsaState& draft,
749                                         size_t& bytes, std::string& error) {
750    return conversation_snapshot_capture_bytes(reuse, view, ss, g, &draft, bytes, error);
751}
752bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& ss,
753                                const ModelGeometry& g, const QsaState& draft, std::string& error,
754                                ConversationKvReuse reuse, size_t* reused_bytes) {
755    return conversation_snapshot_save(image, view, ss, g, &draft, error, std::move(reuse), reused_bytes);
756}
757bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss, const ModelGeometry& g,
758                                    const QsaState& draft, std::string& error) {
759    // the whole-session form: a layer split's image (stage images) is restored stage by stage, never through here
760    if (!image.stage_images.empty()) return fail(error, "a layer split's image restored as a single session");
761    return conversation_snapshot_validate(image, ss, g, &draft, error);
762}
763ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss,
764                                                   const ModelGeometry& g, const QsaState& draft, std::string& error) {
765    conversation_checkpoint_join(image.live.gdn.data());
766    for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data());
767    conversation_park_join_for(image);   // (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot)
768    return conversation_snapshot_restore(image, ss, g, &draft, error);
769}
770ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto,
771                                                          SessionState& ss, const ModelGeometry& g,
772                                                          const QsaState& draft, std::string& error) {
773    conversation_checkpoint_join(image.live.gdn.data());
774    for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data());
775    conversation_park_join_for(image);   // (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot)
776    return conversation_snapshot_restore_prefix(image, upto, ss, g, &draft, error);
777}
778ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto,
779                                                          SessionState& ss, const ModelGeometry& g,
780                                                          const QsaState* draft, std::string& error) {
781    conversation_checkpoint_join(image.live.gdn.data());
782    for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data());
783    conversation_park_join_for(image);   // (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot)
784    // a layer split's image (stage images) is restored stage by stage, never in part
785    if (!image.stage_images.empty()) {
786        fail(error, "a layer split's image restored as a single session");
787        return ConversationRestore::invalid;
788    }
789    if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid;
790    const int64_t captured = (int64_t) image.live.ids.size();
791    if (upto < 1 || upto > captured) {
792        fail(error, "the borrowed prefix is not inside the parked conversation");
793        return ConversationRestore::invalid;
794    }
795    if (!sync(error)) return ConversationRestore::transfer_failed;
796    for (size_t j = 0; j < owned_qsa(ss); ++j)
797        if (!conversation_kv_restore_prefix(image.kv[j], owned(ss, j), g, captured, upto, true, error))
798            return ConversationRestore::transfer_failed;
799    if (draft && !conversation_kv_restore_prefix(image.kv.back(), *draft, g, captured, upto, false, error))
800        return ConversationRestore::transfer_failed;
801    return ConversationRestore::restored;
802}
803
804bool conversation_session_dump(const SessionState& ss, const ModelGeometry& g, const std::vector<int32_t>& ids,
805                               const std::string& path, std::string& error) {
806    const std::vector<ConversationImageKey> images;
807    const std::vector<ConversationCheckpoint> checkpoints;
808    SavedConversation image;
809    if (!conversation_snapshot_save(image, ConversationView{ids, images, checkpoints, true}, ss, g, nullptr, error))
810        return false;
811    conversation_checkpoint_join(image.live.gdn.data());
812    conversation_park_join_for(image);
813    std::FILE* f = std::fopen(path.c_str(), "wb");
814    if (f == nullptr) return fail(error, "the session dump could not be opened");
815    bool ok = true;
816    auto put = [&](const void* p, size_t n) { ok = ok && (n == 0 || std::fwrite(p, 1, n, f) == n); };
817    const int64_t head[3] = {ss.layer_lo, ss.layer_hi, (int64_t) ids.size()};
818    put(head, sizeof head);
819    for (const auto* v : {&image.live.gdn, &image.live.ple, &image.live.tails, &image.live.dead, &image.live.block_pos})
820        put(v->data(), v->size());
821    for (const ConversationKv& kv : image.kv)
822        for (const ConversationBuffer* b : {&kv.k, &kv.v, &kv.k_scale, &kv.v_scale, &kv.pooled})
823            b->visit(0, b->size(), [&](const uint8_t* p, size_t n, size_t) { put(p, n); return ok; });
824    const int32_t ple[3] = {ss.ple_prev[0], ss.ple_prev[1], ss.ple_token};
825    put(ple, sizeof ple);
826    ok = std::fclose(f) == 0 && ok;
827    return ok || fail(error, "the session dump could not be written");
828}
829
830} // namespace strata::core