utils.hpp 48 KB

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