llama-vocab.cpp 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  1. #include "llama-vocab.h"
  2. #include "unicode.h"
  3. #include <algorithm>
  4. #include <cassert>
  5. #include <cfloat>
  6. #include <climits>
  7. #include <cstdarg>
  8. #include <cstring>
  9. #include <forward_list>
  10. #include <queue>
  11. #include <sstream>
  12. //
  13. // helpers
  14. //
  15. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  16. static std::string format(const char * fmt, ...) {
  17. va_list ap;
  18. va_list ap2;
  19. va_start(ap, fmt);
  20. va_copy(ap2, ap);
  21. int size = vsnprintf(NULL, 0, fmt, ap);
  22. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  23. std::vector<char> buf(size + 1);
  24. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  25. GGML_ASSERT(size2 == size);
  26. va_end(ap2);
  27. va_end(ap);
  28. return std::string(buf.data(), size);
  29. }
  30. struct naive_trie {
  31. naive_trie() : has_value(false), value(0) {
  32. }
  33. void insert(const char * key, size_t len, int32_t value = 0) {
  34. if (len == 0) {
  35. this->has_value = true;
  36. this->value = value;
  37. return;
  38. }
  39. char c = key[0];
  40. auto res = children.find(c);
  41. if (res != children.end()) {
  42. res->second.insert(key + 1, len - 1, value);
  43. } else {
  44. auto res = children.insert(std::make_pair(c, naive_trie()));
  45. res.first->second.insert(key + 1, len - 1, value);
  46. }
  47. }
  48. std::pair<const char *, size_t> get_longest_prefix(const char * key, size_t len, size_t offset = 0) const {
  49. if (len == 0 || offset == len) {
  50. return std::make_pair(key, offset);
  51. }
  52. char c = key[offset];
  53. auto res = children.find(c);
  54. if (res != children.end()) {
  55. return res->second.get_longest_prefix(key, len, offset + 1);
  56. }
  57. return std::make_pair(key, offset);
  58. }
  59. const struct naive_trie * traverse(const char c) const {
  60. auto res = children.find(c);
  61. if (res != children.end()) {
  62. return &res->second;
  63. }
  64. return NULL;
  65. }
  66. std::map<char, struct naive_trie> children;
  67. bool has_value;
  68. llama_token value;
  69. };
  70. //
  71. // impl
  72. //
  73. struct llm_tokenizer {
  74. llm_tokenizer() {}
  75. virtual ~llm_tokenizer() = default;
  76. };
  77. llama_vocab::~llama_vocab() {
  78. delete tokenizer;
  79. }
  80. int llama_vocab::find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  81. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  82. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  83. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  84. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  85. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  86. if (it == bpe_ranks.end()) {
  87. return -1;
  88. }
  89. return it->second;
  90. }
  91. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  92. return vocab.type;
  93. }
  94. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  95. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  96. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_NORMAL;
  97. }
  98. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  99. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  100. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_UNKNOWN;
  101. }
  102. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  103. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  104. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_CONTROL;
  105. }
  106. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  107. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  108. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_BYTE;
  109. }
  110. static bool llama_is_user_defined_token(const llama_vocab & vocab, llama_token id) {
  111. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  112. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_USER_DEFINED;
  113. }
  114. static bool llama_is_unused_token(const llama_vocab & vocab, llama_token id) {
  115. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  116. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_UNUSED;
  117. }
  118. static uint8_t llama_token_to_byte(const llama_vocab & vocab, llama_token id) {
  119. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  120. GGML_ASSERT(llama_is_byte_token(vocab, id));
  121. const auto & token_data = vocab.id_to_token.at(id);
  122. switch (llama_vocab_get_type(vocab)) {
  123. case LLAMA_VOCAB_TYPE_SPM:
  124. case LLAMA_VOCAB_TYPE_UGM: {
  125. auto buf = token_data.text.substr(3, 2);
  126. return strtol(buf.c_str(), NULL, 16);
  127. }
  128. case LLAMA_VOCAB_TYPE_BPE: {
  129. GGML_ABORT("fatal error");
  130. //return unicode_utf8_to_byte(token_data.text); // TODO: why is this here after GGML_ASSERT?
  131. }
  132. case LLAMA_VOCAB_TYPE_WPM: {
  133. GGML_ABORT("fatal error");
  134. }
  135. default:
  136. GGML_ABORT("fatal error");
  137. }
  138. }
  139. static void llama_escape_whitespace(std::string & text) {
  140. replace_all(text, " ", "\xe2\x96\x81");
  141. }
  142. static void llama_unescape_whitespace(std::string & word) {
  143. replace_all(word, "\xe2\x96\x81", " ");
  144. }
  145. struct llm_symbol {
  146. using index = int;
  147. index prev;
  148. index next;
  149. const char * text;
  150. size_t n;
  151. };
  152. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  153. //
  154. // SPM tokenizer
  155. // original implementation:
  156. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  157. //
  158. struct llm_bigram_spm {
  159. struct comparator {
  160. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  161. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  162. }
  163. };
  164. using queue_storage = std::vector<llm_bigram_spm>;
  165. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  166. llm_symbol::index left;
  167. llm_symbol::index right;
  168. float score;
  169. size_t size;
  170. };
  171. struct llm_tokenizer_spm : llm_tokenizer {
  172. llm_tokenizer_spm(const llama_vocab & /*vocab*/) : llm_tokenizer() {}
  173. };
  174. struct llm_tokenizer_spm_session {
  175. llm_tokenizer_spm_session(const llama_vocab & vocab) : vocab(vocab) {}
  176. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  177. // split string into utf8 chars
  178. int index = 0;
  179. size_t offs = 0;
  180. while (offs < text.size()) {
  181. llm_symbol sym;
  182. size_t len = unicode_len_utf8(text[offs]);
  183. sym.text = text.c_str() + offs;
  184. sym.n = std::min(len, text.size() - offs);
  185. offs += sym.n;
  186. sym.prev = index - 1;
  187. sym.next = offs == text.size() ? -1 : index + 1;
  188. index++;
  189. symbols.emplace_back(sym);
  190. }
  191. // seed the work queue with all possible 2-character tokens.
  192. for (size_t i = 1; i < symbols.size(); ++i) {
  193. try_add_bigram(i - 1, i);
  194. }
  195. // keep substituting the highest frequency pairs for as long as we can.
  196. while (!work_queue.empty()) {
  197. auto bigram = work_queue.top();
  198. work_queue.pop();
  199. auto & left_sym = symbols[bigram.left];
  200. auto & right_sym = symbols[bigram.right];
  201. // if one of the symbols already got merged, skip it.
  202. if (left_sym.n == 0 || right_sym.n == 0 ||
  203. left_sym.n + right_sym.n != bigram.size) {
  204. continue;
  205. }
  206. // merge the right sym into the left one
  207. left_sym.n += right_sym.n;
  208. right_sym.n = 0;
  209. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  210. // remove the right sym from the chain
  211. left_sym.next = right_sym.next;
  212. if (right_sym.next >= 0) {
  213. symbols[right_sym.next].prev = bigram.left;
  214. }
  215. // find more substitutions
  216. try_add_bigram(left_sym.prev, bigram.left);
  217. try_add_bigram(bigram.left, left_sym.next);
  218. }
  219. for (int i = 0; i != -1; i = symbols[i].next) {
  220. auto & symbol = symbols[i];
  221. resegment(symbol, output);
  222. }
  223. }
  224. private:
  225. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  226. auto text = std::string(symbol.text, symbol.n);
  227. auto token = vocab.token_to_id.find(text);
  228. // Do we need to support is_unused?
  229. if (token != vocab.token_to_id.end()) {
  230. output.push_back((*token).second);
  231. return;
  232. }
  233. const auto p = rev_merge.find(text);
  234. if (p == rev_merge.end()) {
  235. // output any symbols that did not form tokens as bytes.
  236. output.reserve(output.size() + symbol.n);
  237. for (int j = 0; j < (int)symbol.n; ++j) {
  238. llama_vocab::id token_id = llama_byte_to_token_impl(vocab, symbol.text[j]);
  239. output.push_back(token_id);
  240. }
  241. return;
  242. }
  243. resegment(symbols[p->second.first], output);
  244. resegment(symbols[p->second.second], output);
  245. }
  246. void try_add_bigram(int left, int right) {
  247. if (left == -1 || right == -1) {
  248. return;
  249. }
  250. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  251. auto token = vocab.token_to_id.find(text);
  252. if (token == vocab.token_to_id.end()) {
  253. return;
  254. }
  255. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  256. return;
  257. }
  258. const auto & tok_data = vocab.id_to_token[(*token).second];
  259. llm_bigram_spm bigram;
  260. bigram.left = left;
  261. bigram.right = right;
  262. bigram.score = tok_data.score;
  263. bigram.size = text.size();
  264. work_queue.push(bigram);
  265. // Do we need to support is_unused?
  266. rev_merge[text] = std::make_pair(left, right);
  267. }
  268. const llama_vocab & vocab;
  269. // currently unused
  270. // const llm_tokenizer_spm * spm_tokenizer;
  271. std::vector<llm_symbol> symbols;
  272. llm_bigram_spm::queue work_queue;
  273. std::map<std::string, std::pair<int, int>> rev_merge;
  274. };
  275. //
  276. // BPE tokenizer
  277. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  278. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  279. //
  280. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  281. template<typename T, typename Container = std::vector<T>, typename Compare = std::less<typename Container::value_type>>
  282. class llama_priority_queue : public std::priority_queue<T, Container, Compare> {
  283. public:
  284. using std::priority_queue<T, Container, Compare>::priority_queue;
  285. T pop_move() {
  286. T item = std::move(this->c.front());
  287. std::pop_heap(this->c.begin(), this->c.end(), this->comp);
  288. this->c.pop_back();
  289. return item;
  290. }
  291. void pop() = delete;
  292. };
  293. struct llm_bigram_bpe {
  294. struct comparator {
  295. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  296. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  297. }
  298. };
  299. using queue_storage = std::vector<llm_bigram_bpe>;
  300. using queue = llama_priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  301. llm_symbol::index left;
  302. llm_symbol::index right;
  303. std::string text;
  304. int rank;
  305. size_t size;
  306. };
  307. struct llm_tokenizer_bpe : llm_tokenizer {
  308. llm_tokenizer_bpe(const llama_vocab & vocab) : llm_tokenizer() {
  309. GGML_ASSERT(vocab.type == LLAMA_VOCAB_TYPE_BPE);
  310. switch (vocab.type_pre) {
  311. case LLAMA_VOCAB_PRE_TYPE_LLAMA3:
  312. regex_exprs = {
  313. // original regex from tokenizer.json
  314. //"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  315. // adapted: https://github.com/ggerganov/llama.cpp/pull/6920#issuecomment-2080233989
  316. "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  317. };
  318. break;
  319. case LLAMA_VOCAB_PRE_TYPE_DBRX:
  320. case LLAMA_VOCAB_PRE_TYPE_SMAUG:
  321. regex_exprs = {
  322. // same as llama3
  323. "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  324. };
  325. break;
  326. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM:
  327. regex_exprs = {
  328. "[\r\n]",
  329. "\\s?[A-Za-zµÀ-ÖØ-öø-ƺƼ-ƿDŽ-ʓʕ-ʯͰ-ͳͶͷͻ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-ՖႠ-ჅᎠ-Ᏽᏸ-ᏽᲐ-ᲺᲽ-Ჿᴀ-ᴫᵫ-ᵷᵹ-ᶚḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℴℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⱻⱾ-ⳤⳫ-ⳮⳲⳳꙀ-ꙭꚀ-ꚛꜢ-ꝯꝱ-ꞇꞋ-ꞎꭰ-ꮿff-stﬓ-ﬗA-Za-z𐐀-𐑏𐒰-𐓓𐓘-𐓻𐲀-𐲲𐳀-𐳲𑢠-𑣟𞤀-𞥃]+",
  330. "\\s?[!-/:-~!-/:-~‘-‟ -。]+",
  331. "\\s+$",
  332. "[一-龥ࠀ-一가-퟿]+",
  333. "\\p{N}+",
  334. };
  335. break;
  336. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER:
  337. regex_exprs = {
  338. "[\r\n]",
  339. "\\s?\\p{L}+",
  340. "\\s?\\p{P}+",
  341. "[一-龥ࠀ-一가-퟿]+",
  342. "\\p{N}",
  343. };
  344. break;
  345. case LLAMA_VOCAB_PRE_TYPE_FALCON:
  346. regex_exprs = {
  347. "[\\p{P}\\$\\+<=>\\^~\\|`]+",
  348. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  349. "[0-9][0-9][0-9]",
  350. };
  351. break;
  352. case LLAMA_VOCAB_PRE_TYPE_STARCODER:
  353. case LLAMA_VOCAB_PRE_TYPE_REFACT:
  354. case LLAMA_VOCAB_PRE_TYPE_COMMAND_R:
  355. case LLAMA_VOCAB_PRE_TYPE_SMOLLM:
  356. case LLAMA_VOCAB_PRE_TYPE_CODESHELL:
  357. case LLAMA_VOCAB_PRE_TYPE_EXAONE:
  358. regex_exprs = {
  359. "\\p{N}",
  360. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  361. };
  362. break;
  363. case LLAMA_VOCAB_PRE_TYPE_GPT2:
  364. case LLAMA_VOCAB_PRE_TYPE_MPT:
  365. case LLAMA_VOCAB_PRE_TYPE_OLMO:
  366. case LLAMA_VOCAB_PRE_TYPE_JAIS:
  367. regex_exprs = {
  368. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  369. };
  370. break;
  371. case LLAMA_VOCAB_PRE_TYPE_STABLELM2:
  372. case LLAMA_VOCAB_PRE_TYPE_QWEN2:
  373. regex_exprs = {
  374. // original regex from tokenizer.json
  375. // "(?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+"
  376. "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  377. };
  378. break;
  379. case LLAMA_VOCAB_PRE_TYPE_PORO:
  380. case LLAMA_VOCAB_PRE_TYPE_BLOOM:
  381. case LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH:
  382. regex_exprs = {
  383. " ?[^(\\s|.,!?…。,、।۔،)]+",
  384. };
  385. break;
  386. case LLAMA_VOCAB_PRE_TYPE_CHATGLM4:
  387. regex_exprs = {
  388. "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  389. };
  390. break;
  391. case LLAMA_VOCAB_PRE_TYPE_VIKING:
  392. regex_exprs = {
  393. " ?[^(\\s|.,!?…。,、।۔،)]+",
  394. "\\p{N}",
  395. };
  396. break;
  397. case LLAMA_VOCAB_PRE_TYPE_TEKKEN:
  398. // original regex from tokenizer.json
  399. // "[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
  400. regex_exprs = {
  401. "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  402. };
  403. break;
  404. case LLAMA_VOCAB_PRE_TYPE_CHAMELEON:
  405. // Note: in theory, the special token (sentinel and image token) regex_exprs below
  406. // are unnecessary, as they are split in `tokenizer_st_partition` anyway.
  407. // However, since the upstream pre-tokenizer uses them, they are also
  408. // included here (see https://huggingface.co/facebook/chameleon-7b).
  409. regex_exprs = {
  410. "<sentinel:[0-9]+>", // Sentinel tokens
  411. "(IMGIMG)((A|B|C|D|E|F|G|H|I){1,4})Z", // Image tokens
  412. "([\\t\\n]| | )", // directly from tokenizer.json
  413. "\\p{N}", // Individual digits
  414. "[\\p{P}!-/:-@\\[-`{-~]", // Punctuation, Isolated
  415. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  416. };
  417. break;
  418. default:
  419. // default regex for BPE tokenization pre-processing
  420. regex_exprs = {
  421. "[\\p{P}\\$\\+<=>\\^~\\|]+",
  422. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  423. "\\p{N}+",
  424. "[0-9][0-9][0-9]",
  425. };
  426. break;
  427. }
  428. }
  429. std::vector<std::string> regex_exprs;
  430. };
  431. struct llm_tokenizer_bpe_session {
  432. llm_tokenizer_bpe_session(const llama_vocab & vocab) : vocab(vocab),
  433. bpe_tokenizer(static_cast<const llm_tokenizer_bpe *>(vocab.tokenizer)) {}
  434. static void append(const llama_vocab::id token_id, std::vector<llama_vocab::id> & output) {
  435. output.push_back(token_id);
  436. }
  437. bool append_bos(std::vector<llama_vocab::id> & output) const {
  438. if (vocab.tokenizer_add_bos) {
  439. GGML_ASSERT(vocab.special_bos_id != -1);
  440. output.push_back(vocab.special_bos_id);
  441. return true;
  442. }
  443. return false;
  444. }
  445. bool append_eos(std::vector<llama_vocab::id> & output) const {
  446. if (vocab.tokenizer_add_eos) {
  447. GGML_ASSERT(vocab.special_eos_id != -1);
  448. output.push_back(vocab.special_eos_id);
  449. return true;
  450. }
  451. return false;
  452. }
  453. void check_double_bos_eos(const std::vector<llama_vocab::id> & output) const {
  454. if (vocab.tokenizer_add_bos && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  455. LLAMA_LOG_WARN(
  456. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  457. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  458. "Are you sure this is what you want?\n", __FUNCTION__);
  459. }
  460. if (vocab.tokenizer_add_eos && output.size() >= 2 && *(output.end()-2) == vocab.special_eos_id) {
  461. LLAMA_LOG_WARN(
  462. "%s: Added a EOS token to the prompt as specified by the model but the prompt "
  463. "also ends with a EOS token. So now the final prompt ends with 2 EOS tokens. "
  464. "Are you sure this is what you want?\n", __FUNCTION__);
  465. }
  466. }
  467. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  468. int final_prev_index = -1;
  469. const auto word_collection = unicode_regex_split(text, bpe_tokenizer->regex_exprs);
  470. symbols_final.clear();
  471. for (const auto & word : word_collection) {
  472. work_queue = llm_bigram_bpe::queue();
  473. symbols.clear();
  474. int index = 0;
  475. size_t offset = 0;
  476. if (vocab.tokenizer_ignore_merges && vocab.token_to_id.find(word) != vocab.token_to_id.end()) {
  477. symbols.emplace_back(llm_symbol{-1, -1, word.c_str(), word.size()});
  478. offset = word.size();
  479. }
  480. while (offset < word.size()) {
  481. llm_symbol sym;
  482. size_t char_len = std::min(word.size() - offset, (size_t) unicode_len_utf8(word[offset]));
  483. sym.text = word.c_str() + offset;
  484. sym.n = char_len;
  485. offset += sym.n;
  486. sym.prev = index - 1;
  487. sym.next = offset == word.size() ? -1 : index + 1;
  488. index++;
  489. symbols.emplace_back(sym);
  490. }
  491. for (size_t i = 1; i < symbols.size(); ++i) {
  492. add_new_bigram(i - 1, i);
  493. }
  494. // build token(s)
  495. while (!work_queue.empty()) {
  496. auto bigram = work_queue.pop_move();
  497. auto & left_symbol = symbols[bigram.left];
  498. auto & right_symbol = symbols[bigram.right];
  499. if (left_symbol.n == 0 || right_symbol.n == 0) {
  500. continue;
  501. }
  502. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  503. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  504. if (left_token + right_token != bigram.text) {
  505. continue; // Skip this bigram if it's outdated
  506. }
  507. // merge the right sym into the left one
  508. left_symbol.n += right_symbol.n;
  509. right_symbol.n = 0;
  510. // remove the right sym from the chain
  511. left_symbol.next = right_symbol.next;
  512. if (right_symbol.next >= 0) {
  513. symbols[right_symbol.next].prev = bigram.left;
  514. }
  515. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  516. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  517. }
  518. // add the finished tokens to the final list keeping correct order for next and prev
  519. for (auto & sym : symbols) {
  520. if (sym.n > 0) {
  521. sym.prev = final_prev_index;
  522. sym.next = -1;
  523. if (final_prev_index != -1) {
  524. symbols_final[final_prev_index].next = symbols_final.size();
  525. }
  526. symbols_final.emplace_back(sym);
  527. final_prev_index = symbols_final.size() - 1;
  528. }
  529. }
  530. }
  531. symbols = symbols_final;
  532. if (!symbols.empty()) {
  533. for (int i = 0; i != -1; i = symbols[i].next) {
  534. auto & symbol = symbols[i];
  535. if (symbol.n == 0) {
  536. continue;
  537. }
  538. const std::string str = std::string(symbol.text, symbol.n);
  539. const auto token = vocab.token_to_id.find(str);
  540. if (token == vocab.token_to_id.end()) {
  541. for (auto j = str.begin(); j != str.end(); ++j) {
  542. std::string byte_str(1, *j);
  543. auto token_multibyte = vocab.token_to_id.find(byte_str);
  544. if (token_multibyte != vocab.token_to_id.end()) {
  545. output.push_back(token_multibyte->second);
  546. }
  547. }
  548. } else {
  549. output.push_back((*token).second);
  550. }
  551. }
  552. }
  553. }
  554. private:
  555. void add_new_bigram(int left, int right) {
  556. if (left == -1 || right == -1) {
  557. return;
  558. }
  559. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  560. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  561. int rank_found = -1;
  562. rank_found = vocab.find_bpe_rank(left_token, right_token);
  563. if (rank_found < 0) {
  564. return;
  565. }
  566. llm_bigram_bpe bigram;
  567. bigram.left = left;
  568. bigram.right = right;
  569. bigram.text = left_token + right_token;
  570. bigram.size = left_token.size() + right_token.size();
  571. bigram.rank = rank_found;
  572. work_queue.push(bigram);
  573. }
  574. const llama_vocab & vocab;
  575. const llm_tokenizer_bpe * bpe_tokenizer;
  576. std::vector<llm_symbol> symbols;
  577. std::vector<llm_symbol> symbols_final;
  578. llm_bigram_bpe::queue work_queue;
  579. };
  580. //
  581. // WPM tokenizer
  582. //
  583. struct llm_tokenizer_wpm : llm_tokenizer {
  584. llm_tokenizer_wpm(const llama_vocab & /*vocab*/) : llm_tokenizer() {}
  585. };
  586. struct llm_tokenizer_wpm_session {
  587. llm_tokenizer_wpm_session(const llama_vocab & vocab) : vocab(vocab) {}
  588. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  589. const auto & token_map = vocab.token_to_id;
  590. // normalize and split by whitespace
  591. std::vector<std::string> words = preprocess(text);
  592. // bos token prepended already
  593. // find the longest tokens that form the words
  594. for (const std::string & word : words) {
  595. // skip empty words
  596. if (word.size() == 0) {
  597. continue;
  598. }
  599. // prepend phantom space
  600. const std::string word1 = "\xe2\x96\x81" + word;
  601. const int n = word1.size();
  602. const size_t current_tokens = output.size();
  603. // we're at the start of a new word
  604. // move through character position in word
  605. for (int i = 0; i < n; ++i) {
  606. // loop through possible match length
  607. bool match = false;
  608. for (int j = std::min(n, i + vocab.max_token_len + 1); j > i; j--) {
  609. auto it = token_map.find(word1.substr(i, j - i));
  610. if (it != token_map.end()) {
  611. output.push_back(it->second);
  612. match = true;
  613. i = j - 1;
  614. break;
  615. }
  616. }
  617. if (!match) { // discard all
  618. output.resize(current_tokens);
  619. break; // and discard next tokens
  620. }
  621. }
  622. // we didn't find any matches for this word
  623. if (current_tokens == output.size()) {
  624. output.push_back(vocab.special_unk_id);
  625. }
  626. }
  627. }
  628. // TODO: reduce string copies by using cpts_offs array
  629. static std::vector<std::string> preprocess(const std::string & text) {
  630. const std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  631. std::vector<std::string> words(1, "");
  632. for (const uint32_t cpt : cpts_nfd) {
  633. const auto flags = unicode_cpt_flags(cpt);
  634. if (flags.is_whitespace) {
  635. if (words.back().size()) { // finish previous word if any
  636. words.emplace_back();
  637. }
  638. continue;
  639. }
  640. assert (!flags.is_separator);
  641. if (cpt == 0 || cpt == 0xFFFD || flags.is_control) {
  642. continue;
  643. }
  644. const std::string s = unicode_cpt_to_utf8(unicode_tolower(cpt));
  645. if (flags.is_punctuation || ( cpt < 0x7F && flags.is_symbol ) || is_chinese_char(cpt)) {
  646. if (words.back().size()) { // finish previous word if any
  647. words.emplace_back();
  648. }
  649. words.back() = s; // single char word
  650. words.emplace_back(); // start a new word
  651. } else {
  652. words.back() += s; // append char to word
  653. }
  654. }
  655. if (!words.back().size()) {
  656. words.pop_back();
  657. }
  658. return words;
  659. }
  660. static bool is_chinese_char(uint32_t cpt) {
  661. return
  662. (cpt >= 0x04E00 && cpt <= 0x09FFF) ||
  663. (cpt >= 0x03400 && cpt <= 0x04DBF) ||
  664. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  665. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  666. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  667. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  668. (cpt >= 0x0F900 && cpt <= 0x0FAFF) ||
  669. (cpt >= 0x2F800 && cpt <= 0x2FA1F);
  670. //(cpt >= 0x3000 && cpt <= 0x303F) ||
  671. //(cpt >= 0xFF00 && cpt <= 0xFFEF);
  672. }
  673. private:
  674. const llama_vocab & vocab;
  675. // currently unused
  676. // const llm_tokenizer_wpm * wpm_tokenizer;
  677. };
  678. //
  679. // UGM tokenizer
  680. //
  681. struct llm_tokenizer_ugm : llm_tokenizer {
  682. llm_tokenizer_ugm(const llama_vocab & vocab) : llm_tokenizer() {
  683. if (vocab.precompiled_charsmap.size() > 0) {
  684. size_t charsmap_offset = 0;
  685. // First four bytes of precompiled_charsmap contains length of binary
  686. // blob containing XOR-compressed compact double array (XCDA) entries
  687. uint32_t xcda_blob_size = *(const uint32_t *) &vocab.precompiled_charsmap[0];
  688. charsmap_offset += sizeof(xcda_blob_size);
  689. if (xcda_blob_size + charsmap_offset >= vocab.precompiled_charsmap.size()) {
  690. throw std::runtime_error("Index out of array bounds in precompiled charsmap!");
  691. }
  692. // Next xcda_blob_size bytes contain entries of XOR-compressed compact
  693. // double array (XCDA). Each entry is bit-packed into a 32-bit integer.
  694. xcda_array = (const uint32_t *) &vocab.precompiled_charsmap[charsmap_offset];
  695. xcda_array_size = xcda_blob_size / sizeof(uint32_t);
  696. charsmap_offset += xcda_blob_size;
  697. // Remaining bytes of precompiled charsmap contain null-terminated
  698. // replacement strings for prefixes matched by the XCDA.
  699. prefix_replacements = &vocab.precompiled_charsmap[charsmap_offset];
  700. prefix_replacements_size = vocab.precompiled_charsmap.size() - charsmap_offset;
  701. }
  702. for (unsigned int id = 0; id < vocab.id_to_token.size(); ++id) {
  703. const auto &token_data = vocab.id_to_token[id];
  704. if (llama_is_normal_token(vocab, id)) {
  705. min_score = std::min<float>(min_score, token_data.score);
  706. max_score = std::max<float>(max_score, token_data.score);
  707. }
  708. if (llama_is_normal_token(vocab, id) ||
  709. llama_is_user_defined_token(vocab, id) ||
  710. llama_is_unused_token(vocab, id)) {
  711. token_matcher.insert(token_data.text.data(), token_data.text.size(), id);
  712. }
  713. if (llama_is_user_defined_token(vocab, id)) {
  714. user_defined_token_matcher.insert(token_data.text.data(), token_data.text.size());
  715. }
  716. }
  717. unknown_token_score = min_score - unknown_token_score_penalty;
  718. }
  719. // escaped space symbol - U+2581 (Lower One Eighth Block)
  720. const std::string escaped_space = "\xE2\x96\x81";
  721. const char * prefix_replacements = NULL;
  722. size_t prefix_replacements_size = 0;
  723. const uint32_t * xcda_array = NULL;
  724. size_t xcda_array_size = 0;
  725. struct naive_trie user_defined_token_matcher;
  726. float min_score = FLT_MAX;
  727. float max_score = -FLT_MAX;
  728. float unknown_token_score_penalty = 10.0;
  729. float unknown_token_score;
  730. struct naive_trie token_matcher;
  731. };
  732. struct llm_tokenizer_ugm_session {
  733. llm_tokenizer_ugm_session(const llama_vocab & vocab) : vocab(vocab),
  734. ugm_tokenizer(static_cast<const llm_tokenizer_ugm *>(vocab.tokenizer)) {}
  735. /* This implementation is based on SentencePiece optimized Viterbi algorithm for
  736. * unigram language models. The general idea is to:
  737. * - move along the input sequence in steps of one UTF code point,
  738. * - at each step find all possible tokenizations of the prefix by
  739. * traversing the tokens trie,
  740. * - for each tokenization store the best one so far (by higher score)
  741. * - use the position in sequence after given token as an index to store
  742. * results
  743. * - if there was no valid tokenization of the current UTF code point
  744. * then use unknown token with additional score penalty
  745. * After processing the whole sequence we backtrack from the end to get
  746. * the best tokenization.
  747. */
  748. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  749. // get current size of output (for reversal later)
  750. size_t output_size = output.size();
  751. // normalize the input first
  752. std::string normalized;
  753. normalize(text, &normalized);
  754. size_t input_len = normalized.size();
  755. if (input_len == 0) {
  756. return;
  757. }
  758. // initialize score_sum to -FLT_MAX so it will be always lower than sums of token scores
  759. std::vector<struct best_tokenization> tokenization_results(input_len + 1, {vocab.special_unk_id, 0, -FLT_MAX});
  760. // at the beginning tokenization score is zero
  761. tokenization_results[0] = { vocab.special_unk_id, 0, 0 };
  762. for (size_t input_offset = 0; input_offset < input_len;) {
  763. size_t prefix_offset = input_offset;
  764. // calculate how many code units are in the currently processed UTF code point
  765. size_t n_utf8_code_units = std::min<size_t>(unicode_len_utf8(normalized[input_offset]), input_len - input_offset);
  766. // traverse the token matcher trie to find a matching token
  767. bool single_codepoint_token_found = false;
  768. const struct best_tokenization & current_best = tokenization_results[input_offset];
  769. const struct naive_trie * node = ugm_tokenizer->token_matcher.traverse(normalized[prefix_offset++]);
  770. while (prefix_offset <= input_len && node != NULL) {
  771. // check if we found valid token in prefix
  772. if (node->has_value) {
  773. // check if it corresponds to the whole UTF code point
  774. if (prefix_offset - input_offset == n_utf8_code_units) {
  775. single_codepoint_token_found = true;
  776. }
  777. llama_token token_id = node->value;
  778. const auto & token_data = vocab.id_to_token[token_id];
  779. // we set the user-defined token scores to 0 to make them more likely to be selected
  780. // (normal token scores are log probabilities, so they are negative)
  781. // score type is double here to make tokenization results exactly
  782. // the same as in the HF tokenizer using SentencePiece
  783. const double token_score = llama_is_user_defined_token(vocab, token_id) ? 0.0 : token_data.score;
  784. const double challenger_score = current_best.score_sum + token_score;
  785. struct best_tokenization & current_champ = tokenization_results[prefix_offset];
  786. if (challenger_score > current_champ.score_sum) {
  787. struct best_tokenization challenger = { token_id, input_offset, (float) challenger_score };
  788. current_champ = challenger;
  789. }
  790. }
  791. node = node->traverse(normalized[prefix_offset++]);
  792. }
  793. // if we didn't find a valid token corresponding to the whole UTF code point
  794. // then use unknown token as the tokenization of this UTF code point
  795. if (!single_codepoint_token_found) {
  796. const double challenger_score = current_best.score_sum + ugm_tokenizer->unknown_token_score;
  797. prefix_offset = input_offset + n_utf8_code_units;
  798. struct best_tokenization & current_champ = tokenization_results[prefix_offset];
  799. if (challenger_score > current_champ.score_sum) {
  800. struct best_tokenization challenger = { vocab.special_unk_id, input_offset, (float) challenger_score };
  801. current_champ = challenger;
  802. }
  803. }
  804. // move to the next UTF code point
  805. input_offset += n_utf8_code_units;
  806. }
  807. // now backtrack from the end to gather token ids of the best tokenization
  808. // merge sequences of consecutive unknown tokens into single unknown tokens
  809. bool is_prev_unknown = false;
  810. for (struct best_tokenization & tokenization = tokenization_results[input_len]; ; tokenization = tokenization_results[tokenization.input_offset]) {
  811. bool is_unknown = tokenization.token_id == vocab.special_unk_id;
  812. if (!(is_prev_unknown && is_unknown)) {
  813. output.push_back(tokenization.token_id);
  814. }
  815. if (tokenization.input_offset == 0) {
  816. break;
  817. }
  818. is_prev_unknown = is_unknown;
  819. }
  820. // reverse the output since we added tokens starting from the end of the input
  821. std::reverse(output.begin() + output_size, output.end());
  822. }
  823. private:
  824. // helper structure for returning normalization results
  825. struct normalization_result {
  826. const char * normalized;
  827. size_t normalized_len;
  828. size_t consumed_input;
  829. };
  830. void normalize(const std::string& input, std::string * normalized) {
  831. normalized->clear();
  832. normalized->reserve(input.size() * 3);
  833. const std::string space = vocab.tokenizer_escape_whitespaces ? ugm_tokenizer->escaped_space : " ";
  834. bool shall_prepend_space = !vocab.tokenizer_treat_whitespace_as_suffix && vocab.tokenizer_add_space_prefix;
  835. bool shall_append_space = vocab.tokenizer_treat_whitespace_as_suffix && vocab.tokenizer_add_space_prefix;
  836. bool shall_merge_spaces = vocab.tokenizer_remove_extra_whitespaces;
  837. bool is_space_prepended = false;
  838. bool processing_non_ws = false;
  839. size_t input_len = input.size();
  840. for (size_t input_offset = 0; input_offset < input_len; ) {
  841. auto norm_res = normalize_prefix(input, input_offset);
  842. for (size_t i = 0; i < norm_res.normalized_len; i++) {
  843. char c = norm_res.normalized[i];
  844. if (c != ' ') {
  845. if (!processing_non_ws) {
  846. processing_non_ws = true;
  847. if ((shall_prepend_space && !is_space_prepended) || shall_merge_spaces) {
  848. normalized->append(space);
  849. is_space_prepended = true;
  850. }
  851. }
  852. normalized->push_back(c);
  853. } else {
  854. if (processing_non_ws) {
  855. processing_non_ws = false;
  856. }
  857. if (!shall_merge_spaces) {
  858. normalized->append(space);
  859. }
  860. }
  861. }
  862. input_offset += norm_res.consumed_input;
  863. }
  864. if (shall_append_space) {
  865. normalized->append(space);
  866. }
  867. }
  868. /*
  869. * This structure is a view wrapper for XOR-compressed double array (XCDA)
  870. * See Shunsuke Kanda (2018). Space- and Time-Efficient String Dictionaries.
  871. * Each bit-packed entry contains:
  872. * - BASE array value in bits 10-30
  873. * - LCHECK array value in bits 0-7
  874. * - LEAF array value in bit 9
  875. * Entries containing indexes of replacement sequences have set bit 31
  876. */
  877. struct xcda_array_view {
  878. public:
  879. xcda_array_view(const uint32_t * xcda_array, size_t xcda_array_size) : xcda_array(xcda_array), xcda_array_size(xcda_array_size) {
  880. }
  881. uint32_t get_base(size_t index) {
  882. uint32_t packed_node = get_node(index);
  883. return (packed_node >> 10) << ((packed_node & (1U << 9)) >> 6);
  884. }
  885. uint32_t get_lcheck(size_t index) {
  886. uint32_t packed_node = get_node(index);
  887. return packed_node & ((1U << 31) | 0xff);
  888. }
  889. bool get_leaf(size_t index) {
  890. uint32_t packed_node = get_node(index);
  891. return (packed_node >> 8) & 1;
  892. }
  893. uint32_t get_value(size_t index) {
  894. uint32_t packed_node = get_node(index);
  895. return packed_node & ((1U << 31) - 1);
  896. }
  897. private:
  898. uint32_t get_node(size_t index) {
  899. if (index > xcda_array_size) {
  900. throw std::runtime_error("Index out of array bounds in XCDA array!");
  901. }
  902. return xcda_array[index];
  903. }
  904. const uint32_t * xcda_array;
  905. size_t xcda_array_size;
  906. };
  907. // this structure stores the best tokenization so far at input_offset
  908. struct best_tokenization {
  909. llama_token token_id;
  910. size_t input_offset;
  911. float score_sum;
  912. };
  913. struct normalization_result normalize_prefix(const std::string & input, size_t input_offset) {
  914. if (input_offset == input.size()) {
  915. return { &input[input_offset], 0, 0 };
  916. }
  917. // if input prefix matches some user-defined token return this token as normalization result
  918. auto user_defined_token_match =
  919. ugm_tokenizer->user_defined_token_matcher.get_longest_prefix(&input[input_offset], input.size() - input_offset);
  920. if (user_defined_token_match.second > 0) {
  921. return { &input[input_offset], user_defined_token_match.second, user_defined_token_match.second };
  922. }
  923. size_t longest_prefix_length = 0;
  924. size_t longest_prefix_offset = 0;
  925. if (ugm_tokenizer->xcda_array_size > 0) {
  926. struct xcda_array_view xcda_view(ugm_tokenizer->xcda_array, ugm_tokenizer->xcda_array_size);
  927. // Find the longest normalized sequence matching the input prefix by walking
  928. // the XOR-compressed compact double array (XCDA) starting from the root node
  929. // We find the index of the next node by calculating BASE[s] ^ c where s is
  930. // the index of the previous node and c is a numerical character value
  931. uint32_t node_index = 0;
  932. // get BASE of the root node
  933. node_index = xcda_view.get_base(node_index);
  934. for (size_t prefix_offset = input_offset; prefix_offset < input.size(); prefix_offset++) {
  935. unsigned char c = input[prefix_offset];
  936. if (c == 0) {
  937. break;
  938. }
  939. node_index ^= c;
  940. // if value of LCHECK is not c it means that this is not a child of
  941. // the previous node, so we stop matching
  942. if (xcda_view.get_lcheck(node_index) != c) {
  943. break;
  944. }
  945. bool is_leaf = xcda_view.get_leaf(node_index);
  946. // get BASE of the current node
  947. node_index ^= xcda_view.get_base(node_index);
  948. // if LEAF of the current node is true, it means that its BASE points to the node
  949. // containing index of replacement sequence for currently matched input prefix
  950. if (is_leaf)
  951. {
  952. longest_prefix_length = prefix_offset - input_offset + 1;
  953. // get index of replacement sequence for currently matched input prefix
  954. longest_prefix_offset = xcda_view.get_value(node_index);
  955. }
  956. }
  957. }
  958. if (longest_prefix_length > 0) {
  959. // we have a match, so return the replacement sequence
  960. if (longest_prefix_offset >= ugm_tokenizer->prefix_replacements_size) {
  961. throw std::runtime_error("Index out of array bounds in precompiled charsmap!");
  962. }
  963. const char * prefix_replacement = &(ugm_tokenizer->prefix_replacements)[longest_prefix_offset];
  964. return { prefix_replacement, strlen(prefix_replacement), longest_prefix_length };
  965. }
  966. // check if the input prefix contains a valid sequence of UTF-8 code units
  967. try {
  968. // if yes, return this sequence unmodified
  969. size_t prefix_offset = input_offset;
  970. unicode_cpt_from_utf8(input, prefix_offset);
  971. return { &input[input_offset], prefix_offset - input_offset, prefix_offset - input_offset };
  972. } catch (std::invalid_argument & /*ex*/) {
  973. // if no, consume 1 byte and return U+FFFD - REPLACEMENT CHARACTER
  974. return { "\xEF\xBF\xBD", 3, 1 };
  975. }
  976. }
  977. const llama_vocab & vocab;
  978. const llm_tokenizer_ugm * ugm_tokenizer;
  979. };
  980. //
  981. // RWKV tokenizer
  982. //
  983. static std::vector<uint8_t> llama_unescape_rwkv_token(const std::string & escaped) {
  984. std::vector<uint8_t> output;
  985. output.reserve(escaped.size());
  986. // Parser state
  987. bool escaping = false;
  988. uint8_t hex_remaining = 0;
  989. uint8_t hex_acc = 0;
  990. // Step through characters, performing parsing
  991. for (const char & c : escaped) {
  992. // If we're parsing a hex code, interpret the next character
  993. if (hex_remaining != 0) {
  994. uint8_t value = (c >= 'a') ? (c - 'a' + 10) : (c - '0');
  995. hex_acc = (hex_acc << 4) + value;
  996. hex_remaining -= 1;
  997. if (hex_remaining == 0) {
  998. output.push_back(hex_acc);
  999. hex_acc = 0;
  1000. }
  1001. continue;
  1002. }
  1003. // If we got an escape character, interpret it
  1004. if (escaping) {
  1005. if (c == 't') {
  1006. output.push_back('\t');
  1007. } else if (c == 'n') {
  1008. output.push_back('\n');
  1009. } else if (c == 'r') {
  1010. output.push_back('\r');
  1011. } else if (c == 'x') {
  1012. hex_remaining = 2;
  1013. } else {
  1014. output.push_back(c);
  1015. }
  1016. escaping = false;
  1017. continue;
  1018. }
  1019. if (c == '\\') {
  1020. escaping = true;
  1021. continue;
  1022. }
  1023. output.push_back(c);
  1024. }
  1025. return output;
  1026. }
  1027. struct llm_tokenizer_rwkv : llm_tokenizer {
  1028. llm_tokenizer_rwkv(const llama_vocab & vocab) : llm_tokenizer() {
  1029. // RWKV supports arbitrary byte tokens, but the vocab struct only supports string tokens.
  1030. // For now, we decode the vocab here into the lookup we'll use for tokenization.
  1031. // build trie
  1032. for (unsigned int id = 0; id < vocab.id_to_token.size(); ++id) {
  1033. const auto & token = vocab.id_to_token[id];
  1034. const auto data = llama_unescape_rwkv_token(token.text);
  1035. token_matcher.insert((const char *) data.data(), data.size(), id);
  1036. }
  1037. }
  1038. struct naive_trie token_matcher;
  1039. };
  1040. struct llm_tokenizer_rwkv_session {
  1041. llm_tokenizer_rwkv_session(const llama_vocab & vocab) : vocab(vocab),
  1042. rwkv_tokenizer(static_cast<const llm_tokenizer_rwkv &>(*vocab.tokenizer)) {}
  1043. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  1044. uint32_t position = 0;
  1045. while (position < text.size()) {
  1046. const struct naive_trie * node = rwkv_tokenizer.token_matcher.traverse(text[position]);
  1047. if (node == NULL) {
  1048. // no matching token found, add unknown token
  1049. output.push_back(vocab.special_unk_id);
  1050. position += 1;
  1051. continue;
  1052. }
  1053. // traverse the trie to find the longest matching token
  1054. uint32_t token_id = 0;
  1055. uint32_t token_length = 0;
  1056. while (node != NULL) {
  1057. if (node->has_value) {
  1058. token_id = node->value;
  1059. token_length = position + 1;
  1060. }
  1061. node = node->traverse(text[++position]);
  1062. }
  1063. // add the longest matching token
  1064. output.push_back(token_id);
  1065. position = token_length;
  1066. }
  1067. }
  1068. private:
  1069. const llama_vocab & vocab;
  1070. const llm_tokenizer_rwkv & rwkv_tokenizer;
  1071. };
  1072. void llama_vocab::init_tokenizer() {
  1073. switch (type) {
  1074. case LLAMA_VOCAB_TYPE_SPM:
  1075. tokenizer = new llm_tokenizer_spm(*this);
  1076. break;
  1077. case LLAMA_VOCAB_TYPE_BPE:
  1078. tokenizer = new llm_tokenizer_bpe(*this);
  1079. break;
  1080. case LLAMA_VOCAB_TYPE_WPM:
  1081. tokenizer = new llm_tokenizer_wpm(*this);
  1082. break;
  1083. case LLAMA_VOCAB_TYPE_UGM:
  1084. tokenizer = new llm_tokenizer_ugm(*this);
  1085. break;
  1086. case LLAMA_VOCAB_TYPE_RWKV:
  1087. tokenizer = new llm_tokenizer_rwkv(*this);
  1088. break;
  1089. default:
  1090. GGML_ABORT("unsupported vocab type");
  1091. }
  1092. }
  1093. //
  1094. // (de-) tokenize
  1095. //
  1096. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  1097. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  1098. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  1099. } FRAGMENT_BUFFER_VARIANT_TYPE;
  1100. struct fragment_buffer_variant {
  1101. fragment_buffer_variant(llama_vocab::id _token)
  1102. :
  1103. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  1104. token(_token),
  1105. raw_text(_dummy),
  1106. offset(0),
  1107. length(0) {}
  1108. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  1109. :
  1110. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  1111. token((llama_vocab::id) - 1),
  1112. raw_text(_raw_text),
  1113. offset(_offset),
  1114. length(_length){
  1115. GGML_ASSERT(_offset >= 0);
  1116. GGML_ASSERT(_length >= 1);
  1117. GGML_ASSERT(offset + length <= raw_text.length());
  1118. }
  1119. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  1120. const llama_vocab::id token;
  1121. const std::string _dummy;
  1122. const std::string & raw_text;
  1123. const uint64_t offset;
  1124. const uint64_t length;
  1125. };
  1126. // #define PRETOKENIZERDEBUG
  1127. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer, bool parse_special) {
  1128. // for each special token
  1129. for (const llama_vocab::id special_id : vocab.cache_special_tokens) {
  1130. const auto & data = vocab.id_to_token[special_id];
  1131. const auto & special_token = data.text;
  1132. if (!parse_special && (data.attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_UNKNOWN))) {
  1133. // Ignore control and unknown tokens when parse_special == false
  1134. continue;
  1135. // User-defined tokens are still pre-tokenized before everything else
  1136. // ref: https://github.com/huggingface/tokenizers/blob/fdd26ba9a3f0c133427aab0423888cbde91362d7/tokenizers/src/tokenizer/mod.rs#L726
  1137. // This is mostly relevant for neox-style tokenizers (mpt, olmo, stablelm, etc.)
  1138. }
  1139. // for each text fragment
  1140. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  1141. while (it != buffer.end()) {
  1142. auto & fragment = (*it);
  1143. // if a fragment is text ( not yet processed )
  1144. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1145. const auto & raw_text = fragment.raw_text;
  1146. auto raw_text_base_offset = fragment.offset;
  1147. auto raw_text_base_length = fragment.length;
  1148. // loop over the text
  1149. while (true) {
  1150. // find the first occurrence of a given special token in this fragment
  1151. // passing offset argument only limit the "search area" but match coordinates
  1152. // are still relative to the source full raw_text
  1153. auto match = raw_text.find(special_token, raw_text_base_offset);
  1154. // no occurrences found, stop processing this fragment for a given special token
  1155. if (match == std::string::npos) break;
  1156. // check if match is within bounds of offset <-> length
  1157. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  1158. #ifdef PRETOKENIZERDEBUG
  1159. LLAMA_LOG_WARN("FF: (%ld %ld %ld) '%s'\n", raw_text->length(), raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  1160. #endif
  1161. auto source = std::distance(buffer.begin(), it);
  1162. // if match is further than base offset
  1163. // then we have some text to the left of it
  1164. if (match > raw_text_base_offset) {
  1165. // left
  1166. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  1167. int64_t left_reminder_length = match - raw_text_base_offset;
  1168. if (data.attr & LLAMA_TOKEN_ATTR_LSTRIP) {
  1169. while (left_reminder_length > 0 && isspace(raw_text[left_reminder_offset + left_reminder_length - 1])) {
  1170. left_reminder_length--;
  1171. }
  1172. }
  1173. if (left_reminder_length > 0) {
  1174. buffer.emplace_after(it, raw_text, left_reminder_offset, left_reminder_length);
  1175. it++;
  1176. }
  1177. #ifdef PRETOKENIZERDEBUG
  1178. LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  1179. #endif
  1180. }
  1181. // special token
  1182. buffer.emplace_after(it, special_id);
  1183. it++;
  1184. // right
  1185. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  1186. int64_t right_reminder_offset = match + special_token.length();
  1187. int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  1188. if (data.attr & LLAMA_TOKEN_ATTR_RSTRIP) {
  1189. while (right_reminder_length > 0 && isspace(raw_text[right_reminder_offset])) {
  1190. right_reminder_offset++;
  1191. right_reminder_length--;
  1192. }
  1193. }
  1194. if (right_reminder_length > 0) {
  1195. buffer.emplace_after(it, raw_text, right_reminder_offset, right_reminder_length);
  1196. it++;
  1197. }
  1198. #ifdef PRETOKENIZERDEBUG
  1199. LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  1200. #endif
  1201. if (source == 0) {
  1202. buffer.erase_after(buffer.before_begin());
  1203. } else {
  1204. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  1205. }
  1206. // repeat for the right side
  1207. raw_text_base_offset = right_reminder_offset;
  1208. raw_text_base_length = right_reminder_length;
  1209. #ifdef PRETOKENIZERDEBUG
  1210. LLAMA_LOG_WARN("RR: (%ld %ld) '%s'\n", raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  1211. #endif
  1212. } else {
  1213. if (source == 0) {
  1214. buffer.erase_after(buffer.before_begin());
  1215. } else {
  1216. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  1217. }
  1218. break;
  1219. }
  1220. }
  1221. }
  1222. it++;
  1223. }
  1224. }
  1225. }
  1226. std::vector<llama_vocab::id> llama_tokenize_internal(
  1227. const llama_vocab & vocab,
  1228. std::string raw_text,
  1229. bool add_special,
  1230. bool parse_special) {
  1231. GGML_ASSERT(vocab.tokenizer && "Tokenizer not initialized. Call llama_vocab::init_tokenizer() first.");
  1232. std::vector<llama_vocab::id> output;
  1233. std::forward_list<fragment_buffer_variant> fragment_buffer;
  1234. if (!raw_text.empty()) {
  1235. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  1236. tokenizer_st_partition(vocab, fragment_buffer, parse_special);
  1237. }
  1238. switch (vocab.type) {
  1239. case LLAMA_VOCAB_TYPE_SPM:
  1240. {
  1241. // OG tokenizer behavior:
  1242. //
  1243. // tokenizer.encode('', add_special_tokens=True) returns [1]
  1244. // tokenizer.encode('', add_special_tokens=False) returns []
  1245. bool is_prev_special = true; // prefix with space if first token
  1246. if (add_special && vocab.tokenizer_add_bos) {
  1247. GGML_ASSERT(vocab.special_bos_id != -1);
  1248. output.push_back(vocab.special_bos_id);
  1249. is_prev_special = true;
  1250. }
  1251. for (const auto & fragment : fragment_buffer) {
  1252. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1253. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1254. // prefix with space if previous is special
  1255. if (vocab.tokenizer_add_space_prefix && is_prev_special) {
  1256. raw_text = " " + raw_text;
  1257. }
  1258. #ifdef PRETOKENIZERDEBUG
  1259. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1260. #endif
  1261. llama_escape_whitespace(raw_text);
  1262. llm_tokenizer_spm_session session(vocab);
  1263. session.tokenize(raw_text, output);
  1264. is_prev_special = false;
  1265. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1266. output.push_back(fragment.token);
  1267. is_prev_special = true;
  1268. }
  1269. }
  1270. if (add_special && vocab.tokenizer_add_bos && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  1271. LLAMA_LOG_WARN(
  1272. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  1273. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  1274. "Are you sure this is what you want?\n", __FUNCTION__);
  1275. }
  1276. if (add_special && vocab.tokenizer_add_eos) {
  1277. GGML_ASSERT(vocab.special_eos_id != -1);
  1278. output.push_back(vocab.special_eos_id);
  1279. }
  1280. } break;
  1281. case LLAMA_VOCAB_TYPE_BPE:
  1282. {
  1283. llm_tokenizer_bpe_session session(vocab);
  1284. // it calls some other methods that are not exist in llm_tokenizer,
  1285. // here just cast it to bpe tokenizer object
  1286. if (add_special) {
  1287. session.append_bos(output);
  1288. }
  1289. for (const auto & fragment : fragment_buffer) {
  1290. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1291. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1292. #ifdef PRETOKENIZERDEBUG
  1293. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1294. #endif
  1295. session.tokenize(raw_text, output);
  1296. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1297. session.append(fragment.token, output);
  1298. }
  1299. }
  1300. if (add_special) {
  1301. session.append_eos(output);
  1302. session.check_double_bos_eos(output);
  1303. }
  1304. } break;
  1305. case LLAMA_VOCAB_TYPE_WPM:
  1306. {
  1307. if (add_special) {
  1308. GGML_ASSERT(vocab.special_cls_id != -1);
  1309. output.push_back(vocab.special_cls_id);
  1310. }
  1311. llm_tokenizer_wpm_session session(vocab);
  1312. for (const auto & fragment : fragment_buffer) {
  1313. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1314. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1315. #ifdef PRETOKENIZERDEBUG
  1316. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1317. #endif
  1318. session.tokenize(raw_text, output);
  1319. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1320. output.push_back(fragment.token);
  1321. }
  1322. }
  1323. if (add_special) {
  1324. GGML_ASSERT(vocab.special_sep_id != -1);
  1325. output.push_back(vocab.special_sep_id);
  1326. }
  1327. } break;
  1328. case LLAMA_VOCAB_TYPE_UGM:
  1329. {
  1330. if (add_special && vocab.tokenizer_add_bos) {
  1331. GGML_ASSERT(vocab.special_bos_id != -1);
  1332. output.push_back(vocab.special_bos_id);
  1333. }
  1334. llm_tokenizer_ugm_session session(vocab);
  1335. for (const auto & fragment : fragment_buffer) {
  1336. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1337. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1338. #ifdef PRETOKENIZERDEBUG
  1339. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1340. #endif
  1341. session.tokenize(raw_text, output);
  1342. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1343. output.push_back(fragment.token);
  1344. }
  1345. }
  1346. if (add_special && vocab.tokenizer_add_bos && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  1347. LLAMA_LOG_WARN(
  1348. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  1349. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  1350. "Are you sure this is what you want?\n", __FUNCTION__);
  1351. }
  1352. if (add_special && vocab.tokenizer_add_eos) {
  1353. GGML_ASSERT(vocab.special_eos_id != -1);
  1354. output.push_back(vocab.special_eos_id);
  1355. }
  1356. } break;
  1357. case LLAMA_VOCAB_TYPE_RWKV:
  1358. {
  1359. llm_tokenizer_rwkv_session session(vocab);
  1360. for (const auto & fragment : fragment_buffer) {
  1361. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1362. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1363. #ifdef PRETOKENIZERDEBUG
  1364. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1365. #endif
  1366. session.tokenize(raw_text, output);
  1367. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1368. output.push_back(fragment.token);
  1369. }
  1370. }
  1371. } break;
  1372. case LLAMA_VOCAB_TYPE_NONE:
  1373. GGML_ABORT("fatal error");
  1374. }
  1375. return output;
  1376. }
  1377. llama_token llama_byte_to_token_impl(const llama_vocab & vocab, uint8_t ch) {
  1378. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  1379. static const char * hex = "0123456789ABCDEF";
  1380. switch (llama_vocab_get_type(vocab)) {
  1381. case LLAMA_VOCAB_TYPE_SPM:
  1382. case LLAMA_VOCAB_TYPE_UGM: {
  1383. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  1384. auto token = vocab.token_to_id.find(buf);
  1385. if (token != vocab.token_to_id.end()) {
  1386. return (*token).second;
  1387. }
  1388. // Try to fall back to just the byte as a string
  1389. const char buf2[2] = { (char)ch, 0 };
  1390. return vocab.token_to_id.at(buf2);
  1391. }
  1392. case LLAMA_VOCAB_TYPE_WPM:
  1393. case LLAMA_VOCAB_TYPE_BPE: {
  1394. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  1395. }
  1396. default:
  1397. GGML_ABORT("fatal error");
  1398. }
  1399. }
  1400. const char * llama_token_get_text_impl(const struct llama_vocab & vocab, llama_token token) {
  1401. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  1402. return vocab.id_to_token[token].text.c_str();
  1403. }
  1404. float llama_token_get_score_impl(const struct llama_vocab & vocab, llama_token token) {
  1405. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  1406. return vocab.id_to_token[token].score;
  1407. }
  1408. llama_token_attr llama_token_get_attr_impl(const struct llama_vocab & vocab, llama_token token) {
  1409. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  1410. return vocab.id_to_token[token].attr;
  1411. }
  1412. bool llama_token_is_eog_impl(const struct llama_vocab & vocab, llama_token token) {
  1413. return token != -1 && vocab.special_eog_ids.count(token) > 0;
  1414. }
  1415. bool llama_token_is_control_impl(const struct llama_vocab & vocab, llama_token token) {
  1416. return llama_is_control_token(vocab, token);
  1417. }
  1418. llama_token llama_token_bos_impl(const struct llama_vocab & vocab) {
  1419. return vocab.special_bos_id;
  1420. }
  1421. llama_token llama_token_eos_impl(const struct llama_vocab & vocab) {
  1422. return vocab.special_eos_id;
  1423. }
  1424. llama_token llama_token_eot_impl(const struct llama_vocab & vocab) {
  1425. return vocab.special_eot_id;
  1426. }
  1427. llama_token llama_token_eom_impl(const struct llama_vocab & vocab) {
  1428. return vocab.special_eom_id;
  1429. }
  1430. llama_token llama_token_cls_impl(const struct llama_vocab & vocab) {
  1431. return vocab.special_cls_id;
  1432. }
  1433. llama_token llama_token_sep_impl(const struct llama_vocab & vocab) {
  1434. return vocab.special_sep_id;
  1435. }
  1436. llama_token llama_token_nl_impl(const struct llama_vocab & vocab) {
  1437. return vocab.linefeed_id;
  1438. }
  1439. llama_token llama_token_pad_impl(const struct llama_vocab & vocab) {
  1440. return vocab.special_pad_id;
  1441. }
  1442. bool llama_add_bos_token_impl(const struct llama_vocab & vocab) {
  1443. return vocab.tokenizer_add_bos;
  1444. }
  1445. bool llama_add_eos_token_impl(const struct llama_vocab & vocab) {
  1446. return vocab.tokenizer_add_eos;
  1447. }
  1448. llama_token llama_token_prefix_impl(const struct llama_vocab & vocab) {
  1449. return vocab.special_fim_pre_id;
  1450. }
  1451. llama_token llama_token_middle_impl(const struct llama_vocab & vocab) {
  1452. return vocab.special_fim_mid_id;
  1453. }
  1454. llama_token llama_token_suffix_impl(const struct llama_vocab & vocab) {
  1455. return vocab.special_fim_suf_id;
  1456. }
  1457. llama_token llama_token_fim_pre_impl(const struct llama_vocab & vocab) {
  1458. return vocab.special_fim_pre_id;
  1459. }
  1460. llama_token llama_token_fim_suf_impl(const struct llama_vocab & vocab) {
  1461. return vocab.special_fim_suf_id;
  1462. }
  1463. llama_token llama_token_fim_mid_impl(const struct llama_vocab & vocab) {
  1464. return vocab.special_fim_mid_id;
  1465. }
  1466. llama_token llama_token_fim_pad_impl(const struct llama_vocab & vocab) {
  1467. return vocab.special_fim_pad_id;
  1468. }
  1469. llama_token llama_token_fim_rep_impl(const struct llama_vocab & vocab) {
  1470. return vocab.special_fim_rep_id;
  1471. }
  1472. llama_token llama_token_fim_sep_impl(const struct llama_vocab & vocab) {
  1473. return vocab.special_fim_sep_id;
  1474. }
  1475. int32_t llama_tokenize_impl(
  1476. const struct llama_vocab & vocab,
  1477. const char * text,
  1478. int32_t text_len,
  1479. llama_token * tokens,
  1480. int32_t n_tokens_max,
  1481. bool add_special,
  1482. bool parse_special) {
  1483. auto res = llama_tokenize_internal(vocab, std::string(text, text_len), add_special, parse_special);
  1484. if (n_tokens_max < (int) res.size()) {
  1485. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  1486. return -((int) res.size());
  1487. }
  1488. for (size_t i = 0; i < res.size(); i++) {
  1489. tokens[i] = res[i];
  1490. }
  1491. return res.size();
  1492. }
  1493. static std::string llama_decode_text(const std::string & text) {
  1494. std::string decoded_text;
  1495. const auto cpts = unicode_cpts_from_utf8(text);
  1496. for (const auto cpt : cpts) {
  1497. const auto utf8 = unicode_cpt_to_utf8(cpt);
  1498. try {
  1499. decoded_text += unicode_utf8_to_byte(utf8);
  1500. } catch (const std::out_of_range & /*e*/) {
  1501. decoded_text += "[UNK_BYTE_0x";
  1502. for (const auto c : utf8) {
  1503. decoded_text += format("%02x", (uint8_t) c);
  1504. }
  1505. decoded_text += text + "]";
  1506. }
  1507. }
  1508. return decoded_text;
  1509. }
  1510. // does not write null-terminator to buf
  1511. int32_t llama_token_to_piece_impl(const struct llama_vocab & vocab, llama_token token, char * buf, int32_t length, int32_t lstrip, bool special) {
  1512. // ref: https://github.com/ggerganov/llama.cpp/pull/7587#discussion_r1620983843
  1513. static const int attr_special = LLAMA_TOKEN_ATTR_UNKNOWN | LLAMA_TOKEN_ATTR_CONTROL;
  1514. const llama_token_attr attr = llama_token_get_attr_impl(vocab, token);
  1515. if (!special && (attr & attr_special)) {
  1516. return 0;
  1517. }
  1518. // copy piece chars to output text buffer
  1519. // skip up to 'lstrip' leading spaces before copying
  1520. auto _try_copy = [=] (const char * token, size_t size) -> int32_t {
  1521. for (int32_t i = 0; i < lstrip && size && *token == ' '; ++i) {
  1522. token++;
  1523. size--;
  1524. }
  1525. if (length < (int32_t)size) {
  1526. return -(int32_t) size;
  1527. }
  1528. memcpy(buf, token, size);
  1529. return (int32_t) size;
  1530. };
  1531. // if we have a cache - use it
  1532. {
  1533. const auto & cache = vocab.cache_token_to_piece;
  1534. if (!cache.empty()) {
  1535. const auto & result = cache.at(token);
  1536. return _try_copy(result.data(), result.size());
  1537. }
  1538. }
  1539. if (0 <= token && token < (int32_t) vocab.id_to_token.size()) {
  1540. const std::string & token_text = vocab.id_to_token[token].text;
  1541. switch (llama_vocab_get_type(vocab)) {
  1542. case LLAMA_VOCAB_TYPE_WPM:
  1543. case LLAMA_VOCAB_TYPE_SPM:
  1544. case LLAMA_VOCAB_TYPE_UGM: {
  1545. // NOTE: we accept all unsupported token types,
  1546. // suppressing them like CONTROL tokens.
  1547. if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
  1548. return _try_copy(token_text.data(), token_text.size());
  1549. }
  1550. if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
  1551. std::string result = token_text;
  1552. llama_unescape_whitespace(result);
  1553. return _try_copy(result.data(), result.size());
  1554. }
  1555. if (attr & LLAMA_TOKEN_ATTR_BYTE) {
  1556. char byte = (char) llama_token_to_byte(vocab, token);
  1557. return _try_copy((char*) &byte, 1);
  1558. }
  1559. break;
  1560. }
  1561. case LLAMA_VOCAB_TYPE_BPE: {
  1562. // NOTE: we accept all unsupported token types,
  1563. // suppressing them like CONTROL tokens.
  1564. if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
  1565. return _try_copy(token_text.data(), token_text.size());
  1566. }
  1567. if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
  1568. std::string result = llama_decode_text(token_text);
  1569. return _try_copy(result.data(), result.size());
  1570. }
  1571. break;
  1572. }
  1573. case LLAMA_VOCAB_TYPE_RWKV: {
  1574. std::vector<uint8_t> result = llama_unescape_rwkv_token(token_text);
  1575. // If we don't have enough space, return an error
  1576. if (result.size() > (size_t)length) {
  1577. return -(int)result.size();
  1578. }
  1579. memcpy(buf, result.data(), result.size());
  1580. return (int)result.size();
  1581. }
  1582. default:
  1583. GGML_ABORT("fatal error");
  1584. }
  1585. }
  1586. return 0;
  1587. }
  1588. bool llama_token_is_prefix_impl(
  1589. const struct llama_vocab & vocab,
  1590. llama_token token0,
  1591. llama_token token1) {
  1592. char text_buf_0[128];
  1593. char text_buf_1[128];
  1594. const int32_t len0 = llama_token_to_piece_impl(vocab, token0, text_buf_0, sizeof(text_buf_0) - 1, 0, false);
  1595. const int32_t len1 = llama_token_to_piece_impl(vocab, token1, text_buf_1, sizeof(text_buf_1) - 1, 0, false);
  1596. if (len0 <= 0 || len1 <= 0) {
  1597. return false;
  1598. }
  1599. return len0 <= len1 && memcmp(text_buf_0, text_buf_1, len0) == 0;
  1600. }
  1601. int32_t llama_detokenize_impl(
  1602. const struct llama_vocab & vocab,
  1603. const llama_token * tokens,
  1604. int32_t n_tokens,
  1605. char * text,
  1606. int32_t text_len_max,
  1607. bool remove_special,
  1608. bool unparse_special) {
  1609. GGML_ASSERT(vocab.tokenizer && "Tokenizer not initialized. Call llama_vocab::init_tokenizer() first.");
  1610. int32_t avail = text_len_max;
  1611. int32_t total = 0;
  1612. // remove the leading space
  1613. bool remove_space = vocab.tokenizer_add_space_prefix;
  1614. if (remove_special && vocab.tokenizer_add_bos) {
  1615. if (n_tokens > 0 && tokens[0] == vocab.special_bos_id) {
  1616. remove_space = false;
  1617. n_tokens--;
  1618. tokens++;
  1619. }
  1620. }
  1621. if (remove_special && vocab.tokenizer_add_eos) {
  1622. if (n_tokens > 0 && tokens[n_tokens-1] == vocab.special_eos_id) {
  1623. n_tokens--;
  1624. }
  1625. }
  1626. for (int32_t i = 0; i < n_tokens; ++i) {
  1627. GGML_ASSERT(avail >= 0);
  1628. int32_t n_chars = llama_token_to_piece_impl(vocab, tokens[i], text, avail, remove_space, unparse_special);
  1629. remove_space = false;
  1630. if (n_chars < 0) {
  1631. avail = 0;
  1632. total -= n_chars;
  1633. } else if (n_chars > 0) {
  1634. avail -= n_chars;
  1635. text += n_chars;
  1636. total += n_chars;
  1637. }
  1638. }
  1639. if (total > text_len_max) {
  1640. return -total;
  1641. }
  1642. if (vocab.tokenizer_clean_spaces) {
  1643. text -= total; // restart text
  1644. // first pass: characters ?!., //TODO: where do these characters come from?
  1645. const int32_t total1 = total;
  1646. total = total ? 1 : 0;
  1647. for (int32_t i = 1; i < total1; ++i) {
  1648. const char x = text[i];
  1649. if (text[i - 1] == ' ') {
  1650. if (x == '?' || x == '!' || x == '.' || x == ',') { // " ?", " !", " .", " ,"
  1651. total--; // remove space
  1652. }
  1653. }
  1654. text[total++] = x;
  1655. }
  1656. // second pass: strip single apostrophe between spaces
  1657. const int32_t total2 = total;
  1658. total = total ? 1 : 0;
  1659. for (int32_t i = 1; i < total2; ++i) {
  1660. const char x = text[i];
  1661. if (x == '\'' && i + 1 < total2 && text[i - 1] == ' ' && text[i + 1] == ' ') { // " ' "
  1662. total--; // remove prev space
  1663. text[++i] = '\0'; // remove next space
  1664. }
  1665. text[total++] = x;
  1666. }
  1667. // third pass: apostrophe contractions //NOTE: this makes sense?
  1668. const int32_t total3 = total;
  1669. total = total ? 1 : 0;
  1670. for (int32_t i = 1; i < total3; ++i) {
  1671. const char x = text[i];
  1672. if (text[i - 1] == ' ') {
  1673. if (x == '\'' && i + 1 < total3) {
  1674. const char x1 = text[i + 1];
  1675. if (x1 == 't' || x1 == 'd') { // " 't", " 'd"
  1676. //total--; // remove space
  1677. } else if (x1 == 's' || x1 == 'm') { // " 's", " 'm"
  1678. total--; // remove space
  1679. } else if (i + 2 < total3) {
  1680. const char x2 = text[i + 2];
  1681. if ((x1 == 'l' && x2 == 'l')) { // " 'll"
  1682. //total--; // remove space
  1683. } else if ((x1 == 'r' && x2 == 'e') || (x1 == 'v' && x2 == 'e')) { // " 're", " 've"
  1684. total--; // remove space
  1685. } else {
  1686. //total--; // remove space
  1687. }
  1688. } else {
  1689. //total--; // remove space
  1690. }
  1691. }
  1692. }
  1693. text[total++] = x;
  1694. }
  1695. }
  1696. return total <= text_len_max ? total : -total;
  1697. }