server-task.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  1. #include "server-common.h"
  2. #include "server-task.h"
  3. #include "common.h"
  4. #include "llama.h"
  5. #include "chat.h"
  6. #include "sampling.h"
  7. #include "json-schema-to-grammar.h"
  8. using json = nlohmann::ordered_json;
  9. //
  10. // task_params
  11. //
  12. json task_params::format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) const {
  13. json data = json::array();
  14. for (const auto & lb : logit_bias) {
  15. data.push_back(json{
  16. {"bias", lb.bias},
  17. {"token", lb.token},
  18. });
  19. }
  20. return data;
  21. }
  22. json task_params::to_json(bool only_metrics) const {
  23. std::vector<std::string> samplers;
  24. samplers.reserve(sampling.samplers.size());
  25. for (const auto & sampler : sampling.samplers) {
  26. samplers.emplace_back(common_sampler_type_to_str(sampler));
  27. }
  28. json lora = json::array();
  29. for (auto & it : this->lora) {
  30. lora.push_back({{"id", it.first}, {"scale", it.second}});
  31. }
  32. if (only_metrics) {
  33. return json {
  34. {"seed", sampling.seed},
  35. {"temperature", sampling.temp},
  36. {"dynatemp_range", sampling.dynatemp_range},
  37. {"dynatemp_exponent", sampling.dynatemp_exponent},
  38. {"top_k", sampling.top_k},
  39. {"top_p", sampling.top_p},
  40. {"min_p", sampling.min_p},
  41. {"top_n_sigma", sampling.top_n_sigma},
  42. {"xtc_probability", sampling.xtc_probability},
  43. {"xtc_threshold", sampling.xtc_threshold},
  44. {"typical_p", sampling.typ_p},
  45. {"repeat_last_n", sampling.penalty_last_n},
  46. {"repeat_penalty", sampling.penalty_repeat},
  47. {"presence_penalty", sampling.penalty_present},
  48. {"frequency_penalty", sampling.penalty_freq},
  49. {"dry_multiplier", sampling.dry_multiplier},
  50. {"dry_base", sampling.dry_base},
  51. {"dry_allowed_length", sampling.dry_allowed_length},
  52. {"dry_penalty_last_n", sampling.dry_penalty_last_n},
  53. {"mirostat", sampling.mirostat},
  54. {"mirostat_tau", sampling.mirostat_tau},
  55. {"mirostat_eta", sampling.mirostat_eta},
  56. {"max_tokens", n_predict},
  57. {"n_predict", n_predict}, // TODO: deduplicate?
  58. {"n_keep", n_keep},
  59. {"n_discard", n_discard},
  60. {"ignore_eos", sampling.ignore_eos},
  61. {"stream", stream},
  62. {"n_probs", sampling.n_probs},
  63. {"min_keep", sampling.min_keep},
  64. {"chat_format", common_chat_format_name(oaicompat_chat_syntax.format)},
  65. {"reasoning_format", common_reasoning_format_name(oaicompat_chat_syntax.reasoning_format)},
  66. {"reasoning_in_content", oaicompat_chat_syntax.reasoning_in_content},
  67. {"thinking_forced_open", oaicompat_chat_syntax.thinking_forced_open},
  68. {"samplers", samplers},
  69. {"speculative.n_max", speculative.n_max},
  70. {"speculative.n_min", speculative.n_min},
  71. {"speculative.p_min", speculative.p_min},
  72. {"timings_per_token", timings_per_token},
  73. {"post_sampling_probs", post_sampling_probs},
  74. {"lora", lora},
  75. };
  76. }
  77. auto grammar_triggers = json::array();
  78. for (const auto & trigger : sampling.grammar_triggers) {
  79. server_grammar_trigger ct(trigger);
  80. grammar_triggers.push_back(ct.to_json());
  81. }
  82. return json {
  83. {"seed", sampling.seed},
  84. {"temperature", sampling.temp},
  85. {"dynatemp_range", sampling.dynatemp_range},
  86. {"dynatemp_exponent", sampling.dynatemp_exponent},
  87. {"top_k", sampling.top_k},
  88. {"top_p", sampling.top_p},
  89. {"min_p", sampling.min_p},
  90. {"top_n_sigma", sampling.top_n_sigma},
  91. {"xtc_probability", sampling.xtc_probability},
  92. {"xtc_threshold", sampling.xtc_threshold},
  93. {"typical_p", sampling.typ_p},
  94. {"repeat_last_n", sampling.penalty_last_n},
  95. {"repeat_penalty", sampling.penalty_repeat},
  96. {"presence_penalty", sampling.penalty_present},
  97. {"frequency_penalty", sampling.penalty_freq},
  98. {"dry_multiplier", sampling.dry_multiplier},
  99. {"dry_base", sampling.dry_base},
  100. {"dry_allowed_length", sampling.dry_allowed_length},
  101. {"dry_penalty_last_n", sampling.dry_penalty_last_n},
  102. {"dry_sequence_breakers", sampling.dry_sequence_breakers},
  103. {"mirostat", sampling.mirostat},
  104. {"mirostat_tau", sampling.mirostat_tau},
  105. {"mirostat_eta", sampling.mirostat_eta},
  106. {"stop", antiprompt},
  107. {"max_tokens", n_predict},
  108. {"n_predict", n_predict}, // TODO: deduplicate?
  109. {"n_keep", n_keep},
  110. {"n_discard", n_discard},
  111. {"ignore_eos", sampling.ignore_eos},
  112. {"stream", stream},
  113. {"logit_bias", format_logit_bias(sampling.logit_bias)},
  114. {"n_probs", sampling.n_probs},
  115. {"min_keep", sampling.min_keep},
  116. {"grammar", sampling.grammar},
  117. {"grammar_lazy", sampling.grammar_lazy},
  118. {"grammar_triggers", grammar_triggers},
  119. {"preserved_tokens", sampling.preserved_tokens},
  120. {"chat_format", common_chat_format_name(oaicompat_chat_syntax.format)},
  121. {"reasoning_format", common_reasoning_format_name(oaicompat_chat_syntax.reasoning_format)},
  122. {"reasoning_in_content", oaicompat_chat_syntax.reasoning_in_content},
  123. {"thinking_forced_open", oaicompat_chat_syntax.thinking_forced_open},
  124. {"samplers", samplers},
  125. {"speculative.n_max", speculative.n_max},
  126. {"speculative.n_min", speculative.n_min},
  127. {"speculative.p_min", speculative.p_min},
  128. {"timings_per_token", timings_per_token},
  129. {"post_sampling_probs", post_sampling_probs},
  130. {"lora", lora},
  131. };
  132. }
  133. //
  134. // server_task
  135. //
  136. task_params server_task::params_from_json_cmpl(
  137. const llama_vocab * vocab,
  138. const common_params & params_base,
  139. const int n_ctx_slot,
  140. const json & data) {
  141. task_params params;
  142. // Sampling parameter defaults are loaded from the global server context (but individual requests can still them)
  143. task_params defaults;
  144. defaults.sampling = params_base.sampling;
  145. defaults.speculative = params_base.speculative;
  146. defaults.n_keep = params_base.n_keep;
  147. defaults.n_predict = params_base.n_predict;
  148. defaults.n_cache_reuse = params_base.n_cache_reuse;
  149. defaults.antiprompt = params_base.antiprompt;
  150. // enabling this will output extra debug information in the HTTP responses from the server
  151. params.verbose = params_base.verbosity > 9;
  152. params.timings_per_token = json_value(data, "timings_per_token", false);
  153. params.stream = json_value(data, "stream", false);
  154. auto stream_opt = json_value(data, "stream_options", json::object());
  155. params.include_usage = json_value(stream_opt, "include_usage", false);
  156. params.cache_prompt = json_value(data, "cache_prompt", true);
  157. params.return_tokens = json_value(data, "return_tokens", false);
  158. params.return_progress = json_value(data, "return_progress", false);
  159. params.n_predict = json_value(data, "n_predict", json_value(data, "max_tokens", defaults.n_predict));
  160. params.n_indent = json_value(data, "n_indent", defaults.n_indent);
  161. params.n_keep = json_value(data, "n_keep", defaults.n_keep);
  162. params.n_discard = json_value(data, "n_discard", defaults.n_discard);
  163. params.n_cmpl = json_value(data, "n_cmpl", json_value(data, "n", 1));
  164. params.n_cache_reuse = json_value(data, "n_cache_reuse", defaults.n_cache_reuse);
  165. //params.t_max_prompt_ms = json_value(data, "t_max_prompt_ms", defaults.t_max_prompt_ms); // TODO: implement
  166. params.t_max_predict_ms = json_value(data, "t_max_predict_ms", defaults.t_max_predict_ms);
  167. params.response_fields = json_value(data, "response_fields", std::vector<std::string>());
  168. params.sampling.top_k = json_value(data, "top_k", defaults.sampling.top_k);
  169. params.sampling.top_p = json_value(data, "top_p", defaults.sampling.top_p);
  170. params.sampling.min_p = json_value(data, "min_p", defaults.sampling.min_p);
  171. params.sampling.top_n_sigma = json_value(data, "top_n_sigma", defaults.sampling.top_n_sigma);
  172. params.sampling.xtc_probability = json_value(data, "xtc_probability", defaults.sampling.xtc_probability);
  173. params.sampling.xtc_threshold = json_value(data, "xtc_threshold", defaults.sampling.xtc_threshold);
  174. params.sampling.typ_p = json_value(data, "typical_p", defaults.sampling.typ_p);
  175. params.sampling.temp = json_value(data, "temperature", defaults.sampling.temp);
  176. params.sampling.dynatemp_range = json_value(data, "dynatemp_range", defaults.sampling.dynatemp_range);
  177. params.sampling.dynatemp_exponent = json_value(data, "dynatemp_exponent", defaults.sampling.dynatemp_exponent);
  178. params.sampling.penalty_last_n = json_value(data, "repeat_last_n", defaults.sampling.penalty_last_n);
  179. params.sampling.penalty_repeat = json_value(data, "repeat_penalty", defaults.sampling.penalty_repeat);
  180. params.sampling.penalty_freq = json_value(data, "frequency_penalty", defaults.sampling.penalty_freq);
  181. params.sampling.penalty_present = json_value(data, "presence_penalty", defaults.sampling.penalty_present);
  182. params.sampling.dry_multiplier = json_value(data, "dry_multiplier", defaults.sampling.dry_multiplier);
  183. params.sampling.dry_base = json_value(data, "dry_base", defaults.sampling.dry_base);
  184. params.sampling.dry_allowed_length = json_value(data, "dry_allowed_length", defaults.sampling.dry_allowed_length);
  185. params.sampling.dry_penalty_last_n = json_value(data, "dry_penalty_last_n", defaults.sampling.dry_penalty_last_n);
  186. params.sampling.mirostat = json_value(data, "mirostat", defaults.sampling.mirostat);
  187. params.sampling.mirostat_tau = json_value(data, "mirostat_tau", defaults.sampling.mirostat_tau);
  188. params.sampling.mirostat_eta = json_value(data, "mirostat_eta", defaults.sampling.mirostat_eta);
  189. params.sampling.seed = json_value(data, "seed", defaults.sampling.seed);
  190. params.sampling.n_probs = json_value(data, "n_probs", defaults.sampling.n_probs);
  191. params.sampling.min_keep = json_value(data, "min_keep", defaults.sampling.min_keep);
  192. params.post_sampling_probs = json_value(data, "post_sampling_probs", defaults.post_sampling_probs);
  193. params.speculative.n_min = json_value(data, "speculative.n_min", defaults.speculative.n_min);
  194. params.speculative.n_max = json_value(data, "speculative.n_max", defaults.speculative.n_max);
  195. params.speculative.p_min = json_value(data, "speculative.p_min", defaults.speculative.p_min);
  196. params.speculative.n_min = std::min(params.speculative.n_max, params.speculative.n_min);
  197. params.speculative.n_min = std::max(params.speculative.n_min, 0);
  198. params.speculative.n_max = std::max(params.speculative.n_max, 0);
  199. // Use OpenAI API logprobs only if n_probs wasn't provided
  200. if (data.contains("logprobs") && params.sampling.n_probs == defaults.sampling.n_probs){
  201. params.sampling.n_probs = json_value(data, "logprobs", defaults.sampling.n_probs);
  202. }
  203. if (data.contains("lora")) {
  204. if (data.at("lora").is_array()) {
  205. params.lora = parse_lora_request(data.at("lora"));
  206. } else {
  207. throw std::runtime_error("Error: 'lora' must be an array of objects with 'id' and 'scale' fields");
  208. }
  209. } else {
  210. params.lora = {};
  211. }
  212. // TODO: add more sanity checks for the input parameters
  213. if (params.sampling.penalty_last_n < -1) {
  214. throw std::runtime_error("Error: repeat_last_n must be >= -1");
  215. }
  216. if (params.sampling.dry_penalty_last_n < -1) {
  217. throw std::runtime_error("Error: dry_penalty_last_n must be >= -1");
  218. }
  219. if (params.sampling.penalty_last_n == -1) {
  220. // note: should be the slot's context and not the full context, but it's ok
  221. params.sampling.penalty_last_n = n_ctx_slot;
  222. }
  223. if (params.sampling.dry_penalty_last_n == -1) {
  224. params.sampling.dry_penalty_last_n = n_ctx_slot;
  225. }
  226. if (params.sampling.dry_base < 1.0f) {
  227. params.sampling.dry_base = defaults.sampling.dry_base;
  228. }
  229. // sequence breakers for DRY
  230. {
  231. // Currently, this is not compatible with TextGen WebUI, Koboldcpp and SillyTavern format
  232. // Ref: https://github.com/oobabooga/text-generation-webui/blob/d1af7a41ade7bd3c3a463bfa640725edb818ebaf/extensions/openai/typing.py#L39
  233. if (data.contains("dry_sequence_breakers")) {
  234. params.sampling.dry_sequence_breakers = json_value(data, "dry_sequence_breakers", std::vector<std::string>());
  235. if (params.sampling.dry_sequence_breakers.empty()) {
  236. throw std::runtime_error("Error: dry_sequence_breakers must be a non-empty array of strings");
  237. }
  238. }
  239. }
  240. // process "json_schema" and "grammar"
  241. if (data.contains("json_schema") && !data.contains("grammar")) {
  242. try {
  243. auto schema = json_value(data, "json_schema", json::object());
  244. SRV_DBG("JSON schema: %s\n", schema.dump(2).c_str());
  245. params.sampling.grammar = json_schema_to_grammar(schema);
  246. SRV_DBG("Converted grammar: %s\n", params.sampling.grammar.c_str());
  247. } catch (const std::exception & e) {
  248. throw std::runtime_error(std::string("\"json_schema\": ") + e.what());
  249. }
  250. } else {
  251. params.sampling.grammar = json_value(data, "grammar", defaults.sampling.grammar);
  252. SRV_DBG("Grammar: %s\n", params.sampling.grammar.c_str());
  253. params.sampling.grammar_lazy = json_value(data, "grammar_lazy", defaults.sampling.grammar_lazy);
  254. SRV_DBG("Grammar lazy: %s\n", params.sampling.grammar_lazy ? "true" : "false");
  255. }
  256. {
  257. auto it = data.find("chat_format");
  258. if (it != data.end()) {
  259. params.oaicompat_chat_syntax.format = static_cast<common_chat_format>(it->get<int>());
  260. SRV_INF("Chat format: %s\n", common_chat_format_name(params.oaicompat_chat_syntax.format));
  261. } else {
  262. params.oaicompat_chat_syntax.format = defaults.oaicompat_chat_syntax.format;
  263. }
  264. common_reasoning_format reasoning_format = params_base.reasoning_format;
  265. if (data.contains("reasoning_format")) {
  266. reasoning_format = common_reasoning_format_from_name(data.at("reasoning_format").get<std::string>());
  267. }
  268. params.oaicompat_chat_syntax.reasoning_format = reasoning_format;
  269. params.oaicompat_chat_syntax.reasoning_in_content = params.stream && (reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY);
  270. params.oaicompat_chat_syntax.thinking_forced_open = json_value(data, "thinking_forced_open", false);
  271. params.oaicompat_chat_syntax.parse_tool_calls = json_value(data, "parse_tool_calls", false);
  272. if (data.contains("chat_parser")) {
  273. params.oaicompat_chat_syntax.parser.load(data.at("chat_parser").get<std::string>());
  274. }
  275. }
  276. {
  277. const auto preserved_tokens = data.find("preserved_tokens");
  278. if (preserved_tokens != data.end()) {
  279. for (const auto & t : *preserved_tokens) {
  280. auto ids = common_tokenize(vocab, t.get<std::string>(), /* add_special= */ false, /* parse_special= */ true);
  281. if (ids.size() == 1) {
  282. SRV_DBG("Preserved token: %d\n", ids[0]);
  283. params.sampling.preserved_tokens.insert(ids[0]);
  284. } else {
  285. // This may happen when using a tool call style meant for a model with special tokens to preserve on a model without said tokens.
  286. SRV_DBG("Not preserved because more than 1 token: %s\n", t.get<std::string>().c_str());
  287. }
  288. }
  289. }
  290. const auto grammar_triggers = data.find("grammar_triggers");
  291. if (grammar_triggers != data.end()) {
  292. for (const auto & t : *grammar_triggers) {
  293. server_grammar_trigger ct(t);
  294. if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_WORD) {
  295. const auto & word = ct.value.value;
  296. auto ids = common_tokenize(vocab, word, /* add_special= */ false, /* parse_special= */ true);
  297. if (ids.size() == 1) {
  298. auto token = ids[0];
  299. if (std::find(params.sampling.preserved_tokens.begin(), params.sampling.preserved_tokens.end(), (llama_token) token) == params.sampling.preserved_tokens.end()) {
  300. throw std::runtime_error("Grammar trigger word should be marked as preserved token: " + word);
  301. }
  302. SRV_DBG("Grammar trigger token: %d (`%s`)\n", token, word.c_str());
  303. common_grammar_trigger trigger;
  304. trigger.type = COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN;
  305. trigger.value = word;
  306. trigger.token = token;
  307. params.sampling.grammar_triggers.push_back(std::move(trigger));
  308. } else {
  309. SRV_DBG("Grammar trigger word: `%s`\n", word.c_str());
  310. params.sampling.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, word});
  311. }
  312. } else {
  313. if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN) {
  314. SRV_DBG("Grammar trigger pattern: `%s`\n", ct.value.value.c_str());
  315. } else if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL) {
  316. SRV_DBG("Grammar trigger pattern full: `%s`\n", ct.value.value.c_str());
  317. } else {
  318. throw std::runtime_error("Unknown grammar trigger type");
  319. }
  320. params.sampling.grammar_triggers.emplace_back(std::move(ct.value));
  321. }
  322. }
  323. }
  324. if (params.sampling.grammar_lazy && params.sampling.grammar_triggers.empty()) {
  325. throw std::runtime_error("Error: no triggers set for lazy grammar!");
  326. }
  327. }
  328. {
  329. params.sampling.logit_bias.clear();
  330. const auto & logit_bias = data.find("logit_bias");
  331. if (logit_bias != data.end() && logit_bias->is_array()) {
  332. const int n_vocab = llama_vocab_n_tokens(vocab);
  333. for (const auto & el : *logit_bias) {
  334. // TODO: we may want to throw errors here, in case "el" is incorrect
  335. if (el.is_array() && el.size() == 2) {
  336. float bias;
  337. if (el[1].is_number()) {
  338. bias = el[1].get<float>();
  339. } else if (el[1].is_boolean() && !el[1].get<bool>()) {
  340. bias = -INFINITY;
  341. } else {
  342. continue;
  343. }
  344. if (el[0].is_number_integer()) {
  345. llama_token tok = el[0].get<llama_token>();
  346. if (tok >= 0 && tok < n_vocab) {
  347. params.sampling.logit_bias.push_back({tok, bias});
  348. }
  349. } else if (el[0].is_string()) {
  350. auto toks = common_tokenize(vocab, el[0].get<std::string>(), false);
  351. for (auto tok : toks) {
  352. params.sampling.logit_bias.push_back({tok, bias});
  353. }
  354. }
  355. }
  356. }
  357. } else if (logit_bias != data.end() && logit_bias->is_object()) {
  358. const int n_vocab = llama_vocab_n_tokens(vocab);
  359. for (const auto & el : logit_bias->items()) {
  360. float bias;
  361. const auto & key = el.key();
  362. const auto & value = el.value();
  363. if (value.is_number()) {
  364. bias = value.get<float>();
  365. } else if (value.is_boolean() && !value.get<bool>()) {
  366. bias = -INFINITY;
  367. } else {
  368. continue;
  369. }
  370. char *end;
  371. llama_token tok = strtol(key.c_str(), &end, 10);
  372. if (*end == 0) {
  373. if (tok >= 0 && tok < n_vocab) {
  374. params.sampling.logit_bias.push_back({tok, bias});
  375. }
  376. } else {
  377. auto toks = common_tokenize(vocab, key, false);
  378. for (auto tok : toks) {
  379. params.sampling.logit_bias.push_back({tok, bias});
  380. }
  381. }
  382. }
  383. }
  384. params.sampling.ignore_eos = json_value(data, "ignore_eos", params_base.sampling.ignore_eos);
  385. if (params.sampling.ignore_eos) {
  386. params.sampling.logit_bias.insert(
  387. params.sampling.logit_bias.end(),
  388. defaults.sampling.logit_bias_eog.begin(), defaults.sampling.logit_bias_eog.end());
  389. }
  390. }
  391. {
  392. params.antiprompt.clear();
  393. const auto & stop = data.find("stop");
  394. if (stop != data.end() && stop->is_array()) {
  395. for (const auto & word : *stop) {
  396. if (!word.empty()) {
  397. params.antiprompt.push_back(word);
  398. }
  399. }
  400. }
  401. // set reverse prompt from cli args if not set in the request
  402. if (params.antiprompt.empty()) {
  403. params.antiprompt = defaults.antiprompt;
  404. }
  405. }
  406. {
  407. const auto samplers = data.find("samplers");
  408. if (samplers != data.end()) {
  409. if (samplers->is_array()) {
  410. params.sampling.samplers = common_sampler_types_from_names(*samplers, false);
  411. } else if (samplers->is_string()){
  412. params.sampling.samplers = common_sampler_types_from_chars(samplers->get<std::string>());
  413. }
  414. } else {
  415. params.sampling.samplers = defaults.sampling.samplers;
  416. }
  417. }
  418. if (params.n_cmpl > params_base.n_parallel) {
  419. throw std::runtime_error("n_cmpl cannot be greater than the number of slots, please increase -np");
  420. }
  421. return params;
  422. }
  423. //
  424. // result_timings
  425. //
  426. json result_timings::to_json() const {
  427. json base = {
  428. {"cache_n", cache_n},
  429. {"prompt_n", prompt_n},
  430. {"prompt_ms", prompt_ms},
  431. {"prompt_per_token_ms", prompt_per_token_ms},
  432. {"prompt_per_second", prompt_per_second},
  433. {"predicted_n", predicted_n},
  434. {"predicted_ms", predicted_ms},
  435. {"predicted_per_token_ms", predicted_per_token_ms},
  436. {"predicted_per_second", predicted_per_second},
  437. };
  438. if (draft_n > 0) {
  439. base["draft_n"] = draft_n;
  440. base["draft_n_accepted"] = draft_n_accepted;
  441. }
  442. return base;
  443. }
  444. //
  445. // result_prompt_progress
  446. //
  447. json result_prompt_progress::to_json() const {
  448. return json {
  449. {"total", total},
  450. {"cache", cache},
  451. {"processed", processed},
  452. {"time_ms", time_ms},
  453. };
  454. }
  455. static inline std::string stop_type_to_str(stop_type type) {
  456. switch (type) {
  457. case STOP_TYPE_EOS: return "eos";
  458. case STOP_TYPE_WORD: return "word";
  459. case STOP_TYPE_LIMIT: return "limit";
  460. default: return "none";
  461. }
  462. }
  463. //
  464. // completion_token_output
  465. //
  466. json completion_token_output::to_json(bool post_sampling_probs) const {
  467. json probs_for_token = json::array();
  468. for (const auto & p : probs) {
  469. std::string txt(p.txt);
  470. txt.resize(validate_utf8(txt));
  471. probs_for_token.push_back(json {
  472. {"id", p.tok},
  473. {"token", txt},
  474. {"bytes", str_to_bytes(p.txt)},
  475. {
  476. post_sampling_probs ? "prob" : "logprob",
  477. post_sampling_probs ? p.prob : logarithm(p.prob)
  478. },
  479. });
  480. }
  481. return probs_for_token;
  482. }
  483. json completion_token_output::probs_vector_to_json(const std::vector<completion_token_output> & probs, bool post_sampling_probs) {
  484. json out = json::array();
  485. for (const auto & p : probs) {
  486. std::string txt(p.text_to_send);
  487. txt.resize(validate_utf8(txt));
  488. out.push_back(json {
  489. {"id", p.tok},
  490. {"token", txt},
  491. {"bytes", str_to_bytes(p.text_to_send)},
  492. {
  493. post_sampling_probs ? "prob" : "logprob",
  494. post_sampling_probs ? p.prob : logarithm(p.prob)
  495. },
  496. {
  497. post_sampling_probs ? "top_probs" : "top_logprobs",
  498. p.to_json(post_sampling_probs)
  499. },
  500. });
  501. }
  502. return out;
  503. }
  504. float completion_token_output::logarithm(float x) {
  505. // nlohmann::json converts -inf to null, so we need to prevent that
  506. return x == 0.0f ? std::numeric_limits<float>::lowest() : std::log(x);
  507. }
  508. std::vector<unsigned char> completion_token_output::str_to_bytes(const std::string & str) {
  509. std::vector<unsigned char> bytes;
  510. for (unsigned char c : str) {
  511. bytes.push_back(c);
  512. }
  513. return bytes;
  514. }
  515. //
  516. // server_task_result_cmpl_final
  517. //
  518. json server_task_result_cmpl_final::to_json() {
  519. GGML_ASSERT(is_updated && "update() must be called before to_json()");
  520. switch (res_type) {
  521. case TASK_RESPONSE_TYPE_NONE:
  522. return to_json_non_oaicompat();
  523. case TASK_RESPONSE_TYPE_OAI_CMPL:
  524. return to_json_oaicompat();
  525. case TASK_RESPONSE_TYPE_OAI_CHAT:
  526. return stream ? to_json_oaicompat_chat_stream() : to_json_oaicompat_chat();
  527. case TASK_RESPONSE_TYPE_ANTHROPIC:
  528. return stream ? to_json_anthropic_stream() : to_json_anthropic();
  529. default:
  530. GGML_ASSERT(false && "Invalid task_response_type");
  531. }
  532. }
  533. json server_task_result_cmpl_final::to_json_non_oaicompat() {
  534. json res = json {
  535. {"index", index},
  536. {"content", content},
  537. {"tokens", tokens},
  538. {"id_slot", id_slot},
  539. {"stop", true},
  540. {"model", oaicompat_model},
  541. {"tokens_predicted", n_decoded},
  542. {"tokens_evaluated", n_prompt_tokens},
  543. {"generation_settings", generation_params.to_json()},
  544. {"prompt", prompt},
  545. {"has_new_line", has_new_line},
  546. {"truncated", truncated},
  547. {"stop_type", stop_type_to_str(stop)},
  548. {"stopping_word", stopping_word},
  549. {"tokens_cached", n_tokens_cached},
  550. {"timings", timings.to_json()},
  551. };
  552. if (!stream && !probs_output.empty()) {
  553. res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs);
  554. }
  555. return response_fields.empty() ? res : json_get_nested_values(response_fields, res);
  556. }
  557. json server_task_result_cmpl_final::to_json_oaicompat() {
  558. std::time_t t = std::time(0);
  559. json logprobs = json(nullptr); // OAI default to null
  560. if (!stream && probs_output.size() > 0) {
  561. logprobs = json{
  562. {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
  563. };
  564. }
  565. json finish_reason = "length";
  566. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  567. finish_reason = "stop";
  568. }
  569. json res = json {
  570. {"choices", json::array({
  571. json{
  572. {"text", content},
  573. {"index", index},
  574. {"logprobs", logprobs},
  575. {"finish_reason", finish_reason},
  576. }
  577. })},
  578. {"created", t},
  579. {"model", oaicompat_model},
  580. {"system_fingerprint", build_info},
  581. {"object", "text_completion"},
  582. {"usage", json {
  583. {"completion_tokens", n_decoded},
  584. {"prompt_tokens", n_prompt_tokens},
  585. {"total_tokens", n_decoded + n_prompt_tokens}
  586. }},
  587. {"id", oaicompat_cmpl_id}
  588. };
  589. // extra fields for debugging purposes
  590. if (verbose) {
  591. res["__verbose"] = to_json_non_oaicompat();
  592. }
  593. if (timings.prompt_n >= 0) {
  594. res.push_back({"timings", timings.to_json()});
  595. }
  596. return res;
  597. }
  598. json server_task_result_cmpl_final::to_json_oaicompat_chat() {
  599. std::string finish_reason = "length";
  600. common_chat_msg msg;
  601. if (!oaicompat_msg.empty()) {
  602. msg = oaicompat_msg;
  603. } else {
  604. msg.role = "assistant";
  605. msg.content = content;
  606. }
  607. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  608. finish_reason = msg.tool_calls.empty() ? "stop" : "tool_calls";
  609. }
  610. json choice {
  611. {"finish_reason", finish_reason},
  612. {"index", index},
  613. {"message", msg.to_json_oaicompat<json>()},
  614. };
  615. if (!stream && probs_output.size() > 0) {
  616. choice["logprobs"] = json{
  617. {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
  618. };
  619. }
  620. std::time_t t = std::time(0);
  621. json res = json {
  622. {"choices", json::array({choice})},
  623. {"created", t},
  624. {"model", oaicompat_model},
  625. {"system_fingerprint", build_info},
  626. {"object", "chat.completion"},
  627. {"usage", json {
  628. {"completion_tokens", n_decoded},
  629. {"prompt_tokens", n_prompt_tokens},
  630. {"total_tokens", n_decoded + n_prompt_tokens}
  631. }},
  632. {"id", oaicompat_cmpl_id}
  633. };
  634. // extra fields for debugging purposes
  635. if (verbose) {
  636. res["__verbose"] = to_json_non_oaicompat();
  637. }
  638. if (timings.prompt_n >= 0) {
  639. res.push_back({"timings", timings.to_json()});
  640. }
  641. return res;
  642. }
  643. common_chat_msg task_result_state::update_chat_msg(
  644. const std::string & text_added,
  645. bool is_partial,
  646. std::vector<common_chat_msg_diff> & diffs) {
  647. generated_text += text_added;
  648. auto msg_prv_copy = chat_msg;
  649. SRV_DBG("Parsing chat message: %s\n", generated_text.c_str());
  650. auto new_msg = common_chat_parse(
  651. generated_text,
  652. is_partial,
  653. oaicompat_chat_syntax);
  654. if (!new_msg.empty()) {
  655. new_msg.set_tool_call_ids(generated_tool_call_ids, gen_tool_call_id);
  656. chat_msg = new_msg;
  657. diffs = common_chat_msg_diff::compute_diffs(msg_prv_copy, new_msg.empty() ? msg_prv_copy : new_msg);
  658. }
  659. return chat_msg;
  660. }
  661. json server_task_result_cmpl_final::to_json_oaicompat_chat_stream() {
  662. std::time_t t = std::time(0);
  663. std::string finish_reason = "length";
  664. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  665. finish_reason = oaicompat_msg.tool_calls.empty() ? "stop" : "tool_calls";
  666. }
  667. json deltas = json::array();
  668. for (const auto & diff : oaicompat_msg_diffs) {
  669. deltas.push_back({
  670. {"choices", json::array({
  671. json {
  672. {"finish_reason", nullptr},
  673. {"index", 0},
  674. {"delta", common_chat_msg_diff_to_json_oaicompat<json>(diff)},
  675. },
  676. })},
  677. {"created", t},
  678. {"id", oaicompat_cmpl_id},
  679. {"model", oaicompat_model},
  680. {"system_fingerprint", build_info},
  681. {"object", "chat.completion.chunk"},
  682. });
  683. }
  684. deltas.push_back({
  685. {"choices", json::array({
  686. json {
  687. {"finish_reason", finish_reason},
  688. {"index", 0},
  689. {"delta", json::object()},
  690. },
  691. })},
  692. {"created", t},
  693. {"id", oaicompat_cmpl_id},
  694. {"model", oaicompat_model},
  695. {"system_fingerprint", build_info},
  696. {"object", "chat.completion.chunk"},
  697. });
  698. if (include_usage) {
  699. // OpenAI API spec for chat.completion.chunks specifies an empty `choices` array for the last chunk when including usage
  700. // https://platform.openai.com/docs/api-reference/chat_streaming/streaming#chat_streaming/streaming-choices
  701. deltas.push_back({
  702. {"choices", json::array()},
  703. {"created", t},
  704. {"id", oaicompat_cmpl_id},
  705. {"model", oaicompat_model},
  706. {"system_fingerprint", build_info},
  707. {"object", "chat.completion.chunk"},
  708. {"usage", json {
  709. {"completion_tokens", n_decoded},
  710. {"prompt_tokens", n_prompt_tokens},
  711. {"total_tokens", n_decoded + n_prompt_tokens},
  712. }},
  713. });
  714. }
  715. if (timings.prompt_n >= 0) {
  716. deltas.back().push_back({"timings", timings.to_json()});
  717. }
  718. // extra fields for debugging purposes
  719. if (verbose && !deltas.empty()) {
  720. deltas.front()["__verbose"] = to_json_non_oaicompat();
  721. }
  722. return deltas;
  723. }
  724. json server_task_result_cmpl_final::to_json_anthropic() {
  725. std::string stop_reason = "max_tokens";
  726. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  727. stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
  728. }
  729. json content_blocks = json::array();
  730. common_chat_msg msg;
  731. if (!oaicompat_msg.empty()) {
  732. msg = oaicompat_msg;
  733. } else {
  734. msg.role = "assistant";
  735. msg.content = content;
  736. }
  737. if (!msg.content.empty()) {
  738. content_blocks.push_back({
  739. {"type", "text"},
  740. {"text", msg.content}
  741. });
  742. }
  743. for (const auto & tool_call : msg.tool_calls) {
  744. json tool_use_block = {
  745. {"type", "tool_use"},
  746. {"id", tool_call.id},
  747. {"name", tool_call.name}
  748. };
  749. try {
  750. tool_use_block["input"] = json::parse(tool_call.arguments);
  751. } catch (const std::exception &) {
  752. tool_use_block["input"] = json::object();
  753. }
  754. content_blocks.push_back(tool_use_block);
  755. }
  756. json res = {
  757. {"id", oaicompat_cmpl_id},
  758. {"type", "message"},
  759. {"role", "assistant"},
  760. {"content", content_blocks},
  761. {"model", oaicompat_model},
  762. {"stop_reason", stop_reason},
  763. {"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)},
  764. {"usage", {
  765. {"input_tokens", n_prompt_tokens},
  766. {"output_tokens", n_decoded}
  767. }}
  768. };
  769. return res;
  770. }
  771. json server_task_result_cmpl_final::to_json_anthropic_stream() {
  772. json events = json::array();
  773. std::string stop_reason = "max_tokens";
  774. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  775. stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
  776. }
  777. bool has_text = !oaicompat_msg.content.empty();
  778. size_t num_tool_calls = oaicompat_msg.tool_calls.size();
  779. bool text_block_started = false;
  780. std::unordered_set<size_t> tool_calls_started;
  781. for (const auto & diff : oaicompat_msg_diffs) {
  782. if (!diff.content_delta.empty()) {
  783. if (!text_block_started) {
  784. events.push_back({
  785. {"event", "content_block_start"},
  786. {"data", {
  787. {"type", "content_block_start"},
  788. {"index", 0},
  789. {"content_block", {
  790. {"type", "text"},
  791. {"text", ""}
  792. }}
  793. }}
  794. });
  795. text_block_started = true;
  796. }
  797. events.push_back({
  798. {"event", "content_block_delta"},
  799. {"data", {
  800. {"type", "content_block_delta"},
  801. {"index", 0},
  802. {"delta", {
  803. {"type", "text_delta"},
  804. {"text", diff.content_delta}
  805. }}
  806. }}
  807. });
  808. }
  809. if (diff.tool_call_index != std::string::npos) {
  810. size_t content_block_index = (has_text ? 1 : 0) + diff.tool_call_index;
  811. if (tool_calls_started.find(diff.tool_call_index) == tool_calls_started.end()) {
  812. const auto & full_tool_call = oaicompat_msg.tool_calls[diff.tool_call_index];
  813. events.push_back({
  814. {"event", "content_block_start"},
  815. {"data", {
  816. {"type", "content_block_start"},
  817. {"index", content_block_index},
  818. {"content_block", {
  819. {"type", "tool_use"},
  820. {"id", full_tool_call.id},
  821. {"name", full_tool_call.name}
  822. }}
  823. }}
  824. });
  825. tool_calls_started.insert(diff.tool_call_index);
  826. }
  827. if (!diff.tool_call_delta.arguments.empty()) {
  828. events.push_back({
  829. {"event", "content_block_delta"},
  830. {"data", {
  831. {"type", "content_block_delta"},
  832. {"index", content_block_index},
  833. {"delta", {
  834. {"type", "input_json_delta"},
  835. {"partial_json", diff.tool_call_delta.arguments}
  836. }}
  837. }}
  838. });
  839. }
  840. }
  841. }
  842. if (has_text) {
  843. events.push_back({
  844. {"event", "content_block_stop"},
  845. {"data", {
  846. {"type", "content_block_stop"},
  847. {"index", 0}
  848. }}
  849. });
  850. }
  851. for (size_t i = 0; i < num_tool_calls; i++) {
  852. size_t content_block_index = (has_text ? 1 : 0) + i;
  853. events.push_back({
  854. {"event", "content_block_stop"},
  855. {"data", {
  856. {"type", "content_block_stop"},
  857. {"index", content_block_index}
  858. }}
  859. });
  860. }
  861. events.push_back({
  862. {"event", "message_delta"},
  863. {"data", {
  864. {"type", "message_delta"},
  865. {"delta", {
  866. {"stop_reason", stop_reason},
  867. {"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)}
  868. }},
  869. {"usage", {
  870. {"output_tokens", n_decoded}
  871. }}
  872. }}
  873. });
  874. events.push_back({
  875. {"event", "message_stop"},
  876. {"data", {
  877. {"type", "message_stop"}
  878. }}
  879. });
  880. return events;
  881. }
  882. //
  883. // server_task_result_cmpl_partial
  884. //
  885. json server_task_result_cmpl_partial::to_json() {
  886. GGML_ASSERT(is_updated && "update() must be called before to_json()");
  887. switch (res_type) {
  888. case TASK_RESPONSE_TYPE_NONE:
  889. return to_json_non_oaicompat();
  890. case TASK_RESPONSE_TYPE_OAI_CMPL:
  891. return to_json_oaicompat();
  892. case TASK_RESPONSE_TYPE_OAI_CHAT:
  893. return to_json_oaicompat_chat();
  894. case TASK_RESPONSE_TYPE_ANTHROPIC:
  895. return to_json_anthropic();
  896. default:
  897. GGML_ASSERT(false && "Invalid task_response_type");
  898. }
  899. }
  900. json server_task_result_cmpl_partial::to_json_non_oaicompat() {
  901. // non-OAI-compat JSON
  902. json res = json {
  903. {"index", index},
  904. {"content", content},
  905. {"tokens", tokens},
  906. {"stop", false},
  907. {"id_slot", id_slot},
  908. {"tokens_predicted", n_decoded},
  909. {"tokens_evaluated", n_prompt_tokens},
  910. };
  911. // populate the timings object when needed (usually for the last response or with timings_per_token enabled)
  912. if (timings.prompt_n > 0) {
  913. res.push_back({"timings", timings.to_json()});
  914. }
  915. if (is_progress) {
  916. res.push_back({"prompt_progress", progress.to_json()});
  917. }
  918. if (!prob_output.probs.empty()) {
  919. res["completion_probabilities"] = completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs);
  920. }
  921. return res;
  922. }
  923. json server_task_result_cmpl_partial::to_json_oaicompat() {
  924. std::time_t t = std::time(0);
  925. json logprobs = json(nullptr); // OAI default to null
  926. if (prob_output.probs.size() > 0) {
  927. logprobs = json{
  928. {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
  929. };
  930. }
  931. json res = json {
  932. {"choices", json::array({
  933. json{
  934. {"text", content},
  935. {"index", index},
  936. {"logprobs", logprobs},
  937. {"finish_reason", nullptr},
  938. }
  939. })},
  940. {"created", t},
  941. {"model", oaicompat_model},
  942. {"system_fingerprint", build_info},
  943. {"object", "text_completion"},
  944. {"id", oaicompat_cmpl_id}
  945. };
  946. // extra fields for debugging purposes
  947. if (verbose) {
  948. res["__verbose"] = to_json_non_oaicompat();
  949. }
  950. if (timings.prompt_n >= 0) {
  951. res.push_back({"timings", timings.to_json()});
  952. }
  953. if (is_progress) {
  954. res.push_back({"prompt_progress", progress.to_json()});
  955. }
  956. return res;
  957. }
  958. json server_task_result_cmpl_partial::to_json_oaicompat_chat() {
  959. bool first = n_decoded == 1;
  960. std::time_t t = std::time(0);
  961. json choices;
  962. std::vector<json> deltas;
  963. auto add_delta = [&](const json & delta) {
  964. deltas.push_back({
  965. {"choices", json::array({
  966. json {
  967. {"finish_reason", nullptr},
  968. {"index", index},
  969. {"delta", delta},
  970. },
  971. })},
  972. {"created", t},
  973. {"id", oaicompat_cmpl_id},
  974. {"model", oaicompat_model},
  975. {"system_fingerprint", build_info},
  976. {"object", "chat.completion.chunk"},
  977. });
  978. };
  979. // We have to send an initial update to conform to openai behavior
  980. if (first || is_progress) {
  981. add_delta({
  982. {"role", "assistant"},
  983. {"content", nullptr},
  984. });
  985. }
  986. for (const auto & diff : oaicompat_msg_diffs) {
  987. add_delta(common_chat_msg_diff_to_json_oaicompat<json>(diff));
  988. }
  989. if (!deltas.empty()) {
  990. auto & last_json = deltas[deltas.size() - 1];
  991. GGML_ASSERT(last_json.at("choices").size() >= 1);
  992. if (prob_output.probs.size() > 0) {
  993. last_json.at("choices").at(0)["logprobs"] = json {
  994. {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
  995. };
  996. }
  997. if (timings.prompt_n >= 0) {
  998. last_json.push_back({"timings", timings.to_json()});
  999. }
  1000. if (is_progress) {
  1001. last_json.push_back({"prompt_progress", progress.to_json()});
  1002. }
  1003. }
  1004. return deltas;
  1005. }
  1006. //
  1007. // server_task_result_embd
  1008. //
  1009. json server_task_result_embd::to_json() {
  1010. return res_type == TASK_RESPONSE_TYPE_OAI_EMBD
  1011. ? to_json_oaicompat()
  1012. : to_json_non_oaicompat();
  1013. }
  1014. json server_task_result_embd::to_json_non_oaicompat() {
  1015. return json {
  1016. {"index", index},
  1017. {"embedding", embedding},
  1018. };
  1019. }
  1020. json server_task_result_embd::to_json_oaicompat() {
  1021. return json {
  1022. {"index", index},
  1023. {"embedding", embedding[0]},
  1024. {"tokens_evaluated", n_tokens},
  1025. };
  1026. }
  1027. //
  1028. // server_task_result_rerank
  1029. //
  1030. json server_task_result_rerank::to_json() {
  1031. return json {
  1032. {"index", index},
  1033. {"score", score},
  1034. {"tokens_evaluated", n_tokens},
  1035. };
  1036. }
  1037. json server_task_result_cmpl_partial::to_json_anthropic() {
  1038. json events = json::array();
  1039. bool first = (n_decoded == 1);
  1040. bool text_block_started = false;
  1041. if (first) {
  1042. text_block_started = false;
  1043. events.push_back({
  1044. {"event", "message_start"},
  1045. {"data", {
  1046. {"type", "message_start"},
  1047. {"message", {
  1048. {"id", oaicompat_cmpl_id},
  1049. {"type", "message"},
  1050. {"role", "assistant"},
  1051. {"content", json::array()},
  1052. {"model", oaicompat_model},
  1053. {"stop_reason", nullptr},
  1054. {"stop_sequence", nullptr},
  1055. {"usage", {
  1056. {"input_tokens", n_prompt_tokens},
  1057. {"output_tokens", 0}
  1058. }}
  1059. }}
  1060. }}
  1061. });
  1062. }
  1063. for (const auto & diff : oaicompat_msg_diffs) {
  1064. if (!diff.content_delta.empty()) {
  1065. if (!text_block_started) {
  1066. events.push_back({
  1067. {"event", "content_block_start"},
  1068. {"data", {
  1069. {"type", "content_block_start"},
  1070. {"index", 0},
  1071. {"content_block", {
  1072. {"type", "text"},
  1073. {"text", ""}
  1074. }}
  1075. }}
  1076. });
  1077. text_block_started = true;
  1078. }
  1079. events.push_back({
  1080. {"event", "content_block_delta"},
  1081. {"data", {
  1082. {"type", "content_block_delta"},
  1083. {"index", 0},
  1084. {"delta", {
  1085. {"type", "text_delta"},
  1086. {"text", diff.content_delta}
  1087. }}
  1088. }}
  1089. });
  1090. }
  1091. if (diff.tool_call_index != std::string::npos) {
  1092. size_t content_block_index = (text_block_started ? 1 : 0) + diff.tool_call_index;
  1093. if (!diff.tool_call_delta.name.empty()) {
  1094. events.push_back({
  1095. {"event", "content_block_start"},
  1096. {"data", {
  1097. {"type", "content_block_start"},
  1098. {"index", content_block_index},
  1099. {"content_block", {
  1100. {"type", "tool_use"},
  1101. {"id", diff.tool_call_delta.id},
  1102. {"name", diff.tool_call_delta.name}
  1103. }}
  1104. }}
  1105. });
  1106. }
  1107. if (!diff.tool_call_delta.arguments.empty()) {
  1108. events.push_back({
  1109. {"event", "content_block_delta"},
  1110. {"data", {
  1111. {"type", "content_block_delta"},
  1112. {"index", content_block_index},
  1113. {"delta", {
  1114. {"type", "input_json_delta"},
  1115. {"partial_json", diff.tool_call_delta.arguments}
  1116. }}
  1117. }}
  1118. });
  1119. }
  1120. }
  1121. }
  1122. return events;
  1123. }
  1124. //
  1125. // server_task_result_error
  1126. //
  1127. json server_task_result_error::to_json() {
  1128. json res = format_error_response(err_msg, err_type);
  1129. if (err_type == ERROR_TYPE_EXCEED_CONTEXT_SIZE) {
  1130. res["n_prompt_tokens"] = n_prompt_tokens;
  1131. res["n_ctx"] = n_ctx;
  1132. }
  1133. return res;
  1134. }
  1135. //
  1136. // server_task_result_metrics
  1137. //
  1138. json server_task_result_metrics::to_json() {
  1139. return json {
  1140. { "idle", n_idle_slots },
  1141. { "processing", n_processing_slots },
  1142. { "deferred", n_tasks_deferred },
  1143. { "t_start", t_start },
  1144. { "n_prompt_tokens_processed_total", n_prompt_tokens_processed_total },
  1145. { "t_tokens_generation_total", t_tokens_generation_total },
  1146. { "n_tokens_predicted_total", n_tokens_predicted_total },
  1147. { "t_prompt_processing_total", t_prompt_processing_total },
  1148. { "n_tokens_max", n_tokens_max },
  1149. { "n_prompt_tokens_processed", n_prompt_tokens_processed },
  1150. { "t_prompt_processing", t_prompt_processing },
  1151. { "n_tokens_predicted", n_tokens_predicted },
  1152. { "t_tokens_generation", t_tokens_generation },
  1153. { "n_decode_total", n_decode_total },
  1154. { "n_busy_slots_total", n_busy_slots_total },
  1155. { "slots", slots_data },
  1156. };
  1157. }
  1158. //
  1159. // server_task_result_slot_save_load
  1160. //
  1161. json server_task_result_slot_save_load::to_json() {
  1162. if (is_save) {
  1163. return json {
  1164. { "id_slot", id_slot },
  1165. { "filename", filename },
  1166. { "n_saved", n_tokens },
  1167. { "n_written", n_bytes },
  1168. { "timings", {
  1169. { "save_ms", t_ms }
  1170. }},
  1171. };
  1172. }
  1173. return json {
  1174. { "id_slot", id_slot },
  1175. { "filename", filename },
  1176. { "n_restored", n_tokens },
  1177. { "n_read", n_bytes },
  1178. { "timings", {
  1179. { "restore_ms", t_ms }
  1180. }},
  1181. };
  1182. }
  1183. //
  1184. // server_task_result_slot_erase
  1185. //
  1186. json server_task_result_slot_erase::to_json() {
  1187. return json {
  1188. { "id_slot", id_slot },
  1189. { "n_erased", n_erased },
  1190. };
  1191. }
  1192. //
  1193. // server_task_result_get_lora
  1194. //
  1195. json server_task_result_get_lora::to_json() {
  1196. json result = json::array();
  1197. for (size_t i = 0; i < loras.size(); ++i) {
  1198. auto & lora = loras[i];
  1199. json entry = {
  1200. {"id", i},
  1201. {"path", lora.info.path},
  1202. {"scale", lora.info.scale},
  1203. {"task_name", lora.info.task_name},
  1204. {"prompt_prefix", lora.info.prompt_prefix},
  1205. };
  1206. if (!lora.alora_invocation_tokens.empty()) {
  1207. entry["alora_invocation_string"] = lora.alora_invocation_string;
  1208. entry["alora_invocation_tokens"] = lora.alora_invocation_tokens;
  1209. }
  1210. result.push_back(std::move(entry));
  1211. }
  1212. return result;
  1213. }
  1214. //
  1215. // server_task_result_apply_lora
  1216. //
  1217. json server_task_result_apply_lora::to_json() {
  1218. return json {{ "success", true }};
  1219. }
  1220. //
  1221. // server_prompt_cache
  1222. //
  1223. size_t server_prompt_cache::size() const {
  1224. size_t res = 0;
  1225. for (const auto & state : states) {
  1226. res += state.size();
  1227. }
  1228. return res;
  1229. }
  1230. size_t server_prompt_cache::n_tokens() const {
  1231. size_t res = 0;
  1232. for (const auto & state : states) {
  1233. res += state.n_tokens();
  1234. }
  1235. return res;
  1236. }
  1237. server_prompt * server_prompt_cache::alloc(const server_prompt & prompt, size_t state_size) {
  1238. // first check if the current state is contained fully in the cache
  1239. for (auto it = states.begin(); it != states.end(); ++it) {
  1240. const int cur_lcp_len = it->tokens.get_common_prefix(prompt.tokens);
  1241. if (cur_lcp_len == (int) prompt.tokens.size()) {
  1242. SRV_WRN("%s", " - prompt is already in the cache, skipping\n");
  1243. return nullptr;
  1244. }
  1245. }
  1246. // next, remove any cached prompts that are fully contained in the current prompt
  1247. for (auto it = states.begin(); it != states.end();) {
  1248. const int len = it->tokens.get_common_prefix(prompt.tokens);
  1249. if (len == (int) it->tokens.size()) {
  1250. SRV_WRN(" - removing obsolete cached prompt with length %d\n", len);
  1251. it = states.erase(it);
  1252. } else {
  1253. ++it;
  1254. }
  1255. }
  1256. std::vector<uint8_t> state_data;
  1257. // check if we can allocate enough memory for the new state
  1258. try {
  1259. state_data.resize(state_size);
  1260. } catch (const std::bad_alloc & e) {
  1261. SRV_ERR("failed to allocate memory for prompt cache state: %s\n", e.what());
  1262. limit_size = std::max<size_t>(1, 0.4*size());
  1263. SRV_WRN(" - cache size limit reduced to %.3f MiB\n", limit_size / (1024.0 * 1024.0));
  1264. update();
  1265. return nullptr;
  1266. }
  1267. // TODO: for some reason we can't copy server_tokens, so we have to do this workaround
  1268. auto & cur = states.emplace_back();
  1269. cur = {
  1270. /*.tokens =*/ server_tokens(prompt.tokens.get_text_tokens(), false),
  1271. /*.data =*/ std::move(state_data),
  1272. /*.checkpoints =*/ prompt.checkpoints,
  1273. };
  1274. return &cur;
  1275. }
  1276. bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx, int32_t id_slot) {
  1277. const int lcp_best = prompt.tokens.get_common_prefix(tokens_new);
  1278. float f_keep_best = float(lcp_best) / prompt.tokens.size();
  1279. float sim_best = float(lcp_best) / tokens_new.size();
  1280. SRV_WRN(" - looking for better prompt, base f_keep = %.3f, sim = %.3f\n", f_keep_best, sim_best);
  1281. auto it_best = states.end();
  1282. // find the most similar cached prompt, that would also preserve the most context
  1283. for (auto it = states.begin(); it != states.end(); ++it) {
  1284. const int lcp_cur = it->tokens.get_common_prefix(tokens_new);
  1285. const float f_keep_cur = float(lcp_cur) / it->tokens.size();
  1286. const float sim_cur = float(lcp_cur) / tokens_new.size();
  1287. // don't trash large prompts
  1288. if (f_keep_cur < 0.25f) {
  1289. continue;
  1290. }
  1291. if (f_keep_best < f_keep_cur && sim_best < sim_cur) {
  1292. f_keep_best = f_keep_cur;
  1293. sim_best = sim_cur;
  1294. it_best = it;
  1295. }
  1296. }
  1297. if (it_best != states.end()) {
  1298. SRV_WRN(" - found better prompt with f_keep = %.3f, sim = %.3f\n", f_keep_best, sim_best);
  1299. const size_t size = it_best->data.size();
  1300. const size_t n = llama_state_seq_set_data_ext(ctx, it_best->data.data(), size, id_slot, 0);
  1301. if (n != size) {
  1302. SRV_WRN("failed to restore state with size %zu\n", size);
  1303. return false;
  1304. }
  1305. it_best->data.clear();
  1306. it_best->data.shrink_to_fit();
  1307. prompt = std::move(*it_best);
  1308. states.erase(it_best);
  1309. }
  1310. return true;
  1311. }
  1312. void server_prompt_cache::update() {
  1313. if (limit_size > 0) {
  1314. // always keep at least one state, regardless of the limits
  1315. while (states.size() > 1 && size() > limit_size) {
  1316. if (states.empty()) {
  1317. break;
  1318. }
  1319. SRV_WRN(" - cache size limit reached, removing oldest entry (size = %.3f MiB)\n", states.front().size() / (1024.0 * 1024.0));
  1320. states.pop_front();
  1321. }
  1322. }
  1323. // average size per token
  1324. const float size_per_token = std::max<float>(1.0f, float(size()) / (std::max<size_t>(1, n_tokens())));
  1325. // dynamically increase the token limit if it can fit in the memory limit
  1326. const size_t limit_tokens_cur = limit_size > 0 ? std::max<size_t>(limit_tokens, limit_size/size_per_token) : limit_tokens;
  1327. if (limit_tokens > 0) {
  1328. while (states.size() > 1 && n_tokens() > limit_tokens_cur) {
  1329. if (states.empty()) {
  1330. break;
  1331. }
  1332. SRV_WRN(" - cache token limit (%zu, est: %zu) reached, removing oldest entry (size = %.3f MiB)\n",
  1333. limit_tokens, limit_tokens_cur, states.front().size() / (1024.0 * 1024.0));
  1334. states.pop_front();
  1335. }
  1336. }
  1337. SRV_WRN(" - cache state: %zu prompts, %.3f MiB (limits: %.3f MiB, %zu tokens, %zu est)\n",
  1338. states.size(), size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0), limit_tokens, limit_tokens_cur);
  1339. for (const auto & state : states) {
  1340. SRV_WRN(" - prompt %p: %7d tokens, checkpoints: %2zu, %9.3f MiB\n",
  1341. (const void *)&state, state.n_tokens(), state.checkpoints.size(), state.size() / (1024.0 * 1024.0));
  1342. }
  1343. }