utils.hpp 21 KB

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