utils.hpp 57 KB

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