llama-vocab.cpp 75 KB

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