utils.hpp 56 KB

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