okami.mom/strata

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

Niko1221Merge f-own-5b 9b242bb5b into f-own-int (round 15: the own text encoder and tokenizer as test programs, the DiT reference tool and position tables; committed work only)11c8c701a

main
21.5 KiB480 linesraw
1// src/image/te/qwen2_tok.cpp - stable-diffusion.cpp 2988060's Qwen2 tokenizer and prompt template for Qwen-Image-2.1
2// (include/strata/image/qwen2_tok.hpp), in our own code: no regex library, no sd.cpp at run time.
3//
4// What it reproduces, read from the pinned tree:
5//  * BPETokenizer::encode: split_with_special_tokens over sd.cpp's 31 special literals (qwen2_special_tokens(); ids
6//    151643 + index), then the Qwen2 pre-tokenizer regex
7//      (?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+
8//    compiled by Oniguruma (sd::Regex, UTF-8), here a hand-written scanner with the same leftmost-alternative and
9//    backtracking results; \p{L}, \p{N}, \s and the case folds of the contractions are Oniguruma's own, dumped from
10//    sd.cpp's build over every code point (tools/image/gate/te_tok_probe.cpp -> qwen2_tok_unicode.inc);
11//    then GPT-2 byte-level BPE with the merges' ranks (a pair listed twice keeps its last rank; a token string listed
12//    twice keeps its last id: sd.cpp fills std::maps in order).
13//  * The special ids are sd.cpp's, not the GGUF's: sd.cpp numbers its own 31 literals from 151643 on.  At 5 of those
14//    ids the Qwen3-VL GGUF's token list names other literals (te_tok_cases.py adds them as cases; sd.cpp encodes them
15//    as plain text, and so do we), and sd.cpp's last 5 literals (<|boi_token|> .. <|tms_token|>) get the ids 151669-
16//    151673 although the GGUF calls those ids otherwise.  We follow sd.cpp: the gate is sd.cpp's ids.
17//  * Text that is not valid UTF-8 (overlong forms, surrogates, above U+10FFFF, cut sequences) is refused, as sd.cpp's
18//    regex_valid_utf8 refuses it.
19//  * parse_prompt_attention as its code runs, LLMEmbedder::tokenize (the template's pieces encoded one by one) and
20//    prompt_template_encode_start_idx = the system prefix's own token count.
21#include "strata/image/qwen2_tok.hpp"
22
23#include <algorithm>
24#include <cctype>
25#include <cmath>
26#include <cstdlib>
27#include <cstring>
28#include <fstream>
29#include <map>
30#include <set>
31#include <unordered_map>
32
33namespace strata::image {
34namespace {
35
36#include "qwen2_tok_unicode.inc"   // kUniL, kUniN, kUniS, kFold[8] (s t r e v m l d): Oniguruma's, from sd.cpp's build
37
38template <size_t N>
39bool in_ranges(const uint32_t (&r)[N][2], uint32_t cp) {
40    size_t lo = 0, hi = N;
41    while (lo < hi) {
42        const size_t mid = (lo + hi) / 2;
43        if (cp < r[mid][0]) hi = mid;
44        else if (cp > r[mid][1]) lo = mid + 1;
45        else return true;
46    }
47    return false;
48}
49
50bool is_L(uint32_t c) { return in_ranges(kUniL, c); }
51bool is_N(uint32_t c) { return in_ranges(kUniN, c); }
52bool is_S(uint32_t c) { return in_ranges(kUniS, c); }
53bool is_crlf(uint32_t c) { return c == '\r' || c == '\n'; }
54bool is_other(uint32_t c) { return !is_S(c) && !is_L(c) && !is_N(c); }      // [^\s\p{L}\p{N}]
55bool folds_to(char letter, uint32_t c) {                                     // (?i:letter)
56    switch (letter) {
57    case 's': return in_ranges(kFold_s, c);
58    case 't': return in_ranges(kFold_t, c);
59    case 'r': return in_ranges(kFold_r, c);
60    case 'e': return in_ranges(kFold_e, c);
61    case 'v': return in_ranges(kFold_v, c);
62    case 'm': return in_ranges(kFold_m, c);
63    case 'l': return in_ranges(kFold_l, c);
64    case 'd': return in_ranges(kFold_d, c);
65    }
66    return false;
67}
68
69const char* const kSpecials[] = {
70    "<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>",
71    "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>",
72    "<|image_pad|>", "<|video_pad|>", "<tool_call>", "</tool_call>", "<|fim_prefix|>", "<|fim_middle|>",
73    "<|fim_suffix|>", "<|fim_pad|>", "<|repo_name|>", "<|file_sep|>", "<tool_response>", "</tool_response>",
74    "<think>", "</think>", "<|boi_token|>", "<|bor_token|>", "<|eor_token|>", "<|bot_token|>", "<|tms_token|>"};
75constexpr int kNumSpecials = 31;
76constexpr int kUnkId = 151643;            // Qwen2Tokenizer UNK_TOKEN_ID
77
78// regex_valid_utf8 (core/regex.cpp) + decode: code points and the byte offset of each (plus the end)
79bool decode_utf8(const std::string& s, std::vector<uint32_t>& cps, std::vector<size_t>& at) {
80    cps.clear();
81    at.clear();
82    size_t p = 0;
83    while (p < s.size()) {
84        at.push_back(p);
85        const unsigned char lead = (unsigned char) s[p++];
86        if (lead < 0x80) {
87            cps.push_back(lead);
88            continue;
89        }
90        int count = 0;
91        if (lead >= 0xC2 && lead <= 0xDF) count = 1;
92        else if (lead >= 0xE0 && lead <= 0xEF) count = 2;
93        else if (lead >= 0xF0 && lead <= 0xF4) count = 3;
94        if (count == 0 || s.size() - p < (size_t) count) return false;
95        uint32_t cp = lead & (0x7F >> count);
96        for (int i = 0; i < count; ++i) {
97            const unsigned char b = (unsigned char) s[p++];
98            if ((b & 0xC0) != 0x80) return false;
99            cp = (cp << 6) | (b & 0x3F);
100        }
101        static const uint32_t minimum[] = {0, 0x80, 0x800, 0x10000};
102        if (cp < minimum[count] || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) return false;
103        cps.push_back(cp);
104    }
105    at.push_back(s.size());
106    return true;
107}
108
109std::string utf8_of(uint32_t cp) {
110    std::string s;
111    if (cp < 0x80) s += (char) cp;
112    else if (cp < 0x800) { s += (char) (0xC0 | (cp >> 6)); s += (char) (0x80 | (cp & 0x3F)); }
113    else if (cp < 0x10000) { s += (char) (0xE0 | (cp >> 12)); s += (char) (0x80 | ((cp >> 6) & 0x3F)); s += (char) (0x80 | (cp & 0x3F)); }
114    else { s += (char) (0xF0 | (cp >> 18)); s += (char) (0x80 | ((cp >> 12) & 0x3F)); s += (char) (0x80 | ((cp >> 6) & 0x3F)); s += (char) (0x80 | (cp & 0x3F)); }
115    return s;
116}
117
118// The Qwen2 pre-tokenizer on one piece of code points: the end index of the match that starts at i (every code point
119// starts a match: the alternatives cover L, N, whitespace and everything else, and none matches empty).
120size_t match_at(const std::vector<uint32_t>& c, size_t i) {
121    const size_t n = c.size();
122    auto L = [&](size_t k) { return k < n && is_L(c[k]); };
123    // 1. (?i:'s|'t|'re|'ve|'m|'ll|'d), alternatives in this order
124    if (c[i] == '\'' && i + 1 < n) {
125        if (folds_to('s', c[i + 1]) || folds_to('t', c[i + 1])) return i + 2;
126        if (i + 2 < n && folds_to('r', c[i + 1]) && folds_to('e', c[i + 2])) return i + 3;
127        if (i + 2 < n && folds_to('v', c[i + 1]) && folds_to('e', c[i + 2])) return i + 3;
128        if (folds_to('m', c[i + 1])) return i + 2;
129        if (i + 2 < n && folds_to('l', c[i + 1]) && folds_to('l', c[i + 2])) return i + 3;
130        if (folds_to('d', c[i + 1])) return i + 2;
131    }
132    // 2. [^\r\n\p{L}\p{N}]?\p{L}+
133    {
134        size_t k = i;
135        if (!is_crlf(c[i]) && !is_L(c[i]) && !is_N(c[i]) && L(i + 1)) k = i + 1;
136        if (L(k)) {
137            while (L(k)) ++k;
138            return k;
139        }
140    }
141    // 3. \p{N}
142    if (is_N(c[i])) return i + 1;
143    // 4.  ?[^\s\p{L}\p{N}]+[\r\n]*
144    {
145        size_t k = i;
146        if (c[i] == ' ' && i + 1 < n && is_other(c[i + 1])) k = i + 1;
147        if (is_other(c[k])) {
148            while (k < n && is_other(c[k])) ++k;
149            while (k < n && is_crlf(c[k])) ++k;
150            return k;
151        }
152    }
153    // whitespace run W = [i, w)
154    size_t w = i;
155    while (w < n && is_S(c[w])) ++w;
156    // 5. \s*[\r\n]+  (\s* gives back until the last CR / LF of the run)
157    for (size_t k = w; k > i; --k)
158        if (is_crlf(c[k - 1])) return k;
159    // 6. \s+(?!\S)
160    if (w == n) return w;
161    if (w - i >= 2) return w - 1;
162    // 7. \s+
163    return w;
164}
165
166}  // namespace
167
168struct Qwen2Tok::Impl {
169    std::unordered_map<std::string, int> rank;     // "a b" -> rank
170    std::unordered_map<std::string, int> id;       // token string -> id
171    std::string byte_str[256];                     // byte -> its byte-level character (UTF-8)
172    int n_merges = 0;
173    mutable std::vector<int>* trace_ranks = nullptr;
174    mutable std::vector<std::pair<std::string, int>>* trace_tokens = nullptr;
175
176    void init_bytes() {
177        // bytes_to_unicode(): '!'..'~', 161..172, 174..255 keep their value, the others become 256 + n, in this order
178        std::vector<int> order;
179        bool kept[256] = {};
180        for (int b = '!'; b <= '~'; ++b) order.push_back(b), kept[b] = true;
181        for (int b = 161; b <= 172; ++b) order.push_back(b), kept[b] = true;
182        for (int b = 174; b <= 255; ++b) order.push_back(b), kept[b] = true;
183        int extra = 0;
184        uint32_t cp_of[256];
185        for (int b : order) cp_of[b] = (uint32_t) b;
186        for (int b = 0; b < 256; ++b)
187            if (!kept[b]) order.push_back(b), cp_of[b] = 256 + extra++;
188        for (int b = 0; b < 256; ++b) byte_str[b] = utf8_of(cp_of[b]);
189        for (size_t i = 0; i < order.size(); ++i) id[byte_str[order[i]]] = (int) i;   // ids 0..255 in this order
190    }
191
192    std::vector<std::string> bpe(std::vector<std::string> word) const {
193        if (word.size() < 2) return word;
194        while (true) {
195            int best = -1;
196            size_t at = 0;
197            for (size_t i = 0; i + 1 < word.size(); ++i) {
198                auto it = rank.find(word[i] + " " + word[i + 1]);
199                if (it != rank.end() && (best < 0 || it->second < best)) best = it->second, at = i;
200            }
201            if (best < 0) break;
202            if (trace_ranks) trace_ranks->push_back(best);
203            const std::string a = word[at], b = word[at + 1];
204            std::vector<std::string> nw;
205            for (size_t i = 0; i < word.size();) {
206                if (i + 1 < word.size() && word[i] == a && word[i + 1] == b) {
207                    nw.push_back(a + b);
208                    i += 2;
209                } else {
210                    nw.push_back(word[i]);
211                    i += 1;
212                }
213            }
214            word.swap(nw);
215            if (word.size() == 1) break;
216        }
217        return word;
218    }
219
220    void emit(const std::string& tok, std::vector<int32_t>& ids) const {
221        auto it = id.find(tok);
222        const int v = it == id.end() ? kUnkId : it->second;
223        ids.push_back(v);
224        if (trace_tokens) trace_tokens->emplace_back(tok, v);
225    }
226
227    bool encode_piece(const std::string& piece, std::vector<int32_t>& ids, std::string* err) const {
228        std::vector<uint32_t> c;
229        std::vector<size_t> at;
230        if (!decode_utf8(piece, c, at)) {
231            if (err) *err = "regex input is not valid UTF-8";
232            return false;
233        }
234        for (size_t i = 0; i < c.size();) {
235            const size_t e = match_at(c, i);
236            std::vector<std::string> word;
237            for (size_t b = at[i]; b < at[e]; ++b) word.push_back(byte_str[(unsigned char) piece[b]]);
238            for (const auto& t : bpe(std::move(word))) emit(t, ids);
239            i = e;
240        }
241        return true;
242    }
243};
244
245Qwen2Tok::Qwen2Tok(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
246Qwen2Tok::~Qwen2Tok() = default;
247
248void Qwen2Tok::set_trace(std::vector<int>* ranks_used, std::vector<std::pair<std::string, int>>* tokens_emitted) const {
249    impl_->trace_ranks = ranks_used;
250    impl_->trace_tokens = tokens_emitted;
251}
252
253std::unique_ptr<Qwen2Tok> Qwen2Tok::from_ranked(const std::vector<std::pair<int, std::string>>& ranked, int n_merges,
254                                                std::string* err) {
255    auto impl = std::make_unique<Impl>();
256    impl->init_bytes();
257    impl->n_merges = n_merges;
258    std::vector<std::pair<int, std::string>> sorted(ranked);
259    std::sort(sorted.begin(), sorted.end(), [](auto& x, auto& y) { return x.first < y.first; });
260    for (const auto& [r, m] : sorted) {
261        const size_t sp = m.find(' ');
262        if (sp == std::string::npos || r < 0 || r >= n_merges) {
263            if (err) *err = "qwen2_tok: bad merge entry";
264            return nullptr;
265        }
266        impl->rank[m] = r;                                         // later rank wins (bpe_ranks[merge] = rank++)
267        impl->id[m.substr(0, sp) + m.substr(sp + 1)] = 256 + r;    // encoder[token] = i, later wins
268    }
269    for (int i = 0; i < kNumSpecials; ++i) impl->id[kSpecials[i]] = 256 + n_merges + i;
270    return std::unique_ptr<Qwen2Tok>(new Qwen2Tok(std::move(impl)));
271}
272
273std::unique_ptr<Qwen2Tok> Qwen2Tok::from_gguf(const std::string& path, std::string* err) {
274    // a GGUF v3 header walk that keeps one key: tokenizer.ggml.merges (array of strings)
275    std::ifstream f(path, std::ios::binary);
276    auto fail = [&](const std::string& m) -> std::unique_ptr<Qwen2Tok> {
277        if (err) *err = "qwen2_tok: " + path + ": " + m;
278        return nullptr;
279    };
280    if (!f) return fail("cannot open");
281    auto rd = [&](void* p, size_t n) { f.read((char*) p, (std::streamsize) n); return (bool) f; };
282    auto u32 = [&]() { uint32_t v = 0; rd(&v, 4); return v; };
283    auto u64 = [&]() { uint64_t v = 0; rd(&v, 8); return v; };
284    auto str = [&]() { uint64_t n = u64(); std::string s; if (n > (1u << 30)) { f.setstate(std::ios::failbit); return s; } s.resize(n); rd(&s[0], n); return s; };
285    if (u32() != 0x46554747u) return fail("not a GGUF file");
286    if (u32() != 3) return fail("not GGUF v3");
287    u64();
288    const uint64_t n_kv = u64();
289    static const int size_of[] = {1, 1, 2, 2, 4, 4, 4, 1, -1, -1, 8, 8, 8};
290    std::vector<std::string> merges;
291    for (uint64_t k = 0; k < n_kv && f; ++k) {
292        const std::string key = str();
293        const uint32_t t = u32();
294        auto skip = [&](uint32_t ty, uint64_t count) {
295            if (ty == 8) { for (uint64_t i = 0; i < count && f; ++i) (void) str(); }
296            else if (ty < 13 && size_of[ty] > 0) f.seekg((std::streamoff) (count * (uint64_t) size_of[ty]), std::ios::cur);
297            else f.setstate(std::ios::failbit);
298        };
299        if (t == 9) {
300            const uint32_t et = u32();
301            const uint64_t count = u64();
302            if (key == "tokenizer.ggml.merges" && et == 8) {
303                merges.reserve(count);
304                for (uint64_t i = 0; i < count && f; ++i) merges.push_back(str());
305                break;
306            }
307            skip(et, count);
308        } else {
309            skip(t, 1);
310        }
311    }
312    if (!f || merges.empty()) return fail("no tokenizer.ggml.merges");
313    std::vector<std::pair<int, std::string>> ranked;
314    ranked.reserve(merges.size());
315    for (size_t i = 0; i < merges.size(); ++i) ranked.emplace_back((int) i, std::move(merges[i]));
316    return from_ranked(ranked, (int) ranked.size(), err);
317}
318
319bool Qwen2Tok::encode(const std::string& text, std::vector<int32_t>& ids, std::string* err) const {
320    ids.clear();
321    // split_with_special_tokens: at each step the earliest special literal (the longest one at equal positions)
322    size_t pos = 0;
323    while (pos < text.size()) {
324        size_t next = text.size();
325        int match = -1;
326        size_t mlen = 0;
327        for (int s = 0; s < kNumSpecials; ++s) {
328            const size_t p = text.find(kSpecials[s], pos);
329            const size_t len = std::strlen(kSpecials[s]);
330            if (p != std::string::npos && (p < next || (p == next && len > mlen))) next = p, match = s, mlen = len;
331        }
332        if (next > pos && !impl_->encode_piece(text.substr(pos, next - pos), ids, err)) {
333            ids.clear();
334            return false;
335        }
336        if (match < 0) break;
337        impl_->emit(kSpecials[match], ids);
338        pos = next + mlen;
339    }
340    return true;
341}
342
343std::vector<std::pair<std::string, float>> parse_prompt_attention(const std::string& text) {
344    std::vector<std::pair<std::string, float>> res;
345    std::vector<int> round_brackets, square_brackets;
346    const float round_mul = 1.1f, square_mul = 1 / 1.1f;
347    auto multiply_range = [&](int start, float m) {
348        for (size_t p = (size_t) start; p < res.size(); ++p) res[p].second *= m;
349    };
350    auto word = [](unsigned char ch) { return std::isalnum(ch) || ch == '_'; };
351    // lex_weight: [+-]?[0-9.]* then ')', the number all of it, finite; returns the length incl. ')' or 0
352    auto lex_weight = [](const std::string& s, size_t from, float& value) -> size_t {
353        size_t end = from;
354        if (end < s.size() && (s[end] == '+' || s[end] == '-')) ++end;
355        while (end < s.size() && (std::isdigit((unsigned char) s[end]) || s[end] == '.')) ++end;
356        if (end >= s.size() || s[end] != ')') return 0;
357        const std::string number = s.substr(from, end - from);
358        char* number_end = nullptr;
359        const float parsed = std::strtof(number.c_str(), &number_end);
360        if (number.empty() || number_end != number.c_str() + number.size() || !std::isfinite(parsed)) return 0;
361        value = parsed;
362        return end - from + 1;
363    };
364    // The regex, alternative by alternative, always matching at the start of the remaining text (every byte starts one):
365    // \\\( \\\) \\\[ \\\] \\\\ \\ \( \[ \) \] \bBREAK\b [^\\()\[\]:B]{1,1024} : \bB
366    size_t pos = 0;
367    while (pos < text.size()) {
368        const char ch = text[pos];
369        std::string tok;
370        if (ch == '\\' && pos + 1 < text.size() && std::strchr("()[]\\", text[pos + 1]) && text[pos + 1] != '\0') {
371            tok = text.substr(pos, 2);
372        } else if (ch == '\\' || ch == '(' || ch == '[' || ch == ')' || ch == ']' || ch == ':') {
373            tok = std::string(1, ch);
374        } else if (text.compare(pos, 5, "BREAK") == 0 && (pos + 5 == text.size() || !word((unsigned char) text[pos + 5]))) {
375            tok = "BREAK";     // \b before: the remaining text starts here (std::regex sees a new string)
376        } else if (ch == 'B') {
377            tok = "B";
378        } else {
379            size_t e = pos;
380            while (e < text.size() && e - pos < 1024 && !std::strchr("\\()[]:B", text[e])) ++e;
381            if (e < text.size() && text[e] == '\0' && e == pos) ++e;   // (a NUL byte: strchr matches the terminator)
382            tok = text.substr(pos, e - pos);
383        }
384        size_t next = pos + tok.size();
385        if (tok == ":") {
386            float w = 1.0f;
387            const size_t len = lex_weight(text, next, w);
388            if (len > 0) {
389                if (!round_brackets.empty()) {
390                    multiply_range(round_brackets.back(), w);
391                    round_brackets.pop_back();
392                }
393                pos = next + len;
394                continue;
395            }
396        }
397        if (tok == "(") round_brackets.push_back((int) res.size());
398        else if (tok == "[") square_brackets.push_back((int) res.size());
399        else if (tok == ")" && !round_brackets.empty()) { multiply_range(round_brackets.back(), round_mul); round_brackets.pop_back(); }
400        else if (tok == "]" && !square_brackets.empty()) { multiply_range(square_brackets.back(), square_mul); square_brackets.pop_back(); }
401        else if (tok == "\\(") res.push_back({tok.substr(1), 1.0f});
402        else if (tok == "BREAK") res.push_back({"BREAK", -1.0f});
403        else res.push_back({tok, 1.0f});
404        pos = next;
405    }
406    for (int p : round_brackets) multiply_range(p, round_mul);
407    for (int p : square_brackets) multiply_range(p, square_mul);
408    if (res.empty()) res.push_back({"", 1.0f});
409    for (size_t i = 0; i + 1 < res.size();) {
410        if (res[i].second == res[i + 1].second) {
411            res[i].first += res[i + 1].first;
412            res.erase(res.begin() + (long) i + 1);
413        } else {
414            ++i;
415        }
416    }
417    return res;
418}
419
420namespace {
421// std::regex <lora:([^:>]+):([^>]+)> in the remaining text: the earliest start where it matches -> [begin, end)
422bool find_lora_tag(const std::string& s, size_t from, size_t& b, size_t& e) {
423    for (size_t p = s.find("<lora:", from); p != std::string::npos; p = s.find("<lora:", p + 1)) {
424        size_t q = p + 6;
425        while (q < s.size() && s[q] != ':' && s[q] != '>') ++q;
426        if (q == p + 6 || q >= s.size() || s[q] != ':') continue;
427        size_t r = q + 1;
428        while (r < s.size() && s[r] != '>') ++r;
429        if (r == q + 1 || r >= s.size()) continue;
430        b = p;
431        e = r + 1;
432        return true;
433    }
434    return false;
435}
436}  // namespace
437
438std::string strip_lora_tags(const std::string& prompt) {
439    // the loop of extract_and_remove_lora: one pass over the text finds the tags (each search continues after the
440    // previous match); for each one found, regex_replace(format_first_only) removes the first tag of the prompt as it
441    // is by then
442    std::string out = prompt;
443    size_t from = 0, b = 0, e = 0;
444    while (find_lora_tag(prompt, from, b, e)) {
445        from = e;
446        size_t ob = 0, oe = 0;
447        if (find_lora_tag(out, 0, ob, oe)) out.erase(ob, oe - ob);
448    }
449    return out;
450}
451
452std::string qwen_image_tokens(const Qwen2Tok& tok, const std::string& prompt_in, QwenImageTokens* out) {
453    const std::string prompt = strip_lora_tags(prompt_in);
454    static const std::string kSystem = "<|im_start|>system\nComprehend and analyze the provided prompt.<|im_end|>\n";
455    static const std::string kUser = "<|im_start|>user\n";
456    static const std::string kSuffix = "<|im_end|>\n<|im_start|>assistant\n";
457    std::string err;
458    std::vector<int32_t> sys;
459    if (!tok.encode(kSystem, sys, &err)) return err;
460    out->ids.clear();
461    out->weights.clear();
462    out->n_system = (int) sys.size();
463    std::vector<std::pair<std::string, float>> pieces;
464    pieces.push_back({kSystem + kUser, 1.0f});
465    for (auto& p : parse_prompt_attention(prompt.empty() ? std::string(" ") : prompt)) pieces.push_back(std::move(p));
466    pieces.push_back({kSuffix, 1.0f});
467    for (const auto& [text, w] : pieces) {
468        std::vector<int32_t> ids;
469        if (!tok.encode(text, ids, &err)) {
470            out->ids.clear();
471            out->weights.clear();
472            return err;
473        }
474        out->ids.insert(out->ids.end(), ids.begin(), ids.end());
475        out->weights.insert(out->weights.end(), ids.size(), w);
476    }
477    return std::string();
478}
479
480}  // namespace strata::image