llama-vocab.cpp 71 KB

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