utils.hpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. #pragma once
  2. #include "common.h"
  3. #include "log.h"
  4. #include "llama.h"
  5. #include "arg.h" // common_remote_get_content
  6. #include "base64.hpp"
  7. #include "mtmd.h"
  8. #include "mtmd-helper.h"
  9. #include "chat.h"
  10. // increase max payload length to allow use of larger context size
  11. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 1048576
  12. // disable Nagle's algorithm
  13. #define CPPHTTPLIB_TCP_NODELAY true
  14. #include <cpp-httplib/httplib.h>
  15. #define JSON_ASSERT GGML_ASSERT
  16. #include <nlohmann/json.hpp>
  17. #include <random>
  18. #include <sstream>
  19. #include <string>
  20. #include <vector>
  21. #include <memory>
  22. #include <cinttypes>
  23. #define DEFAULT_OAICOMPAT_MODEL "gpt-3.5-turbo"
  24. using json = nlohmann::ordered_json;
  25. #define SLT_INF(slot, fmt, ...) LOG_INF("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  26. #define SLT_WRN(slot, fmt, ...) LOG_WRN("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  27. #define SLT_ERR(slot, fmt, ...) LOG_ERR("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  28. #define SLT_DBG(slot, fmt, ...) LOG_DBG("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  29. #define SRV_INF(fmt, ...) LOG_INF("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  30. #define SRV_WRN(fmt, ...) LOG_WRN("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  31. #define SRV_ERR(fmt, ...) LOG_ERR("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  32. #define SRV_DBG(fmt, ...) LOG_DBG("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  33. #define QUE_INF(fmt, ...) LOG_INF("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  34. #define QUE_WRN(fmt, ...) LOG_WRN("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  35. #define QUE_ERR(fmt, ...) LOG_ERR("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  36. #define QUE_DBG(fmt, ...) LOG_DBG("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  37. using raw_buffer = std::vector<uint8_t>;
  38. template <typename T>
  39. static T json_value(const json & body, const std::string & key, const T & default_value) {
  40. // Fallback null to default value
  41. if (body.contains(key) && !body.at(key).is_null()) {
  42. try {
  43. return body.at(key);
  44. } catch (NLOHMANN_JSON_NAMESPACE::detail::type_error const &) {
  45. LOG_WRN("Wrong type supplied for parameter '%s'. Expected '%s', using default value\n", key.c_str(), json(default_value).type_name());
  46. return default_value;
  47. }
  48. } else {
  49. return default_value;
  50. }
  51. }
  52. const static std::string build_info("b" + std::to_string(LLAMA_BUILD_NUMBER) + "-" + LLAMA_COMMIT);
  53. // thin wrapper around common_grammar_trigger with (de)serialization functions
  54. struct server_grammar_trigger {
  55. common_grammar_trigger value;
  56. server_grammar_trigger() = default;
  57. server_grammar_trigger(const common_grammar_trigger & value) : value(value) {}
  58. server_grammar_trigger(const json & in) {
  59. value.type = (common_grammar_trigger_type) in.at("type").get<int>();
  60. value.value = in.at("value").get<std::string>();
  61. if (value.type == COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN) {
  62. value.token = (llama_token) in.at("token").get<int>();
  63. }
  64. }
  65. json to_json() const {
  66. json out {
  67. {"type", (int) value.type},
  68. {"value", value.value},
  69. };
  70. if (value.type == COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN) {
  71. out["token"] = (int) value.token;
  72. }
  73. return out;
  74. }
  75. };
  76. //
  77. // tokenizer and input processing utils
  78. //
  79. static bool json_is_array_of_numbers(const json & data) {
  80. if (data.is_array()) {
  81. for (const auto & e : data) {
  82. if (!e.is_number_integer()) {
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. return false;
  89. }
  90. // is array having BOTH numbers & strings?
  91. static bool json_is_array_of_mixed_numbers_strings(const json & data) {
  92. bool seen_string = false;
  93. bool seen_number = false;
  94. if (data.is_array()) {
  95. for (const auto & e : data) {
  96. seen_string |= e.is_string();
  97. seen_number |= e.is_number_integer();
  98. if (seen_number && seen_string) {
  99. return true;
  100. }
  101. }
  102. }
  103. return false;
  104. }
  105. // get value by path(key1 / key2)
  106. static json json_get_nested_values(const std::vector<std::string> & paths, const json & js) {
  107. json result = json::object();
  108. for (const std::string & path : paths) {
  109. json current = js;
  110. const auto keys = string_split<std::string>(path, /*separator*/ '/');
  111. bool valid_path = true;
  112. for (const std::string & k : keys) {
  113. if (valid_path && current.is_object() && current.contains(k)) {
  114. current = current[k];
  115. } else {
  116. valid_path = false;
  117. }
  118. }
  119. if (valid_path) {
  120. result[path] = current;
  121. }
  122. }
  123. return result;
  124. }
  125. /**
  126. * this handles 2 cases:
  127. * - only string, example: "string"
  128. * - mixed string and tokens, example: [12, 34, "string", 56, 78]
  129. */
  130. static llama_tokens tokenize_mixed(const llama_vocab * vocab, const json & json_prompt, bool add_special, bool parse_special) {
  131. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  132. // or the first element of the json_prompt array is a string.
  133. llama_tokens prompt_tokens;
  134. if (json_prompt.is_array()) {
  135. bool first = true;
  136. for (const auto & p : json_prompt) {
  137. if (p.is_string()) {
  138. auto s = p.template get<std::string>();
  139. llama_tokens p;
  140. if (first) {
  141. p = common_tokenize(vocab, s, add_special, parse_special);
  142. first = false;
  143. } else {
  144. p = common_tokenize(vocab, s, false, parse_special);
  145. }
  146. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  147. } else {
  148. if (first) {
  149. first = false;
  150. }
  151. prompt_tokens.push_back(p.template get<llama_token>());
  152. }
  153. }
  154. } else {
  155. auto s = json_prompt.template get<std::string>();
  156. prompt_tokens = common_tokenize(vocab, s, add_special, parse_special);
  157. }
  158. return prompt_tokens;
  159. }
  160. /**
  161. * break the input "prompt" object into multiple prompt if needed, then tokenize them
  162. * this supports these cases:
  163. * - "prompt": "string"
  164. * - "prompt": [12, 34, 56]
  165. * - "prompt": [12, 34, "string", 56, 78]
  166. * and multiple prompts (multi-tasks):
  167. * - "prompt": ["string1", "string2"]
  168. * - "prompt": ["string1", [12, 34, 56]]
  169. * - "prompt": [[12, 34, 56], [78, 90, 12]]
  170. * - "prompt": [[12, 34, "string", 56, 78], [12, 34, 56]]
  171. */
  172. static std::vector<llama_tokens> tokenize_input_prompts(const llama_vocab * vocab, const json & json_prompt, bool add_special, bool parse_special) {
  173. std::vector<llama_tokens> result;
  174. if (json_prompt.is_string() || json_is_array_of_mixed_numbers_strings(json_prompt)) {
  175. // string or mixed
  176. result.push_back(tokenize_mixed(vocab, json_prompt, add_special, parse_special));
  177. } else if (json_is_array_of_numbers(json_prompt)) {
  178. // array of tokens
  179. result.push_back(json_prompt.get<llama_tokens>());
  180. } else if (json_prompt.is_array()) {
  181. // array of prompts
  182. result.reserve(json_prompt.size());
  183. for (const auto & p : json_prompt) {
  184. if (p.is_string() || json_is_array_of_mixed_numbers_strings(p)) {
  185. result.push_back(tokenize_mixed(vocab, p, add_special, parse_special));
  186. } else if (json_is_array_of_numbers(p)) {
  187. // array of tokens
  188. result.push_back(p.get<llama_tokens>());
  189. } else {
  190. throw std::runtime_error("element of \"prompt\" must be a string, an list of tokens, or a list of mixed strings & tokens");
  191. }
  192. }
  193. } else {
  194. throw std::runtime_error("\"prompt\" must be a string, an list of tokens, a list of mixed strings & tokens, or a list of prompts");
  195. }
  196. if (result.empty()) {
  197. throw std::runtime_error("\"prompt\" must not be empty");
  198. }
  199. return result;
  200. }
  201. // return the last index of character that can form a valid string
  202. // if the last character is potentially cut in half, return the index before the cut
  203. // if validate_utf8(text) == text.size(), then the whole text is valid utf8
  204. static size_t validate_utf8(const std::string& text) {
  205. size_t len = text.size();
  206. if (len == 0) return 0;
  207. // Check the last few bytes to see if a multi-byte character is cut off
  208. for (size_t i = 1; i <= 4 && i <= len; ++i) {
  209. unsigned char c = text[len - i];
  210. // Check for start of a multi-byte sequence from the end
  211. if ((c & 0xE0) == 0xC0) {
  212. // 2-byte character start: 110xxxxx
  213. // Needs at least 2 bytes
  214. if (i < 2) return len - i;
  215. } else if ((c & 0xF0) == 0xE0) {
  216. // 3-byte character start: 1110xxxx
  217. // Needs at least 3 bytes
  218. if (i < 3) return len - i;
  219. } else if ((c & 0xF8) == 0xF0) {
  220. // 4-byte character start: 11110xxx
  221. // Needs at least 4 bytes
  222. if (i < 4) return len - i;
  223. }
  224. }
  225. // If no cut-off multi-byte character is found, return full length
  226. return len;
  227. }
  228. //
  229. // template utils
  230. //
  231. // format rerank task: [BOS]query[EOS][SEP]doc[EOS]
  232. static llama_tokens format_rerank(const struct llama_vocab * vocab, const llama_tokens & query, const llama_tokens & doc) {
  233. llama_tokens result;
  234. // Get EOS token - use SEP token as fallback if EOS is not available
  235. llama_token eos_token = llama_vocab_eos(vocab);
  236. if (eos_token == LLAMA_TOKEN_NULL) {
  237. eos_token = llama_vocab_sep(vocab);
  238. }
  239. result.reserve(doc.size() + query.size() + 4);
  240. if (llama_vocab_get_add_bos(vocab)) {
  241. result.push_back(llama_vocab_bos(vocab));
  242. }
  243. result.insert(result.end(), query.begin(), query.end());
  244. if (llama_vocab_get_add_eos(vocab)) {
  245. result.push_back(eos_token);
  246. }
  247. if (llama_vocab_get_add_sep(vocab)) {
  248. result.push_back(llama_vocab_sep(vocab));
  249. }
  250. result.insert(result.end(), doc.begin(), doc.end());
  251. if (llama_vocab_get_add_eos(vocab)) {
  252. result.push_back(eos_token);
  253. }
  254. return result;
  255. }
  256. // format infill task
  257. static llama_tokens format_infill(
  258. const llama_vocab * vocab,
  259. const json & input_prefix,
  260. const json & input_suffix,
  261. const json & input_extra,
  262. const int n_batch,
  263. const int n_predict,
  264. const int n_ctx,
  265. const bool spm_infill,
  266. const llama_tokens & tokens_prompt
  267. ) {
  268. // TODO: optimize this block by reducing memory allocations and movement
  269. // use FIM repo-level pattern:
  270. // ref: https://arxiv.org/pdf/2409.12186
  271. //
  272. // [FIM_REP]myproject
  273. // [FIM_SEP]filename0
  274. // extra chunk 0
  275. // [FIM_SEP]filename1
  276. // extra chunk 1
  277. // ...
  278. // [FIM_SEP]filename
  279. // [FIM_PRE]prefix[FIM_SUF]suffix[FIM_MID]prompt
  280. //
  281. llama_tokens extra_tokens;
  282. extra_tokens.reserve(n_ctx);
  283. auto tokens_prefix = tokenize_mixed(vocab, input_prefix, false, false);
  284. auto tokens_suffix = tokenize_mixed(vocab, input_suffix, false, false);
  285. if (llama_vocab_fim_rep(vocab) != LLAMA_TOKEN_NULL) {
  286. // TODO: make project name an input
  287. static const auto k_fim_repo = common_tokenize(vocab, "myproject\n", false, false);
  288. extra_tokens.push_back(llama_vocab_fim_rep(vocab));
  289. extra_tokens.insert(extra_tokens.end(), k_fim_repo.begin(), k_fim_repo.end());
  290. }
  291. for (const auto & chunk : input_extra) {
  292. // { "text": string, "filename": string }
  293. const std::string text = json_value(chunk, "text", std::string());
  294. const std::string filename = json_value(chunk, "filename", std::string("tmp"));
  295. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  296. const auto k_fim_file = common_tokenize(vocab, filename + "\n", false, false);
  297. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  298. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  299. } else {
  300. // chunk separator in binary form to avoid confusing the AI
  301. static const char k_chunk_prefix_str[] = {0x0a, 0x0a, 0x2d, 0x2d, 0x2d, 0x20, 0x73, 0x6e, 0x69, 0x70, 0x70, 0x65, 0x74, 0x20, 0x2d, 0x2d, 0x2d, 0x0a, 0x0a, 0x00};
  302. static const auto k_chunk_prefix_tokens = common_tokenize(vocab, k_chunk_prefix_str, false, false);
  303. extra_tokens.insert(extra_tokens.end(), k_chunk_prefix_tokens.begin(), k_chunk_prefix_tokens.end());
  304. }
  305. const auto chunk_tokens = common_tokenize(vocab, text, false, false);
  306. extra_tokens.insert(extra_tokens.end(), chunk_tokens.begin(), chunk_tokens.end());
  307. }
  308. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  309. // TODO: current filename
  310. static const auto k_fim_file = common_tokenize(vocab, "filename\n", false, false);
  311. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  312. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  313. }
  314. // for now pick FIM context to fit in a batch (ratio prefix:suffix = 3:1, TODO: configurable?)
  315. const int n_prefix_take = std::min<int>(tokens_prefix.size(), 3*(n_batch/4));
  316. const int n_suffix_take = std::min<int>(tokens_suffix.size(), std::max<int>(0, (n_batch/4) - (2 + tokens_prompt.size())));
  317. SRV_DBG("n_prefix_take = %d, n_suffix_take = %d, total = %d\n", n_prefix_take, n_suffix_take, (n_prefix_take + n_suffix_take));
  318. // fill the rest of the context with extra chunks
  319. const int n_extra_take = std::min<int>(std::max<int>(0, n_ctx - (n_batch) - 2*n_predict), extra_tokens.size());
  320. tokens_prefix.erase(tokens_prefix.begin(), tokens_prefix.begin() + tokens_prefix.size() - n_prefix_take);
  321. tokens_suffix.resize(n_suffix_take);
  322. tokens_prefix.insert(tokens_prefix.begin(), llama_vocab_fim_pre(vocab));
  323. tokens_prefix.insert(tokens_prefix.end(), tokens_prompt.begin(), tokens_prompt.end());
  324. tokens_suffix.insert(tokens_suffix.begin(), llama_vocab_fim_suf(vocab));
  325. auto embd_inp = spm_infill ? tokens_suffix : tokens_prefix;
  326. auto embd_end = spm_infill ? tokens_prefix : tokens_suffix;
  327. if (llama_vocab_get_add_bos(vocab)) {
  328. embd_inp.insert(embd_inp.begin(), llama_vocab_bos(vocab));
  329. }
  330. SRV_DBG("extra: n_ctx = %d, n_extra_take = %d, n_extra = %d\n", n_ctx, n_extra_take, (int) extra_tokens.size());
  331. // put the extra context before the FIM prefix
  332. embd_inp.insert(embd_inp.begin(), extra_tokens.end() - n_extra_take, extra_tokens.end());
  333. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  334. embd_inp.push_back(llama_vocab_fim_mid(vocab));
  335. return embd_inp;
  336. }
  337. //
  338. // base64 utils (TODO: move to common in the future)
  339. //
  340. static const std::string base64_chars =
  341. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  342. "abcdefghijklmnopqrstuvwxyz"
  343. "0123456789+/";
  344. static inline bool is_base64(uint8_t c) {
  345. return (isalnum(c) || (c == '+') || (c == '/'));
  346. }
  347. static inline raw_buffer base64_decode(const std::string & encoded_string) {
  348. int i = 0;
  349. int j = 0;
  350. int in_ = 0;
  351. int in_len = encoded_string.size();
  352. uint8_t char_array_4[4];
  353. uint8_t char_array_3[3];
  354. raw_buffer ret;
  355. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  356. char_array_4[i++] = encoded_string[in_]; in_++;
  357. if (i == 4) {
  358. for (i = 0; i < 4; i++) {
  359. char_array_4[i] = base64_chars.find(char_array_4[i]);
  360. }
  361. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  362. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  363. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  364. for (i = 0; (i < 3); i++) {
  365. ret.push_back(char_array_3[i]);
  366. }
  367. i = 0;
  368. }
  369. }
  370. if (i) {
  371. for (j = i; j < 4; j++) {
  372. char_array_4[j] = 0;
  373. }
  374. for (j = 0; j < 4; j++) {
  375. char_array_4[j] = base64_chars.find(char_array_4[j]);
  376. }
  377. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  378. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  379. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  380. for (j = 0; j < i - 1; j++) {
  381. ret.push_back(char_array_3[j]);
  382. }
  383. }
  384. return ret;
  385. }
  386. //
  387. // random string / id
  388. //
  389. static std::string random_string() {
  390. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  391. std::random_device rd;
  392. std::mt19937 generator(rd());
  393. std::string result(32, ' ');
  394. for (int i = 0; i < 32; ++i) {
  395. result[i] = str[generator() % str.size()];
  396. }
  397. return result;
  398. }
  399. static std::string gen_chatcmplid() {
  400. return "chatcmpl-" + random_string();
  401. }
  402. static std::string gen_tool_call_id() {
  403. return random_string();
  404. }
  405. //
  406. // other common utils
  407. //
  408. // TODO: reuse llama_detokenize
  409. template <class Iter>
  410. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  411. std::string ret;
  412. for (; begin != end; ++begin) {
  413. ret += common_token_to_piece(ctx, *begin);
  414. }
  415. return ret;
  416. }
  417. // format incomplete utf-8 multibyte character for output
  418. static std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  419. std::string out = token == LLAMA_TOKEN_NULL ? "" : common_token_to_piece(ctx, token);
  420. // if the size is 1 and first bit is 1, meaning it's a partial character
  421. // (size > 1 meaning it's already a known token)
  422. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  423. std::stringstream ss;
  424. ss << std::hex << (out[0] & 0xff);
  425. std::string res(ss.str());
  426. out = "byte: \\x" + res;
  427. }
  428. return out;
  429. }
  430. static bool server_sent_event(httplib::DataSink & sink, const char * event, const json & data) {
  431. const std::string str =
  432. std::string(event) + ": " +
  433. data.dump(-1, ' ', false, json::error_handler_t::replace) +
  434. "\n\n"; // required by RFC 8895 - A message is terminated by a blank line (two line terminators in a row).
  435. LOG_DBG("data stream, to_send: %s", str.c_str());
  436. return sink.write(str.c_str(), str.size());
  437. }
  438. //
  439. // OAI utils
  440. //
  441. // used by /completions endpoint
  442. static json oaicompat_completion_params_parse(const json & body) {
  443. json llama_params;
  444. if (!body.contains("prompt")) {
  445. throw std::runtime_error("\"prompt\" is required");
  446. }
  447. // Handle "stop" field
  448. if (body.contains("stop") && body.at("stop").is_string()) {
  449. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  450. } else {
  451. llama_params["stop"] = json_value(body, "stop", json::array());
  452. }
  453. // Handle "n" field
  454. int n_choices = json_value(body, "n", 1);
  455. if (n_choices != 1) {
  456. throw std::runtime_error("Only one completion choice is allowed");
  457. }
  458. // Handle "echo" field
  459. if (json_value(body, "echo", false)) {
  460. throw std::runtime_error("Only no echo is supported");
  461. }
  462. // Params supported by OAI but unsupported by llama.cpp
  463. static const std::vector<std::string> unsupported_params { "best_of", "suffix" };
  464. for (const auto & param : unsupported_params) {
  465. if (body.contains(param)) {
  466. throw std::runtime_error("Unsupported param: " + param);
  467. }
  468. }
  469. // Copy remaining properties to llama_params
  470. for (const auto & item : body.items()) {
  471. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  472. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  473. llama_params[item.key()] = item.value();
  474. }
  475. }
  476. return llama_params;
  477. }
  478. struct oaicompat_parser_options {
  479. bool use_jinja;
  480. bool prefill_assistant;
  481. common_reasoning_format reasoning_format;
  482. std::map<std::string,std::string> chat_template_kwargs;
  483. common_chat_templates * tmpls;
  484. bool allow_image;
  485. bool allow_audio;
  486. bool enable_thinking = true;
  487. };
  488. // used by /chat/completions endpoint
  489. static json oaicompat_chat_params_parse(
  490. json & body, /* openai api json semantics */
  491. const oaicompat_parser_options & opt,
  492. std::vector<raw_buffer> & out_files)
  493. {
  494. json llama_params;
  495. auto tools = json_value(body, "tools", json());
  496. auto has_tools = tools.is_array() && !tools.empty();
  497. auto stream = json_value(body, "stream", false);
  498. auto tool_choice = json_value(body, "tool_choice", std::string("auto"));
  499. if (!opt.use_jinja) {
  500. if (has_tools) {
  501. throw std::runtime_error("tools param requires --jinja flag");
  502. }
  503. if (tool_choice != "auto") {
  504. throw std::runtime_error("tool_choice param requires --jinja flag");
  505. }
  506. }
  507. // Handle "stop" field
  508. if (body.contains("stop") && body.at("stop").is_string()) {
  509. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  510. } else {
  511. llama_params["stop"] = json_value(body, "stop", json::array());
  512. }
  513. auto json_schema = json_value(body, "json_schema", json());
  514. auto grammar = json_value(body, "grammar", std::string());
  515. if (!json_schema.is_null() && !grammar.empty()) {
  516. throw std::runtime_error("Cannot use both json_schema and grammar");
  517. }
  518. // Handle "response_format" field
  519. if (body.contains("response_format")) {
  520. json response_format = json_value(body, "response_format", json::object());
  521. std::string response_type = json_value(response_format, "type", std::string());
  522. if (response_type == "json_object") {
  523. json_schema = json_value(response_format, "schema", json::object());
  524. } else if (response_type == "json_schema") {
  525. auto schema_wrapper = json_value(response_format, "json_schema", json::object());
  526. json_schema = json_value(schema_wrapper, "schema", json::object());
  527. } else if (!response_type.empty() && response_type != "text") {
  528. throw std::runtime_error("response_format type must be one of \"text\" or \"json_object\", but got: " + response_type);
  529. }
  530. }
  531. // get input files
  532. if (!body.contains("messages")) {
  533. throw std::runtime_error("'messages' is required");
  534. }
  535. json & messages = body.at("messages");
  536. if (!messages.is_array()) {
  537. throw std::runtime_error("Expected 'messages' to be an array");
  538. }
  539. for (auto & msg : messages) {
  540. std::string role = json_value(msg, "role", std::string());
  541. if (role != "assistant" && !msg.contains("content")) {
  542. throw std::runtime_error("All non-assistant messages must contain 'content'");
  543. }
  544. if (role == "assistant") {
  545. if (!msg.contains("content") && !msg.contains("tool_calls")) {
  546. throw std::runtime_error("Assistant message must contain either 'content' or 'tool_calls'!");
  547. }
  548. if (!msg.contains("content")) {
  549. continue; // avoid errors with no content
  550. }
  551. }
  552. json & content = msg.at("content");
  553. if (content.is_string() || content.is_null()) {
  554. continue;
  555. }
  556. if (!content.is_array()) {
  557. throw std::runtime_error("Expected 'content' to be a string or an array");
  558. }
  559. for (auto & p : content) {
  560. std::string type = json_value(p, "type", std::string());
  561. if (type == "image_url") {
  562. if (!opt.allow_image) {
  563. throw std::runtime_error("image input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
  564. }
  565. json image_url = json_value(p, "image_url", json::object());
  566. std::string url = json_value(image_url, "url", std::string());
  567. if (string_starts_with(url, "http")) {
  568. // download remote image
  569. // TODO @ngxson : maybe make these params configurable
  570. common_remote_params params;
  571. params.headers.push_back("User-Agent: llama.cpp/" + build_info);
  572. params.max_size = 1024 * 1024 * 10; // 10MB
  573. params.timeout = 10; // seconds
  574. SRV_INF("downloading image from '%s'\n", url.c_str());
  575. auto res = common_remote_get_content(url, params);
  576. if (200 <= res.first && res.first < 300) {
  577. SRV_INF("downloaded %ld bytes\n", res.second.size());
  578. raw_buffer data;
  579. data.insert(data.end(), res.second.begin(), res.second.end());
  580. out_files.push_back(data);
  581. } else {
  582. throw std::runtime_error("Failed to download image");
  583. }
  584. } else {
  585. // try to decode base64 image
  586. std::vector<std::string> parts = string_split<std::string>(url, /*separator*/ ',');
  587. if (parts.size() != 2) {
  588. throw std::runtime_error("Invalid image_url.url value");
  589. } else if (!string_starts_with(parts[0], "data:image/")) {
  590. throw std::runtime_error("Invalid image_url.url format: " + parts[0]);
  591. } else if (!string_ends_with(parts[0], "base64")) {
  592. throw std::runtime_error("image_url.url must be base64 encoded");
  593. } else {
  594. auto base64_data = parts[1];
  595. auto decoded_data = base64_decode(base64_data);
  596. out_files.push_back(decoded_data);
  597. }
  598. }
  599. // replace this chunk with a marker
  600. p["type"] = "text";
  601. p["text"] = mtmd_default_marker();
  602. p.erase("image_url");
  603. } else if (type == "input_audio") {
  604. if (!opt.allow_audio) {
  605. throw std::runtime_error("audio input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
  606. }
  607. json input_audio = json_value(p, "input_audio", json::object());
  608. std::string data = json_value(input_audio, "data", std::string());
  609. std::string format = json_value(input_audio, "format", std::string());
  610. // while we also support flac, we don't allow it here so we matches the OAI spec
  611. if (format != "wav" && format != "mp3") {
  612. throw std::runtime_error("input_audio.format must be either 'wav' or 'mp3'");
  613. }
  614. auto decoded_data = base64_decode(data); // expected to be base64 encoded
  615. out_files.push_back(decoded_data);
  616. // replace this chunk with a marker
  617. p["type"] = "text";
  618. p["text"] = mtmd_default_marker();
  619. p.erase("input_audio");
  620. } else if (type != "text") {
  621. throw std::runtime_error("unsupported content[].type");
  622. }
  623. }
  624. }
  625. common_chat_templates_inputs inputs;
  626. inputs.messages = common_chat_msgs_parse_oaicompat(messages);
  627. inputs.tools = common_chat_tools_parse_oaicompat(tools);
  628. inputs.tool_choice = common_chat_tool_choice_parse_oaicompat(tool_choice);
  629. inputs.json_schema = json_schema.is_null() ? "" : json_schema.dump();
  630. inputs.grammar = grammar;
  631. inputs.use_jinja = opt.use_jinja;
  632. inputs.parallel_tool_calls = json_value(body, "parallel_tool_calls", false);
  633. inputs.add_generation_prompt = json_value(body, "add_generation_prompt", true);
  634. inputs.reasoning_format = opt.reasoning_format;
  635. inputs.enable_thinking = opt.enable_thinking;
  636. if (!inputs.tools.empty() && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
  637. if (body.contains("grammar")) {
  638. throw std::runtime_error("Cannot use custom grammar constraints with tools.");
  639. }
  640. llama_params["parse_tool_calls"] = true;
  641. }
  642. // merge the template args provided from command line with the args provided in the user request
  643. auto chat_template_kwargs_object = json_value(body, "chat_template_kwargs", json::object());
  644. inputs.chat_template_kwargs = opt.chat_template_kwargs;
  645. for (const auto & item : chat_template_kwargs_object.items()) {
  646. inputs.chat_template_kwargs[item.key()] = item.value().dump();
  647. }
  648. // if the assistant message appears at the end of list, we do not add end-of-turn token
  649. // for ex. this can be useful to modify the reasoning process in reasoning models
  650. bool prefill_assistant_message = !inputs.messages.empty() && inputs.messages.back().role == "assistant" && opt.prefill_assistant;
  651. common_chat_msg last_message;
  652. if (prefill_assistant_message) {
  653. last_message = inputs.messages.back();
  654. inputs.messages.pop_back();
  655. /* sanity check, max one assistant message at the end of the list */
  656. if (!inputs.messages.empty() && inputs.messages.back().role == "assistant"){
  657. throw std::runtime_error("Cannot have 2 or more assistant messages at the end of the list.");
  658. }
  659. /* TODO: test this properly */
  660. inputs.reasoning_format = COMMON_REASONING_FORMAT_NONE;
  661. if ( (!inputs.enable_thinking) || inputs.chat_template_kwargs.find("enable_thinking") != inputs.chat_template_kwargs.end()) {
  662. throw std::runtime_error("Assistant response prefill is incompatible with enable_thinking.");
  663. }
  664. inputs.add_generation_prompt = true;
  665. }
  666. // Apply chat template to the list of messages
  667. auto chat_params = common_chat_templates_apply(opt.tmpls, inputs);
  668. /* Append assistant prefilled message */
  669. if (prefill_assistant_message) {
  670. chat_params.prompt += last_message.content;
  671. }
  672. llama_params["chat_format"] = static_cast<int>(chat_params.format);
  673. llama_params["prompt"] = chat_params.prompt;
  674. if (!chat_params.grammar.empty()) {
  675. llama_params["grammar"] = chat_params.grammar;
  676. }
  677. llama_params["grammar_lazy"] = chat_params.grammar_lazy;
  678. auto grammar_triggers = json::array();
  679. for (const auto & trigger : chat_params.grammar_triggers) {
  680. server_grammar_trigger ct(trigger);
  681. grammar_triggers.push_back(ct.to_json());
  682. }
  683. llama_params["grammar_triggers"] = grammar_triggers;
  684. llama_params["preserved_tokens"] = chat_params.preserved_tokens;
  685. llama_params["thinking_forced_open"] = chat_params.thinking_forced_open;
  686. for (const auto & stop : chat_params.additional_stops) {
  687. llama_params["stop"].push_back(stop);
  688. }
  689. // Handle "n" field
  690. int n_choices = json_value(body, "n", 1);
  691. if (n_choices != 1) {
  692. throw std::runtime_error("Only one completion choice is allowed");
  693. }
  694. // Handle "logprobs" field
  695. // TODO: The response format of this option is not yet OAI-compatible, but seems like no one really using it; We may need to fix it in the future
  696. if (json_value(body, "logprobs", false)) {
  697. if (has_tools && stream) {
  698. throw std::runtime_error("logprobs is not supported with tools + stream");
  699. }
  700. llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
  701. } else if (body.contains("top_logprobs") && !body.at("top_logprobs").is_null()) {
  702. throw std::runtime_error("top_logprobs requires logprobs to be set to true");
  703. }
  704. // Copy remaining properties to llama_params
  705. // This allows user to use llama.cpp-specific params like "mirostat", ... via OAI endpoint.
  706. // See "launch_slot_with_task()" for a complete list of params supported by llama.cpp
  707. for (const auto & item : body.items()) {
  708. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  709. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  710. llama_params[item.key()] = item.value();
  711. }
  712. }
  713. return llama_params;
  714. }
  715. static json format_embeddings_response_oaicompat(const json & request, const json & embeddings, bool use_base64 = false) {
  716. json data = json::array();
  717. int32_t n_tokens = 0;
  718. int i = 0;
  719. for (const auto & elem : embeddings) {
  720. json embedding_obj;
  721. if (use_base64) {
  722. const auto& vec = json_value(elem, "embedding", json::array()).get<std::vector<float>>();
  723. const char* data_ptr = reinterpret_cast<const char*>(vec.data());
  724. size_t data_size = vec.size() * sizeof(float);
  725. embedding_obj = {
  726. {"embedding", base64::encode(data_ptr, data_size)},
  727. {"index", i++},
  728. {"object", "embedding"},
  729. {"encoding_format", "base64"}
  730. };
  731. } else {
  732. embedding_obj = {
  733. {"embedding", json_value(elem, "embedding", json::array())},
  734. {"index", i++},
  735. {"object", "embedding"}
  736. };
  737. }
  738. data.push_back(embedding_obj);
  739. n_tokens += json_value(elem, "tokens_evaluated", 0);
  740. }
  741. json res = json {
  742. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  743. {"object", "list"},
  744. {"usage", json {
  745. {"prompt_tokens", n_tokens},
  746. {"total_tokens", n_tokens}
  747. }},
  748. {"data", data}
  749. };
  750. return res;
  751. }
  752. static json format_response_rerank(
  753. const json & request,
  754. const json & ranks,
  755. bool is_tei_format,
  756. std::vector<std::string> & texts) {
  757. json res;
  758. if (is_tei_format) {
  759. // TEI response format
  760. res = json::array();
  761. bool return_text = json_value(request, "return_text", false);
  762. for (const auto & rank : ranks) {
  763. int index = json_value(rank, "index", 0);
  764. json elem = json{
  765. {"index", index},
  766. {"score", json_value(rank, "score", 0.0)},
  767. };
  768. if (return_text) {
  769. elem["text"] = std::move(texts[index]);
  770. }
  771. res.push_back(elem);
  772. }
  773. } else {
  774. // Jina response format
  775. json results = json::array();
  776. int32_t n_tokens = 0;
  777. for (const auto & rank : ranks) {
  778. results.push_back(json{
  779. {"index", json_value(rank, "index", 0)},
  780. {"relevance_score", json_value(rank, "score", 0.0)},
  781. });
  782. n_tokens += json_value(rank, "tokens_evaluated", 0);
  783. }
  784. res = json{
  785. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  786. {"object", "list"},
  787. {"usage", json{
  788. {"prompt_tokens", n_tokens},
  789. {"total_tokens", n_tokens}
  790. }},
  791. {"results", results}
  792. };
  793. }
  794. return res;
  795. }
  796. static bool is_valid_utf8(const std::string & str) {
  797. const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data());
  798. const unsigned char* end = bytes + str.length();
  799. while (bytes < end) {
  800. if (*bytes <= 0x7F) {
  801. // 1-byte sequence (0xxxxxxx)
  802. bytes++;
  803. } else if ((*bytes & 0xE0) == 0xC0) {
  804. // 2-byte sequence (110xxxxx 10xxxxxx)
  805. if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80)
  806. return false;
  807. bytes += 2;
  808. } else if ((*bytes & 0xF0) == 0xE0) {
  809. // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx)
  810. if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80)
  811. return false;
  812. bytes += 3;
  813. } else if ((*bytes & 0xF8) == 0xF0) {
  814. // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
  815. if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 ||
  816. (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80)
  817. return false;
  818. bytes += 4;
  819. } else {
  820. // Invalid UTF-8 lead byte
  821. return false;
  822. }
  823. }
  824. return true;
  825. }
  826. static json format_tokenizer_response(const json & tokens) {
  827. return json {
  828. {"tokens", tokens}
  829. };
  830. }
  831. static json format_detokenized_response(const std::string & content) {
  832. return json {
  833. {"content", content}
  834. };
  835. }
  836. static json format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) {
  837. json data = json::array();
  838. for (const auto & lb : logit_bias) {
  839. data.push_back(json{
  840. {"bias", lb.bias},
  841. {"token", lb.token},
  842. });
  843. }
  844. return data;
  845. }
  846. static std::string safe_json_to_str(const json & data) {
  847. return data.dump(-1, ' ', false, json::error_handler_t::replace);
  848. }
  849. static std::vector<llama_token_data> get_token_probabilities(llama_context * ctx, int idx) {
  850. std::vector<llama_token_data> cur;
  851. const auto * logits = llama_get_logits_ith(ctx, idx);
  852. const llama_model * model = llama_get_model(ctx);
  853. const llama_vocab * vocab = llama_model_get_vocab(model);
  854. const int n_vocab = llama_vocab_n_tokens(vocab);
  855. cur.resize(n_vocab);
  856. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  857. cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
  858. }
  859. // sort tokens by logits
  860. std::sort(cur.begin(), cur.end(), [](const llama_token_data & a, const llama_token_data & b) {
  861. return a.logit > b.logit;
  862. });
  863. // apply softmax
  864. float max_l = cur[0].logit;
  865. float cum_sum = 0.0f;
  866. for (size_t i = 0; i < cur.size(); ++i) {
  867. float p = expf(cur[i].logit - max_l);
  868. cur[i].p = p;
  869. cum_sum += p;
  870. }
  871. for (size_t i = 0; i < cur.size(); ++i) {
  872. cur[i].p /= cum_sum;
  873. }
  874. return cur;
  875. }
  876. static bool are_lora_equal(
  877. const std::vector<common_adapter_lora_info> & l1,
  878. const std::vector<common_adapter_lora_info> & l2) {
  879. if (l1.size() != l2.size()) {
  880. return false;
  881. }
  882. for (size_t i = 0; i < l1.size(); ++i) {
  883. // we don't check lora.path to reduce the time complexity
  884. if (l1[i].scale != l2[i].scale || l1[i].ptr != l2[i].ptr) {
  885. return false;
  886. }
  887. }
  888. return true;
  889. }
  890. // parse lora config from JSON request, returned a copy of lora_base with updated scale
  891. static std::vector<common_adapter_lora_info> parse_lora_request(
  892. const std::vector<common_adapter_lora_info> & lora_base,
  893. const json & data) {
  894. std::vector<common_adapter_lora_info> lora(lora_base);
  895. int max_idx = lora.size();
  896. // clear existing value
  897. for (auto & entry : lora) {
  898. entry.scale = 0.0f;
  899. }
  900. // set value
  901. for (const auto & entry : data) {
  902. int id = json_value(entry, "id", -1);
  903. float scale = json_value(entry, "scale", 0.0f);
  904. if (0 <= id && id < max_idx) {
  905. lora[id].scale = scale;
  906. } else {
  907. throw std::runtime_error("invalid adapter id");
  908. }
  909. }
  910. return lora;
  911. }
  912. //
  913. // utils for interacting with libmtmd
  914. // (may need to refactor in near future)
  915. //
  916. /**
  917. * server_tokens is a helper to manage the input tokens and image for the server.
  918. * it is made this way to simplify the logic of KV cache management.
  919. */
  920. struct server_tokens {
  921. bool has_mtmd = false;
  922. private: // disallow accessing these members directly, risking out-of-sync
  923. // map a **start** position in tokens to the image chunk
  924. std::unordered_map<llama_pos, mtmd::input_chunk_ptr> map_pos_to_media;
  925. // list of tokens
  926. // it can include LLAMA_TOKEN_NULL, which is used to indicate a token that is not a text token
  927. // a mtmd_input_chunk can occupy multiple tokens, one llama_token per **position**
  928. // important: for models using mrope, an image can contain multiple tokens but will use only one **position**
  929. llama_tokens tokens;
  930. // for ex. with input of 5 text tokens and 2 images:
  931. // [0] [1] [2] [3] [4] [img0] [img0] [img0] [img1] [img1]
  932. // pos 0 1 2 3 4 5 6 7 8 9
  933. // map_pos_to_media will contain: {5, img0}, {8, img1}
  934. public:
  935. server_tokens() = default;
  936. ~server_tokens() = default;
  937. // Prevent copying
  938. server_tokens(const server_tokens&) = delete;
  939. server_tokens& operator=(const server_tokens&) = delete;
  940. // Allow moving (usually implicitly generated if members are movable)
  941. server_tokens(server_tokens&&) = default;
  942. server_tokens& operator=(server_tokens&&) = default;
  943. // Allow accessing elements using [] operator
  944. llama_token operator[](size_t index) { return tokens[index]; }
  945. const llama_token& operator[](size_t index) const { return tokens[index]; }
  946. server_tokens(mtmd::input_chunks & mtmd_chunks, bool has_mtmd) : has_mtmd(has_mtmd) {
  947. for (size_t i = 0; i < mtmd_chunks.size(); ++i) {
  948. push_back(mtmd_chunks[i]);
  949. }
  950. }
  951. server_tokens(llama_tokens & tokens, bool has_mtmd) : has_mtmd(has_mtmd), tokens(tokens) {}
  952. // for debugging
  953. std::string str() const {
  954. std::ostringstream oss;
  955. oss << "tokens: ";
  956. for (const auto & t : tokens) {
  957. if (t == LLAMA_TOKEN_NULL) {
  958. oss << "<embd> ";
  959. } else {
  960. oss << t << " ";
  961. }
  962. }
  963. oss << "\n";
  964. oss << "image pos: ";
  965. for (const auto & it : map_pos_to_media) {
  966. oss << it.first << ", ";
  967. }
  968. return oss.str();
  969. }
  970. const mtmd::input_chunk_ptr & find_chunk(llama_pos pos) const {
  971. auto it = map_pos_to_media.find(pos);
  972. if (it != map_pos_to_media.end()) {
  973. return it->second;
  974. } else {
  975. throw std::runtime_error("Chunk not found");
  976. }
  977. }
  978. void push_back(llama_token tok) {
  979. if (tok == LLAMA_TOKEN_NULL) {
  980. throw std::runtime_error("Invalid token");
  981. }
  982. tokens.emplace_back(tok);
  983. }
  984. // will create a copy of the chunk if it contains non-text data
  985. void push_back(const mtmd_input_chunk * chunk) {
  986. auto type = mtmd_input_chunk_get_type(chunk);
  987. if (type == MTMD_INPUT_CHUNK_TYPE_IMAGE || type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  988. GGML_ASSERT(has_mtmd);
  989. const int n_pos = mtmd_input_chunk_get_n_pos(chunk);
  990. llama_pos start_pos = tokens.size();
  991. for (int i = 0; i < n_pos; ++i) {
  992. tokens.emplace_back(LLAMA_TOKEN_NULL);
  993. }
  994. mtmd::input_chunk_ptr new_chunk(mtmd_input_chunk_copy(chunk));
  995. map_pos_to_media[start_pos] = std::move(new_chunk);
  996. } else if (type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  997. size_t n_tokens;
  998. auto text_tokens = mtmd_input_chunk_get_tokens_text(chunk, &n_tokens);
  999. for (size_t i = 0; i < n_tokens; ++i) {
  1000. push_back(text_tokens[i]);
  1001. }
  1002. } else {
  1003. GGML_ABORT("Invalid chunk type");
  1004. }
  1005. }
  1006. // for compatibility with context shift and prompt truncation
  1007. void insert(const llama_tokens & inp_tokens) {
  1008. GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
  1009. tokens.insert(tokens.end(), inp_tokens.begin(), inp_tokens.end());
  1010. }
  1011. // for compatibility with speculative decoding, ctx shift, slot save/load
  1012. const llama_tokens & get_text_tokens() const {
  1013. GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
  1014. return tokens;
  1015. }
  1016. // for compatibility with speculative decoding
  1017. void set_token(llama_pos pos, llama_token id) {
  1018. GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
  1019. tokens[pos] = id;
  1020. }
  1021. size_t size() const {
  1022. return tokens.size();
  1023. }
  1024. bool empty() const {
  1025. return tokens.empty();
  1026. }
  1027. void clear() {
  1028. tokens.clear();
  1029. }
  1030. void keep_first(size_t n) {
  1031. GGML_ASSERT(n <= tokens.size());
  1032. if (has_mtmd) {
  1033. if (n == tokens.size()) {
  1034. return; // nothing to do
  1035. }
  1036. // we throw an error if we try to remove a token in the middle of an image
  1037. // for ex. with input of 5 text tokens and 2 images:
  1038. // [0] [1] [2] [3] [4] [img0] [img0] [img0] [img1] [img1]
  1039. // n 1 2 3 4 5 6 7 8 9 10
  1040. // allowed to resize ^ ^
  1041. // disallowed to resize ^ ^ ^
  1042. if (n > 0) {
  1043. llama_token last_token = tokens[n - 1];
  1044. // make sure we never remove tokens in the middle of an image
  1045. if (last_token == LLAMA_TOKEN_NULL) {
  1046. find_chunk(n - 1); // will throw an error if the token is not begin-of-chunk
  1047. }
  1048. }
  1049. // remove all image chunks that are not used anymore
  1050. for (auto it = map_pos_to_media.begin(); it != map_pos_to_media.end(); ) {
  1051. llama_pos pos = it->first;
  1052. if (pos >= (llama_pos)n) {
  1053. it = map_pos_to_media.erase(it);
  1054. } else {
  1055. ++it;
  1056. }
  1057. }
  1058. }
  1059. tokens.resize(n);
  1060. }
  1061. std::string detokenize(const llama_context * ctx, bool special) const {
  1062. llama_tokens text_tokens;
  1063. text_tokens.reserve(tokens.size());
  1064. for (const auto & t : tokens) {
  1065. if (t != LLAMA_TOKEN_NULL) {
  1066. text_tokens.push_back(t);
  1067. }
  1068. }
  1069. return common_detokenize(ctx, text_tokens, special);
  1070. }
  1071. size_t get_common_prefix(const server_tokens & b) const {
  1072. size_t max_idx = std::min(tokens.size(), b.tokens.size());
  1073. for (size_t i = 0; i < max_idx; ++i) {
  1074. auto & ai = tokens[i];
  1075. auto & bi = b.tokens[i];
  1076. if (ai == LLAMA_TOKEN_NULL && bi == LLAMA_TOKEN_NULL) {
  1077. GGML_ASSERT(has_mtmd);
  1078. const auto & a_chunk = find_chunk(i);
  1079. const auto & b_chunk = b.find_chunk(i);
  1080. GGML_ASSERT(a_chunk && b_chunk);
  1081. std::string ai_id = mtmd_input_chunk_get_id(a_chunk.get());
  1082. std::string bi_id = mtmd_input_chunk_get_id(b_chunk.get());
  1083. size_t a_pos = mtmd_input_chunk_get_n_pos(a_chunk.get());
  1084. size_t b_pos = mtmd_input_chunk_get_n_pos(b_chunk.get());
  1085. if (ai_id == bi_id && a_pos == b_pos) {
  1086. GGML_ASSERT(a_pos > 0 && "Invalid media chunk"); // should never happen
  1087. i += a_pos - 1; // will be +1 by the for loop
  1088. continue;
  1089. } else {
  1090. return i;
  1091. }
  1092. } else if (ai == bi) {
  1093. continue;
  1094. } else {
  1095. return i;
  1096. }
  1097. }
  1098. return max_idx; // all tokens are equal
  1099. }
  1100. // make sure all text tokens are within the vocab range
  1101. bool validate(const struct llama_context * ctx) const {
  1102. const llama_model * model = llama_get_model(ctx);
  1103. const llama_vocab * vocab = llama_model_get_vocab(model);
  1104. const int32_t n_vocab = llama_vocab_n_tokens(vocab);
  1105. for (size_t i = 0; i < tokens.size(); ++i) {
  1106. auto & t = tokens[i];
  1107. if (t == LLAMA_TOKEN_NULL) {
  1108. try {
  1109. const auto & chunk = find_chunk(i);
  1110. size_t n_pos = mtmd_input_chunk_get_n_pos(chunk.get());
  1111. i += n_pos - 1; // will be +1 by the for loop
  1112. } catch (const std::exception & e) {
  1113. return false;
  1114. }
  1115. } else if (t < 0 || t >= n_vocab) {
  1116. return false;
  1117. }
  1118. }
  1119. return true;
  1120. }
  1121. // encode and decode the image chunk
  1122. int32_t process_chunk(
  1123. llama_context * ctx,
  1124. mtmd_context * mctx,
  1125. llama_pos n_past,
  1126. int32_t seq_id,
  1127. llama_pos & n_pos_out) {
  1128. auto & chunk = find_chunk(n_past);
  1129. const char * name = mtmd_input_chunk_get_type(chunk.get()) == MTMD_INPUT_CHUNK_TYPE_IMAGE
  1130. ? "image" : "audio";
  1131. SRV_INF("processing %s...\n", name);
  1132. int32_t n_batch = llama_n_batch(ctx);
  1133. int64_t t0 = ggml_time_ms();
  1134. llama_pos new_n_past = n_past;
  1135. int32_t result = mtmd_helper_eval_chunk_single(mctx, ctx,
  1136. chunk.get(),
  1137. n_past,
  1138. seq_id,
  1139. n_batch,
  1140. true, // logits last
  1141. &new_n_past);
  1142. SRV_INF("%s processed in %" PRId64 " ms\n", name, ggml_time_ms() - t0);
  1143. if (result != 0) {
  1144. LOG_ERR("mtmd_helper_eval failed with status %d", result);
  1145. n_pos_out = n_past;
  1146. return result;
  1147. }
  1148. n_pos_out = new_n_past;
  1149. return 0;
  1150. }
  1151. };
  1152. // Computes FNV-1a hash of the data
  1153. static std::string fnv_hash(const uint8_t * data, size_t len) {
  1154. const uint64_t fnv_prime = 0x100000001b3ULL;
  1155. uint64_t hash = 0xcbf29ce484222325ULL;
  1156. for (size_t i = 0; i < len; ++i) {
  1157. hash ^= data[i];
  1158. hash *= fnv_prime;
  1159. }
  1160. return std::to_string(hash);
  1161. }