utils.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. #pragma once
  2. #include <string>
  3. #include <vector>
  4. #include <set>
  5. #include <mutex>
  6. #include <condition_variable>
  7. #include <unordered_map>
  8. #include "json.hpp"
  9. #include "../llava/clip.h"
  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. enum server_state {
  32. SERVER_STATE_LOADING_MODEL, // Server is starting up, model not fully loaded yet
  33. SERVER_STATE_READY, // Server is ready and model is loaded
  34. SERVER_STATE_ERROR // An error occurred, load_model failed
  35. };
  36. enum task_type {
  37. TASK_TYPE_COMPLETION,
  38. TASK_TYPE_CANCEL,
  39. TASK_TYPE_NEXT_RESPONSE,
  40. TASK_TYPE_METRICS
  41. };
  42. struct task_server {
  43. int id = -1; // to be filled by llama_server_queue
  44. int target_id;
  45. task_type type;
  46. json data;
  47. bool infill_mode = false;
  48. bool embedding_mode = false;
  49. int multitask_id = -1;
  50. };
  51. struct task_result {
  52. int id;
  53. int multitask_id = -1;
  54. bool stop;
  55. bool error;
  56. json result_json;
  57. };
  58. struct task_multi {
  59. int id;
  60. std::set<int> subtasks_remaining{};
  61. std::vector<task_result> results{};
  62. };
  63. // completion token output with probabilities
  64. struct completion_token_output {
  65. struct token_prob
  66. {
  67. llama_token tok;
  68. float prob;
  69. };
  70. std::vector<token_prob> probs;
  71. llama_token tok;
  72. std::string text_to_send;
  73. };
  74. struct token_translator {
  75. llama_context * ctx;
  76. std::string operator()(llama_token tok) const { return llama_token_to_piece(ctx, tok); }
  77. std::string operator()(const completion_token_output &cto) const { return (*this)(cto.tok); }
  78. };
  79. static inline void server_log(const char *level, const char *function, int line, const char *message, const nlohmann::ordered_json &extra) {
  80. std::stringstream ss_tid;
  81. ss_tid << std::this_thread::get_id();
  82. json log = nlohmann::ordered_json{
  83. {"tid", ss_tid.str()},
  84. {"timestamp", time(nullptr)},
  85. };
  86. if (server_log_json) {
  87. log.merge_patch(
  88. {
  89. {"level", level},
  90. {"function", function},
  91. {"line", line},
  92. {"msg", message},
  93. });
  94. if (!extra.empty()) {
  95. log.merge_patch(extra);
  96. }
  97. std::cout << log.dump(-1, ' ', false, json::error_handler_t::replace) << "\n" << std::flush;
  98. } else {
  99. char buf[1024];
  100. snprintf(buf, 1024, "%4s [%24s] %s", level, function, message);
  101. if (!extra.empty()) {
  102. log.merge_patch(extra);
  103. }
  104. std::stringstream ss;
  105. ss << buf << " |";
  106. for (const auto& el : log.items())
  107. {
  108. const std::string value = el.value().dump(-1, ' ', false, json::error_handler_t::replace);
  109. snprintf(buf, 1024, " %s=%s", el.key().c_str(), value.c_str());
  110. ss << buf;
  111. }
  112. const std::string str = ss.str();
  113. printf("%.*s\n", (int)str.size(), str.data());
  114. fflush(stdout);
  115. }
  116. }
  117. //
  118. // server utils
  119. //
  120. template <typename T>
  121. static T json_value(const json &body, const std::string &key, const T &default_value) {
  122. // Fallback null to default value
  123. return body.contains(key) && !body.at(key).is_null()
  124. ? body.value(key, default_value)
  125. : default_value;
  126. }
  127. // Check if the template supplied via "--chat-template" is supported or not. Returns true if it's valid
  128. inline bool verify_custom_template(const std::string & tmpl) {
  129. llama_chat_message chat[] = {{"user", "test"}};
  130. std::vector<char> buf(1);
  131. int res = llama_chat_apply_template(nullptr, tmpl.c_str(), chat, 1, true, buf.data(), buf.size());
  132. return res >= 0;
  133. }
  134. // Format given chat. If tmpl is empty, we take the template from model metadata
  135. inline std::string format_chat(const struct llama_model * model, const std::string & tmpl, const std::vector<json> & messages) {
  136. size_t alloc_size = 0;
  137. // vector holding all allocated string to be passed to llama_chat_apply_template
  138. std::vector<std::string> str(messages.size() * 2);
  139. std::vector<llama_chat_message> chat(messages.size());
  140. for (size_t i = 0; i < messages.size(); ++i) {
  141. auto &curr_msg = messages[i];
  142. str[i*2 + 0] = json_value(curr_msg, "role", std::string(""));
  143. str[i*2 + 1] = json_value(curr_msg, "content", std::string(""));
  144. alloc_size += str[i*2 + 1].length();
  145. chat[i].role = str[i*2 + 0].c_str();
  146. chat[i].content = str[i*2 + 1].c_str();
  147. }
  148. const char * ptr_tmpl = tmpl.empty() ? nullptr : tmpl.c_str();
  149. std::vector<char> buf(alloc_size * 2);
  150. // run the first time to get the total output length
  151. int32_t res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), true, buf.data(), buf.size());
  152. // if it turns out that our buffer is too small, we resize it
  153. if ((size_t) res > buf.size()) {
  154. buf.resize(res);
  155. res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), true, buf.data(), buf.size());
  156. }
  157. std::string formatted_chat(buf.data(), res);
  158. LOG_VERBOSE("formatted_chat", {{"text", formatted_chat.c_str()}});
  159. return formatted_chat;
  160. }
  161. //
  162. // work queue utils
  163. //
  164. struct llama_server_queue {
  165. int id = 0;
  166. std::mutex mutex_tasks;
  167. bool running;
  168. // queues
  169. std::vector<task_server> queue_tasks;
  170. std::vector<task_server> queue_tasks_deferred;
  171. std::vector<task_multi> queue_multitasks;
  172. std::condition_variable condition_tasks;
  173. // callback functions
  174. std::function<void(task_server&)> callback_new_task;
  175. std::function<void(task_multi&)> callback_finish_multitask;
  176. std::function<void(void)> callback_run_slots;
  177. // Add a new task to the end of the queue
  178. int post(task_server task) {
  179. std::unique_lock<std::mutex> lock(mutex_tasks);
  180. if (task.id == -1) {
  181. task.id = id++;
  182. LOG_VERBOSE("new task id", {{"new_id", task.id}});
  183. }
  184. queue_tasks.push_back(std::move(task));
  185. condition_tasks.notify_one();
  186. return task.id;
  187. }
  188. // Add a new task, but defer until one slot is available
  189. void defer(task_server task) {
  190. std::unique_lock<std::mutex> lock(mutex_tasks);
  191. queue_tasks_deferred.push_back(std::move(task));
  192. }
  193. // Get the next id for creating anew task
  194. int get_new_id() {
  195. std::unique_lock<std::mutex> lock(mutex_tasks);
  196. int new_id = id++;
  197. LOG_VERBOSE("new task id", {{"new_id", new_id}});
  198. return new_id;
  199. }
  200. // Register function to process a new task
  201. void on_new_task(std::function<void(task_server&)> callback) {
  202. callback_new_task = callback;
  203. }
  204. // Register function to process a multitask when it is finished
  205. void on_finish_multitask(std::function<void(task_multi&)> callback) {
  206. callback_finish_multitask = callback;
  207. }
  208. // Register the function to be called when all slots data is ready to be processed
  209. void on_run_slots(std::function<void(void)> callback) {
  210. callback_run_slots = callback;
  211. }
  212. // Call when the state of one slot is changed
  213. void notify_slot_changed() {
  214. // move deferred tasks back to main loop
  215. std::unique_lock<std::mutex> lock(mutex_tasks);
  216. for (auto & task : queue_tasks_deferred) {
  217. queue_tasks.push_back(std::move(task));
  218. }
  219. queue_tasks_deferred.clear();
  220. }
  221. // end the start_loop routine
  222. void terminate() {
  223. {
  224. std::unique_lock<std::mutex> lock(mutex_tasks);
  225. running = false;
  226. }
  227. condition_tasks.notify_all();
  228. }
  229. /**
  230. * Main loop consists of these steps:
  231. * - Wait until a new task arrives
  232. * - Process the task (i.e. maybe copy data into slot)
  233. * - Check if multitask is finished
  234. * - Run all slots
  235. */
  236. void start_loop() {
  237. running = true;
  238. while (true) {
  239. LOG_VERBOSE("new task may arrive", {});
  240. {
  241. while (true)
  242. {
  243. std::unique_lock<std::mutex> lock(mutex_tasks);
  244. if (queue_tasks.empty()) {
  245. lock.unlock();
  246. break;
  247. }
  248. task_server task = queue_tasks.front();
  249. queue_tasks.erase(queue_tasks.begin());
  250. lock.unlock();
  251. LOG_VERBOSE("callback_new_task", {{"task_id", task.id}});
  252. callback_new_task(task);
  253. }
  254. LOG_VERBOSE("update_multitasks", {});
  255. // check if we have any finished multitasks
  256. auto queue_iterator = queue_multitasks.begin();
  257. while (queue_iterator != queue_multitasks.end())
  258. {
  259. if (queue_iterator->subtasks_remaining.empty())
  260. {
  261. // all subtasks done == multitask is done
  262. task_multi current_multitask = *queue_iterator;
  263. callback_finish_multitask(current_multitask);
  264. // remove this multitask
  265. queue_iterator = queue_multitasks.erase(queue_iterator);
  266. }
  267. else
  268. {
  269. ++queue_iterator;
  270. }
  271. }
  272. // all tasks in the current loop is processed, slots data is now ready
  273. LOG_VERBOSE("callback_run_slots", {});
  274. callback_run_slots();
  275. }
  276. LOG_VERBOSE("wait for new task", {});
  277. // wait for new task
  278. {
  279. std::unique_lock<std::mutex> lock(mutex_tasks);
  280. if (queue_tasks.empty()) {
  281. if (!running) {
  282. LOG_VERBOSE("ending start_loop", {});
  283. return;
  284. }
  285. condition_tasks.wait(lock, [&]{
  286. return (!queue_tasks.empty() || !running);
  287. });
  288. }
  289. }
  290. }
  291. }
  292. //
  293. // functions to manage multitasks
  294. //
  295. // add a multitask by specifying the id of all subtask (subtask is a task_server)
  296. void add_multitask(int multitask_id, std::vector<int>& sub_ids)
  297. {
  298. std::lock_guard<std::mutex> lock(mutex_tasks);
  299. task_multi multi;
  300. multi.id = multitask_id;
  301. std::copy(sub_ids.begin(), sub_ids.end(), std::inserter(multi.subtasks_remaining, multi.subtasks_remaining.end()));
  302. queue_multitasks.push_back(multi);
  303. }
  304. // updatethe remaining subtasks, while appending results to multitask
  305. void update_multitask(int multitask_id, int subtask_id, task_result& result)
  306. {
  307. std::lock_guard<std::mutex> lock(mutex_tasks);
  308. for (auto& multitask : queue_multitasks)
  309. {
  310. if (multitask.id == multitask_id)
  311. {
  312. multitask.subtasks_remaining.erase(subtask_id);
  313. multitask.results.push_back(result);
  314. }
  315. }
  316. }
  317. };
  318. struct llama_server_response {
  319. typedef std::function<void(int, int, task_result&)> callback_multitask_t;
  320. callback_multitask_t callback_update_multitask;
  321. // for keeping track of all tasks waiting for the result
  322. std::set<int> waiting_task_ids;
  323. // the main result queue
  324. std::vector<task_result> queue_results;
  325. std::mutex mutex_results;
  326. std::condition_variable condition_results;
  327. // add the task_id to the list of tasks waiting for response
  328. void add_waiting_task_id(int task_id) {
  329. LOG_VERBOSE("waiting for task id", {{"task_id", task_id}});
  330. std::unique_lock<std::mutex> lock(mutex_results);
  331. waiting_task_ids.insert(task_id);
  332. }
  333. // when the request is finished, we can remove task associated with it
  334. void remove_waiting_task_id(int task_id) {
  335. LOG_VERBOSE("remove waiting for task id", {{"task_id", task_id}});
  336. std::unique_lock<std::mutex> lock(mutex_results);
  337. waiting_task_ids.erase(task_id);
  338. }
  339. // This function blocks the thread until there is a response for this task_id
  340. task_result recv(int task_id) {
  341. while (true)
  342. {
  343. std::unique_lock<std::mutex> lock(mutex_results);
  344. condition_results.wait(lock, [&]{
  345. return !queue_results.empty();
  346. });
  347. for (int i = 0; i < (int) queue_results.size(); i++)
  348. {
  349. if (queue_results[i].id == task_id)
  350. {
  351. assert(queue_results[i].multitask_id == -1);
  352. task_result res = queue_results[i];
  353. queue_results.erase(queue_results.begin() + i);
  354. return res;
  355. }
  356. }
  357. }
  358. // should never reach here
  359. }
  360. // Register the function to update multitask
  361. void on_multitask_update(callback_multitask_t callback) {
  362. callback_update_multitask = callback;
  363. }
  364. // Send a new result to a waiting task_id
  365. void send(task_result result) {
  366. std::unique_lock<std::mutex> lock(mutex_results);
  367. LOG_VERBOSE("send new result", {{"task_id", result.id}});
  368. for (auto& task_id : waiting_task_ids) {
  369. // LOG_TEE("waiting task id %i \n", task_id);
  370. // for now, tasks that have associated parent multitasks just get erased once multitask picks up the result
  371. if (result.multitask_id == task_id)
  372. {
  373. LOG_VERBOSE("callback_update_multitask", {{"task_id", task_id}});
  374. callback_update_multitask(task_id, result.id, result);
  375. continue;
  376. }
  377. if (result.id == task_id)
  378. {
  379. LOG_VERBOSE("queue_results.push_back", {{"task_id", task_id}});
  380. queue_results.push_back(result);
  381. condition_results.notify_all();
  382. return;
  383. }
  384. }
  385. }
  386. };
  387. //
  388. // base64 utils (TODO: move to common in the future)
  389. //
  390. static const std::string base64_chars =
  391. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  392. "abcdefghijklmnopqrstuvwxyz"
  393. "0123456789+/";
  394. static inline bool is_base64(uint8_t c)
  395. {
  396. return (isalnum(c) || (c == '+') || (c == '/'));
  397. }
  398. static inline std::vector<uint8_t> base64_decode(const std::string & encoded_string)
  399. {
  400. int i = 0;
  401. int j = 0;
  402. int in_ = 0;
  403. int in_len = encoded_string.size();
  404. uint8_t char_array_4[4];
  405. uint8_t char_array_3[3];
  406. std::vector<uint8_t> ret;
  407. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_]))
  408. {
  409. char_array_4[i++] = encoded_string[in_]; in_++;
  410. if (i == 4)
  411. {
  412. for (i = 0; i <4; i++)
  413. {
  414. char_array_4[i] = base64_chars.find(char_array_4[i]);
  415. }
  416. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  417. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  418. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  419. for (i = 0; (i < 3); i++)
  420. {
  421. ret.push_back(char_array_3[i]);
  422. }
  423. i = 0;
  424. }
  425. }
  426. if (i)
  427. {
  428. for (j = i; j <4; j++)
  429. {
  430. char_array_4[j] = 0;
  431. }
  432. for (j = 0; j <4; j++)
  433. {
  434. char_array_4[j] = base64_chars.find(char_array_4[j]);
  435. }
  436. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  437. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  438. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  439. for (j = 0; (j < i - 1); j++)
  440. {
  441. ret.push_back(char_array_3[j]);
  442. }
  443. }
  444. return ret;
  445. }
  446. //
  447. // random string / id
  448. //
  449. static std::string random_string()
  450. {
  451. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  452. std::random_device rd;
  453. std::mt19937 generator(rd());
  454. std::string result(32, ' ');
  455. for (int i = 0; i < 32; ++i) {
  456. result[i] = str[generator() % str.size()];
  457. }
  458. return result;
  459. }
  460. static std::string gen_chatcmplid()
  461. {
  462. std::stringstream chatcmplid;
  463. chatcmplid << "chatcmpl-" << random_string();
  464. return chatcmplid.str();
  465. }
  466. //
  467. // other common utils
  468. //
  469. static size_t common_part(const std::vector<llama_token> &a, const std::vector<llama_token> &b)
  470. {
  471. size_t i;
  472. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++)
  473. {
  474. }
  475. return i;
  476. }
  477. static bool ends_with(const std::string &str, const std::string &suffix)
  478. {
  479. return str.size() >= suffix.size() &&
  480. 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  481. }
  482. static size_t find_partial_stop_string(const std::string &stop,
  483. const std::string &text)
  484. {
  485. if (!text.empty() && !stop.empty())
  486. {
  487. const char text_last_char = text.back();
  488. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--)
  489. {
  490. if (stop[char_index] == text_last_char)
  491. {
  492. const std::string current_partial = stop.substr(0, char_index + 1);
  493. if (ends_with(text, current_partial))
  494. {
  495. return text.size() - char_index - 1;
  496. }
  497. }
  498. }
  499. }
  500. return std::string::npos;
  501. }
  502. // TODO: reuse llama_detokenize
  503. template <class Iter>
  504. static std::string tokens_to_str(llama_context *ctx, Iter begin, Iter end)
  505. {
  506. std::string ret;
  507. for (; begin != end; ++begin)
  508. {
  509. ret += llama_token_to_piece(ctx, *begin);
  510. }
  511. return ret;
  512. }
  513. // format incomplete utf-8 multibyte character for output
  514. static std::string tokens_to_output_formatted_string(const llama_context *ctx, const llama_token token)
  515. {
  516. std::string out = token == -1 ? "" : llama_token_to_piece(ctx, token);
  517. // if the size is 1 and first bit is 1, meaning it's a partial character
  518. // (size > 1 meaning it's already a known token)
  519. if (out.size() == 1 && (out[0] & 0x80) == 0x80)
  520. {
  521. std::stringstream ss;
  522. ss << std::hex << (out[0] & 0xff);
  523. std::string res(ss.str());
  524. out = "byte: \\x" + res;
  525. }
  526. return out;
  527. }
  528. // convert a vector of completion_token_output to json
  529. static json probs_vector_to_json(const llama_context *ctx, const std::vector<completion_token_output> &probs)
  530. {
  531. json out = json::array();
  532. for (const auto &prob : probs)
  533. {
  534. json probs_for_token = json::array();
  535. for (const auto &p : prob.probs)
  536. {
  537. std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  538. probs_for_token.push_back(json
  539. {
  540. {"tok_str", tok_str},
  541. {"prob", p.prob},
  542. });
  543. }
  544. std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  545. out.push_back(json{
  546. {"content", tok_str},
  547. {"probs", probs_for_token},
  548. });
  549. }
  550. return out;
  551. }