llama-vocab.cpp 76 KB

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