server-task.cpp 57 KB

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