llama-vocab.cpp 66 KB

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