okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
11c8c701a
main
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 ) { 40size_t lo = 0 ,hi = N ; 41while (lo < hi ) { 42const size_t mid = (lo + hi ) /2 ; 43if (cp < r [mid ][0 ])hi = mid ; 44else if (cp > r [mid ][1 ])lo = mid + 1 ; 45else return true; 46 } 47return 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) 56switch (letter ) { 57case 's' :return in_ranges (kFold_s ,c ); 58case 't' :return in_ranges (kFold_t ,c ); 59case 'r' :return in_ranges (kFold_r ,c ); 60case 'e' :return in_ranges (kFold_e ,c ); 61case 'v' :return in_ranges (kFold_v ,c ); 62case 'm' :return in_ranges (kFold_m ,c ); 63case 'l' :return in_ranges (kFold_l ,c ); 64case 'd' :return in_ranges (kFold_d ,c ); 65 } 66return 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 ) { 80cps .clear (); 81at .clear (); 82size_t p = 0 ; 83while (p < s .size ()) { 84at .push_back (p ); 85const unsigned char lead = (unsigned char )s [p ++ ]; 86if (lead < 0x80 ) { 87cps .push_back (lead ); 88continue ; 89 } 90int count = 0 ; 91if (lead >=0xC2 && lead <=0xDF )count = 1 ; 92else if (lead >=0xE0 && lead <=0xEF )count = 2 ; 93else if (lead >=0xF0 && lead <=0xF4 )count = 3 ; 94if (count == 0 || s .size ()- p < (size_t )count )return false; 95uint32_t cp = lead & (0x7F >>count ); 96for (int i = 0 ;i < count ;++ i ) { 97const unsigned char b = (unsigned char )s [p ++ ]; 98if ((b & 0xC0 )!= 0x80 )return false; 99cp = (cp <<6 ) | (b & 0x3F ); 100 } 101static const uint32_t minimum []= {0 ,0x80 ,0x800 ,0x10000 }; 102if (cp < minimum [count ]|| cp > 0x10FFFF || (cp >=0xD800 && cp <=0xDFFF ))return false; 103cps .push_back (cp ); 104 } 105at .push_back (s .size ()); 106return true; 107} 108 109std::string utf8_of (uint32_t cp ) { 110 std::string s ; 111if (cp < 0x80 )s += (char )cp ; 112else if (cp < 0x800 ) {s += (char ) (0xC0 | (cp >>6 ));s += (char ) (0x80 | (cp & 0x3F )); } 113else if (cp < 0x10000 ) {s += (char ) (0xE0 | (cp >>12 ));s += (char ) (0x80 | ((cp >>6 )& 0x3F ));s += (char ) (0x80 | (cp & 0x3F )); } 114else {s += (char ) (0xF0 | (cp >>18 ));s += (char ) (0x80 | ((cp >>12 )& 0x3F ));s += (char ) (0x80 | ((cp >>6 )& 0x3F ));s += (char ) (0x80 | (cp & 0x3F )); } 115return 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 ) { 121const size_t n = c .size (); 122auto 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 124if (c [i ]== '\'' && i + 1 < n ) { 125if (folds_to ('s' ,c [i + 1 ])|| folds_to ('t' ,c [i + 1 ]))return i + 2 ; 126if (i + 2 < n && folds_to ('r' ,c [i + 1 ])&& folds_to ('e' ,c [i + 2 ]))return i + 3 ; 127if (i + 2 < n && folds_to ('v' ,c [i + 1 ])&& folds_to ('e' ,c [i + 2 ]))return i + 3 ; 128if (folds_to ('m' ,c [i + 1 ]))return i + 2 ; 129if (i + 2 < n && folds_to ('l' ,c [i + 1 ])&& folds_to ('l' ,c [i + 2 ]))return i + 3 ; 130if (folds_to ('d' ,c [i + 1 ]))return i + 2 ; 131 } 132// 2. [^\r\n\p{L}\p{N}]?\p{L}+ 133 { 134size_t k = i ; 135if (!is_crlf (c [i ])&& !is_L (c [i ])&& !is_N (c [i ])&& L (i + 1 ))k = i + 1 ; 136if (L (k )) { 137while (L (k ))++ k ; 138return k ; 139 } 140 } 141// 3. \p{N} 142if (is_N (c [i ]))return i + 1 ; 143// 4. ?[^\s\p{L}\p{N}]+[\r\n]* 144 { 145size_t k = i ; 146if (c [i ]== ' ' && i + 1 < n && is_other (c [i + 1 ]))k = i + 1 ; 147if (is_other (c [k ])) { 148while (k < n && is_other (c [k ]))++ k ; 149while (k < n && is_crlf (c [k ]))++ k ; 150return k ; 151 } 152 } 153// whitespace run W = [i, w) 154size_t w = i ; 155while (w < n && is_S (c [w ]))++ w ; 156// 5. \s*[\r\n]+ (\s* gives back until the last CR / LF of the run) 157for (size_t k = w ;k > i ;-- k ) 158if (is_crlf (c [k - 1 ]))return k ; 159// 6. \s+(?!\S) 160if (w == n )return w ; 161if (w - i >=2 )return w - 1 ; 162// 7. \s+ 163return 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) 172int n_merges = 0 ; 173mutable std::vector < int >* trace_ranks = nullptr ; 174mutable std::vector < std::pair < std::string ,int >>* trace_tokens = nullptr ; 175 176void 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 ; 179bool kept [256 ]= {}; 180for (int b = '!' ;b <='~' ;++ b )order .push_back (b ),kept [b ]= true; 181for (int b = 161 ;b <=172 ;++ b )order .push_back (b ),kept [b ]= true; 182for (int b = 174 ;b <=255 ;++ b )order .push_back (b ),kept [b ]= true; 183int extra = 0 ; 184uint32_t cp_of [256 ]; 185for (int b :order )cp_of [b ]= (uint32_t )b ; 186for (int b = 0 ;b < 256 ;++ b ) 187if (!kept [b ])order .push_back (b ),cp_of [b ]= 256 + extra ++ ; 188for (int b = 0 ;b < 256 ;++ b )byte_str [b ]= utf8_of (cp_of [b ]); 189for (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 { 193if (word .size ()< 2 )return word ; 194while (true) { 195int best = -1 ; 196size_t at = 0 ; 197for (size_t i = 0 ;i + 1 < word .size ();++ i ) { 198auto it = rank .find (word [i ]+ " " + word [i + 1 ]); 199if (it != rank .end ()&& (best < 0 || it -> second < best ))best = it -> second ,at = i ; 200 } 201if (best < 0 )break ; 202if (trace_ranks )trace_ranks -> push_back (best ); 203const std::string a = word [at ],b = word [at + 1 ]; 204 std::vector < std::string > nw ; 205for (size_t i = 0 ;i < word .size ();) { 206if (i + 1 < word .size ()&& word [i ]== a && word [i + 1 ]== b ) { 207nw .push_back (a + b ); 208i += 2 ; 209 }else { 210nw .push_back (word [i ]); 211i += 1 ; 212 } 213 } 214word .swap (nw ); 215if (word .size ()== 1 )break ; 216 } 217return word ; 218 } 219 220void emit (const std::string & tok , std::vector < int32_t >& ids )const { 221auto it = id .find (tok ); 222const int v = it == id .end () ?kUnkId :it -> second ; 223ids .push_back (v ); 224if (trace_tokens )trace_tokens -> emplace_back (tok ,v ); 225 } 226 227bool 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 ; 230if (!decode_utf8 (piece ,c ,at )) { 231if (err )* err = "regex input is not valid UTF-8" ; 232return false; 233 } 234for (size_t i = 0 ;i < c .size ();) { 235const size_t e = match_at (c ,i ); 236 std::vector < std::string > word ; 237for (size_t b = at [i ];b < at [e ];++ b )word .push_back (byte_str [(unsigned char )piece [b ]]); 238for (const auto & t :bpe (std::move (word )))emit (t ,ids ); 239i = e ; 240 } 241return 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 { 249impl_ -> trace_ranks = ranks_used ; 250impl_ -> 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 ) { 255auto impl = std::make_unique < Impl > (); 256impl -> init_bytes (); 257impl -> 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 ; }); 260for (const auto & [r ,m ] :sorted ) { 261const size_t sp = m .find (' ' ); 262if (sp == std::string::npos || r < 0 || r >=n_merges ) { 263if (err )* err = "qwen2_tok: bad merge entry" ; 264return nullptr ; 265 } 266impl -> rank [m ]= r ;// later rank wins (bpe_ranks[merge] = rank++) 267impl -> id [m .substr (0 ,sp )+ m .substr (sp + 1 )]= 256 + r ;// encoder[token] = i, later wins 268 } 269for (int i = 0 ;i < kNumSpecials ;++ i )impl -> id [kSpecials [i ]]= 256 + n_merges + i ; 270return 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 ); 276auto fail = [& ](const std::string & m )-> std::unique_ptr < Qwen2Tok > { 277if (err )* err = "qwen2_tok: " + path + ": " + m ; 278return nullptr ; 279 }; 280if (!f )return fail ("cannot open" ); 281auto rd = [& ](void * p ,size_t n ) {f .read ((char * )p , (std::streamsize )n );return (bool )f ; }; 282auto u32 = [& ]() {uint32_t v = 0 ;rd (& v ,4 );return v ; }; 283auto u64 = [& ]() {uint64_t v = 0 ;rd (& v ,8 );return v ; }; 284auto 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 ; }; 285if (u32 ()!= 0x46554747u )return fail ("not a GGUF file" ); 286if (u32 ()!= 3 )return fail ("not GGUF v3" ); 287u64 (); 288const uint64_t n_kv = u64 (); 289static const int size_of []= {1 ,1 ,2 ,2 ,4 ,4 ,4 ,1 ,-1 ,-1 ,8 ,8 ,8 }; 290 std::vector < std::string > merges ; 291for (uint64_t k = 0 ;k < n_kv && f ;++ k ) { 292const std::string key = str (); 293const uint32_t t = u32 (); 294auto skip = [& ](uint32_t ty ,uint64_t count ) { 295if (ty == 8 ) {for (uint64_t i = 0 ;i < count && f ;++ i ) (void )str (); } 296else if (ty < 13 && size_of [ty ]> 0 )f .seekg ((std::streamoff ) (count * (uint64_t )size_of [ty ]), std::ios::cur ); 297else f .setstate (std::ios::failbit ); 298 }; 299if (t == 9 ) { 300const uint32_t et = u32 (); 301const uint64_t count = u64 (); 302if (key == "tokenizer.ggml.merges" && et == 8 ) { 303merges .reserve (count ); 304for (uint64_t i = 0 ;i < count && f ;++ i )merges .push_back (str ()); 305break ; 306 } 307skip (et ,count ); 308 }else { 309skip (t ,1 ); 310 } 311 } 312if (!f || merges .empty ())return fail ("no tokenizer.ggml.merges" ); 313 std::vector < std::pair < int , std::string >> ranked ; 314ranked .reserve (merges .size ()); 315for (size_t i = 0 ;i < merges .size ();++ i )ranked .emplace_back ((int )i , std::move (merges [i ])); 316return 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 { 320ids .clear (); 321// split_with_special_tokens: at each step the earliest special literal (the longest one at equal positions) 322size_t pos = 0 ; 323while (pos < text .size ()) { 324size_t next = text .size (); 325int match = -1 ; 326size_t mlen = 0 ; 327for (int s = 0 ;s < kNumSpecials ;++ s ) { 328const size_t p = text .find (kSpecials [s ],pos ); 329const size_t len = std::strlen (kSpecials [s ]); 330if (p != std::string::npos && (p < next || (p == next && len > mlen )))next = p ,match = s ,mlen = len ; 331 } 332if (next > pos && !impl_ -> encode_piece (text .substr (pos ,next - pos ),ids ,err )) { 333ids .clear (); 334return false; 335 } 336if (match < 0 )break ; 337impl_ -> emit (kSpecials [match ],ids ); 338pos = next + mlen ; 339 } 340return 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 ; 346const float round_mul = 1.1f ,square_mul = 1 /1.1f ; 347auto multiply_range = [& ](int start ,float m ) { 348for (size_t p = (size_t )start ;p < res .size ();++ p )res [p ].second *=m ; 349 }; 350auto 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 352auto lex_weight = [](const std::string & s ,size_t from ,float & value )-> size_t { 353size_t end = from ; 354if (end < s .size ()&& (s [end ]== '+' || s [end ]== '-' ))++ end ; 355while (end < s .size ()&& (std::isdigit ((unsigned char )s [end ])|| s [end ]== '.' ))++ end ; 356if (end >=s .size ()|| s [end ]!= ')' )return 0 ; 357const std::string number = s .substr (from ,end - from ); 358char * number_end = nullptr ; 359const float parsed = std::strtof (number .c_str (),& number_end ); 360if (number .empty ()|| number_end != number .c_str ()+ number .size ()|| !std::isfinite (parsed ))return 0 ; 361value = parsed ; 362return 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 366size_t pos = 0 ; 367while (pos < text .size ()) { 368const char ch = text [pos ]; 369 std::string tok ; 370if (ch == '\\' && pos + 1 < text .size ()&& std::strchr ("()[]\\" ,text [pos + 1 ])&& text [pos + 1 ]!= '\0' ) { 371tok = text .substr (pos ,2 ); 372 }else if (ch == '\\' || ch == '(' || ch == '[' || ch == ')' || ch == ']' || ch == ':' ) { 373tok = std::string (1 ,ch ); 374 }else if (text .compare (pos ,5 ,"BREAK" )== 0 && (pos + 5 == text .size ()|| !word ((unsigned char )text [pos + 5 ]))) { 375tok = "BREAK" ;// \b before: the remaining text starts here (std::regex sees a new string) 376 }else if (ch == 'B' ) { 377tok = "B" ; 378 }else { 379size_t e = pos ; 380while (e < text .size ()&& e - pos < 1024 && !std::strchr ("\\()[]:B" ,text [e ]))++ e ; 381if (e < text .size ()&& text [e ]== '\0' && e == pos )++ e ;// (a NUL byte: strchr matches the terminator) 382tok = text .substr (pos ,e - pos ); 383 } 384size_t next = pos + tok .size (); 385if (tok == ":" ) { 386float w = 1.0f ; 387const size_t len = lex_weight (text ,next ,w ); 388if (len > 0 ) { 389if (!round_brackets .empty ()) { 390multiply_range (round_brackets .back (),w ); 391round_brackets .pop_back (); 392 } 393pos = next + len ; 394continue ; 395 } 396 } 397if (tok == "(" )round_brackets .push_back ((int )res .size ()); 398else if (tok == "[" )square_brackets .push_back ((int )res .size ()); 399else if (tok == ")" && !round_brackets .empty ()) {multiply_range (round_brackets .back (),round_mul );round_brackets .pop_back (); } 400else if (tok == "]" && !square_brackets .empty ()) {multiply_range (square_brackets .back (),square_mul );square_brackets .pop_back (); } 401else if (tok == "\\(" )res .push_back ({tok .substr (1 ),1.0f }); 402else if (tok == "BREAK" )res .push_back ({"BREAK" ,-1.0f }); 403else res .push_back ({tok ,1.0f }); 404pos = next ; 405 } 406for (int p :round_brackets )multiply_range (p ,round_mul ); 407for (int p :square_brackets )multiply_range (p ,square_mul ); 408if (res .empty ())res .push_back ({"" ,1.0f }); 409for (size_t i = 0 ;i + 1 < res .size ();) { 410if (res [i ].second == res [i + 1 ].second ) { 411res [i ].first += res [i + 1 ].first ; 412res .erase (res .begin ()+ (long )i + 1 ); 413 }else { 414++ i ; 415 } 416 } 417return 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 ) { 423for (size_t p = s .find ("<lora:" ,from );p != std::string::npos ;p = s .find ("<lora:" ,p + 1 )) { 424size_t q = p + 6 ; 425while (q < s .size ()&& s [q ]!= ':' && s [q ]!= '>' )++ q ; 426if (q == p + 6 || q >=s .size ()|| s [q ]!= ':' )continue ; 427size_t r = q + 1 ; 428while (r < s .size ()&& s [r ]!= '>' )++ r ; 429if (r == q + 1 || r >=s .size ())continue ; 430b = p ; 431e = r + 1 ; 432return true; 433 } 434return 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 ; 443size_t from = 0 ,b = 0 ,e = 0 ; 444while (find_lora_tag (prompt ,from ,b ,e )) { 445from = e ; 446size_t ob = 0 ,oe = 0 ; 447if (find_lora_tag (out ,0 ,ob ,oe ))out .erase (ob ,oe - ob ); 448 } 449return out ; 450} 451 452std::string qwen_image_tokens (const Qwen2Tok & tok ,const std::string & prompt_in ,QwenImageTokens * out ) { 453const std::string prompt = strip_lora_tags (prompt_in ); 454static const std::string kSystem = "<|im_start|>system\nComprehend and analyze the provided prompt.<|im_end|>\n" ; 455static const std::string kUser = "<|im_start|>user\n" ; 456static const std::string kSuffix = "<|im_end|>\n<|im_start|>assistant\n" ; 457 std::string err ; 458 std::vector < int32_t > sys ; 459if (!tok .encode (kSystem ,sys ,& err ))return err ; 460out -> ids .clear (); 461out -> weights .clear (); 462out -> n_system = (int )sys .size (); 463 std::vector < std::pair < std::string ,float >> pieces ; 464pieces .push_back ({kSystem + kUser ,1.0f }); 465for (auto & p :parse_prompt_attention (prompt .empty () ? std::string (" " ) :prompt ))pieces .push_back (std::move (p )); 466pieces .push_back ({kSuffix ,1.0f }); 467for (const auto & [text ,w ] :pieces ) { 468 std::vector < int32_t > ids ; 469if (!tok .encode (text ,ids ,& err )) { 470out -> ids .clear (); 471out -> weights .clear (); 472return err ; 473 } 474out -> ids .insert (out -> ids .end (),ids .begin (),ids .end ()); 475out -> weights .insert (out -> weights .end (),ids .size (),w ); 476 } 477return std::string (); 478} 479 480}// namespace strata::image