server-task.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #pragma once
  2. #include "common.h"
  3. #include "llama.h"
  4. #include <string>
  5. #include <unordered_set>
  6. #include <list>
  7. // TODO: prevent including the whole server-common.h as we only use server_tokens
  8. #include "server-common.h"
  9. using json = nlohmann::ordered_json;
  10. enum server_task_type {
  11. SERVER_TASK_TYPE_COMPLETION,
  12. SERVER_TASK_TYPE_EMBEDDING,
  13. SERVER_TASK_TYPE_RERANK,
  14. SERVER_TASK_TYPE_INFILL,
  15. SERVER_TASK_TYPE_CANCEL,
  16. SERVER_TASK_TYPE_NEXT_RESPONSE,
  17. SERVER_TASK_TYPE_METRICS,
  18. SERVER_TASK_TYPE_SLOT_SAVE,
  19. SERVER_TASK_TYPE_SLOT_RESTORE,
  20. SERVER_TASK_TYPE_SLOT_ERASE,
  21. SERVER_TASK_TYPE_SET_LORA,
  22. };
  23. // TODO: change this to more generic "response_format" to replace the "format_response_*" in server-common
  24. enum task_response_type {
  25. TASK_RESPONSE_TYPE_NONE, // llama.cpp native format
  26. TASK_RESPONSE_TYPE_OAI_CHAT,
  27. TASK_RESPONSE_TYPE_OAI_CMPL,
  28. TASK_RESPONSE_TYPE_OAI_EMBD,
  29. TASK_RESPONSE_TYPE_ANTHROPIC,
  30. };
  31. enum stop_type {
  32. STOP_TYPE_NONE,
  33. STOP_TYPE_EOS,
  34. STOP_TYPE_WORD,
  35. STOP_TYPE_LIMIT,
  36. };
  37. struct task_params {
  38. bool stream = true;
  39. bool include_usage = false;
  40. bool cache_prompt = true; // remember the prompt to avoid reprocessing all prompt
  41. bool return_tokens = false;
  42. bool return_progress = false;
  43. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  44. int32_t n_discard = 0; // number of tokens after n_keep that may be discarded when shifting context, 0 defaults to half
  45. int32_t n_predict = -1; // new tokens to predict
  46. int32_t n_indent = 0; // minimum line indentation for the generated text in number of whitespace characters
  47. int64_t t_max_prompt_ms = -1; // TODO: implement
  48. int64_t t_max_predict_ms = -1; // if positive, limit the generation phase to this time limit
  49. std::vector<common_adapter_lora_info> lora;
  50. std::vector<std::string> antiprompt;
  51. std::vector<std::string> response_fields;
  52. bool timings_per_token = false;
  53. bool post_sampling_probs = false;
  54. struct common_params_sampling sampling;
  55. struct common_params_speculative speculative;
  56. // response formatting
  57. bool verbose = false;
  58. task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
  59. std::string oaicompat_model;
  60. std::string oaicompat_cmpl_id;
  61. common_chat_syntax oaicompat_chat_syntax;
  62. // Embeddings
  63. int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm)
  64. json format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) const;
  65. json to_json(bool only_metrics = false) const;
  66. };
  67. struct server_task {
  68. int id = -1; // to be filled by server_queue
  69. int index = -1; // used when there are multiple prompts (batch request)
  70. // used by SERVER_TASK_TYPE_CANCEL
  71. int id_target = -1;
  72. int id_slot = -1;
  73. // used by SERVER_TASK_TYPE_INFERENCE
  74. task_params params;
  75. server_tokens tokens;
  76. server_task_type type;
  77. // used by SERVER_TASK_TYPE_SLOT_SAVE, SERVER_TASK_TYPE_SLOT_RESTORE, SERVER_TASK_TYPE_SLOT_ERASE
  78. struct slot_action {
  79. int slot_id;
  80. std::string filename;
  81. std::string filepath;
  82. };
  83. slot_action slot_action;
  84. // used by SERVER_TASK_TYPE_METRICS
  85. bool metrics_reset_bucket = false;
  86. // used by SERVER_TASK_TYPE_SET_LORA
  87. std::vector<common_adapter_lora_info> set_lora;
  88. server_task() = default;
  89. server_task(server_task_type type) : type(type) {}
  90. int32_t n_tokens() const {
  91. return tokens.size();
  92. }
  93. static task_params params_from_json_cmpl(
  94. const llama_context * ctx,
  95. const common_params & params_base,
  96. const json & data);
  97. // utility function
  98. static std::unordered_set<int> get_list_id(const std::vector<server_task> & tasks) {
  99. std::unordered_set<int> ids(tasks.size());
  100. for (size_t i = 0; i < tasks.size(); i++) {
  101. ids.insert(tasks[i].id);
  102. }
  103. return ids;
  104. }
  105. };
  106. struct result_timings {
  107. int32_t cache_n = -1;
  108. int32_t prompt_n = -1;
  109. double prompt_ms;
  110. double prompt_per_token_ms;
  111. double prompt_per_second;
  112. int32_t predicted_n = -1;
  113. double predicted_ms;
  114. double predicted_per_token_ms;
  115. double predicted_per_second;
  116. // Optional speculative metrics - only included when > 0
  117. int32_t draft_n = 0;
  118. int32_t draft_n_accepted = 0;
  119. json to_json() const;
  120. };
  121. struct result_prompt_progress {
  122. int32_t total = 0;
  123. int32_t cache = 0;
  124. int32_t processed = 0;
  125. int64_t time_ms = 0;
  126. json to_json() const;
  127. };
  128. // struct for tracking the state of a task (e.g., for streaming)
  129. struct task_result_state {
  130. // tracking diffs for partial tool calls
  131. std::vector<common_chat_msg_diff> diffs;
  132. common_chat_syntax oaicompat_chat_syntax;
  133. common_chat_msg chat_msg;
  134. std::string generated_text; // append new chunks of generated text here
  135. std::vector<std::string> generated_tool_call_ids;
  136. task_result_state(const common_chat_syntax & oaicompat_chat_syntax)
  137. : oaicompat_chat_syntax(oaicompat_chat_syntax) {}
  138. // parse partial tool calls and update the internal state
  139. common_chat_msg update_chat_msg(
  140. const std::string & text_added,
  141. bool is_partial,
  142. std::vector<common_chat_msg_diff> & diffs);
  143. };
  144. struct server_task_result {
  145. int id = -1;
  146. int id_slot = -1;
  147. virtual bool is_error() {
  148. // only used by server_task_result_error
  149. return false;
  150. }
  151. virtual bool is_stop() {
  152. // only used by server_task_result_cmpl_*
  153. return true;
  154. }
  155. virtual int get_index() {
  156. return -1;
  157. }
  158. virtual void update(task_result_state &) {
  159. // only used by server_task_result_cmpl_*
  160. }
  161. virtual json to_json() = 0;
  162. virtual ~server_task_result() = default;
  163. };
  164. // using shared_ptr for polymorphism of server_task_result
  165. using server_task_result_ptr = std::unique_ptr<server_task_result>;
  166. struct completion_token_output {
  167. llama_token tok;
  168. float prob;
  169. std::string text_to_send;
  170. struct prob_info {
  171. llama_token tok;
  172. std::string txt;
  173. float prob;
  174. };
  175. std::vector<prob_info> probs;
  176. json to_json(bool post_sampling_probs) const;
  177. static json probs_vector_to_json(const std::vector<completion_token_output> & probs, bool post_sampling_probs);
  178. static float logarithm(float x);
  179. static std::vector<unsigned char> str_to_bytes(const std::string & str);
  180. };
  181. struct server_task_result_cmpl_final : server_task_result {
  182. int index = 0;
  183. std::string content;
  184. llama_tokens tokens;
  185. bool stream;
  186. bool include_usage;
  187. result_timings timings;
  188. std::string prompt;
  189. bool truncated;
  190. int32_t n_decoded;
  191. int32_t n_prompt_tokens;
  192. int32_t n_tokens_cached;
  193. bool has_new_line;
  194. std::string stopping_word;
  195. stop_type stop = STOP_TYPE_NONE;
  196. bool post_sampling_probs;
  197. std::vector<completion_token_output> probs_output;
  198. std::vector<std::string> response_fields;
  199. task_params generation_params;
  200. // response formatting
  201. bool verbose = false;
  202. task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
  203. std::string oaicompat_model;
  204. std::string oaicompat_cmpl_id;
  205. common_chat_msg oaicompat_msg; // to be populated by update()
  206. std::vector<common_chat_msg_diff> oaicompat_msg_diffs; // to be populated by update()
  207. bool is_updated = false;
  208. virtual int get_index() override {
  209. return index;
  210. }
  211. virtual bool is_stop() override {
  212. return true; // in stream mode, final responses are considered stop
  213. }
  214. virtual json to_json() override;
  215. virtual void update(task_result_state & state) override {
  216. is_updated = true;
  217. oaicompat_msg = state.update_chat_msg(content, false, oaicompat_msg_diffs);
  218. }
  219. json to_json_non_oaicompat();
  220. json to_json_oaicompat();
  221. json to_json_oaicompat_chat();
  222. json to_json_oaicompat_chat_stream();
  223. json to_json_anthropic();
  224. json to_json_anthropic_stream();
  225. };
  226. struct server_task_result_cmpl_partial : server_task_result {
  227. int index = 0;
  228. std::string content;
  229. llama_tokens tokens;
  230. int32_t n_decoded;
  231. int32_t n_prompt_tokens;
  232. bool post_sampling_probs;
  233. bool is_progress = false;
  234. completion_token_output prob_output;
  235. result_timings timings;
  236. result_prompt_progress progress;
  237. // response formatting
  238. bool verbose = false;
  239. task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
  240. std::string oaicompat_model;
  241. std::string oaicompat_cmpl_id;
  242. std::vector<common_chat_msg_diff> oaicompat_msg_diffs; // to be populated by update()
  243. bool is_updated = false;
  244. virtual int get_index() override {
  245. return index;
  246. }
  247. virtual bool is_stop() override {
  248. return false; // in stream mode, partial responses are not considered stop
  249. }
  250. virtual json to_json() override;
  251. virtual void update(task_result_state & state) override {
  252. is_updated = true;
  253. state.update_chat_msg(content, true, oaicompat_msg_diffs);
  254. }
  255. json to_json_non_oaicompat();
  256. json to_json_oaicompat();
  257. json to_json_oaicompat_chat();
  258. json to_json_anthropic();
  259. };
  260. struct server_task_result_embd : server_task_result {
  261. int index = 0;
  262. std::vector<std::vector<float>> embedding;
  263. int32_t n_tokens;
  264. // response formatting
  265. task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
  266. virtual int get_index() override {
  267. return index;
  268. }
  269. virtual json to_json() override;
  270. json to_json_non_oaicompat();
  271. json to_json_oaicompat();
  272. };
  273. struct server_task_result_rerank : server_task_result {
  274. int index = 0;
  275. float score = -1e6;
  276. int32_t n_tokens;
  277. virtual int get_index() override {
  278. return index;
  279. }
  280. virtual json to_json() override;
  281. };
  282. struct server_task_result_error : server_task_result {
  283. int index = 0;
  284. error_type err_type = ERROR_TYPE_SERVER;
  285. std::string err_msg;
  286. // for ERROR_TYPE_EXCEED_CONTEXT_SIZE
  287. int32_t n_prompt_tokens = 0;
  288. int32_t n_ctx = 0;
  289. virtual bool is_error() override {
  290. return true;
  291. }
  292. virtual json to_json() override;
  293. };
  294. struct server_task_result_metrics : server_task_result {
  295. int n_idle_slots;
  296. int n_processing_slots;
  297. int n_tasks_deferred;
  298. int64_t t_start;
  299. // TODO: somehow reuse server_metrics in the future, instead of duplicating the fields
  300. uint64_t n_prompt_tokens_processed_total = 0;
  301. uint64_t t_prompt_processing_total = 0;
  302. uint64_t n_tokens_predicted_total = 0;
  303. uint64_t t_tokens_generation_total = 0;
  304. uint64_t n_tokens_max = 0;
  305. uint64_t n_prompt_tokens_processed = 0;
  306. uint64_t t_prompt_processing = 0;
  307. uint64_t n_tokens_predicted = 0;
  308. uint64_t t_tokens_generation = 0;
  309. uint64_t n_decode_total = 0;
  310. uint64_t n_busy_slots_total = 0;
  311. // while we can also use std::vector<server_slot> this requires copying the slot object which can be quite messy
  312. // therefore, we use json to temporarily store the slot.to_json() result
  313. json slots_data = json::array();
  314. virtual json to_json() override;
  315. };
  316. struct server_task_result_slot_save_load : server_task_result {
  317. std::string filename;
  318. bool is_save; // true = save, false = load
  319. size_t n_tokens;
  320. size_t n_bytes;
  321. double t_ms;
  322. virtual json to_json() override;
  323. };
  324. struct server_task_result_slot_erase : server_task_result {
  325. size_t n_erased;
  326. virtual json to_json() override;
  327. };
  328. struct server_task_result_apply_lora : server_task_result {
  329. virtual json to_json() override;
  330. };
  331. struct server_prompt_checkpoint {
  332. llama_pos pos_min;
  333. llama_pos pos_max;
  334. std::vector<uint8_t> data;
  335. size_t size() const {
  336. return data.size();
  337. }
  338. };
  339. struct server_prompt {
  340. server_tokens tokens;
  341. std::vector<uint8_t> data;
  342. std::list<server_prompt_checkpoint> checkpoints;
  343. size_t size() const {
  344. size_t res = data.size();
  345. for (const auto & checkpoint : checkpoints) {
  346. res += checkpoint.size();
  347. }
  348. return res;
  349. }
  350. int n_tokens() const {
  351. return tokens.size();
  352. }
  353. };
  354. struct server_prompt_cache {
  355. server_prompt_cache(int32_t limit_size_mib, size_t limit_tokens) {
  356. this->limit_size = 1024ull*1024ull*(limit_size_mib < 0 ? 0 : limit_size_mib);
  357. this->limit_tokens = limit_tokens;
  358. }
  359. std::list<server_prompt> states;
  360. // in bytes, 0 = no limit
  361. size_t limit_size = 0;
  362. // in tokens, 0 = no limit
  363. size_t limit_tokens = 0;
  364. size_t size() const;
  365. size_t n_tokens() const;
  366. server_prompt * alloc(const server_prompt & prompt, size_t state_size);
  367. bool load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx, int32_t id_slot);
  368. void update();
  369. };