utils.hpp 57 KB

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