llama-vocab.cpp 66 KB

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