server-task.h 15 KB

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