utils.hpp 49 KB

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