utils.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. #pragma once
  2. #include "llama.h"
  3. #include "common.h"
  4. #include "json.hpp"
  5. #include <string>
  6. #include <vector>
  7. #include <sstream>
  8. #include <random>
  9. #define DEFAULT_OAICOMPAT_MODEL "gpt-3.5-turbo-0613"
  10. using json = nlohmann::json;
  11. extern bool server_verbose;
  12. extern bool server_log_json;
  13. #ifndef SERVER_VERBOSE
  14. #define SERVER_VERBOSE 1
  15. #endif
  16. #if SERVER_VERBOSE != 1
  17. #define LOG_VERBOSE(MSG, ...)
  18. #else
  19. #define LOG_VERBOSE(MSG, ...) \
  20. do \
  21. { \
  22. if (server_verbose) \
  23. { \
  24. server_log("VERB", __func__, __LINE__, MSG, __VA_ARGS__); \
  25. } \
  26. } while (0)
  27. #endif
  28. #define LOG_ERROR( MSG, ...) server_log("ERR", __func__, __LINE__, MSG, __VA_ARGS__)
  29. #define LOG_WARNING(MSG, ...) server_log("WARN", __func__, __LINE__, MSG, __VA_ARGS__)
  30. #define LOG_INFO( MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
  31. template <typename T>
  32. static T json_value(const json &body, const std::string &key, const T &default_value) {
  33. // Fallback null to default value
  34. return body.contains(key) && !body.at(key).is_null()
  35. ? body.value(key, default_value)
  36. : default_value;
  37. }
  38. static inline void server_log(const char *level, const char *function, int line, const char *message, const nlohmann::ordered_json &extra) {
  39. std::stringstream ss_tid;
  40. ss_tid << std::this_thread::get_id();
  41. json log = nlohmann::ordered_json{
  42. {"tid", ss_tid.str()},
  43. {"timestamp", time(nullptr)},
  44. };
  45. if (server_log_json) {
  46. log.merge_patch( {
  47. {"level", level},
  48. {"function", function},
  49. {"line", line},
  50. {"msg", message},
  51. });
  52. if (!extra.empty()) {
  53. log.merge_patch(extra);
  54. }
  55. printf("%s\n", log.dump(-1, ' ', false, json::error_handler_t::replace).c_str());
  56. } else {
  57. char buf[1024];
  58. snprintf(buf, 1024, "%4s [%24s] %s", level, function, message);
  59. if (!extra.empty()) {
  60. log.merge_patch(extra);
  61. }
  62. std::stringstream ss;
  63. ss << buf << " |";
  64. for (const auto& el : log.items())
  65. {
  66. const std::string value = el.value().dump(-1, ' ', false, json::error_handler_t::replace);
  67. ss << " " << el.key() << "=" << value;
  68. }
  69. const std::string str = ss.str();
  70. printf("%.*s\n", (int)str.size(), str.data());
  71. fflush(stdout);
  72. }
  73. }
  74. //
  75. // chat template utils
  76. //
  77. // Check if the template supplied via "--chat-template" is supported or not. Returns true if it's valid
  78. inline bool verify_custom_template(const std::string & tmpl) {
  79. llama_chat_message chat[] = {{"user", "test"}};
  80. int res = llama_chat_apply_template(nullptr, tmpl.c_str(), chat, 1, true, nullptr, 0);
  81. return res >= 0;
  82. }
  83. // Format given chat. If tmpl is empty, we take the template from model metadata
  84. inline std::string format_chat(const struct llama_model * model, const std::string & tmpl, const std::vector<json> & messages) {
  85. size_t alloc_size = 0;
  86. // vector holding all allocated string to be passed to llama_chat_apply_template
  87. std::vector<std::string> str(messages.size() * 2);
  88. std::vector<llama_chat_message> chat(messages.size());
  89. for (size_t i = 0; i < messages.size(); ++i) {
  90. const auto & curr_msg = messages[i];
  91. str[i*2 + 0] = json_value(curr_msg, "role", std::string(""));
  92. str[i*2 + 1] = json_value(curr_msg, "content", std::string(""));
  93. alloc_size += str[i*2 + 1].length();
  94. chat[i].role = str[i*2 + 0].c_str();
  95. chat[i].content = str[i*2 + 1].c_str();
  96. }
  97. const char * ptr_tmpl = tmpl.empty() ? nullptr : tmpl.c_str();
  98. std::vector<char> buf(alloc_size * 2);
  99. // run the first time to get the total output length
  100. int32_t res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), true, buf.data(), buf.size());
  101. // if it turns out that our buffer is too small, we resize it
  102. if ((size_t) res > buf.size()) {
  103. buf.resize(res);
  104. res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), true, buf.data(), buf.size());
  105. }
  106. const std::string formatted_chat(buf.data(), res);
  107. LOG_VERBOSE("formatted_chat", {{"text", formatted_chat.c_str()}});
  108. return formatted_chat;
  109. }
  110. //
  111. // base64 utils (TODO: move to common in the future)
  112. //
  113. static const std::string base64_chars =
  114. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  115. "abcdefghijklmnopqrstuvwxyz"
  116. "0123456789+/";
  117. static inline bool is_base64(uint8_t c) {
  118. return (isalnum(c) || (c == '+') || (c == '/'));
  119. }
  120. static inline std::vector<uint8_t> base64_decode(const std::string & encoded_string) {
  121. int i = 0;
  122. int j = 0;
  123. int in_ = 0;
  124. int in_len = encoded_string.size();
  125. uint8_t char_array_4[4];
  126. uint8_t char_array_3[3];
  127. std::vector<uint8_t> ret;
  128. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  129. char_array_4[i++] = encoded_string[in_]; in_++;
  130. if (i == 4) {
  131. for (i = 0; i < 4; i++) {
  132. char_array_4[i] = base64_chars.find(char_array_4[i]);
  133. }
  134. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  135. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  136. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  137. for (i = 0; (i < 3); i++) {
  138. ret.push_back(char_array_3[i]);
  139. }
  140. i = 0;
  141. }
  142. }
  143. if (i) {
  144. for (j = i; j < 4; j++) {
  145. char_array_4[j] = 0;
  146. }
  147. for (j = 0; j < 4; j++) {
  148. char_array_4[j] = base64_chars.find(char_array_4[j]);
  149. }
  150. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  151. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  152. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  153. for (j = 0; j < i - 1; j++) {
  154. ret.push_back(char_array_3[j]);
  155. }
  156. }
  157. return ret;
  158. }
  159. //
  160. // random string / id
  161. //
  162. static std::string random_string() {
  163. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  164. std::random_device rd;
  165. std::mt19937 generator(rd());
  166. std::string result(32, ' ');
  167. for (int i = 0; i < 32; ++i) {
  168. result[i] = str[generator() % str.size()];
  169. }
  170. return result;
  171. }
  172. static std::string gen_chatcmplid() {
  173. std::stringstream chatcmplid;
  174. chatcmplid << "chatcmpl-" << random_string();
  175. return chatcmplid.str();
  176. }
  177. //
  178. // other common utils
  179. //
  180. static size_t common_part(const std::vector<llama_token> & a, const std::vector<llama_token> & b) {
  181. size_t i;
  182. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  183. return i;
  184. }
  185. static bool ends_with(const std::string & str, const std::string & suffix) {
  186. return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  187. }
  188. static size_t find_partial_stop_string(const std::string &stop, const std::string &text) {
  189. if (!text.empty() && !stop.empty()) {
  190. const char text_last_char = text.back();
  191. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
  192. if (stop[char_index] == text_last_char) {
  193. const std::string current_partial = stop.substr(0, char_index + 1);
  194. if (ends_with(text, current_partial)) {
  195. return text.size() - char_index - 1;
  196. }
  197. }
  198. }
  199. }
  200. return std::string::npos;
  201. }
  202. // TODO: reuse llama_detokenize
  203. template <class Iter>
  204. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  205. std::string ret;
  206. for (; begin != end; ++begin) {
  207. ret += llama_token_to_piece(ctx, *begin);
  208. }
  209. return ret;
  210. }
  211. // format incomplete utf-8 multibyte character for output
  212. static std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  213. std::string out = token == -1 ? "" : llama_token_to_piece(ctx, token);
  214. // if the size is 1 and first bit is 1, meaning it's a partial character
  215. // (size > 1 meaning it's already a known token)
  216. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  217. std::stringstream ss;
  218. ss << std::hex << (out[0] & 0xff);
  219. std::string res(ss.str());
  220. out = "byte: \\x" + res;
  221. }
  222. return out;
  223. }
  224. struct completion_token_output {
  225. llama_token tok;
  226. std::string text_to_send;
  227. struct token_prob {
  228. llama_token tok;
  229. float prob;
  230. };
  231. std::vector<token_prob> probs;
  232. };
  233. // convert a vector of completion_token_output to json
  234. static json probs_vector_to_json(const llama_context * ctx, const std::vector<completion_token_output> & probs) {
  235. json out = json::array();
  236. for (const auto & prob : probs) {
  237. json probs_for_token = json::array();
  238. for (const auto & p : prob.probs) {
  239. const std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  240. probs_for_token.push_back(json {
  241. {"tok_str", tok_str},
  242. {"prob", p.prob},
  243. });
  244. }
  245. const std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  246. out.push_back(json {
  247. {"content", tok_str},
  248. {"probs", probs_for_token},
  249. });
  250. }
  251. return out;
  252. }
  253. //
  254. // OAI utils
  255. //
  256. static json oaicompat_completion_params_parse(
  257. const struct llama_model * model,
  258. const json & body, /* openai api json semantics */
  259. const std::string & chat_template) {
  260. json llama_params;
  261. llama_params["__oaicompat"] = true;
  262. // Map OpenAI parameters to llama.cpp parameters
  263. //
  264. // For parameters that are defined by the OpenAI documentation (e.g.
  265. // temperature), we explicitly specify OpenAI's intended default; we
  266. // need to do that because sometimes OpenAI disagrees with llama.cpp
  267. //
  268. // https://platform.openai.com/docs/api-reference/chat/create
  269. llama_sampling_params default_sparams;
  270. llama_params["model"] = json_value(body, "model", std::string("unknown"));
  271. llama_params["prompt"] = format_chat(model, chat_template, body["messages"]);
  272. llama_params["cache_prompt"] = json_value(body, "cache_prompt", false);
  273. llama_params["temperature"] = json_value(body, "temperature", 0.0);
  274. llama_params["top_k"] = json_value(body, "top_k", default_sparams.top_k);
  275. llama_params["top_p"] = json_value(body, "top_p", 1.0);
  276. llama_params["n_predict"] = json_value(body, "max_tokens", -1);
  277. llama_params["logit_bias"] = json_value(body, "logit_bias", json::object());
  278. llama_params["frequency_penalty"] = json_value(body, "frequency_penalty", 0.0);
  279. llama_params["presence_penalty"] = json_value(body, "presence_penalty", 0.0);
  280. llama_params["seed"] = json_value(body, "seed", LLAMA_DEFAULT_SEED);
  281. llama_params["stream"] = json_value(body, "stream", false);
  282. llama_params["mirostat"] = json_value(body, "mirostat", default_sparams.mirostat);
  283. llama_params["mirostat_tau"] = json_value(body, "mirostat_tau", default_sparams.mirostat_tau);
  284. llama_params["mirostat_eta"] = json_value(body, "mirostat_eta", default_sparams.mirostat_eta);
  285. llama_params["penalize_nl"] = json_value(body, "penalize_nl", default_sparams.penalize_nl);
  286. llama_params["typical_p"] = json_value(body, "typical_p", default_sparams.typical_p);
  287. llama_params["repeat_last_n"] = json_value(body, "repeat_last_n", default_sparams.penalty_last_n);
  288. llama_params["ignore_eos"] = json_value(body, "ignore_eos", false);
  289. llama_params["tfs_z"] = json_value(body, "tfs_z", default_sparams.tfs_z);
  290. if (body.count("grammar") != 0) {
  291. llama_params["grammar"] = json_value(body, "grammar", json::object());
  292. }
  293. // Handle 'stop' field
  294. if (body.contains("stop") && body["stop"].is_string()) {
  295. llama_params["stop"] = json::array({body["stop"].get<std::string>()});
  296. } else {
  297. llama_params["stop"] = json_value(body, "stop", json::array());
  298. }
  299. // Ensure there is ChatML-specific end sequence among stop words
  300. llama_params["stop"].push_back("<|im_end|>");
  301. return llama_params;
  302. }
  303. static json format_final_response_oaicompat(const json & request, json result, bool streaming = false) {
  304. bool stopped_word = result.count("stopped_word") != 0;
  305. bool stopped_eos = json_value(result, "stopped_eos", false);
  306. int num_tokens_predicted = json_value(result, "tokens_predicted", 0);
  307. int num_prompt_tokens = json_value(result, "tokens_evaluated", 0);
  308. std::string content = json_value(result, "content", std::string(""));
  309. std::string finish_reason = "length";
  310. if (stopped_word || stopped_eos) {
  311. finish_reason = "stop";
  312. }
  313. json choices =
  314. streaming ? json::array({json{{"finish_reason", finish_reason},
  315. {"index", 0},
  316. {"delta", json::object()}}})
  317. : json::array({json{{"finish_reason", finish_reason},
  318. {"index", 0},
  319. {"message", json{{"content", content},
  320. {"role", "assistant"}}}}});
  321. std::time_t t = std::time(0);
  322. json res = json {
  323. {"choices", choices},
  324. {"created", t},
  325. {"model",
  326. json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  327. {"object", streaming ? "chat.completion.chunk" : "chat.completion"},
  328. {"usage", json {
  329. {"completion_tokens", num_tokens_predicted},
  330. {"prompt_tokens", num_prompt_tokens},
  331. {"total_tokens", num_tokens_predicted + num_prompt_tokens}
  332. }},
  333. {"id", gen_chatcmplid()}
  334. };
  335. if (server_verbose) {
  336. res["__verbose"] = result;
  337. }
  338. if (result.contains("completion_probabilities")) {
  339. res["completion_probabilities"] = json_value(result, "completion_probabilities", json::array());
  340. }
  341. return res;
  342. }
  343. // return value is vector as there is one case where we might need to generate two responses
  344. static std::vector<json> format_partial_response_oaicompat(json result) {
  345. if (!result.contains("model") || !result.contains("oaicompat_token_ctr")) {
  346. return std::vector<json>({result});
  347. }
  348. bool first = json_value(result, "oaicompat_token_ctr", 0) == 0;
  349. std::string modelname = json_value(result, "model", std::string(DEFAULT_OAICOMPAT_MODEL));
  350. bool stopped_word = json_value(result, "stopped_word", false);
  351. bool stopped_eos = json_value(result, "stopped_eos", false);
  352. bool stopped_limit = json_value(result, "stopped_limit", false);
  353. std::string content = json_value(result, "content", std::string(""));
  354. std::string finish_reason;
  355. if (stopped_word || stopped_eos) {
  356. finish_reason = "stop";
  357. }
  358. if (stopped_limit) {
  359. finish_reason = "length";
  360. }
  361. std::time_t t = std::time(0);
  362. json choices;
  363. if (!finish_reason.empty()) {
  364. choices = json::array({json{{"finish_reason", finish_reason},
  365. {"index", 0},
  366. {"delta", json::object()}}});
  367. } else {
  368. if (first) {
  369. if (content.empty()) {
  370. choices = json::array({json{{"finish_reason", nullptr},
  371. {"index", 0},
  372. {"delta", json{{"role", "assistant"}}}}});
  373. } else {
  374. // We have to send this as two updates to conform to openai behavior
  375. json initial_ret = json{{"choices", json::array({json{
  376. {"finish_reason", nullptr},
  377. {"index", 0},
  378. {"delta", json{
  379. {"role", "assistant"}
  380. }}}})},
  381. {"created", t},
  382. {"id", gen_chatcmplid()},
  383. {"model", modelname},
  384. {"object", "chat.completion.chunk"}};
  385. json second_ret = json{
  386. {"choices", json::array({json{{"finish_reason", nullptr},
  387. {"index", 0},
  388. {"delta", json{
  389. {"content", content}}}
  390. }})},
  391. {"created", t},
  392. {"id", gen_chatcmplid()},
  393. {"model", modelname},
  394. {"object", "chat.completion.chunk"}};
  395. return std::vector<json>({initial_ret, second_ret});
  396. }
  397. } else {
  398. // Some idiosyncrasy in task processing logic makes several trailing calls
  399. // with empty content, we ignore these at the calee site.
  400. if (content.empty()) {
  401. return std::vector<json>({json::object()});
  402. }
  403. choices = json::array({json{
  404. {"finish_reason", nullptr},
  405. {"index", 0},
  406. {"delta",
  407. json{
  408. {"content", content},
  409. }},
  410. }});
  411. }
  412. }
  413. json ret = json {
  414. {"choices", choices},
  415. {"created", t},
  416. {"id", gen_chatcmplid()},
  417. {"model", modelname},
  418. {"object", "chat.completion.chunk"}
  419. };
  420. return std::vector<json>({ret});
  421. }
  422. static json format_embeddings_response_oaicompat(const json & request, const json & embeddings) {
  423. json res = json {
  424. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  425. {"object", "list"},
  426. {"usage", json {
  427. {"prompt_tokens", 0},
  428. {"total_tokens", 0}
  429. }},
  430. {"data", embeddings}
  431. };
  432. return res;
  433. }
  434. static json format_tokenizer_response(const std::vector<llama_token> & tokens) {
  435. return json {
  436. {"tokens", tokens}
  437. };
  438. }
  439. static json format_detokenized_response(const std::string & content) {
  440. return json {
  441. {"content", content}
  442. };
  443. }