okami.mom/strata

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

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

main
17.1 KiB336 linesraw
1#define DPCT_PROFILING_ENABLED
2#include <sycl/sycl.hpp>
3#include <dpct/dpct.hpp>
4#include "strata/core/conversation_snapshot.hpp"
5#include "strata/kernels/kv_q4.hpp"
6#include "conversation_checked.hpp"
7
8#include <array>
9#include <cstring>
10#include <limits>
11#include <memory>
12
13namespace strata::core {
14namespace {
15struct Layout {
16    int format;
17    int64_t cells, pooled_rows, page_size;
18    size_t data, scales, pooled, value_data, value_scales;
19};
20
21bool valid_extent(const QsaState& st, int64_t upto, std::string& error) {
22    const int64_t page = strata::kernels::qsa_real_shapes().page_size;
23    if (upto < 0 || upto > st.max_cells || upto > std::numeric_limits<int64_t>::max() - (page - 1)) {
24        error = "conversation snapshot: invalid K/V extent";
25        return false;
26    }
27    return true;
28}
29
30bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) {
31    if (!valid_extent(st, upto, error)) return false;
32    if (st.kv_hybrid && (st.kv_mode == 2 || st.kv_q4 || st.kv_int8)) {   // a streamed one reads its host copy
33        error = "conversation snapshot: hybrid K8V4 cannot be a ring and needs distinct format flags";
34        return false;
35    }
36    const auto s = strata::kernels::qsa_real_shapes();
37    const bool int8_keys = st.kv_int8 || st.kv_hybrid;
38    if (g.n_head_kv <= 0 || g.head_dim <= 0 || g.head_dim > INT32_MAX || g.idx_key_dim <= 0 ||
39        (st.kv_q4 && g.head_dim % 32) || (int8_keys && !st.kv_q4 && g.head_dim % 64)) {
40        error = "conversation snapshot: invalid K/V geometry";
41        return false;
42    }
43    const int64_t cells = ((upto + s.page_size - 1) / s.page_size) * s.page_size;
44    const size_t per = st.kv_q4 ? (size_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)
45                              : (size_t) g.head_dim * (int8_keys ? 1 : 2);
46    // Include the moving spare row, not only completed blocks. The checkpoint
47    // restore reconstructs that row when rewinding to an earlier prefix.
48    const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0;
49    // Format 3 identifies snapshot K8V4 only; never pass it to the block movers.  Rotated INT8 K/V (#293,
50    // STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a
51    // snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse.
52    // (Q4_0 is always rotated: nothing to tell apart; without the rotation the format is the one it always was.)
53    const int rotated = st.kv_rot && !st.kv_q4 && !st.kv_hybrid ? 16 : 0;
54    l = {(st.kv_hybrid ? 3 : qsa_kv_format(st)) + rotated, cells, pooled, s.page_size, 0, 0, 0, 0, 0};
55    using conversation_detail::product;
56    if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) ||
57        !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv,
58                           int8_keys && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) ||
59        !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)})) {
60        error = "conversation snapshot: K/V byte count overflow";
61        return false;
62    }
63    l.value_data = l.data;
64    l.value_scales = l.scales;
65    if (st.kv_hybrid) {
66        if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv,
67                                   (uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) {
68            error = "conversation snapshot: hybrid V byte count overflow";
69            return false;
70        }
71        l.value_scales = 0;
72    }
73    return true;
74}
75
76std::array<void*, 5> pools(const QsaState& st, bool resident = false) {
77    const bool host = st.kv_mode != 0 && !resident;
78    if (st.kv_hybrid)
79        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,
80                nullptr, st.idx_pooled};
81    if (st.kv_q4)
82        return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled};
83    if (st.kv_int8)
84        return {host ? st.host.k_q : st.k_q, host ? st.host.v_q : st.v_q,
85                host ? st.host.k_scale : st.k_scale, host ? st.host.v_scale : st.v_scale, st.idx_pooled};
86    return {host ? st.host.k_pool : st.k_pool, host ? st.host.v_pool : st.v_pool, nullptr, nullptr, st.idx_pooled};
87}
88
89bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error) {
90    if (upto < 0 || upto > st.max_cells || st.n_pages < 0 || l.cells / l.page_size > st.n_pages ||
91        st.kv_mode < 0 || st.kv_mode > 2 || st.n_slots <= 0 ||
92        (st.kv_mode == 0 && st.n_slots < st.n_pages) ||
93        l.pooled_rows > st.idx_pooled_rows || (st.kv_mode != 0 && !st.host.present())) {
94        error = "conversation snapshot: invalid K/V extent or missing authoritative host pool";
95        return false;
96    }
97    if (st.kv_mode == 1) {
98        const auto& m = st.map;
99        if (m.n_blocks != st.n_pages || m.n_slots != st.n_slots || !m.page_table || !m.slot_block ||
100            !m.slot_stamp || !m.slot_ref || !m.ctl || !m.miss_block || !m.miss_slot) {
101            error = "conversation snapshot: invalid streaming map";
102            return false;
103        }
104    }
105    if (st.kv_mode == 2 && (!st.page_table ||
106        (st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale
107                                                    : !st.k_pool || !st.v_pool))) {
108        error = "conversation snapshot: invalid draft ring";
109        return false;
110    }
111    return true;
112}
113
114// SYCL port: a copy with neither end in device memory (pinned USM host <-> pageable host) goes through memcpy on the
115// CPU. Through the queue it runs on the Arc's copy engine, which hung on it (dmesg "Engine reset: engine_class=bcs";
116// repeated, the B70 was declared wedged): conversation_snapshot_test, and the parked KV of a --kv-resident session.
117inline bool host_only_copy(void* dst, const void* src) {
118    const sycl::context ctx = dpct::get_in_order_queue().get_context();
119    const auto host = [&](const void* p) {
120        const sycl::usm::alloc t = sycl::get_pointer_type(p, ctx);
121        return t == sycl::usm::alloc::host || t == sycl::usm::alloc::unknown;
122    };
123    return host(dst) && host(src);
124}
125bool transfer(void *dst, const void *src, size_t n, std::string &error) try {
126    if (!n) return true;
127    if (!src || !dst) { error = "conversation snapshot: missing state buffer"; return false; }
128    if (host_only_copy(dst, src)) { std::memcpy(dst, src, n); return true; }
129    // Default handles both device allocations and device-mapped host pool aliases.
130    const dpct::err0 e =
131        DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(dst, src, n).wait());
132    if (e == 0) return true;
133    /*
134    DPCT1009: SYCL reports errors using exceptions and does not use error
135    codes. Please replace the "get_error_string_dummy(...)" with a real
136    error-handling function.
137    */
138    error = std::string("conversation snapshot copy: ") +
139            dpct::get_error_string_dummy(e);
140    return false;
141}
142catch (sycl::exception const &exc) {
143  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
144            << ", line:" << __LINE__ << std::endl;
145  std::exit(1);
146}
147} // namespace
148
149bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
150                                   int64_t upto, bool index, size_t& bytes, std::string& error) {
151    Layout l{};
152    if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false;
153    const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
154    const std::array<const ConversationBuffer*,5> buffers = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
155    bytes = 0;
156    for (size_t i = 0; i < buffers.size(); ++i) {
157        const size_t n = buffers[i]->allocation_peak(sizes[i]);
158        if (n == SIZE_MAX || !conversation_detail::add(bytes, n)) {
159            error = "conversation snapshot: segmented K/V allocation overflow";
160            return false;
161        }
162    }
163    return true;
164}
165
166size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) {
167    size_t bytes = 0;
168    std::string error;
169    return conversation_kv_capture_bytes({}, st, g, upto, index, bytes, error) ? bytes : 0;
170}
171
172bool conversation_kv_save(ConversationKv& image, const QsaState& st, const ModelGeometry& g,
173                          int64_t upto, bool index, std::string& error,
174                          int64_t unchanged_tokens, size_t* reused_bytes) {
175    Layout l{};
176    if (!layout(st, g, upto, index, l, error)) return false;
177    if (!valid(st, l, upto, error)) return false;
178    if (unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image.cells) {
179        error = "conversation snapshot: invalid unchanged prefix";
180        return false;
181    }
182    const int64_t whole_cells = (unchanged_tokens / l.page_size) * l.page_size;
183    image.format = l.format;
184    image.cells = l.cells;
185    image.heads = g.n_head_kv;
186    image.head_dim = g.head_dim;
187    image.page_size = l.page_size;
188    image.pooled_rows = l.pooled_rows;
189    image.idx_dim = g.idx_key_dim;
190    const auto src = pools(st);
191    const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
192    const std::array<ConversationBuffer*,5> dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
193    for (size_t i = 0; i < dst.size(); ++i) {
194        // Recopy the partial page and the indexer's moving spare row. Completed
195        // pages/rows strictly before the first rewritten token remain identical.
196        const size_t keep = i == 4 ? (index ? size_t(unchanged_tokens / strata::kernels::qsa_real_shapes().idx_block) * g.idx_key_dim * 4 : 0)
197                                  : l.cells ? (sizes[i] / size_t(l.cells)) * size_t(whole_cells) : 0;
198        if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; }
199        dst[i]->resize(sizes[i]);
200        if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) {
201                return transfer(p, src[i] ? static_cast<const uint8_t*>(src[i]) + at : nullptr, n, error);
202            })) return false;
203        if (reused_bytes) *reused_bytes += keep;
204    }
205    return true;
206}
207
208bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
209                              int64_t upto, bool index, std::string& error) {
210    Layout l{};
211    if (!layout(st, g, upto, index, l, error)) return false;
212    if (!valid(st, l, upto, error)) return false;
213    const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
214    const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
215    if (image.format != l.format || image.cells != l.cells || image.heads != g.n_head_kv ||
216        image.head_dim != g.head_dim || image.page_size != l.page_size || image.pooled_rows != l.pooled_rows ||
217        image.idx_dim != g.idx_key_dim) {
218        error = "conversation snapshot: incompatible K/V geometry";
219        return false;
220    }
221    for (size_t i = 0; i < src.size(); ++i)
222        if (src[i]->size() != sizes[i]) { error = "conversation snapshot: invalid K/V payload size"; return false; }
223    const auto dst = pools(st);
224    for (size_t i = 0; i < src.size(); ++i)
225        if (sizes[i] && !dst[i]) { error = "conversation snapshot: missing target state buffer"; return false; }
226    return true;
227}
228
229bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
230                             int64_t upto, bool index, std::string& error) {
231    if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;
232    const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
233    const auto dst = pools(st);
234    for (size_t i = 0; i < src.size(); ++i)
235        if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) {
236                return transfer(static_cast<uint8_t*>(dst[i]) + at, p, n, error);
237            })) return false;
238    // VRAM slots still contain the outgoing conversation. Resolve must refill
239    // them from the restored authoritative pools before any attention reads.
240    if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr);
241    if (st.kv_mode == 2 && upto > 0) {
242        auto shapes = strata::kernels::qsa_real_shapes();
243        shapes.n_head_kv = g.n_head_kv; shapes.head_dim = g.head_dim;
244        const int64_t end = (upto + shapes.page_size - 1) / shapes.page_size;
245        strata::kernels::kv_ring_restore(qsa_attn_pools(st), st.host, qsa_kv_format(st),
246                                        std::max<int64_t>(0, end - st.n_slots), end, st.n_slots, shapes, nullptr);
247    }
248    /*
249    DPCT1010: SYCL uses exceptions to report errors and does not use the
250    error codes. The cudaGetLastError function call was replaced with 0. You
251    need to rewrite this code.
252    */
253    const auto status = 0;
254    if (status == 0) return true;
255    /*
256    DPCT1009: SYCL reports errors using exceptions and does not use error
257    codes. Please replace the "get_error_string_dummy(...)" with a real
258    error-handling function.
259    */
260    error = std::string("conversation snapshot residency restore: ") +
261            dpct::get_error_string_dummy(status);
262    return false;
263}
264
265bool conversation_kv_part_sizes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index,
266                                std::array<uint64_t, 5>& sizes, std::string& error) {
267    Layout l{};
268    if (!layout(st, g, upto, index, l, error)) return false;
269    sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
270    return true;
271}
272
273bool conversation_kv_source(SessionKvSource& out, const QsaState& st, const ModelGeometry& g,
274                            int64_t upto, bool index, std::string& error) {
275    Layout l{};
276    if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false;
277    SessionKvSource s;
278    s.format = l.format; s.cells = l.cells; s.heads = g.n_head_kv; s.head_dim = g.head_dim;
279    s.page_size = l.page_size; s.pooled_rows = l.pooled_rows; s.idx_dim = g.idx_key_dim;
280    s.sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
281    const auto src = pools(st);
282    const auto sizes = s.sizes;
283    auto why = std::make_shared<std::string>();
284    s.read = [src, sizes, why](size_t part, size_t offset, void* dst, size_t n) {
285        if (part >= 5 || offset > sizes[part] || n > sizes[part] - offset) { *why = "K/V read out of range"; return false; }
286        return transfer(dst, src[part] ? static_cast<const uint8_t*>(src[part]) + offset : nullptr, n, *why);
287    };
288    s.error = [why] { return *why; };
289    out = std::move(s);
290    return true;
291}
292
293bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
294                            int64_t upto, bool index, uint64_t& fingerprint, std::string& error) {
295    if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;
296    std::array<uint8_t, 65536> buffer;
297    uint64_t hash = 1469598103934665603ull;
298    auto compare = [&](const void* device, const uint8_t* expected, size_t bytes, bool include_hash) {
299        for (size_t offset = 0; offset < bytes;) {
300            const size_t n = std::min(buffer.size(), bytes - offset);
301            if (!transfer(buffer.data(), static_cast<const uint8_t*>(device) + offset, n, error)) return false;
302            if (std::memcmp(buffer.data(), expected + offset, n) != 0) {
303                error = "conversation snapshot: restored K/V bytes differ";
304                return false;
305            }
306            if (include_hash) for (size_t i = 0; i < n; ++i) { hash ^= buffer[i]; hash *= 1099511628211ull; }
307            offset += n;
308        }
309        return true;
310    };
311    const std::array<const ConversationBuffer*, 5> saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
312    const auto authoritative = pools(st);
313    for (size_t i = 0; i < saved.size(); ++i)
314        if (!saved[i]->visit(0, saved[i]->size(), [&](const uint8_t* p, size_t n, size_t at) {
315                return compare(static_cast<const uint8_t*>(authoritative[i]) + at, p, n, true);
316            })) return false;
317    if (st.kv_mode == 2 && image.cells > 0) {
318        const auto resident = pools(st, true);
319        const int64_t end = image.cells / image.page_size;
320        const int64_t begin = std::max<int64_t>(0, end - st.n_slots);
321        for (size_t i = 0; i < 4; ++i) {
322            if (saved[i]->empty()) continue;
323            const size_t page_bytes = saved[i]->size() / size_t(end);
324            for (int64_t page = begin; page < end; ++page)
325                if (!saved[i]->visit(size_t(page) * page_bytes, page_bytes,
326                        [&](const uint8_t* p, size_t n, size_t at) {
327                            const size_t offset = size_t(page % st.n_slots) * page_bytes + at - size_t(page) * page_bytes;
328                            return compare(static_cast<const uint8_t*>(resident[i]) + offset, p, n, false);
329                        })) return false;
330        }
331    }
332    fingerprint = hash;
333    return true;
334}
335
336} // namespace strata::core