utils.hpp 20 KB

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