utils.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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. #ifndef SERVER_VERBOSE
  13. #define SERVER_VERBOSE 1
  14. #endif
  15. #if SERVER_VERBOSE != 1
  16. #define LOG_VERBOSE(MSG, ...)
  17. #else
  18. #define LOG_VERBOSE(MSG, ...) \
  19. do \
  20. { \
  21. if (server_verbose) \
  22. { \
  23. server_log("VERBOSE", __func__, __LINE__, MSG, __VA_ARGS__); \
  24. } \
  25. } while (0)
  26. #endif
  27. #define LOG_ERROR( MSG, ...) server_log("ERROR", __func__, __LINE__, MSG, __VA_ARGS__)
  28. #define LOG_WARNING(MSG, ...) server_log("WARNING", __func__, __LINE__, MSG, __VA_ARGS__)
  29. #define LOG_INFO( MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
  30. //
  31. // parallel
  32. //
  33. enum server_state {
  34. SERVER_STATE_LOADING_MODEL, // Server is starting up, model not fully loaded yet
  35. SERVER_STATE_READY, // Server is ready and model is loaded
  36. SERVER_STATE_ERROR // An error occurred, load_model failed
  37. };
  38. enum task_type {
  39. TASK_TYPE_COMPLETION,
  40. TASK_TYPE_CANCEL,
  41. TASK_TYPE_NEXT_RESPONSE
  42. };
  43. struct task_server {
  44. int id = -1; // to be filled by llama_server_queue
  45. int target_id;
  46. task_type type;
  47. json data;
  48. bool infill_mode = false;
  49. bool embedding_mode = false;
  50. int multitask_id = -1;
  51. };
  52. struct task_result {
  53. int id;
  54. int multitask_id = -1;
  55. bool stop;
  56. bool error;
  57. json result_json;
  58. };
  59. struct task_multi {
  60. int id;
  61. std::set<int> subtasks_remaining{};
  62. std::vector<task_result> results{};
  63. };
  64. // TODO: can become bool if we can't find use of more states
  65. enum slot_state
  66. {
  67. IDLE,
  68. PROCESSING,
  69. };
  70. enum slot_command
  71. {
  72. NONE,
  73. LOAD_PROMPT,
  74. RELEASE,
  75. };
  76. struct slot_params
  77. {
  78. bool stream = true;
  79. bool cache_prompt = false; // remember the prompt to avoid reprocessing all prompt
  80. uint32_t seed = -1; // RNG seed
  81. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  82. int32_t n_predict = -1; // new tokens to predict
  83. std::vector<std::string> antiprompt;
  84. json input_prefix;
  85. json input_suffix;
  86. };
  87. struct slot_image
  88. {
  89. int32_t id;
  90. bool request_encode_image = false;
  91. float * image_embedding = nullptr;
  92. int32_t image_tokens = 0;
  93. clip_image_u8 * img_data;
  94. std::string prefix_prompt; // before of this image
  95. };
  96. // completion token output with probabilities
  97. struct completion_token_output
  98. {
  99. struct token_prob
  100. {
  101. llama_token tok;
  102. float prob;
  103. };
  104. std::vector<token_prob> probs;
  105. llama_token tok;
  106. std::string text_to_send;
  107. };
  108. static inline void server_log(const char *level, const char *function, int line,
  109. const char *message, const nlohmann::ordered_json &extra)
  110. {
  111. nlohmann::ordered_json log
  112. {
  113. {"timestamp", time(nullptr)},
  114. {"level", level},
  115. {"function", function},
  116. {"line", line},
  117. {"message", message},
  118. };
  119. if (!extra.empty())
  120. {
  121. log.merge_patch(extra);
  122. }
  123. const std::string str = log.dump(-1, ' ', false, json::error_handler_t::replace);
  124. printf("%.*s\n", (int)str.size(), str.data());
  125. fflush(stdout);
  126. }
  127. //
  128. // server utils
  129. //
  130. template <typename T>
  131. static T json_value(const json &body, const std::string &key, const T &default_value)
  132. {
  133. // Fallback null to default value
  134. return body.contains(key) && !body.at(key).is_null()
  135. ? body.value(key, default_value)
  136. : default_value;
  137. }
  138. inline std::string format_llama2(std::vector<json> messages)
  139. {
  140. std::ostringstream output;
  141. bool is_inside_turn = false;
  142. for (auto it = messages.begin(); it != messages.end(); ++it) {
  143. if (!is_inside_turn) {
  144. output << "[INST] ";
  145. }
  146. std::string role = json_value(*it, "role", std::string("user"));
  147. std::string content = json_value(*it, "content", std::string(""));
  148. if (role == "system") {
  149. output << "<<SYS>>\n" << content << "\n<<SYS>>\n\n";
  150. is_inside_turn = true;
  151. } else if (role == "user") {
  152. output << content << " [/INST]";
  153. is_inside_turn = true;
  154. } else {
  155. output << " " << content << " </s>";
  156. is_inside_turn = false;
  157. }
  158. }
  159. LOG_VERBOSE("format_llama2", {{"text", output.str()}});
  160. return output.str();
  161. }
  162. inline std::string format_chatml(std::vector<json> messages)
  163. {
  164. std::ostringstream chatml_msgs;
  165. for (auto it = messages.begin(); it != messages.end(); ++it) {
  166. chatml_msgs << "<|im_start|>"
  167. << json_value(*it, "role", std::string("user")) << '\n';
  168. chatml_msgs << json_value(*it, "content", std::string(""))
  169. << "<|im_end|>\n";
  170. }
  171. chatml_msgs << "<|im_start|>assistant" << '\n';
  172. LOG_VERBOSE("format_chatml", {{"text", chatml_msgs.str()}});
  173. return chatml_msgs.str();
  174. }
  175. //
  176. // work queue utils
  177. //
  178. struct llama_server_queue {
  179. int id = 0;
  180. std::mutex mutex_tasks;
  181. bool running;
  182. // queues
  183. std::vector<task_server> queue_tasks;
  184. std::vector<task_server> queue_tasks_deferred;
  185. std::vector<task_multi> queue_multitasks;
  186. std::condition_variable condition_tasks;
  187. // callback functions
  188. std::function<void(task_server&)> callback_new_task;
  189. std::function<void(task_multi&)> callback_finish_multitask;
  190. std::function<void(void)> callback_all_task_finished;
  191. // Add a new task to the end of the queue
  192. int post(task_server task) {
  193. std::unique_lock<std::mutex> lock(mutex_tasks);
  194. if (task.id == -1) {
  195. task.id = id++;
  196. }
  197. queue_tasks.push_back(std::move(task));
  198. condition_tasks.notify_one();
  199. return task.id;
  200. }
  201. // Add a new task, but defer until one slot is available
  202. void defer(task_server task) {
  203. std::unique_lock<std::mutex> lock(mutex_tasks);
  204. queue_tasks_deferred.push_back(std::move(task));
  205. }
  206. // Get the next id for creating anew task
  207. int get_new_id() {
  208. std::unique_lock<std::mutex> lock(mutex_tasks);
  209. return id++;
  210. }
  211. // Register function to process a new task
  212. void on_new_task(std::function<void(task_server&)> callback) {
  213. callback_new_task = callback;
  214. }
  215. // Register function to process a multitask
  216. void on_finish_multitask(std::function<void(task_multi&)> callback) {
  217. callback_finish_multitask = callback;
  218. }
  219. // Register the function to be called when the batch of tasks is finished
  220. void on_all_tasks_finished(std::function<void(void)> callback) {
  221. callback_all_task_finished = callback;
  222. }
  223. // Call when the state of one slot is changed
  224. void notify_slot_changed() {
  225. // move deferred tasks back to main loop
  226. std::unique_lock<std::mutex> lock(mutex_tasks);
  227. for (auto & task : queue_tasks_deferred) {
  228. queue_tasks.push_back(std::move(task));
  229. }
  230. queue_tasks_deferred.clear();
  231. }
  232. // end the start_loop routine
  233. void terminate() {
  234. {
  235. std::unique_lock<std::mutex> lock(mutex_tasks);
  236. running = false;
  237. }
  238. condition_tasks.notify_all();
  239. }
  240. // Start the main loop.
  241. void start_loop() {
  242. running = true;
  243. while (true) {
  244. // new task arrived
  245. LOG_VERBOSE("have new task", {});
  246. {
  247. while (true)
  248. {
  249. std::unique_lock<std::mutex> lock(mutex_tasks);
  250. if (queue_tasks.empty()) {
  251. lock.unlock();
  252. break;
  253. }
  254. task_server task = queue_tasks.front();
  255. queue_tasks.erase(queue_tasks.begin());
  256. lock.unlock();
  257. LOG_VERBOSE("callback_new_task", {});
  258. callback_new_task(task);
  259. }
  260. LOG_VERBOSE("callback_all_task_finished", {});
  261. // process and update all the multitasks
  262. auto queue_iterator = queue_multitasks.begin();
  263. while (queue_iterator != queue_multitasks.end())
  264. {
  265. if (queue_iterator->subtasks_remaining.empty())
  266. {
  267. // all subtasks done == multitask is done
  268. task_multi current_multitask = *queue_iterator;
  269. callback_finish_multitask(current_multitask);
  270. // remove this multitask
  271. queue_iterator = queue_multitasks.erase(queue_iterator);
  272. }
  273. else
  274. {
  275. ++queue_iterator;
  276. }
  277. }
  278. // all tasks in the current loop is finished
  279. callback_all_task_finished();
  280. }
  281. LOG_VERBOSE("wait for new task", {});
  282. // wait for new task
  283. {
  284. std::unique_lock<std::mutex> lock(mutex_tasks);
  285. if (queue_tasks.empty()) {
  286. if (!running) {
  287. LOG_VERBOSE("ending start_loop", {});
  288. return;
  289. }
  290. condition_tasks.wait(lock, [&]{
  291. return (!queue_tasks.empty() || !running);
  292. });
  293. }
  294. }
  295. }
  296. }
  297. //
  298. // functions to manage multitasks
  299. //
  300. // add a multitask by specifying the id of all subtask (subtask is a task_server)
  301. void add_multitask(int multitask_id, std::vector<int>& sub_ids)
  302. {
  303. std::lock_guard<std::mutex> lock(mutex_tasks);
  304. task_multi multi;
  305. multi.id = multitask_id;
  306. std::copy(sub_ids.begin(), sub_ids.end(), std::inserter(multi.subtasks_remaining, multi.subtasks_remaining.end()));
  307. queue_multitasks.push_back(multi);
  308. }
  309. // updatethe remaining subtasks, while appending results to multitask
  310. void update_multitask(int multitask_id, int subtask_id, task_result& result)
  311. {
  312. std::lock_guard<std::mutex> lock(mutex_tasks);
  313. for (auto& multitask : queue_multitasks)
  314. {
  315. if (multitask.id == multitask_id)
  316. {
  317. multitask.subtasks_remaining.erase(subtask_id);
  318. multitask.results.push_back(result);
  319. }
  320. }
  321. }
  322. };
  323. struct llama_server_response {
  324. typedef std::function<void(int, int, task_result&)> callback_multitask_t;
  325. callback_multitask_t callback_update_multitask;
  326. // for keeping track of all tasks waiting for the result
  327. std::set<int> waiting_task_ids;
  328. // the main result queue
  329. std::vector<task_result> queue_results;
  330. std::mutex mutex_results;
  331. std::condition_variable condition_results;
  332. void add_waiting_task_id(int task_id) {
  333. std::unique_lock<std::mutex> lock(mutex_results);
  334. waiting_task_ids.insert(task_id);
  335. }
  336. void remove_waiting_task_id(int task_id) {
  337. std::unique_lock<std::mutex> lock(mutex_results);
  338. waiting_task_ids.erase(task_id);
  339. }
  340. // This function blocks the thread until there is a response for this task_id
  341. task_result recv(int task_id) {
  342. while (true)
  343. {
  344. std::unique_lock<std::mutex> lock(mutex_results);
  345. condition_results.wait(lock, [&]{
  346. return !queue_results.empty();
  347. });
  348. LOG_VERBOSE("condition_results unblock", {});
  349. for (int i = 0; i < (int) queue_results.size(); i++)
  350. {
  351. if (queue_results[i].id == task_id)
  352. {
  353. assert(queue_results[i].multitask_id == -1);
  354. task_result res = queue_results[i];
  355. queue_results.erase(queue_results.begin() + i);
  356. return res;
  357. }
  358. }
  359. }
  360. // should never reach here
  361. }
  362. // Register the function to update multitask
  363. void on_multitask_update(callback_multitask_t callback) {
  364. callback_update_multitask = callback;
  365. }
  366. // Send a new result to a waiting task_id
  367. void send(task_result result) {
  368. std::unique_lock<std::mutex> lock(mutex_results);
  369. LOG_VERBOSE("send new result", {});
  370. for (auto& task_id : waiting_task_ids) {
  371. // LOG_TEE("waiting task id %i \n", task_id);
  372. // for now, tasks that have associated parent multitasks just get erased once multitask picks up the result
  373. if (result.multitask_id == task_id)
  374. {
  375. LOG_VERBOSE("callback_update_multitask", {});
  376. callback_update_multitask(task_id, result.id, result);
  377. continue;
  378. }
  379. if (result.id == task_id)
  380. {
  381. LOG_VERBOSE("queue_results.push_back", {});
  382. queue_results.push_back(result);
  383. condition_results.notify_one();
  384. return;
  385. }
  386. }
  387. }
  388. };
  389. //
  390. // base64 utils (TODO: move to common in the future)
  391. //
  392. static const std::string base64_chars =
  393. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  394. "abcdefghijklmnopqrstuvwxyz"
  395. "0123456789+/";
  396. static inline bool is_base64(uint8_t c)
  397. {
  398. return (isalnum(c) || (c == '+') || (c == '/'));
  399. }
  400. static inline std::vector<uint8_t> base64_decode(const std::string & encoded_string)
  401. {
  402. int i = 0;
  403. int j = 0;
  404. int in_ = 0;
  405. int in_len = encoded_string.size();
  406. uint8_t char_array_4[4];
  407. uint8_t char_array_3[3];
  408. std::vector<uint8_t> ret;
  409. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_]))
  410. {
  411. char_array_4[i++] = encoded_string[in_]; in_++;
  412. if (i == 4)
  413. {
  414. for (i = 0; i <4; i++)
  415. {
  416. char_array_4[i] = base64_chars.find(char_array_4[i]);
  417. }
  418. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  419. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  420. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  421. for (i = 0; (i < 3); i++)
  422. {
  423. ret.push_back(char_array_3[i]);
  424. }
  425. i = 0;
  426. }
  427. }
  428. if (i)
  429. {
  430. for (j = i; j <4; j++)
  431. {
  432. char_array_4[j] = 0;
  433. }
  434. for (j = 0; j <4; j++)
  435. {
  436. char_array_4[j] = base64_chars.find(char_array_4[j]);
  437. }
  438. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  439. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  440. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  441. for (j = 0; (j < i - 1); j++)
  442. {
  443. ret.push_back(char_array_3[j]);
  444. }
  445. }
  446. return ret;
  447. }
  448. //
  449. // random string / id
  450. //
  451. static std::string random_string()
  452. {
  453. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  454. std::random_device rd;
  455. std::mt19937 generator(rd());
  456. std::string result(32, ' ');
  457. for (int i = 0; i < 32; ++i) {
  458. result[i] = str[generator() % str.size()];
  459. }
  460. return result;
  461. }
  462. static std::string gen_chatcmplid()
  463. {
  464. std::stringstream chatcmplid;
  465. chatcmplid << "chatcmpl-" << random_string();
  466. return chatcmplid.str();
  467. }