server-task.h 14 KB

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