utils.hpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  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. // disable Nagle's algorithm
  13. #define CPPHTTPLIB_TCP_NODELAY true
  14. #include <cpp-httplib/httplib.h>
  15. #define JSON_ASSERT GGML_ASSERT
  16. #include <nlohmann/json.hpp>
  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. // Get EOS token - use SEP token as fallback if EOS is not available
  235. llama_token eos_token = llama_vocab_eos(vocab);
  236. if (eos_token == LLAMA_TOKEN_NULL) {
  237. eos_token = llama_vocab_sep(vocab);
  238. }
  239. result.reserve(doc.size() + query.size() + 4);
  240. if (llama_vocab_get_add_bos(vocab)) {
  241. result.push_back(llama_vocab_bos(vocab));
  242. }
  243. result.insert(result.end(), query.begin(), query.end());
  244. if (llama_vocab_get_add_eos(vocab)) {
  245. result.push_back(eos_token);
  246. }
  247. if (llama_vocab_get_add_sep(vocab)) {
  248. result.push_back(llama_vocab_sep(vocab));
  249. }
  250. result.insert(result.end(), doc.begin(), doc.end());
  251. if (llama_vocab_get_add_eos(vocab)) {
  252. result.push_back(eos_token);
  253. }
  254. return result;
  255. }
  256. // format infill task
  257. static llama_tokens format_infill(
  258. const llama_vocab * vocab,
  259. const json & input_prefix,
  260. const json & input_suffix,
  261. const json & input_extra,
  262. const int n_batch,
  263. const int n_predict,
  264. const int n_ctx,
  265. const bool spm_infill,
  266. const llama_tokens & tokens_prompt
  267. ) {
  268. // TODO: optimize this block by reducing memory allocations and movement
  269. // use FIM repo-level pattern:
  270. // ref: https://arxiv.org/pdf/2409.12186
  271. //
  272. // [FIM_REP]myproject
  273. // [FIM_SEP]filename0
  274. // extra chunk 0
  275. // [FIM_SEP]filename1
  276. // extra chunk 1
  277. // ...
  278. // [FIM_SEP]filename
  279. // [FIM_PRE]prefix[FIM_SUF]suffix[FIM_MID]prompt
  280. //
  281. llama_tokens extra_tokens;
  282. extra_tokens.reserve(n_ctx);
  283. auto tokens_prefix = tokenize_mixed(vocab, input_prefix, false, false);
  284. auto tokens_suffix = tokenize_mixed(vocab, input_suffix, false, false);
  285. if (llama_vocab_fim_rep(vocab) != LLAMA_TOKEN_NULL) {
  286. // TODO: make project name an input
  287. static const auto k_fim_repo = common_tokenize(vocab, "myproject\n", false, false);
  288. extra_tokens.push_back(llama_vocab_fim_rep(vocab));
  289. extra_tokens.insert(extra_tokens.end(), k_fim_repo.begin(), k_fim_repo.end());
  290. }
  291. for (const auto & chunk : input_extra) {
  292. // { "text": string, "filename": string }
  293. const std::string text = json_value(chunk, "text", std::string());
  294. const std::string filename = json_value(chunk, "filename", std::string("tmp"));
  295. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  296. const auto k_fim_file = common_tokenize(vocab, filename + "\n", false, false);
  297. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  298. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  299. } else {
  300. // chunk separator in binary form to avoid confusing the AI
  301. 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};
  302. static const auto k_chunk_prefix_tokens = common_tokenize(vocab, k_chunk_prefix_str, false, false);
  303. extra_tokens.insert(extra_tokens.end(), k_chunk_prefix_tokens.begin(), k_chunk_prefix_tokens.end());
  304. }
  305. const auto chunk_tokens = common_tokenize(vocab, text, false, false);
  306. extra_tokens.insert(extra_tokens.end(), chunk_tokens.begin(), chunk_tokens.end());
  307. }
  308. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  309. // TODO: current filename
  310. static const auto k_fim_file = common_tokenize(vocab, "filename\n", false, false);
  311. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  312. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  313. }
  314. // for now pick FIM context to fit in a batch (ratio prefix:suffix = 3:1, TODO: configurable?)
  315. const int n_prefix_take = std::min<int>(tokens_prefix.size(), 3*(n_batch/4));
  316. const int n_suffix_take = std::min<int>(tokens_suffix.size(), std::max<int>(0, (n_batch/4) - (2 + tokens_prompt.size())));
  317. 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));
  318. // fill the rest of the context with extra chunks
  319. const int n_extra_take = std::min<int>(std::max<int>(0, n_ctx - (n_batch) - 2*n_predict), extra_tokens.size());
  320. tokens_prefix.erase(tokens_prefix.begin(), tokens_prefix.begin() + tokens_prefix.size() - n_prefix_take);
  321. tokens_suffix.resize(n_suffix_take);
  322. tokens_prefix.insert(tokens_prefix.begin(), llama_vocab_fim_pre(vocab));
  323. tokens_prefix.insert(tokens_prefix.end(), tokens_prompt.begin(), tokens_prompt.end());
  324. tokens_suffix.insert(tokens_suffix.begin(), llama_vocab_fim_suf(vocab));
  325. auto embd_inp = spm_infill ? tokens_suffix : tokens_prefix;
  326. auto embd_end = spm_infill ? tokens_prefix : tokens_suffix;
  327. if (llama_vocab_get_add_bos(vocab)) {
  328. embd_inp.insert(embd_inp.begin(), llama_vocab_bos(vocab));
  329. }
  330. SRV_DBG("extra: n_ctx = %d, n_extra_take = %d, n_extra = %d\n", n_ctx, n_extra_take, (int) extra_tokens.size());
  331. // put the extra context before the FIM prefix
  332. embd_inp.insert(embd_inp.begin(), extra_tokens.end() - n_extra_take, extra_tokens.end());
  333. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  334. embd_inp.push_back(llama_vocab_fim_mid(vocab));
  335. return embd_inp;
  336. }
  337. //
  338. // base64 utils (TODO: move to common in the future)
  339. //
  340. static const std::string base64_chars =
  341. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  342. "abcdefghijklmnopqrstuvwxyz"
  343. "0123456789+/";
  344. static inline bool is_base64(uint8_t c) {
  345. return (isalnum(c) || (c == '+') || (c == '/'));
  346. }
  347. static inline raw_buffer base64_decode(const std::string & encoded_string) {
  348. int i = 0;
  349. int j = 0;
  350. int in_ = 0;
  351. int in_len = encoded_string.size();
  352. uint8_t char_array_4[4];
  353. uint8_t char_array_3[3];
  354. raw_buffer ret;
  355. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  356. char_array_4[i++] = encoded_string[in_]; in_++;
  357. if (i == 4) {
  358. for (i = 0; i < 4; i++) {
  359. char_array_4[i] = base64_chars.find(char_array_4[i]);
  360. }
  361. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  362. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  363. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  364. for (i = 0; (i < 3); i++) {
  365. ret.push_back(char_array_3[i]);
  366. }
  367. i = 0;
  368. }
  369. }
  370. if (i) {
  371. for (j = i; j < 4; j++) {
  372. char_array_4[j] = 0;
  373. }
  374. for (j = 0; j < 4; j++) {
  375. char_array_4[j] = base64_chars.find(char_array_4[j]);
  376. }
  377. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  378. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  379. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  380. for (j = 0; j < i - 1; j++) {
  381. ret.push_back(char_array_3[j]);
  382. }
  383. }
  384. return ret;
  385. }
  386. //
  387. // random string / id
  388. //
  389. static std::string random_string() {
  390. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  391. std::random_device rd;
  392. std::mt19937 generator(rd());
  393. std::string result(32, ' ');
  394. for (int i = 0; i < 32; ++i) {
  395. result[i] = str[generator() % str.size()];
  396. }
  397. return result;
  398. }
  399. static std::string gen_chatcmplid() {
  400. return "chatcmpl-" + random_string();
  401. }
  402. static std::string gen_tool_call_id() {
  403. return random_string();
  404. }
  405. //
  406. // other common utils
  407. //
  408. // TODO: reuse llama_detokenize
  409. template <class Iter>
  410. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  411. std::string ret;
  412. for (; begin != end; ++begin) {
  413. ret += common_token_to_piece(ctx, *begin);
  414. }
  415. return ret;
  416. }
  417. // format incomplete utf-8 multibyte character for output
  418. static std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  419. std::string out = token == LLAMA_TOKEN_NULL ? "" : common_token_to_piece(ctx, token);
  420. // if the size is 1 and first bit is 1, meaning it's a partial character
  421. // (size > 1 meaning it's already a known token)
  422. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  423. std::stringstream ss;
  424. ss << std::hex << (out[0] & 0xff);
  425. std::string res(ss.str());
  426. out = "byte: \\x" + res;
  427. }
  428. return out;
  429. }
  430. static bool server_sent_event(httplib::DataSink & sink, const char * event, const json & data) {
  431. const std::string str =
  432. std::string(event) + ": " +
  433. data.dump(-1, ' ', false, json::error_handler_t::replace) +
  434. "\n\n"; // required by RFC 8895 - A message is terminated by a blank line (two line terminators in a row).
  435. LOG_DBG("data stream, to_send: %s", str.c_str());
  436. return sink.write(str.c_str(), str.size());
  437. }
  438. //
  439. // OAI utils
  440. //
  441. // used by /completions endpoint
  442. static json oaicompat_completion_params_parse(const json & body) {
  443. json llama_params;
  444. if (!body.contains("prompt")) {
  445. throw std::runtime_error("\"prompt\" is required");
  446. }
  447. // Handle "stop" field
  448. if (body.contains("stop") && body.at("stop").is_string()) {
  449. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  450. } else {
  451. llama_params["stop"] = json_value(body, "stop", json::array());
  452. }
  453. // Handle "n" field
  454. int n_choices = json_value(body, "n", 1);
  455. if (n_choices != 1) {
  456. throw std::runtime_error("Only one completion choice is allowed");
  457. }
  458. // Handle "echo" field
  459. if (json_value(body, "echo", false)) {
  460. throw std::runtime_error("Only no echo is supported");
  461. }
  462. // Params supported by OAI but unsupported by llama.cpp
  463. static const std::vector<std::string> unsupported_params { "best_of", "suffix" };
  464. for (const auto & param : unsupported_params) {
  465. if (body.contains(param)) {
  466. throw std::runtime_error("Unsupported param: " + param);
  467. }
  468. }
  469. // Copy remaining properties to llama_params
  470. for (const auto & item : body.items()) {
  471. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  472. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  473. llama_params[item.key()] = item.value();
  474. }
  475. }
  476. return llama_params;
  477. }
  478. struct oaicompat_parser_options {
  479. bool use_jinja;
  480. bool prefill_assistant;
  481. common_reasoning_format reasoning_format;
  482. common_chat_templates * tmpls;
  483. bool allow_image;
  484. bool allow_audio;
  485. bool enable_thinking = true;
  486. };
  487. // used by /chat/completions endpoint
  488. static json oaicompat_chat_params_parse(
  489. json & body, /* openai api json semantics */
  490. const oaicompat_parser_options & opt,
  491. std::vector<raw_buffer> & out_files)
  492. {
  493. json llama_params;
  494. auto tools = json_value(body, "tools", json());
  495. auto has_tools = tools.is_array() && !tools.empty();
  496. auto stream = json_value(body, "stream", false);
  497. auto tool_choice = json_value(body, "tool_choice", std::string("auto"));
  498. if (!opt.use_jinja) {
  499. if (has_tools) {
  500. throw std::runtime_error("tools param requires --jinja flag");
  501. }
  502. if (tool_choice != "auto") {
  503. throw std::runtime_error("tool_choice param requires --jinja flag");
  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. if (type == "image_url") {
  561. if (!opt.allow_image) {
  562. throw std::runtime_error("image input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
  563. }
  564. json image_url = json_value(p, "image_url", json::object());
  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_marker();
  601. p.erase("image_url");
  602. } else if (type == "input_audio") {
  603. if (!opt.allow_audio) {
  604. throw std::runtime_error("audio input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
  605. }
  606. json input_audio = json_value(p, "input_audio", json::object());
  607. std::string data = json_value(input_audio, "data", std::string());
  608. std::string format = json_value(input_audio, "format", std::string());
  609. // while we also support flac, we don't allow it here so we matches the OAI spec
  610. if (format != "wav" && format != "mp3") {
  611. throw std::runtime_error("input_audio.format must be either 'wav' or 'mp3'");
  612. }
  613. auto decoded_data = base64_decode(data); // expected to be base64 encoded
  614. out_files.push_back(decoded_data);
  615. // replace this chunk with a marker
  616. p["type"] = "text";
  617. p["text"] = mtmd_default_marker();
  618. p.erase("input_audio");
  619. } else if (type != "text") {
  620. throw std::runtime_error("unsupported content[].type");
  621. }
  622. }
  623. }
  624. common_chat_templates_inputs inputs;
  625. inputs.messages = common_chat_msgs_parse_oaicompat(messages);
  626. inputs.tools = common_chat_tools_parse_oaicompat(tools);
  627. inputs.tool_choice = common_chat_tool_choice_parse_oaicompat(tool_choice);
  628. inputs.json_schema = json_schema.is_null() ? "" : json_schema.dump();
  629. inputs.grammar = grammar;
  630. inputs.use_jinja = opt.use_jinja;
  631. inputs.parallel_tool_calls = json_value(body, "parallel_tool_calls", false);
  632. inputs.add_generation_prompt = json_value(body, "add_generation_prompt", true);
  633. inputs.reasoning_format = opt.reasoning_format;
  634. inputs.enable_thinking = opt.enable_thinking;
  635. if (!inputs.tools.empty() && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
  636. if (body.contains("grammar")) {
  637. throw std::runtime_error("Cannot use custom grammar constraints with tools.");
  638. }
  639. llama_params["parse_tool_calls"] = true;
  640. }
  641. // if the assistant message appears at the end of list, we do not add end-of-turn token
  642. // for ex. this can be useful to modify the reasoning process in reasoning models
  643. bool prefill_assistant_message = !inputs.messages.empty() && inputs.messages.back().role == "assistant" && opt.prefill_assistant;
  644. common_chat_msg last_message;
  645. if (prefill_assistant_message) {
  646. last_message = inputs.messages.back();
  647. inputs.messages.pop_back();
  648. /* sanity check, max one assistant message at the end of the list */
  649. if (!inputs.messages.empty() && inputs.messages.back().role == "assistant"){
  650. throw std::runtime_error("Cannot have 2 or more assistant messages at the end of the list.");
  651. }
  652. /* TODO: test this properly */
  653. inputs.reasoning_format = COMMON_REASONING_FORMAT_NONE;
  654. inputs.add_generation_prompt = true;
  655. }
  656. // Apply chat template to the list of messages
  657. auto chat_params = common_chat_templates_apply(opt.tmpls, inputs);
  658. /* Append assistant prefilled message */
  659. if (prefill_assistant_message) {
  660. chat_params.prompt += last_message.content;
  661. }
  662. llama_params["chat_format"] = static_cast<int>(chat_params.format);
  663. llama_params["prompt"] = chat_params.prompt;
  664. if (!chat_params.grammar.empty()) {
  665. llama_params["grammar"] = chat_params.grammar;
  666. }
  667. llama_params["grammar_lazy"] = chat_params.grammar_lazy;
  668. auto grammar_triggers = json::array();
  669. for (const auto & trigger : chat_params.grammar_triggers) {
  670. server_grammar_trigger ct(trigger);
  671. grammar_triggers.push_back(ct.to_json());
  672. }
  673. llama_params["grammar_triggers"] = grammar_triggers;
  674. llama_params["preserved_tokens"] = chat_params.preserved_tokens;
  675. llama_params["thinking_forced_open"] = chat_params.thinking_forced_open;
  676. for (const auto & stop : chat_params.additional_stops) {
  677. llama_params["stop"].push_back(stop);
  678. }
  679. // Handle "n" field
  680. int n_choices = json_value(body, "n", 1);
  681. if (n_choices != 1) {
  682. throw std::runtime_error("Only one completion choice is allowed");
  683. }
  684. // Handle "logprobs" field
  685. // 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
  686. if (json_value(body, "logprobs", false)) {
  687. if (has_tools && stream) {
  688. throw std::runtime_error("logprobs is not supported with tools + stream");
  689. }
  690. llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
  691. } else if (body.contains("top_logprobs") && !body.at("top_logprobs").is_null()) {
  692. throw std::runtime_error("top_logprobs requires logprobs to be set to true");
  693. }
  694. // Copy remaining properties to llama_params
  695. // This allows user to use llama.cpp-specific params like "mirostat", ... via OAI endpoint.
  696. // See "launch_slot_with_task()" for a complete list of params supported by llama.cpp
  697. for (const auto & item : body.items()) {
  698. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  699. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  700. llama_params[item.key()] = item.value();
  701. }
  702. }
  703. return llama_params;
  704. }
  705. static json format_embeddings_response_oaicompat(const json & request, const json & embeddings, bool use_base64 = false) {
  706. json data = json::array();
  707. int32_t n_tokens = 0;
  708. int i = 0;
  709. for (const auto & elem : embeddings) {
  710. json embedding_obj;
  711. if (use_base64) {
  712. const auto& vec = json_value(elem, "embedding", json::array()).get<std::vector<float>>();
  713. const char* data_ptr = reinterpret_cast<const char*>(vec.data());
  714. size_t data_size = vec.size() * sizeof(float);
  715. embedding_obj = {
  716. {"embedding", base64::encode(data_ptr, data_size)},
  717. {"index", i++},
  718. {"object", "embedding"},
  719. {"encoding_format", "base64"}
  720. };
  721. } else {
  722. embedding_obj = {
  723. {"embedding", json_value(elem, "embedding", json::array())},
  724. {"index", i++},
  725. {"object", "embedding"}
  726. };
  727. }
  728. data.push_back(embedding_obj);
  729. n_tokens += json_value(elem, "tokens_evaluated", 0);
  730. }
  731. json res = json {
  732. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  733. {"object", "list"},
  734. {"usage", json {
  735. {"prompt_tokens", n_tokens},
  736. {"total_tokens", n_tokens}
  737. }},
  738. {"data", data}
  739. };
  740. return res;
  741. }
  742. static json format_response_rerank(
  743. const json & request,
  744. const json & ranks,
  745. bool is_tei_format,
  746. std::vector<std::string> & texts) {
  747. json res;
  748. if (is_tei_format) {
  749. // TEI response format
  750. res = json::array();
  751. bool return_text = json_value(request, "return_text", false);
  752. for (const auto & rank : ranks) {
  753. int index = json_value(rank, "index", 0);
  754. json elem = json{
  755. {"index", index},
  756. {"score", json_value(rank, "score", 0.0)},
  757. };
  758. if (return_text) {
  759. elem["text"] = std::move(texts[index]);
  760. }
  761. res.push_back(elem);
  762. }
  763. } else {
  764. // Jina response format
  765. json results = json::array();
  766. int32_t n_tokens = 0;
  767. for (const auto & rank : ranks) {
  768. results.push_back(json{
  769. {"index", json_value(rank, "index", 0)},
  770. {"relevance_score", json_value(rank, "score", 0.0)},
  771. });
  772. n_tokens += json_value(rank, "tokens_evaluated", 0);
  773. }
  774. res = json{
  775. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  776. {"object", "list"},
  777. {"usage", json{
  778. {"prompt_tokens", n_tokens},
  779. {"total_tokens", n_tokens}
  780. }},
  781. {"results", results}
  782. };
  783. }
  784. return res;
  785. }
  786. static bool is_valid_utf8(const std::string & str) {
  787. const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data());
  788. const unsigned char* end = bytes + str.length();
  789. while (bytes < end) {
  790. if (*bytes <= 0x7F) {
  791. // 1-byte sequence (0xxxxxxx)
  792. bytes++;
  793. } else if ((*bytes & 0xE0) == 0xC0) {
  794. // 2-byte sequence (110xxxxx 10xxxxxx)
  795. if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80)
  796. return false;
  797. bytes += 2;
  798. } else if ((*bytes & 0xF0) == 0xE0) {
  799. // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx)
  800. if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80)
  801. return false;
  802. bytes += 3;
  803. } else if ((*bytes & 0xF8) == 0xF0) {
  804. // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
  805. if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 ||
  806. (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80)
  807. return false;
  808. bytes += 4;
  809. } else {
  810. // Invalid UTF-8 lead byte
  811. return false;
  812. }
  813. }
  814. return true;
  815. }
  816. static json format_tokenizer_response(const json & tokens) {
  817. return json {
  818. {"tokens", tokens}
  819. };
  820. }
  821. static json format_detokenized_response(const std::string & content) {
  822. return json {
  823. {"content", content}
  824. };
  825. }
  826. static json format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) {
  827. json data = json::array();
  828. for (const auto & lb : logit_bias) {
  829. data.push_back(json{
  830. {"bias", lb.bias},
  831. {"token", lb.token},
  832. });
  833. }
  834. return data;
  835. }
  836. static std::string safe_json_to_str(const json & data) {
  837. return data.dump(-1, ' ', false, json::error_handler_t::replace);
  838. }
  839. static std::vector<llama_token_data> get_token_probabilities(llama_context * ctx, int idx) {
  840. std::vector<llama_token_data> cur;
  841. const auto * logits = llama_get_logits_ith(ctx, idx);
  842. const llama_model * model = llama_get_model(ctx);
  843. const llama_vocab * vocab = llama_model_get_vocab(model);
  844. const int n_vocab = llama_vocab_n_tokens(vocab);
  845. cur.resize(n_vocab);
  846. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  847. cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
  848. }
  849. // sort tokens by logits
  850. std::sort(cur.begin(), cur.end(), [](const llama_token_data & a, const llama_token_data & b) {
  851. return a.logit > b.logit;
  852. });
  853. // apply softmax
  854. float max_l = cur[0].logit;
  855. float cum_sum = 0.0f;
  856. for (size_t i = 0; i < cur.size(); ++i) {
  857. float p = expf(cur[i].logit - max_l);
  858. cur[i].p = p;
  859. cum_sum += p;
  860. }
  861. for (size_t i = 0; i < cur.size(); ++i) {
  862. cur[i].p /= cum_sum;
  863. }
  864. return cur;
  865. }
  866. static bool are_lora_equal(
  867. const std::vector<common_adapter_lora_info> & l1,
  868. const std::vector<common_adapter_lora_info> & l2) {
  869. if (l1.size() != l2.size()) {
  870. return false;
  871. }
  872. for (size_t i = 0; i < l1.size(); ++i) {
  873. // we don't check lora.path to reduce the time complexity
  874. if (l1[i].scale != l2[i].scale || l1[i].ptr != l2[i].ptr) {
  875. return false;
  876. }
  877. }
  878. return true;
  879. }
  880. // parse lora config from JSON request, returned a copy of lora_base with updated scale
  881. static std::vector<common_adapter_lora_info> parse_lora_request(
  882. const std::vector<common_adapter_lora_info> & lora_base,
  883. const json & data) {
  884. std::vector<common_adapter_lora_info> lora(lora_base);
  885. int max_idx = lora.size();
  886. // clear existing value
  887. for (auto & entry : lora) {
  888. entry.scale = 0.0f;
  889. }
  890. // set value
  891. for (const auto & entry : data) {
  892. int id = json_value(entry, "id", -1);
  893. float scale = json_value(entry, "scale", 0.0f);
  894. if (0 <= id && id < max_idx) {
  895. lora[id].scale = scale;
  896. } else {
  897. throw std::runtime_error("invalid adapter id");
  898. }
  899. }
  900. return lora;
  901. }
  902. //
  903. // utils for interacting with libmtmd
  904. // (may need to refactor in near future)
  905. //
  906. /**
  907. * server_tokens is a helper to manage the input tokens and image for the server.
  908. * it is made this way to simplify the logic of KV cache management.
  909. */
  910. struct server_tokens {
  911. bool has_mtmd = false;
  912. private: // disallow accessing these members directly, risking out-of-sync
  913. // map a **start** position in tokens to the image chunk
  914. std::unordered_map<llama_pos, mtmd::input_chunk_ptr> map_pos_to_media;
  915. // list of tokens
  916. // it can include LLAMA_TOKEN_NULL, which is used to indicate a token that is not a text token
  917. // a mtmd_input_chunk can occupy multiple tokens, one llama_token per **position**
  918. // important: for models using mrope, an image can contain multiple tokens but will use only one **position**
  919. llama_tokens tokens;
  920. // for ex. with input of 5 text tokens and 2 images:
  921. // [0] [1] [2] [3] [4] [img0] [img0] [img0] [img1] [img1]
  922. // pos 0 1 2 3 4 5 6 7 8 9
  923. // map_pos_to_media will contain: {5, img0}, {8, img1}
  924. public:
  925. server_tokens() = default;
  926. ~server_tokens() = default;
  927. // Prevent copying
  928. server_tokens(const server_tokens&) = delete;
  929. server_tokens& operator=(const server_tokens&) = delete;
  930. // Allow moving (usually implicitly generated if members are movable)
  931. server_tokens(server_tokens&&) = default;
  932. server_tokens& operator=(server_tokens&&) = default;
  933. // Allow accessing elements using [] operator
  934. llama_token operator[](size_t index) { return tokens[index]; }
  935. const llama_token& operator[](size_t index) const { return tokens[index]; }
  936. server_tokens(mtmd::input_chunks & mtmd_chunks, bool has_mtmd) : has_mtmd(has_mtmd) {
  937. for (size_t i = 0; i < mtmd_chunks.size(); ++i) {
  938. push_back(mtmd_chunks[i]);
  939. }
  940. }
  941. server_tokens(llama_tokens & tokens, bool has_mtmd) : has_mtmd(has_mtmd), tokens(tokens) {}
  942. // for debugging
  943. std::string str() const {
  944. std::ostringstream oss;
  945. oss << "tokens: ";
  946. for (const auto & t : tokens) {
  947. if (t == LLAMA_TOKEN_NULL) {
  948. oss << "<embd> ";
  949. } else {
  950. oss << t << " ";
  951. }
  952. }
  953. oss << "\n";
  954. oss << "image pos: ";
  955. for (const auto & it : map_pos_to_media) {
  956. oss << it.first << ", ";
  957. }
  958. return oss.str();
  959. }
  960. const mtmd::input_chunk_ptr & find_chunk(llama_pos pos) const {
  961. auto it = map_pos_to_media.find(pos);
  962. if (it != map_pos_to_media.end()) {
  963. return it->second;
  964. } else {
  965. throw std::runtime_error("Chunk not found");
  966. }
  967. }
  968. void push_back(llama_token tok) {
  969. if (tok == LLAMA_TOKEN_NULL) {
  970. throw std::runtime_error("Invalid token");
  971. }
  972. tokens.emplace_back(tok);
  973. }
  974. // will create a copy of the chunk if it contains non-text data
  975. void push_back(const mtmd_input_chunk * chunk) {
  976. auto type = mtmd_input_chunk_get_type(chunk);
  977. if (type == MTMD_INPUT_CHUNK_TYPE_IMAGE || type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  978. GGML_ASSERT(has_mtmd);
  979. const int n_pos = mtmd_input_chunk_get_n_pos(chunk);
  980. llama_pos start_pos = tokens.size();
  981. for (int i = 0; i < n_pos; ++i) {
  982. tokens.emplace_back(LLAMA_TOKEN_NULL);
  983. }
  984. mtmd::input_chunk_ptr new_chunk(mtmd_input_chunk_copy(chunk));
  985. map_pos_to_media[start_pos] = std::move(new_chunk);
  986. } else if (type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  987. size_t n_tokens;
  988. auto text_tokens = mtmd_input_chunk_get_tokens_text(chunk, &n_tokens);
  989. for (size_t i = 0; i < n_tokens; ++i) {
  990. push_back(text_tokens[i]);
  991. }
  992. } else {
  993. GGML_ABORT("Invalid chunk type");
  994. }
  995. }
  996. // for compatibility with context shift and prompt truncation
  997. void insert(const llama_tokens & inp_tokens) {
  998. GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
  999. tokens.insert(tokens.end(), inp_tokens.begin(), inp_tokens.end());
  1000. }
  1001. // for compatibility with speculative decoding, ctx shift, slot save/load
  1002. const llama_tokens & get_text_tokens() const {
  1003. GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
  1004. return tokens;
  1005. }
  1006. // for compatibility with speculative decoding
  1007. void set_token(llama_pos pos, llama_token id) {
  1008. GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
  1009. tokens[pos] = id;
  1010. }
  1011. size_t size() const {
  1012. return tokens.size();
  1013. }
  1014. bool empty() const {
  1015. return tokens.empty();
  1016. }
  1017. void clear() {
  1018. tokens.clear();
  1019. }
  1020. void keep_first(size_t n) {
  1021. GGML_ASSERT(n <= tokens.size());
  1022. if (has_mtmd) {
  1023. if (n == tokens.size()) {
  1024. return; // nothing to do
  1025. }
  1026. // we throw an error if we try to remove a token in the middle of an image
  1027. // for ex. with input of 5 text tokens and 2 images:
  1028. // [0] [1] [2] [3] [4] [img0] [img0] [img0] [img1] [img1]
  1029. // n 1 2 3 4 5 6 7 8 9 10
  1030. // allowed to resize ^ ^
  1031. // disallowed to resize ^ ^ ^
  1032. if (n > 0) {
  1033. llama_token last_token = tokens[n - 1];
  1034. // make sure we never remove tokens in the middle of an image
  1035. if (last_token == LLAMA_TOKEN_NULL) {
  1036. find_chunk(n - 1); // will throw an error if the token is not begin-of-chunk
  1037. }
  1038. }
  1039. // remove all image chunks that are not used anymore
  1040. for (auto it = map_pos_to_media.begin(); it != map_pos_to_media.end(); ) {
  1041. llama_pos pos = it->first;
  1042. if (pos >= (llama_pos)n) {
  1043. it = map_pos_to_media.erase(it);
  1044. } else {
  1045. ++it;
  1046. }
  1047. }
  1048. }
  1049. tokens.resize(n);
  1050. }
  1051. std::string detokenize(const llama_context * ctx, bool special) const {
  1052. llama_tokens text_tokens;
  1053. text_tokens.reserve(tokens.size());
  1054. for (const auto & t : tokens) {
  1055. if (t != LLAMA_TOKEN_NULL) {
  1056. text_tokens.push_back(t);
  1057. }
  1058. }
  1059. return common_detokenize(ctx, text_tokens, special);
  1060. }
  1061. size_t get_common_prefix(const server_tokens & b) const {
  1062. size_t max_idx = std::min(tokens.size(), b.tokens.size());
  1063. for (size_t i = 0; i < max_idx; ++i) {
  1064. auto & ai = tokens[i];
  1065. auto & bi = b.tokens[i];
  1066. if (ai == LLAMA_TOKEN_NULL && bi == LLAMA_TOKEN_NULL) {
  1067. GGML_ASSERT(has_mtmd);
  1068. const auto & a_chunk = find_chunk(i);
  1069. const auto & b_chunk = b.find_chunk(i);
  1070. GGML_ASSERT(a_chunk && b_chunk);
  1071. std::string ai_id = mtmd_input_chunk_get_id(a_chunk.get());
  1072. std::string bi_id = mtmd_input_chunk_get_id(b_chunk.get());
  1073. size_t a_pos = mtmd_input_chunk_get_n_pos(a_chunk.get());
  1074. size_t b_pos = mtmd_input_chunk_get_n_pos(b_chunk.get());
  1075. if (ai_id == bi_id && a_pos == b_pos) {
  1076. GGML_ASSERT(a_pos > 0 && "Invalid media chunk"); // should never happen
  1077. i += a_pos - 1; // will be +1 by the for loop
  1078. continue;
  1079. } else {
  1080. return i;
  1081. }
  1082. } else if (ai == bi) {
  1083. continue;
  1084. } else {
  1085. return i;
  1086. }
  1087. }
  1088. return max_idx; // all tokens are equal
  1089. }
  1090. // make sure all text tokens are within the vocab range
  1091. bool validate(const struct llama_context * ctx) const {
  1092. const llama_model * model = llama_get_model(ctx);
  1093. const llama_vocab * vocab = llama_model_get_vocab(model);
  1094. const int32_t n_vocab = llama_vocab_n_tokens(vocab);
  1095. for (size_t i = 0; i < tokens.size(); ++i) {
  1096. auto & t = tokens[i];
  1097. if (t == LLAMA_TOKEN_NULL) {
  1098. try {
  1099. const auto & chunk = find_chunk(i);
  1100. size_t n_pos = mtmd_input_chunk_get_n_pos(chunk.get());
  1101. i += n_pos - 1; // will be +1 by the for loop
  1102. } catch (const std::exception & e) {
  1103. return false;
  1104. }
  1105. } else if (t < 0 || t >= n_vocab) {
  1106. return false;
  1107. }
  1108. }
  1109. return true;
  1110. }
  1111. // encode and decode the image chunk
  1112. int32_t process_chunk(
  1113. llama_context * ctx,
  1114. mtmd_context * mctx,
  1115. llama_pos n_past,
  1116. int32_t seq_id,
  1117. llama_pos & n_pos_out) {
  1118. auto & chunk = find_chunk(n_past);
  1119. const char * name = mtmd_input_chunk_get_type(chunk.get()) == MTMD_INPUT_CHUNK_TYPE_IMAGE
  1120. ? "image" : "audio";
  1121. SRV_INF("processing %s...\n", name);
  1122. int32_t n_batch = llama_n_batch(ctx);
  1123. int64_t t0 = ggml_time_ms();
  1124. llama_pos new_n_past = n_past;
  1125. int32_t result = mtmd_helper_eval_chunk_single(mctx, ctx,
  1126. chunk.get(),
  1127. n_past,
  1128. seq_id,
  1129. n_batch,
  1130. true, // logits last
  1131. &new_n_past);
  1132. SRV_INF("%s processed in %" PRId64 " ms\n", name, ggml_time_ms() - t0);
  1133. if (result != 0) {
  1134. LOG_ERR("mtmd_helper_eval failed with status %d", result);
  1135. n_pos_out = n_past;
  1136. return result;
  1137. }
  1138. n_pos_out = new_n_past;
  1139. return 0;
  1140. }
  1141. };
  1142. // Computes FNV-1a hash of the data
  1143. static std::string fnv_hash(const uint8_t * data, size_t len) {
  1144. const uint64_t fnv_prime = 0x100000001b3ULL;
  1145. uint64_t hash = 0xcbf29ce484222325ULL;
  1146. for (size_t i = 0; i < len; ++i) {
  1147. hash ^= data[i];
  1148. hash *= fnv_prime;
  1149. }
  1150. return std::to_string(hash);
  1151. }