okami.mom/strata

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

waveringanadsv41: conversation slots and SCR keep conversations with pictures - spans matched by picture hash (picspans::keyed), a slot's pictures in a .pics file, SCR moves or reads a picture's span whole24d897c06

main
6.9 KiB160 linesraw
1// Pictures in the kept-conversation and SCR bookkeeping (no GPU): every position of a picture's span carries the same
2// image token, so token equality is not picture equality.  The matchers (prefix reuse, the slot a prompt takes back,
3// SCR's runs) compare a "keyed" copy of the tokens instead, where each span position is a negative id derived from the
4// picture's hash and the position's offset in its span: two spans agree only for the same picture, offset by offset,
5// and never with a real token or the pad.  SCR moves or reads a picture's span whole (whole_spans); a slot keeps its
6// pictures in a .pics file beside its .bin (write / read).  The engine's serve loop (ds4_main.cpp) uses these;
7// tests/dsv41/slot_test.cpp checks them alone.
8//
9// .pics layout (little endian): u64 magic "DS4PICS1", u64 count, then per picture i64 start, i64 len, u64 hash,
10// i32 width, i32 height; u64 magic
11#pragma once
12
13#include "strata/core/scr.hpp"
14
15#include <algorithm>
16#include <cstdint>
17#include <filesystem>
18#include <fstream>
19#include <string>
20#include <vector>
21
22namespace strata::ds4::picspans {
23
24struct Span {
25    int64_t start = 0, len = 0;
26    uint64_t hash = 0;
27    int32_t width = 0, height = 0;
28};
29
30constexpr uint64_t kMagic = 0x3153434950345344ull;   // "DS4PICS1"
31
32// the matcher's id of a picture's position `off` (negative: never a real token, the pad or -1)
33inline int32_t key(uint64_t hash, int64_t off) {
34    uint64_t h = (hash ^ ((uint64_t) off * 0x9E3779B97F4A7C15ull)) * 0xBF58476D1CE4E5B9ull;
35    h ^= h >> 31;
36    return -2 - (int32_t) (h & 0x3FFFFFFF);
37}
38
39// `toks` with every span position replaced by its key (a span past the end is cut there)
40template <class T>
41std::vector<int32_t> keyed(const std::vector<T>& toks, const std::vector<Span>& spans) {
42    std::vector<int32_t> out(toks.begin(), toks.end());
43    for (const Span& s : spans)
44        for (int64_t i = 0; i < s.len && s.start + i < (int64_t) out.size(); ++i)
45            if (s.start + i >= 0) out[(size_t) (s.start + i)] = key(s.hash, i);
46    return out;
47}
48
49// each picture's span in a prompt: the run of image tokens from its start, up to the next picture's start
50template <class T>
51void measure(const std::vector<T>& ids, int image_token, std::vector<Span>& spans) {
52    for (size_t k = 0; k < spans.size(); ++k) {
53        const int64_t lim = k + 1 < spans.size() ? spans[k + 1].start : (int64_t) ids.size();
54        int64_t n = 0;
55        while (spans[k].start + n < lim && (int) ids[(size_t) (spans[k].start + n)] == image_token) ++n;
56        spans[k].len = n;
57    }
58}
59
60// the spans after `n` positions were inserted into their prompt: map[i] is old position i's new one
61inline std::vector<Span> moved(const std::vector<Span>& spans, const std::vector<int64_t>& map) {
62    std::vector<Span> out;
63    for (Span s : spans) {
64        if (s.start < 0 || s.start >= (int64_t) map.size()) continue;
65        s.start = map[(size_t) s.start];
66        out.push_back(s);
67    }
68    return out;
69}
70
71// positions 0..n-1 after inserting a slot at each of `at` (sorted positions in the result): the new place of each
72inline std::vector<int64_t> insert_map(size_t n, const std::vector<int64_t>& at) {
73    std::vector<int64_t> map(n);
74    size_t k = 0;
75    int64_t out = 0;
76    for (size_t i = 0; i < n; ++i) {
77        while (k < at.size() && at[k] == out) ++k, ++out;
78        map[i] = out++;
79    }
80    return map;
81}
82
83// SCR's runs cut so no picture is split: each run reuses [new_start, new_start + n - band) of the prompt and reads its
84// last `band` tokens again, and a picture's span must lie wholly in one or the other (or outside the run).  A run that
85// starts inside a span starts after it; one whose kept part ends inside a span ends before it.  Runs shorter than
86// `min_n` go, and every run's pad is worked out again (block 2: an even shift).  `spans` are in the prompt's
87// coordinates (the plan's new_start's).
88inline void whole_spans(core::ScrPlan& plan, const std::vector<Span>& spans, int64_t band, int64_t min_n) {
89    if (spans.empty() || plan.runs.empty()) return;
90    for (core::ScrRun& r : plan.runs) {
91        bool changed = true;
92        while (changed && r.n > 0) {
93            changed = false;
94            for (const Span& s : spans) {
95                const int64_t e = s.start + s.len;
96                if (s.start < r.new_start && e > r.new_start) {   // starts inside a span: after it, on an even step
97                    const int64_t cut = (e - r.new_start + 1) / 2 * 2;
98                    r.new_start += cut, r.old_start += cut, r.n -= cut;
99                    changed = true;
100                }
101                const int64_t keep_end = r.new_start + r.n - band;
102                if (r.n > 0 && s.start < keep_end && e > keep_end) {   // the kept part ends inside: before the span
103                    r.n = std::max<int64_t>(0, (s.start + band - r.new_start) / 2 * 2);
104                    changed = true;
105                }
106            }
107        }
108    }
109    plan.runs.erase(std::remove_if(plan.runs.begin(), plan.runs.end(),
110                                   [&](const core::ScrRun& r) { return r.n < min_n; }),
111                    plan.runs.end());
112    int64_t pads = 0;
113    for (core::ScrRun& r : plan.runs) {
114        r.pad = ((r.old_start - (r.new_start + pads)) % 2 + 2) % 2;
115        pads += r.pad;
116        r.at = r.new_start + pads;
117    }
118}
119
120// written under a temporary name and renamed over `path`
121inline bool write(const std::string& path, const std::vector<Span>& spans) {
122    const std::string tmp = path + ".tmp";
123    {
124        std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
125        const uint64_t n = spans.size();
126        f.write((const char*) &kMagic, 8);
127        f.write((const char*) &n, 8);
128        for (const Span& s : spans) {
129            f.write((const char*) &s.start, 8);
130            f.write((const char*) &s.len, 8);
131            f.write((const char*) &s.hash, 8);
132            f.write((const char*) &s.width, 4);
133            f.write((const char*) &s.height, 4);
134        }
135        f.write((const char*) &kMagic, 8);
136        f.flush();
137        if (!f) return false;
138    }
139    std::error_code ec;
140    std::filesystem::rename(tmp, path, ec);
141    return !ec;
142}
143
144// false: damaged, cut short, or a span outside the slot's n tokens (no file: true, no pictures)
145inline bool read(const std::string& path, int64_t n_tokens, std::vector<Span>& spans) {
146    spans.clear();
147    std::ifstream f(path, std::ios::binary);
148    if (!f) return !std::filesystem::exists(path);
149    uint64_t m0 = 0, n = 0, m1 = 0;
150    if (!f.read((char*) &m0, 8) || m0 != kMagic || !f.read((char*) &n, 8) || n > 4096) return false;
151    spans.resize(n);
152    for (Span& s : spans)
153        if (!f.read((char*) &s.start, 8) || !f.read((char*) &s.len, 8) || !f.read((char*) &s.hash, 8) ||
154            !f.read((char*) &s.width, 4) || !f.read((char*) &s.height, 4) || s.start < 0 || s.len <= 0 ||
155            s.start + s.len > n_tokens)
156            return false;
157    return f.read((char*) &m1, 8) && m1 == kMagic;
158}
159
160}  // namespace strata::ds4::picspans