utils.hpp 47 KB

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