server-task.h 14 KB

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