server-task.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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. // per-request parameters for chat parsing
  66. common_chat_parser_params chat_parser_params;
  67. // Embeddings
  68. int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm)
  69. json format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) const;
  70. json to_json(bool only_metrics = false) const;
  71. };
  72. // struct for tracking the state of a task (e.g., for streaming)
  73. struct task_result_state {
  74. // tracking diffs for partial tool calls
  75. std::vector<common_chat_msg_diff> diffs;
  76. common_chat_parser_params chat_parser_params;
  77. common_chat_msg chat_msg;
  78. std::string generated_text; // append new chunks of generated text here
  79. std::vector<std::string> generated_tool_call_ids;
  80. // for Anthropic API streaming: track content block state across chunks
  81. bool anthropic_thinking_block_started = false;
  82. bool anthropic_text_block_started = false;
  83. task_result_state(const common_chat_parser_params & chat_parser_params)
  84. : chat_parser_params(chat_parser_params) {}
  85. // parse partial tool calls and update the internal state
  86. common_chat_msg update_chat_msg(
  87. const std::string & text_added,
  88. bool is_partial,
  89. std::vector<common_chat_msg_diff> & diffs);
  90. };
  91. struct server_task {
  92. int id = -1; // to be filled by server_queue
  93. // TODO @ngxson : remove this field and implement a mapping task_id -> idx in the response_reader
  94. size_t index = 0; // used when there are multiple prompts (batch request)
  95. // used by SERVER_TASK_TYPE_CANCEL
  96. int id_target = -1;
  97. int id_slot = -1;
  98. // used by parallel sampling (multiple completions from same prompt)
  99. int id_parent = -1;
  100. // temporary store of child tasks for scheduling
  101. // note: accessing to elements is invalid after the task is moved to server_slot
  102. std::vector<server_task> child_tasks;
  103. // used by SERVER_TASK_TYPE_INFERENCE
  104. task_params params;
  105. server_tokens tokens;
  106. // only used by CLI, this allow tokenizing CLI inputs on server side
  107. // we need this because mtmd_context and vocab are not accessible outside of server_context
  108. bool cli = false;
  109. std::string cli_prompt;
  110. std::vector<raw_buffer> cli_files;
  111. server_task_type type;
  112. // used by SERVER_TASK_TYPE_SLOT_SAVE, SERVER_TASK_TYPE_SLOT_RESTORE, SERVER_TASK_TYPE_SLOT_ERASE
  113. struct slot_action {
  114. int slot_id;
  115. std::string filename;
  116. std::string filepath;
  117. };
  118. slot_action slot_action;
  119. // used by SERVER_TASK_TYPE_METRICS
  120. bool metrics_reset_bucket = false;
  121. // used by SERVER_TASK_TYPE_SET_LORA
  122. std::map<int, float> set_lora; // mapping adapter ID -> scale
  123. server_task() = default;
  124. server_task(server_task_type type) : type(type) {}
  125. int32_t n_tokens() const {
  126. return tokens.size();
  127. }
  128. bool need_embd() const {
  129. switch (type) {
  130. case SERVER_TASK_TYPE_EMBEDDING:
  131. case SERVER_TASK_TYPE_RERANK:
  132. return true;
  133. default:
  134. return false;
  135. }
  136. }
  137. bool need_logits() const {
  138. switch (type) {
  139. case SERVER_TASK_TYPE_COMPLETION:
  140. case SERVER_TASK_TYPE_INFILL:
  141. return true;
  142. default:
  143. return false;
  144. }
  145. }
  146. bool need_sampling() const {
  147. switch (type) {
  148. case SERVER_TASK_TYPE_COMPLETION:
  149. case SERVER_TASK_TYPE_INFILL:
  150. return true;
  151. default:
  152. return false;
  153. }
  154. }
  155. static task_params params_from_json_cmpl(
  156. const llama_vocab * vocab,
  157. const common_params & params_base,
  158. const int n_ctx_slot,
  159. const json & data);
  160. // utility function
  161. static std::unordered_set<int> get_list_id(const std::vector<server_task> & tasks) {
  162. std::unordered_set<int> ids(tasks.size());
  163. for (size_t i = 0; i < tasks.size(); i++) {
  164. ids.insert(tasks[i].id);
  165. for (auto & child : tasks[i].child_tasks) {
  166. ids.insert(child.id);
  167. }
  168. }
  169. return ids;
  170. }
  171. void add_child(int id_parent, int id_child) {
  172. server_task copy;
  173. copy.id = id_child;
  174. copy.id_parent = id_parent;
  175. copy.params = params;
  176. copy.type = type;
  177. copy.tokens = tokens.clone();
  178. copy.id_slot = -1; // child tasks cannot specify slot
  179. // use different sampling seed for each child
  180. // note: https://github.com/ggml-org/llama.cpp/pull/18700#discussion_r2675115723
  181. if (copy.params.sampling.seed != LLAMA_DEFAULT_SEED) {
  182. copy.params.sampling.seed += (uint32_t)child_tasks.size() + 1;
  183. }
  184. child_tasks.push_back(std::move(copy));
  185. }
  186. // the task will be moved into queue, then onto slots
  187. // however, the state must be kept by caller (e.g., HTTP thread)
  188. task_result_state create_state() const {
  189. return task_result_state(params.chat_parser_params);
  190. }
  191. bool is_parent() const {
  192. return child_tasks.size() > 0;
  193. }
  194. bool is_child() const {
  195. return id_parent != -1;
  196. }
  197. };
  198. struct result_timings {
  199. int32_t cache_n = -1;
  200. int32_t prompt_n = -1;
  201. double prompt_ms;
  202. double prompt_per_token_ms;
  203. double prompt_per_second;
  204. int32_t predicted_n = -1;
  205. double predicted_ms;
  206. double predicted_per_token_ms;
  207. double predicted_per_second;
  208. // Optional speculative metrics - only included when > 0
  209. int32_t draft_n = 0;
  210. int32_t draft_n_accepted = 0;
  211. json to_json() const;
  212. };
  213. struct result_prompt_progress {
  214. int32_t total = 0;
  215. int32_t cache = 0;
  216. int32_t processed = 0;
  217. int64_t time_ms = 0;
  218. json to_json() const;
  219. };
  220. struct server_task_result {
  221. int id = -1;
  222. int id_slot = -1;
  223. // TODO @ngxson : remove this field and implement a mapping task_id -> idx in the response_reader
  224. size_t index = 0; // to be used for batched tasks
  225. virtual bool is_error() {
  226. // only used by server_task_result_error
  227. return false;
  228. }
  229. virtual bool is_stop() {
  230. // only used by server_task_result_cmpl_*
  231. return true;
  232. }
  233. virtual void update(task_result_state &) {
  234. // only used by server_task_result_cmpl_*
  235. }
  236. virtual json to_json() = 0;
  237. virtual ~server_task_result() = default;
  238. };
  239. // using shared_ptr for polymorphism of server_task_result
  240. using server_task_result_ptr = std::unique_ptr<server_task_result>;
  241. struct completion_token_output {
  242. llama_token tok;
  243. float prob;
  244. std::string text_to_send;
  245. struct prob_info {
  246. llama_token tok;
  247. std::string txt;
  248. float prob;
  249. };
  250. std::vector<prob_info> probs;
  251. json to_json(bool post_sampling_probs) const;
  252. static json probs_vector_to_json(const std::vector<completion_token_output> & probs, bool post_sampling_probs);
  253. static float logarithm(float x);
  254. static std::vector<unsigned char> str_to_bytes(const std::string & str);
  255. };
  256. struct server_task_result_cmpl_final : server_task_result {
  257. std::string content;
  258. llama_tokens tokens;
  259. bool stream;
  260. bool include_usage;
  261. result_timings timings;
  262. std::string prompt;
  263. bool truncated;
  264. int32_t n_decoded;
  265. int32_t n_prompt_tokens;
  266. int32_t n_tokens_cached;
  267. bool has_new_line;
  268. std::string stopping_word;
  269. stop_type stop = STOP_TYPE_NONE;
  270. bool post_sampling_probs;
  271. std::vector<completion_token_output> probs_output;
  272. std::vector<std::string> response_fields;
  273. task_params generation_params;
  274. // response formatting
  275. bool verbose = false;
  276. task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
  277. std::string oaicompat_model;
  278. std::string oaicompat_cmpl_id;
  279. common_chat_msg oaicompat_msg; // to be populated by update()
  280. std::vector<common_chat_msg_diff> oaicompat_msg_diffs; // to be populated by update()
  281. bool is_updated = false;
  282. virtual bool is_stop() override {
  283. return true; // in stream mode, final responses are considered stop
  284. }
  285. virtual json to_json() override;
  286. virtual void update(task_result_state & state) override {
  287. is_updated = true;
  288. oaicompat_msg = state.update_chat_msg(content, false, oaicompat_msg_diffs);
  289. }
  290. json to_json_non_oaicompat();
  291. json to_json_oaicompat();
  292. json to_json_oaicompat_chat();
  293. json to_json_oaicompat_chat_stream();
  294. json to_json_anthropic();
  295. json to_json_anthropic_stream();
  296. };
  297. struct server_task_result_cmpl_partial : server_task_result {
  298. std::string content;
  299. llama_tokens tokens;
  300. int32_t n_decoded;
  301. int32_t n_prompt_tokens;
  302. bool post_sampling_probs;
  303. bool is_progress = false;
  304. completion_token_output prob_output;
  305. result_timings timings;
  306. result_prompt_progress progress;
  307. // response formatting
  308. bool verbose = false;
  309. task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
  310. std::string oaicompat_model;
  311. std::string oaicompat_cmpl_id;
  312. std::vector<common_chat_msg_diff> oaicompat_msg_diffs; // to be populated by update()
  313. bool is_updated = false;
  314. // for Anthropic API: track if any reasoning content has been generated
  315. bool anthropic_has_reasoning = false;
  316. // Streaming state copied from task_result_state for this chunk
  317. bool anthropic_thinking_block_started = false;
  318. bool anthropic_text_block_started = false;
  319. virtual bool is_stop() override {
  320. return false; // in stream mode, partial responses are not considered stop
  321. }
  322. virtual json to_json() override;
  323. virtual void update(task_result_state & state) override {
  324. is_updated = true;
  325. state.update_chat_msg(content, true, oaicompat_msg_diffs);
  326. // track if the accumulated message has any reasoning content
  327. anthropic_has_reasoning = !state.chat_msg.reasoning_content.empty();
  328. // Copy current state for use in to_json_anthropic() (reflects state BEFORE this chunk)
  329. anthropic_thinking_block_started = state.anthropic_thinking_block_started;
  330. anthropic_text_block_started = state.anthropic_text_block_started;
  331. // Pre-compute state updates based on diffs (for next chunk)
  332. for (const auto & diff : oaicompat_msg_diffs) {
  333. if (!diff.reasoning_content_delta.empty() && !state.anthropic_thinking_block_started) {
  334. state.anthropic_thinking_block_started = true;
  335. }
  336. if (!diff.content_delta.empty() && !state.anthropic_text_block_started) {
  337. state.anthropic_text_block_started = true;
  338. }
  339. }
  340. }
  341. json to_json_non_oaicompat();
  342. json to_json_oaicompat();
  343. json to_json_oaicompat_chat();
  344. json to_json_anthropic();
  345. };
  346. struct server_task_result_embd : server_task_result {
  347. std::vector<std::vector<float>> embedding;
  348. int32_t n_tokens;
  349. // response formatting
  350. task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
  351. virtual json to_json() override;
  352. json to_json_non_oaicompat();
  353. json to_json_oaicompat();
  354. };
  355. struct server_task_result_rerank : server_task_result {
  356. float score = -1e6;
  357. int32_t n_tokens;
  358. virtual json to_json() override;
  359. };
  360. struct server_task_result_error : server_task_result {
  361. error_type err_type = ERROR_TYPE_SERVER;
  362. std::string err_msg;
  363. // for ERROR_TYPE_EXCEED_CONTEXT_SIZE
  364. int32_t n_prompt_tokens = 0;
  365. int32_t n_ctx = 0;
  366. virtual bool is_error() override {
  367. return true;
  368. }
  369. virtual json to_json() override;
  370. };
  371. struct server_task_result_metrics : server_task_result {
  372. int n_idle_slots;
  373. int n_processing_slots;
  374. int n_tasks_deferred;
  375. int64_t t_start;
  376. // TODO: somehow reuse server_metrics in the future, instead of duplicating the fields
  377. uint64_t n_prompt_tokens_processed_total = 0;
  378. uint64_t t_prompt_processing_total = 0;
  379. uint64_t n_tokens_predicted_total = 0;
  380. uint64_t t_tokens_generation_total = 0;
  381. uint64_t n_tokens_max = 0;
  382. uint64_t n_prompt_tokens_processed = 0;
  383. uint64_t t_prompt_processing = 0;
  384. uint64_t n_tokens_predicted = 0;
  385. uint64_t t_tokens_generation = 0;
  386. uint64_t n_decode_total = 0;
  387. uint64_t n_busy_slots_total = 0;
  388. // while we can also use std::vector<server_slot> this requires copying the slot object which can be quite messy
  389. // therefore, we use json to temporarily store the slot.to_json() result
  390. json slots_data = json::array();
  391. virtual json to_json() override;
  392. };
  393. struct server_task_result_slot_save_load : server_task_result {
  394. std::string filename;
  395. bool is_save; // true = save, false = load
  396. size_t n_tokens;
  397. size_t n_bytes;
  398. double t_ms;
  399. virtual json to_json() override;
  400. };
  401. struct server_task_result_slot_erase : server_task_result {
  402. size_t n_erased;
  403. virtual json to_json() override;
  404. };
  405. struct server_task_result_get_lora : server_task_result {
  406. struct lora {
  407. common_adapter_lora_info info;
  408. std::string alora_invocation_string;
  409. llama_tokens alora_invocation_tokens;
  410. };
  411. std::vector<lora> loras;
  412. virtual json to_json() override;
  413. };
  414. struct server_task_result_apply_lora : server_task_result {
  415. virtual json to_json() override;
  416. };
  417. struct server_prompt_checkpoint {
  418. llama_pos pos_min;
  419. llama_pos pos_max;
  420. std::vector<uint8_t> data;
  421. size_t size() const {
  422. return data.size();
  423. }
  424. };
  425. struct server_prompt {
  426. server_tokens tokens;
  427. std::vector<uint8_t> data;
  428. std::list<server_prompt_checkpoint> checkpoints;
  429. size_t size() const {
  430. size_t res = data.size();
  431. for (const auto & checkpoint : checkpoints) {
  432. res += checkpoint.size();
  433. }
  434. return res;
  435. }
  436. int n_tokens() const {
  437. return tokens.size();
  438. }
  439. server_prompt clone() const {
  440. return server_prompt {
  441. tokens.clone(),
  442. data,
  443. checkpoints
  444. };
  445. }
  446. };
  447. struct server_prompt_cache {
  448. server_prompt_cache(int32_t limit_size_mib, size_t limit_tokens) {
  449. this->limit_size = 1024ull*1024ull*(limit_size_mib < 0 ? 0 : limit_size_mib);
  450. this->limit_tokens = limit_tokens;
  451. }
  452. std::list<server_prompt> states;
  453. // in bytes, 0 = no limit
  454. size_t limit_size = 0;
  455. // in tokens, 0 = no limit
  456. size_t limit_tokens = 0;
  457. size_t size() const;
  458. size_t n_tokens() const;
  459. server_prompt * alloc(const server_prompt & prompt, size_t state_size);
  460. bool load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx, int32_t id_slot);
  461. void update();
  462. };